diff --git a/.github/workflows/Java_CI.yaml b/.github/workflows/Java_CI.yaml new file mode 100644 index 000000000..0f3af48c8 --- /dev/null +++ b/.github/workflows/Java_CI.yaml @@ -0,0 +1,33 @@ +name: Java CI + +on: + pull_request: + branches: + - wrims-devops + push: + branches: + - wrims-devops + +jobs: + build: + + runs-on: windows-2022 + + steps: + - uses: actions/checkout@v2 + + - name: Set up JDK 1.8 + uses: actions/setup-java@v2 + with: + java-version: '8' + distribution: 'temurin' + cache: 'gradle' + + - name: Build with Gradle + run: ./gradlew build + + - name: Upload jars + uses: actions/upload-artifact@v4.0.0 + with: + name: jars result + path: ./wrims-core/build/libs/*.jar diff --git a/.gitignore b/.gitignore index 0c478ae12..88c018b53 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,46 @@ -/.tgitconfig -/build.properties -/debug.log -/feature.xml -bin -/3rd_party/ +**/target +tmp +**/\.~lock* + +**/.gradle +**/gradle/license-plugin/ +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath .project -.idea +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ -mil.army.usace.hec-dependencies/.gradle/ +### Mac OS ### +.DS_Store -mil.army.usace.hec-dependencies/build/ +gradle.properties \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 000000000..a8404786f --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +The "wrims_v2" directory here contains files and directories from the WRIMS project as it existed before the DevOps revisions were started. +All other files and folders at the root level in this branch and its descendants are structured to support GitHub-style CI/CD builds with Gradle. + +Directories here: +- .github/workflow -- home to the GitHub workflows that build WRIMS components on the GitHub site +- buildSrc -- Holds build configuration information common to all subprojects. For specifics, see Gradle documentation https://docs.gradle.org/current/userguide/organizing_gradle_projects.html#sec:build_sources +- gradle -- configurations for the gradle build, most significantly the file "libs.version.toml" which sets the version numbers for the libraries that will be retrieved from Maven Central or other artifact repositories at build time +- wrims-core -- the gradle sub-project that produces the equivalent of the previous WRIMSv2.jar file +- wrims_v2 -- see above + +The remaining files at this level are set up to support a mult-project gradle build as described at https://docs.gradle.org/current/userguide/intro_multi_project_builds.html + +Files were moved (rather than copied) from wrims_v2/wrims_v2/src to new locations in wrims-core/src so that their git histories would be preserved. Source files for non-java program components were left in their original folders, and will be moved as the project goes forward. A [README file in wrims_v2/wrims_v2/src](./wrims_v2/wrims_v2/src/README.md) lists the groups of files that were moved and left behind. + +The jar that's built from this branch (wrims-core) of the project does not contain the +antler classes. To run wrims using this jar, you'll need to include the antler runtime (v 3.5.2) +in addition to the wrims-core jar to replace the old WRIMSv2.jar. + diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..190415de6 --- /dev/null +++ b/build.gradle @@ -0,0 +1,22 @@ +// This is the root build.gradle, which defines a few project-wide properties. +// Notably, this project sets the version of all projects, as well as the group name. + +plugins { + id "com.palantir.git-version" version "3.0.0" + id 'base' +} + +// This utilizes Git Tag based versioning to set the version of the project based on the current Git Branch or Tag. +// If a tag is checked out, the version will be the name of the most recent tag on this commit. +// Otherwise, the version will be branchname-SNAPSHOT. +def versionLabel(gitInfo) { + def branch = gitInfo.branchName // all branches are snapshots, only tags get released + def tag = gitInfo.lastTag + // tag is returned as is. Branch may need cleanup + return branch == null ? tag : branch.replace("/","-") + "-SNAPSHOT" +} + +allprojects { + group = 'gov.ca.dwr' + version = versionLabel(versionDetails()) +} \ No newline at end of file diff --git a/buildSrc/README.MD b/buildSrc/README.MD new file mode 100644 index 000000000..8b89dc68a --- /dev/null +++ b/buildSrc/README.MD @@ -0,0 +1,6 @@ +# buildSrc + +The `buildSrc` directory contains a set of template Gradle files that can be pulled in to other builds like plugins. +This allows autoconfiguring many components of the build with a single line in the `build.gradle` file, and avoids +copying and pasting a lot of boilerplate code. The single location of all of the logic also makes it much easier to +update for the entire library, such as updating the version of Java. \ No newline at end of file diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle new file mode 100644 index 000000000..1957c3393 --- /dev/null +++ b/buildSrc/build.gradle @@ -0,0 +1,3 @@ +plugins { + id 'groovy-gradle-plugin' +} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/library.deps-conventions.gradle b/buildSrc/src/main/groovy/library.deps-conventions.gradle new file mode 100644 index 000000000..5f182e9ee --- /dev/null +++ b/buildSrc/src/main/groovy/library.deps-conventions.gradle @@ -0,0 +1,12 @@ +// This file provides a set of defaults for defining the `repositories` block for subprojects within this build. +// This ensures that all subprojects use the same repositories and credentials. + +// Define a standard set of repositories, a specific library may need to customize this list and add or remove some items +repositories { + maven { + // The HEC Public repository where a lot of base dependencies are stored like hec-monolith + url 'https://www.hec.usace.army.mil/nexus/repository/maven-public' + } + // The primary public Maven repository, Maven Central where most 3rd party dependencies can be found + mavenCentral() +} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/library.java-conventions.gradle b/buildSrc/src/main/groovy/library.java-conventions.gradle new file mode 100644 index 000000000..24e1ee877 --- /dev/null +++ b/buildSrc/src/main/groovy/library.java-conventions.gradle @@ -0,0 +1,28 @@ +// This file defines the default configurations for the Java plugin, such as configuring the Java version to target +// and setting up a few common dependencies. + +plugins { + id 'java-library' +} + +compileJava { + // Configure the Java release that you wish to target. Note that this does not necessarily directly correlate + // to the version of Java you have installed. This format requires at least Java 9, but will work with any release + // after that. Specifying the release with the `options.release` format enables compiling targeting a previous JDK + // when only a more recent JDK is available (for example, compile for Java 11 with Java 17 or 21). + sourceCompatibility = '1.8' + targetCompatibility = '1.8' + + // This is the preferred method to specify the Java version. There is also the sourceCompatibility property, but + // Gradle recommends the options.release property instead. There is also the Java Toolchains system, but that + // does not appear to support cross compiling (target 11 with JDK 17); it instead expects to find exactly the matching + // JDK for the target version. (This limits it to compiling for Java 11 with Java 11, and targeting Java 11 with + // Java 17 doesn't work.) +} + +java { + // When building a library, ensure that a Sources and Javadoc jar are included as well; this makes sure + // that IDEs are able to automatically download and use the sources and javadoc for your library. + // withSourcesJar() + // withJavadocJar() +} diff --git a/buildSrc/src/main/groovy/library.publishing-conventions.gradle b/buildSrc/src/main/groovy/library.publishing-conventions.gradle new file mode 100644 index 000000000..9782b1187 --- /dev/null +++ b/buildSrc/src/main/groovy/library.publishing-conventions.gradle @@ -0,0 +1,23 @@ +// This file defines the default configurations for publishing a subproject to HEC Nexus. Note that each subproject +// still requires a `publishing` block to actually specify the component that will be published. + +plugins { + id 'maven-publish' +} + +publishing { + // Publish to HEC's Maven-public by targeting the appropriate maven-snapshots or maven-releases repo based on the + // version of the library being deployed. + repositories { + maven { + credentials { + username = project.hasProperty('nexusUser') ? "$nexusUser" : "noUserSpecified" + password = project.hasProperty('nexusPassword') ? "$nexusPassword" : "noPasswordSpecified" + } + def baseUrl = "https://www.hec.usace.army.mil/nexus/repository" + afterEvaluate { + url = version.toString().endsWith("SNAPSHOT") ? "$baseUrl/maven-snapshots/" : "$baseUrl/maven-releases/" + } + } + } +} \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 000000000..525ade4d9 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,28 @@ +[versions] +hec-monolith = "3.3.22" +hec-nucleus-metadata = "2.0.1" +guava = "11.0.2" +commons-io = "2.1" +xstream = "1.4.3" +javatuples = "1.2" +java-object-diff = "0.95" +kryo = "2.24.0" +jep = "3.8.2" +libtensorflow = "1.14.0" +testng = "6.3" + +[libraries] +hec-monolith = { module = "mil.army.usace.hec:hec-monolith", version.ref = "hec-monolith" } +hec-nucleus-metadata = { module = "mil.army.usace.hec:hec-nucleus-metadata", version.ref = "hec-nucleus-metadata" } +antlr = "org.antlr:antlr:3.5.2" +guava = { module = "com.google.guava:guava", version.ref = "guava" } +commons-io = { module = "commons-io:commons-io", version.ref = "commons-io" } +xstream = { module = "com.thoughtworks.xstream:xstream", version.ref = "xstream" } +javatuples = { module = "org.javatuples:javatuples", version.ref = "javatuples" } +java-object-diff = { module = "de.danielbechler:java-object-diff", version.ref = "java-object-diff" } +kryo = { module = "com.esotericsoftware.kryo:kryo", version.ref = "kryo" } +jep = { module = "black.ninia:jep", version.ref = "jep" } +libtensorflow = { module = "org.tensorflow:libtensorflow", version.ref = "libtensorflow" } +testng = { module = "org.testng:testng", version.ref = "testng" } + +[bundles] \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..033e24c4c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..1af9e0930 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 000000000..fcb6fca14 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..baa288278 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'wrims' +include 'wrims-core' \ No newline at end of file diff --git a/wrims-core/build.gradle b/wrims-core/build.gradle new file mode 100644 index 000000000..78d6736c6 --- /dev/null +++ b/wrims-core/build.gradle @@ -0,0 +1,96 @@ + +plugins{ + id 'antlr' + id 'library.deps-conventions' + id 'library.java-conventions' +} + +sourceSets { + src { + antlr { + srcDir "src/main/antlr/" + } + java { + srcDirs "src/main/java/", "generated-src" + } + } +} + +dependencies { + antlr libs.antlr + + implementation libs.hec.monolith + implementation libs.hec.nucleus.metadata + implementation libs.guava + implementation libs.commons.io + implementation libs.xstream + implementation libs.javatuples + implementation libs.java.object.diff + implementation libs.kryo + implementation libs.jep + implementation libs.libtensorflow + + // dependency ont testng exists in main as well as in test + implementation libs.testng + + // It's not obvious which version of hdf-java is needed. + // The packages in the local jars are + // ncsa.hdf.hdf5lib + // ncsa.hdf.object + // ncsa.hdf.object.h5 + // implementation 'org.hdfgroup:hdf-java:2.6' from 2010 is present + // at + implementation files('dep-local/jarhdf5-2.11.0.jar') + implementation files('dep-local/jarhdfobj.jar') + implementation files('dep-local/jarh5obj.jar') + + // The oldest implementation of Google's linearsolver in mavencentral appears to be + // implementation 'com.google.ortools:ortools-java:8.2.9004' + // from 20 April 2021. + // The local jar file contents are from 2013, so we'll use the local jar + // until we verify that a newer version will work. + implementation files('dep-local/com.google.ortools.linearsolver.jar') + + // The oldest implementation of gurobi in a maven repository appears to be + // from 2014. We'll use the local jar (2012) until we verify that a newer version + // will work. + implementation files('dep-local/gurobi.jar') + + implementation files('dep-local/coinor.jar') + implementation files('dep-local/lpsolve55j.jar') + implementation files('dep-local/XAOptimizer.jar') + +} + +configurations.all { + exclude group: "javax.media", module: "jai_core" + exclude group: "javax.media", module: "jai_codec" + exclude group: "com.sun.media", module: "jai_imageio" +} + +// This moves .tokens files into the same generated-src files with the .java files +tasks.withType(AntlrTask) { + if (name.startsWith('generate')) { + doLast { + logger.info("Copying .tokens files to corresponding java folders") + copy { + from "${buildDir}/generated-src/antlr/main" + include '*Evaluator*.tokens' + into "${buildDir}/generated-src/antlr/main/wrimsv2/evaluator/" + } + copy { + from "${buildDir}/generated-src/antlr/main" + include 'WreslTree*.tokens' + into "${buildDir}/generated-src/antlr/main/wrimsv2/wreslparser/grammar/" + } + copy{ + from "${buildDir}/generated-src/antlr/main" + include 'IncFileFinder.tokens' + include 'WreslPlus.tokens' + into "${buildDir}/generated-src/antlr/main/wrimsv2/wreslplus/grammar/" + } + delete "${buildDir}/generated-src/antlr/main/*.tokens" + } + } +} + diff --git a/wrims-core/dep-local/XAOptimizer.jar b/wrims-core/dep-local/XAOptimizer.jar new file mode 100644 index 000000000..33ce8505b Binary files /dev/null and b/wrims-core/dep-local/XAOptimizer.jar differ diff --git a/wrims-core/dep-local/coinor.jar b/wrims-core/dep-local/coinor.jar new file mode 100644 index 000000000..82872beae Binary files /dev/null and b/wrims-core/dep-local/coinor.jar differ diff --git a/wrims-core/dep-local/com.google.ortools.linearsolver.jar b/wrims-core/dep-local/com.google.ortools.linearsolver.jar new file mode 100644 index 000000000..8729c1289 Binary files /dev/null and b/wrims-core/dep-local/com.google.ortools.linearsolver.jar differ diff --git a/wrims-core/dep-local/gurobi.jar b/wrims-core/dep-local/gurobi.jar new file mode 100644 index 000000000..59962f33a Binary files /dev/null and b/wrims-core/dep-local/gurobi.jar differ diff --git a/wrims-core/dep-local/jarh5obj.jar b/wrims-core/dep-local/jarh5obj.jar new file mode 100644 index 000000000..b53bcb267 Binary files /dev/null and b/wrims-core/dep-local/jarh5obj.jar differ diff --git a/wrims-core/dep-local/jarhdf5-2.11.0.jar b/wrims-core/dep-local/jarhdf5-2.11.0.jar new file mode 100644 index 000000000..36bbb18e6 Binary files /dev/null and b/wrims-core/dep-local/jarhdf5-2.11.0.jar differ diff --git a/wrims-core/dep-local/jarhdfobj.jar b/wrims-core/dep-local/jarhdfobj.jar new file mode 100644 index 000000000..0996ed696 Binary files /dev/null and b/wrims-core/dep-local/jarhdfobj.jar differ diff --git a/wrims-core/dep-local/lpsolve55j.jar b/wrims-core/dep-local/lpsolve55j.jar new file mode 100644 index 000000000..5815d427e Binary files /dev/null and b/wrims-core/dep-local/lpsolve55j.jar differ diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/Evaluator.g b/wrims-core/src/main/antlr/wrimsv2/evaluator/Evaluator.g similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/Evaluator.g rename to wrims-core/src/main/antlr/wrimsv2/evaluator/Evaluator.g index 89fd796d9..d37ce10ef 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/Evaluator.g +++ b/wrims-core/src/main/antlr/wrimsv2/evaluator/Evaluator.g @@ -1,560 +1,560 @@ -grammar Evaluator; - -options { - language = Java; -} - -@header { - package wrimsv2.evaluator; - - import org.antlr.runtime.ANTLRFileStream; - import org.antlr.runtime.CharStream; - import org.antlr.runtime.CommonTokenStream; - import org.antlr.runtime.RecognitionException; - import org.antlr.runtime.TokenStream; - - import java.util.HashMap; - import wrimsv2.components.Error; - import wrimsv2.components.IntDouble; - import wrimsv2.parallel.ParallelVars; -} - -@lexer::header { - package wrimsv2.evaluator; -} - -@members { - public IntDouble evalValue; - public EvalExpression evalExpression; - public EvalConstraint evalConstraint; - public boolean evalCondition; - public ParallelVars prvs; - public Stack sumIndex= new Stack (); - - @Override - public void reportError(RecognitionException e) { - Error.addEvaluationError(getErrorMessage(e, tokenNames)); - } - - public void setParallelVars (ParallelVars prvs1) { - prvs=prvs1; - } - - public void setSumIndex(Stack sumIndex){ - this.sumIndex=sumIndex; - } -} - -evaluator returns [String result] - : goalInput| - expressionInput | - softConstraint| - conditionInput - ; - -/////////////////// -/// input rules /// -/////////////////// - -goalInput: 'g:' constraintStatement {evalConstraint = $constraintStatement.ec;}; -expressionInput: 'v:' expressionCollection{evalValue=Evaluation.expressionInput($expressionCollection.ee);}; -softConstraint: 's:' expressionCollection{evalExpression=$expressionCollection.ee;}; -conditionInput: 'c:' conditionStatement {evalCondition=$conditionStatement.result;}; - -/////////////////// -/// basic rules /// -/////////////////// -lhsrhs: expression|CONSTRAIN; - -//weight : (allnumber|(allnumber '*' TAFCFS)) (('+' allnumber)|('-' allnumber))?; - -units: IDENT|(IDENT '/' IDENT); - -fileName - : (':'|';'|'.'|'|'|SYMBOLS|'-'|'+'|BACKSLASH|IDENT|IDENT1|IDENT2|INTEGER|FLOAT|usedKeywords)+{ - } - ; - -externalFile - : (';'|'.'|'|'|SYMBOLS|'-'|'+'|INTEGER|FLOAT|IDENT|usedKeywords)+ - ; - -text : LETTER (LETTER | DIGIT )*; - -expressionCollection returns [EvalExpression ee] - : (expression{ee=$expression.ee;}) - |(tableSQL){ee=$tableSQL.ee;} - |(timeseriesWithUnits) - |((timeseries){ee=$timeseries.ee;}) - | sumExpression {ee=$sumExpression.ee;} - |(UPPERUNBOUNDED{ee=new EvalExpression(new IntDouble(1e38,true));}) - |(LOWERUNBOUNDED{ee=new EvalExpression(new IntDouble(-1e38,true));}) - ; - -func returns[EvalExpression ee]: - (max_func{ee=$max_func.ee;})| - (min_func{ee=$min_func.ee;})| - (int_func{ee=$int_func.ee;})| - (real_func{ee=$real_func.ee;})| - (abs_func{ee=$abs_func.ee;})| - (exp_func{ee=$exp_func.ee;})| - (log_func{ee=$log_func.ee;})| - (log10_func{ee=$log10_func.ee;})| - (pow_func{ee=$pow_func.ee;})| - (mod_func{ee=$mod_func.ee;})| - (round_func{ee=$round_func.ee;})| - (sin_func{ee=$sin_func.ee;})| - (cos_func{ee=$cos_func.ee;})| - (tan_func{ee=$tan_func.ee;})| - (cot_func{ee=$cot_func.ee;})| - (asin_func{ee=$asin_func.ee;})| - (acos_func{ee=$acos_func.ee;})| - (atan_func{ee=$atan_func.ee;})| - (acot_func{ee=$acot_func.ee;})| - (exceedFunc{ee=$exceedFunc.ee;})| - (exceedtsiFunc{ee=$exceedtsiFunc.ee;}) - ; - -round_func returns[EvalExpression ee] - : ROUND '(' (e1=expression)')'{ - ee=Evaluation.round($e1.ee); - } - ; - -mod_func returns[EvalExpression ee] - : MOD '(' (e1=expression) (';' (e2=expression)) ')'{ - ee=Evaluation.mod($e1.ee, $e2.ee); - } - ; - -max_func returns[EvalExpression ee] - : MAX '(' (e1=expression){ee=$e1.ee;}(';' (e2=expression{ - ee=Evaluation.max(ee, $e2.ee); - }))+ ')' - ; - -min_func returns[EvalExpression ee] - : MIN '(' (e1=expression){ee=$e1.ee;}(';' (e2=expression{ - ee=Evaluation.min(ee, $e2.ee); - }))+ ')' - ; - -int_func returns[EvalExpression ee] - : INT '(' (e=expression) ')'{ - ee=Evaluation.intFunc($e.ee); - } - ; - -real_func returns[EvalExpression ee] - : REAL '(' (e=expression) ')'{ - ee=Evaluation.realFunc($e.ee); - } - ; - -abs_func returns[EvalExpression ee] - : ABS '(' (e=expression) ')'{ - ee=Evaluation.abs($e.ee); - } - ; - -exp_func returns[EvalExpression ee] - : EXP '(' (e=expression) ')'{ - ee=Evaluation.exp($e.ee); - } - ; - -log_func returns[EvalExpression ee] - : LOG '(' (e=expression) ')'{ - ee=Evaluation.log($e.ee); - } - ; - -log10_func returns[EvalExpression ee] - : LOG10 '(' (e=expression) ')'{ - ee=Evaluation.log10($e.ee); - } - ; - -pow_func returns[EvalExpression ee] - : POW '(' (e1=expression) (';' (e2=expression)) ')'{ - ee=Evaluation.pow($e1.ee, $e2.ee); - } - ; - -sin_func returns[EvalExpression ee] - : SIN '(' (e=expression) ')'{ - ee=Evaluation.sin($e.ee); - } - ; - -cos_func returns[EvalExpression ee] - : COS '(' (e=expression) ')'{ - ee=Evaluation.cos($e.ee); - } - ; - -tan_func returns[EvalExpression ee] - : TAN '(' (e=expression) ')'{ - ee=Evaluation.tan($e.ee); - } - ; - -cot_func returns[EvalExpression ee] - : COT '(' (e=expression) ')'{ - ee=Evaluation.cot($e.ee); - } - ; - -asin_func returns[EvalExpression ee] - : ASIN '(' (e=expression) ')'{ - ee=Evaluation.asin($e.ee); - } - ; - -acos_func returns[EvalExpression ee] - : ACOS '(' (e=expression) ')'{ - ee=Evaluation.acos($e.ee); - } - ; - -atan_func returns[EvalExpression ee] - : ATAN '(' (e=expression) ')'{ - ee=Evaluation.atan($e.ee); - } - ; - -acot_func returns[EvalExpression ee] - : ACOT '(' (e=expression) ')'{ - ee=Evaluation.acot($e.ee); - } - ; - -exceedFunc returns[EvalExpression ee] - : EXCEEDANCE '(' var=IDENT ';' exc=term ';' (mon=MONTH_CONST|mon=MONTH_RANGE|mon=ALL) ';' sy=INTEGER ';' sm=MONTH_CONST ';' sd=INTEGER ';' ey=INTEGER ';' em=MONTH_CONST ';' ed=INTEGER ')' { - ee=Evaluation.exceedance($var.text, $exc.ee, $mon.text, $sy.text, $sm.text, $sd.text, $ey.text, $em.text, $ed.text); - } - ; - -exceedtsiFunc returns[EvalExpression ee] - : EXCEEDANCE_TSI '(' var=IDENT ';' exc=term ';' (mon=MONTH_CONST|mon=MONTH_RANGE|mon=ALL) ';' sy=INTEGER ';' sm=MONTH_CONST ';' sd=INTEGER ';' ey=INTEGER ';' em=MONTH_CONST ';' ed=INTEGER ')' { - ee=Evaluation.exceedance_tsi($var.text, $exc.ee, $mon.text, $sy.text, $sm.text, $sd.text, $ey.text, $em.text, $ed.text); - } - ; - -range_func returns [boolean result] - : RANGE '(' MONTH ';' m1=MONTH_CONST ';' m2=MONTH_CONST ')' {Evaluation.range($m1.text, $m2.text);}; - -timeseriesWithUnits - : 'timeseries' 'kind' '=' partC 'units' '=' IDENT - ; - -timeseries returns [EvalExpression ee] - : 'timeseries' {ee=Evaluation.timeseries();} - ; - - - -partC: (IDENT|IDENT1|usedKeywords) ('-' (IDENT|IDENT1|usedKeywords))*; - -usedKeywords: YEAR|MONTH|MONTH_CONST|MONTH_RANGE|DAY|PASTMONTH|RANGE|TAFCFS|DAYSIN|DAYSINTIMESTEP|SUM|MAX|MIN|INT|REAL|ABS|EXP|LOG|LOG10|POW|MOD|ROUND|SELECT|FROM|GIVEN|USE|WHERE -|CONSTRAIN|ALWAYS|NAME|DVAR|CYCLE|FILE| CONDITION|INCLUDE|LOWERBOUND|UPPERBOUND|INTEGERTYPE|UNITS|CONVERTUNITS|TYPE|OUTPUT -|CASE|ORDER|EXPRESSION|LHSGTRHS|LHSLTRHS|WEIGHT|FUNCTION|FROM_WRESL_FILE|UPPERUNBOUNDED|LOWERUNBOUNDED|AND|OR|NOT -|SIN|COS|TAN|COT|ASIN|ACOS|ATAN|ACOT|EXCEEDANCE|EXCEEDANCE_TSI|ALL; - -tableSQL returns [EvalExpression ee] @init{String table=null; String select=null; String use=null; HashMap given=null; HashMap where=null;} - : SELECT ((i1=IDENT{select=$i1.text;})|(u1=usedKeywords{select=$u1.text;})) FROM i2=IDENT{table=$i2.text;} - (GIVEN a=assignStatement{given=new HashMap(); given.put($a.assignIdent, $a.value);})? (USE i3=IDENT{use=$i3.text;})? - (where_items{where=$where_items.where;})? {ee=Evaluation.tableSQL(table, select, where, given, use);} - ; - -where_items returns [HashMap where] - : WHERE (r1=whereStatement{where=new HashMap(); where.put($r1.whereIdent, $r1.value);}) - (';' r=whereStatement{where.put($r.whereIdent, $r.value);})* - ; - - -upperbound: IDENT|allnumber|(allnumber '*' TAFCFS); - -lowerbound: IDENT|allnumber|(allnumber '*' TAFCFS); - -//sumExpression -// : SUM '(' I '=' e1=expression_sum ';' e2=expression_sum (';' (s='-')? INTEGER )? ')' e3=expression -// ; -//term_sum: (MONTH|MONTH_CONST|PASTMONTH|I|INTEGER|'(' expression_sum ')'); - -//unary_sum : ('-')? term_sum ; -//add_sum : unary_sum(('+' | '-') unary_sum)* ; -//expression_sum: add_sum ; - -//sumExpression was redesign. If not work, switch back to the original design above - -sumExpression returns [EvalExpression ee] @init{String s="";} - : SUM '(' IDENT{Evaluation.sumExpression_IDENT($IDENT.text, sumIndex);} '=' e1=expression ';' e2=expression (';' (('-'{s=s+"-";})? INTEGER {s=s+$INTEGER.text;}))? ')' {Evaluation.initSumExpression($e1.ee, $e2.ee, s, sumIndex);} e3=expression{ee=Evaluation.sumExpression($e3.ee, $e3.text, sumIndex);} - ; - -term returns [EvalExpression ee] - : (IDENT {ee=Evaluation.term_IDENT($IDENT.text, sumIndex);}) - | (FLOAT {ee=Evaluation.term_FLOAT($FLOAT.text);}) - | ('(' (e=expression) ')' {ee=$e.ee;}) - | pastCycleValue{ee=Evaluation.term_knownTS($pastCycleValue.result);} - | function{ee=$function.ee;} - | func{ee=$func.ee;} - | (INTEGER {ee=Evaluation.term_INTEGER($INTEGER.text);}) - | tafcfs_term{ee=$tafcfs_term.ee;} - | YEAR{ee=Evaluation.term_YEAR();} - | MONTH{ee=Evaluation.term_MONTH();} - | DAY{ee=Evaluation.term_DAY();} - | MONTH_CONST{ee=Evaluation.term_MONTH_CONST($MONTH_CONST.text);} - | PASTMONTH{ee=Evaluation.term_PASTMONTH($PASTMONTH.text);} - | DAYSIN{ee=Evaluation.daysIn();} - | DAYSINTIMESTEP{ee=Evaluation.daysInTimeStep();} - | (SVAR{ee=Evaluation.term_SVAR($SVAR.text.replace("{","").replace("}",""));}) - | ARRAY_ITERATOR{ee=Evaluation.term_ARRAY_ITERATOR(prvs);} - | '(' sumExpression ')'{ee=$sumExpression.ee;} - ; - -tafcfs_term returns [EvalExpression ee]: TAFCFS ('(' expression ')')? { - ee=Evaluation.tafcfs_term($TAFCFS.text, $expression.ee, sumIndex); -}; - -pastCycleValue returns[IntDouble result] - : (p1=pastCycleNoTimeArray{return $p1.result;})|(p2=pastCycleTimeArray{return $p2.result;})|(p3=pastCycleIndexNoTimeArray{return $p3.result;})|(p4=pastCycleIndexTimeArray{return $p4.result;}) - ; - -pastCycleNoTimeArray returns [IntDouble result] - : i1=IDENT '[' i2=IDENT ']'{result=Evaluation.pastCycleNoTimeArray($i1.text,$i2.text);} - ; - -pastCycleTimeArray returns [IntDouble result] - : i1=IDENT '[' i2=IDENT ']' '(' e1=expression ')' {result=Evaluation.pastCycleTimeArray($i1.text,$i2.text, $e1.ee);} - ; - -pastCycleIndexNoTimeArray returns [IntDouble result] - : i1=IDENT '[' '-' index=INTEGER ']'{result=Evaluation.pastCycleIndexNoTimeArray($i1.text,-Integer.parseInt($index.text));} - ; - -pastCycleIndexTimeArray returns [IntDouble result] - : i1=IDENT '[' '-' index=INTEGER ']' '(' e1=expression ')' {result=Evaluation.pastCycleIndexTimeArray($i1.text,-Integer.parseInt($index.text), $e1.ee);} - ; - -function returns [EvalExpression ee] - : (n=noArgFunction{ee=$n.ee;})|(a=argFunction{ee=$a.ee;}) - ; - -noArgFunction returns [EvalExpression ee] - : IDENT '(' ')' {ee=Evaluation.noArgFunction($IDENT.text);}; - -argFunction returns [EvalExpression ee] @init{ArrayList> eeArray = new ArrayList>(); ArrayList ee0Array=new ArrayList();} - : IDENT '(' (e1=expression {ArrayList eeArray1=new ArrayList(); eeArray1.add($e1.ee); eeArray.add(eeArray1);} - |t1=trunk_timeArray{eeArray.add($t1.eeArray);}) - (';' (e2=expression{ArrayList eeArray1=new ArrayList(); eeArray1.add($e2.ee); eeArray.add(eeArray1);} - |t2=trunk_timeArray{eeArray.add($t2.eeArray);}))* ')' ('(' e0=expression {ee0Array.add($e0.ee);} ')')? - { - if (ee0Array.size()==0){ - ee=Evaluation.argFunction($IDENT.text,eeArray,sumIndex); - }else{ - ee=Evaluation.pastTSFV($IDENT.text, $e0.ee, eeArray, prvs); - } - }; - -trunk_timeArray returns[ArrayList eeArray] @init{eeArray = new ArrayList(); IntDouble start=new IntDouble(1, true); IntDouble end=new IntDouble(1, true);} - : i0=IDENT '(' (n1=integer{start=ValueEvaluation.term_INTEGER($n1.text);}|i1=IDENT{start=ValueEvaluation.term_IDENT($i1.text, sumIndex);}) ':' (n2=integer{end=ValueEvaluation.term_INTEGER($n2.text);}|i2=IDENT{end=ValueEvaluation.term_IDENT($i2.text, sumIndex);}) ')' - { - eeArray=Evaluation.trunk_timeArray($i0.text, start, end); - } - ; - -unary returns [EvalExpression ee] - : (s=('+'|'-'))? term{ee=Evaluation.unary($s.text, $term.ee); - }; - -allnumber - : ('-')? number; - -mult returns [EvalExpression ee] - : (u1=unary {ee=$u1.ee;}) (s=('*'| '/') (u2=unary){ - if ($s.text.equals("*")){ - ee=Evaluation.mult(ee, $u2.ee); - }else{ - ee=Evaluation.divide(ee, $u2.ee); - } - })* - ; - -add returns [EvalExpression ee] - : (m1=mult {ee=$m1.ee;}) ((s=('+'|'-')) (m2=mult){ - if ($s.text.equals("+")){ - ee=Evaluation.add(ee, $m2.ee); - }else{ - ee=Evaluation.substract(ee, $m2.ee); - } - })* - ; - -expression returns [EvalExpression ee] - : i=add {$ee=$add.ee;} - ; - -relation - : '==' - | '<' - | '>' - | '>=' - | '<=' - ; - -whereStatement returns [String whereIdent, Number value] - : ((i=IDENT{$whereIdent=$i.text;})|(u=usedKeywords{$whereIdent=$u.text;})) '=' expression{$value=Evaluation.assignWhereStatement($expression.ee);} - ; - -conditionStatement returns [boolean result] - : ((r=relationUnary{result=$r.result;})|ALWAYS{result=true;}) - ; - -relationUnary returns [boolean result] - : (n=NOT)? r=relationOr{ - if ($n==null){ - return $r.result; - }else{ - if ($r.result){ - return false; - }else{ - return true; - } - } - } - ; - -relationOr returns [boolean result] - : r1=relationAnd {result=$r1.result;} - (s=OR r2=relationAnd {result=Evaluation.relationStatementSeries(result, $r2.result, $s.text);})* ; - -relationAnd returns [boolean result] - : r1=relationRangeStatement {result=$r1.result;} - (s=AND r2=relationRangeStatement {result=Evaluation.relationStatementSeries(result, $r2.result, $s.text);})* ; - -relationRangeStatement returns [boolean result] - : (r1=relationStatement{result=$r1.result;})|(r2=range_func{result=$r2.result;}) - ; - -relationStatement returns [boolean result] - : ( ( expression relation expression ) => (e1=expression) relation (e2=expression) {result=Evaluation.relationStatement($e1.ee, $e2.ee, $relation.text);} ) - | ( ( '('relationUnary')' ) => '('r2=relationUnary')' {result=$r2.result;} ) - ; - -constraintStatement returns [EvalConstraint ec] - : e1=expression ((s='=')|(s='>')|(s='<')) e2=expression{ec=Evaluation.constraintStatement($e1.ee, $e2.ee, $s.text);} - ; - -assignStatement returns [String assignIdent, Number value] - : IDENT '=' expression {$assignIdent=$IDENT.text; $value=Evaluation.assignWhereStatement($expression.ee);} - ; - -number - : INTEGER - | FLOAT - ; - -integer : integer_p|integer_n ; -integer_p : INTEGER ; -integer_n : '-' INTEGER ; - -MULTILINE_COMMENT : '/*' .* '*/' {$channel = HIDDEN;} ; - -fragment LETTER : ('a'..'z' | 'A'..'Z') ; -fragment DIGIT : '0'..'9'; -fragment SYMBOLS : '_'; - -BACKSLASH : '\\'; - -INTEGER : DIGIT+ ; -FLOAT : INTEGER? '.' INTEGER - | INTEGER '.' - ; - -//I: 'i'; -YEAR: 'wateryear'; -MONTH: 'month'; -DAY: 'day'; -MONTH_CONST: 'jan'|'feb'|'mar'|'apr'|'may'|'jun'|'jul'|'aug'|'sep'|'oct'|'nov'|'dec'; -MONTH_RANGE: MONTH_CONST MONTH_CONST; -ALL: 'all'; -PASTMONTH: 'prevjan'|'prevfeb'|'prevmar'|'prevapr'|'prevmay'|'prevjun'|'prevjul'|'prevaug'|'prevsep'|'prevoct'|'prevnov'|'prevdec'; -RANGE: 'range'; - -TAFCFS: 'taf_cfs'|'cfs_taf'|'cfs_af'|'af_cfs'; -DAYSIN: 'daysin'|'daysinmonth'; -DAYSINTIMESTEP: 'daysintimestep'; - -ARRAY_ITERATOR : '$m' ; - -AND: '.and.'; -OR: '.or.'; -NOT: '.not.'; - -SUM: 'sum'; -MAX : 'max'; -MIN : 'min'; -INT : 'int'; -REAL: 'real'; -ABS: 'abs'; -EXP: 'exp'; -LOG: 'log'; -LOG10: 'log10'; -POW: 'pow'; -MOD: 'mod'; -ROUND: 'round'; -SIN : 'sin'; -COS : 'cos'; -TAN : 'tan'; -COT : 'cot'; -ASIN : 'asin'; -ACOS : 'acos'; -ATAN : 'atan'; -ACOT : 'acot'; -EXCEEDANCE : 'exceedance'; -EXCEEDANCE_TSI : 'exceedance_tsi'; - -SELECT: 'select'; -FROM: 'from'; -GIVEN: 'given'; -USE: 'use'; -WHERE : 'where'; - -CONSTRAIN: 'constrain'; -ALWAYS: 'always'; - -NAME: 'name'; -DVAR: 'dvar'; -CYCLE: 'cycle'; -FILE: 'file'; -CONDITION: 'condition'; -INCLUDE: 'include'; -LOWERBOUND: 'lower_bound'; -UPPERBOUND: 'upper_bound'; -INTEGERTYPE: 'integer'; -UNITS: 'units'; -CONVERTUNITS: 'convert_to_units'; -TYPE: 'type'; -OUTPUT: 'output'; -CASE: 'case'; -ORDER: 'order'; -EXPRESSION: 'expression'; -LHSGTRHS: 'lhs_gt_rhs'; -LHSLTRHS: 'lhs_lt_rhs'; -WEIGHT: 'weight'; -FUNCTION: 'function'; -FROM_WRESL_FILE: 'from_wresl_file'; -UPPERUNBOUNDED: 'upper_unbounded'; -LOWERUNBOUNDED: 'lower_unbounded'; - -SVAR: '{' IDENT '}'; -IDENT : LETTER (LETTER | DIGIT | SYMBOLS )*; -IDENT1 : DIGIT (LETTER | DIGIT | SYMBOLS )*; -IDENT2 : SYMBOLS (LETTER | DIGIT | SYMBOLS )*; - -WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}; -COMMENT : '!' .* ('\n'|'\r') {$channel = HIDDEN;}; - - - +grammar Evaluator; + +options { + language = Java; +} + +@header { + package wrimsv2.evaluator; + + import org.antlr.runtime.ANTLRFileStream; + import org.antlr.runtime.CharStream; + import org.antlr.runtime.CommonTokenStream; + import org.antlr.runtime.RecognitionException; + import org.antlr.runtime.TokenStream; + + import java.util.HashMap; + import wrimsv2.components.Error; + import wrimsv2.components.IntDouble; + import wrimsv2.parallel.ParallelVars; +} + +@lexer::header { + package wrimsv2.evaluator; +} + +@members { + public IntDouble evalValue; + public EvalExpression evalExpression; + public EvalConstraint evalConstraint; + public boolean evalCondition; + public ParallelVars prvs; + public Stack sumIndex= new Stack (); + + @Override + public void reportError(RecognitionException e) { + Error.addEvaluationError(getErrorMessage(e, tokenNames)); + } + + public void setParallelVars (ParallelVars prvs1) { + prvs=prvs1; + } + + public void setSumIndex(Stack sumIndex){ + this.sumIndex=sumIndex; + } +} + +evaluator returns [String result] + : goalInput| + expressionInput | + softConstraint| + conditionInput + ; + +/////////////////// +/// input rules /// +/////////////////// + +goalInput: 'g:' constraintStatement {evalConstraint = $constraintStatement.ec;}; +expressionInput: 'v:' expressionCollection{evalValue=Evaluation.expressionInput($expressionCollection.ee);}; +softConstraint: 's:' expressionCollection{evalExpression=$expressionCollection.ee;}; +conditionInput: 'c:' conditionStatement {evalCondition=$conditionStatement.result;}; + +/////////////////// +/// basic rules /// +/////////////////// +lhsrhs: expression|CONSTRAIN; + +//weight : (allnumber|(allnumber '*' TAFCFS)) (('+' allnumber)|('-' allnumber))?; + +units: IDENT|(IDENT '/' IDENT); + +fileName + : (':'|';'|'.'|'|'|SYMBOLS|'-'|'+'|BACKSLASH|IDENT|IDENT1|IDENT2|INTEGER|FLOAT|usedKeywords)+{ + } + ; + +externalFile + : (';'|'.'|'|'|SYMBOLS|'-'|'+'|INTEGER|FLOAT|IDENT|usedKeywords)+ + ; + +text : LETTER (LETTER | DIGIT )*; + +expressionCollection returns [EvalExpression ee] + : (expression{ee=$expression.ee;}) + |(tableSQL){ee=$tableSQL.ee;} + |(timeseriesWithUnits) + |((timeseries){ee=$timeseries.ee;}) + | sumExpression {ee=$sumExpression.ee;} + |(UPPERUNBOUNDED{ee=new EvalExpression(new IntDouble(1e38,true));}) + |(LOWERUNBOUNDED{ee=new EvalExpression(new IntDouble(-1e38,true));}) + ; + +func returns[EvalExpression ee]: + (max_func{ee=$max_func.ee;})| + (min_func{ee=$min_func.ee;})| + (int_func{ee=$int_func.ee;})| + (real_func{ee=$real_func.ee;})| + (abs_func{ee=$abs_func.ee;})| + (exp_func{ee=$exp_func.ee;})| + (log_func{ee=$log_func.ee;})| + (log10_func{ee=$log10_func.ee;})| + (pow_func{ee=$pow_func.ee;})| + (mod_func{ee=$mod_func.ee;})| + (round_func{ee=$round_func.ee;})| + (sin_func{ee=$sin_func.ee;})| + (cos_func{ee=$cos_func.ee;})| + (tan_func{ee=$tan_func.ee;})| + (cot_func{ee=$cot_func.ee;})| + (asin_func{ee=$asin_func.ee;})| + (acos_func{ee=$acos_func.ee;})| + (atan_func{ee=$atan_func.ee;})| + (acot_func{ee=$acot_func.ee;})| + (exceedFunc{ee=$exceedFunc.ee;})| + (exceedtsiFunc{ee=$exceedtsiFunc.ee;}) + ; + +round_func returns[EvalExpression ee] + : ROUND '(' (e1=expression)')'{ + ee=Evaluation.round($e1.ee); + } + ; + +mod_func returns[EvalExpression ee] + : MOD '(' (e1=expression) (';' (e2=expression)) ')'{ + ee=Evaluation.mod($e1.ee, $e2.ee); + } + ; + +max_func returns[EvalExpression ee] + : MAX '(' (e1=expression){ee=$e1.ee;}(';' (e2=expression{ + ee=Evaluation.max(ee, $e2.ee); + }))+ ')' + ; + +min_func returns[EvalExpression ee] + : MIN '(' (e1=expression){ee=$e1.ee;}(';' (e2=expression{ + ee=Evaluation.min(ee, $e2.ee); + }))+ ')' + ; + +int_func returns[EvalExpression ee] + : INT '(' (e=expression) ')'{ + ee=Evaluation.intFunc($e.ee); + } + ; + +real_func returns[EvalExpression ee] + : REAL '(' (e=expression) ')'{ + ee=Evaluation.realFunc($e.ee); + } + ; + +abs_func returns[EvalExpression ee] + : ABS '(' (e=expression) ')'{ + ee=Evaluation.abs($e.ee); + } + ; + +exp_func returns[EvalExpression ee] + : EXP '(' (e=expression) ')'{ + ee=Evaluation.exp($e.ee); + } + ; + +log_func returns[EvalExpression ee] + : LOG '(' (e=expression) ')'{ + ee=Evaluation.log($e.ee); + } + ; + +log10_func returns[EvalExpression ee] + : LOG10 '(' (e=expression) ')'{ + ee=Evaluation.log10($e.ee); + } + ; + +pow_func returns[EvalExpression ee] + : POW '(' (e1=expression) (';' (e2=expression)) ')'{ + ee=Evaluation.pow($e1.ee, $e2.ee); + } + ; + +sin_func returns[EvalExpression ee] + : SIN '(' (e=expression) ')'{ + ee=Evaluation.sin($e.ee); + } + ; + +cos_func returns[EvalExpression ee] + : COS '(' (e=expression) ')'{ + ee=Evaluation.cos($e.ee); + } + ; + +tan_func returns[EvalExpression ee] + : TAN '(' (e=expression) ')'{ + ee=Evaluation.tan($e.ee); + } + ; + +cot_func returns[EvalExpression ee] + : COT '(' (e=expression) ')'{ + ee=Evaluation.cot($e.ee); + } + ; + +asin_func returns[EvalExpression ee] + : ASIN '(' (e=expression) ')'{ + ee=Evaluation.asin($e.ee); + } + ; + +acos_func returns[EvalExpression ee] + : ACOS '(' (e=expression) ')'{ + ee=Evaluation.acos($e.ee); + } + ; + +atan_func returns[EvalExpression ee] + : ATAN '(' (e=expression) ')'{ + ee=Evaluation.atan($e.ee); + } + ; + +acot_func returns[EvalExpression ee] + : ACOT '(' (e=expression) ')'{ + ee=Evaluation.acot($e.ee); + } + ; + +exceedFunc returns[EvalExpression ee] + : EXCEEDANCE '(' var=IDENT ';' exc=term ';' (mon=MONTH_CONST|mon=MONTH_RANGE|mon=ALL) ';' sy=INTEGER ';' sm=MONTH_CONST ';' sd=INTEGER ';' ey=INTEGER ';' em=MONTH_CONST ';' ed=INTEGER ')' { + ee=Evaluation.exceedance($var.text, $exc.ee, $mon.text, $sy.text, $sm.text, $sd.text, $ey.text, $em.text, $ed.text); + } + ; + +exceedtsiFunc returns[EvalExpression ee] + : EXCEEDANCE_TSI '(' var=IDENT ';' exc=term ';' (mon=MONTH_CONST|mon=MONTH_RANGE|mon=ALL) ';' sy=INTEGER ';' sm=MONTH_CONST ';' sd=INTEGER ';' ey=INTEGER ';' em=MONTH_CONST ';' ed=INTEGER ')' { + ee=Evaluation.exceedance_tsi($var.text, $exc.ee, $mon.text, $sy.text, $sm.text, $sd.text, $ey.text, $em.text, $ed.text); + } + ; + +range_func returns [boolean result] + : RANGE '(' MONTH ';' m1=MONTH_CONST ';' m2=MONTH_CONST ')' {Evaluation.range($m1.text, $m2.text);}; + +timeseriesWithUnits + : 'timeseries' 'kind' '=' partC 'units' '=' IDENT + ; + +timeseries returns [EvalExpression ee] + : 'timeseries' {ee=Evaluation.timeseries();} + ; + + + +partC: (IDENT|IDENT1|usedKeywords) ('-' (IDENT|IDENT1|usedKeywords))*; + +usedKeywords: YEAR|MONTH|MONTH_CONST|MONTH_RANGE|DAY|PASTMONTH|RANGE|TAFCFS|DAYSIN|DAYSINTIMESTEP|SUM|MAX|MIN|INT|REAL|ABS|EXP|LOG|LOG10|POW|MOD|ROUND|SELECT|FROM|GIVEN|USE|WHERE +|CONSTRAIN|ALWAYS|NAME|DVAR|CYCLE|FILE| CONDITION|INCLUDE|LOWERBOUND|UPPERBOUND|INTEGERTYPE|UNITS|CONVERTUNITS|TYPE|OUTPUT +|CASE|ORDER|EXPRESSION|LHSGTRHS|LHSLTRHS|WEIGHT|FUNCTION|FROM_WRESL_FILE|UPPERUNBOUNDED|LOWERUNBOUNDED|AND|OR|NOT +|SIN|COS|TAN|COT|ASIN|ACOS|ATAN|ACOT|EXCEEDANCE|EXCEEDANCE_TSI|ALL; + +tableSQL returns [EvalExpression ee] @init{String table=null; String select=null; String use=null; HashMap given=null; HashMap where=null;} + : SELECT ((i1=IDENT{select=$i1.text;})|(u1=usedKeywords{select=$u1.text;})) FROM i2=IDENT{table=$i2.text;} + (GIVEN a=assignStatement{given=new HashMap(); given.put($a.assignIdent, $a.value);})? (USE i3=IDENT{use=$i3.text;})? + (where_items{where=$where_items.where;})? {ee=Evaluation.tableSQL(table, select, where, given, use);} + ; + +where_items returns [HashMap where] + : WHERE (r1=whereStatement{where=new HashMap(); where.put($r1.whereIdent, $r1.value);}) + (';' r=whereStatement{where.put($r.whereIdent, $r.value);})* + ; + + +upperbound: IDENT|allnumber|(allnumber '*' TAFCFS); + +lowerbound: IDENT|allnumber|(allnumber '*' TAFCFS); + +//sumExpression +// : SUM '(' I '=' e1=expression_sum ';' e2=expression_sum (';' (s='-')? INTEGER )? ')' e3=expression +// ; +//term_sum: (MONTH|MONTH_CONST|PASTMONTH|I|INTEGER|'(' expression_sum ')'); + +//unary_sum : ('-')? term_sum ; +//add_sum : unary_sum(('+' | '-') unary_sum)* ; +//expression_sum: add_sum ; + +//sumExpression was redesign. If not work, switch back to the original design above + +sumExpression returns [EvalExpression ee] @init{String s="";} + : SUM '(' IDENT{Evaluation.sumExpression_IDENT($IDENT.text, sumIndex);} '=' e1=expression ';' e2=expression (';' (('-'{s=s+"-";})? INTEGER {s=s+$INTEGER.text;}))? ')' {Evaluation.initSumExpression($e1.ee, $e2.ee, s, sumIndex);} e3=expression{ee=Evaluation.sumExpression($e3.ee, $e3.text, sumIndex);} + ; + +term returns [EvalExpression ee] + : (IDENT {ee=Evaluation.term_IDENT($IDENT.text, sumIndex);}) + | (FLOAT {ee=Evaluation.term_FLOAT($FLOAT.text);}) + | ('(' (e=expression) ')' {ee=$e.ee;}) + | pastCycleValue{ee=Evaluation.term_knownTS($pastCycleValue.result);} + | function{ee=$function.ee;} + | func{ee=$func.ee;} + | (INTEGER {ee=Evaluation.term_INTEGER($INTEGER.text);}) + | tafcfs_term{ee=$tafcfs_term.ee;} + | YEAR{ee=Evaluation.term_YEAR();} + | MONTH{ee=Evaluation.term_MONTH();} + | DAY{ee=Evaluation.term_DAY();} + | MONTH_CONST{ee=Evaluation.term_MONTH_CONST($MONTH_CONST.text);} + | PASTMONTH{ee=Evaluation.term_PASTMONTH($PASTMONTH.text);} + | DAYSIN{ee=Evaluation.daysIn();} + | DAYSINTIMESTEP{ee=Evaluation.daysInTimeStep();} + | (SVAR{ee=Evaluation.term_SVAR($SVAR.text.replace("{","").replace("}",""));}) + | ARRAY_ITERATOR{ee=Evaluation.term_ARRAY_ITERATOR(prvs);} + | '(' sumExpression ')'{ee=$sumExpression.ee;} + ; + +tafcfs_term returns [EvalExpression ee]: TAFCFS ('(' expression ')')? { + ee=Evaluation.tafcfs_term($TAFCFS.text, $expression.ee, sumIndex); +}; + +pastCycleValue returns[IntDouble result] + : (p1=pastCycleNoTimeArray{return $p1.result;})|(p2=pastCycleTimeArray{return $p2.result;})|(p3=pastCycleIndexNoTimeArray{return $p3.result;})|(p4=pastCycleIndexTimeArray{return $p4.result;}) + ; + +pastCycleNoTimeArray returns [IntDouble result] + : i1=IDENT '[' i2=IDENT ']'{result=Evaluation.pastCycleNoTimeArray($i1.text,$i2.text);} + ; + +pastCycleTimeArray returns [IntDouble result] + : i1=IDENT '[' i2=IDENT ']' '(' e1=expression ')' {result=Evaluation.pastCycleTimeArray($i1.text,$i2.text, $e1.ee);} + ; + +pastCycleIndexNoTimeArray returns [IntDouble result] + : i1=IDENT '[' '-' index=INTEGER ']'{result=Evaluation.pastCycleIndexNoTimeArray($i1.text,-Integer.parseInt($index.text));} + ; + +pastCycleIndexTimeArray returns [IntDouble result] + : i1=IDENT '[' '-' index=INTEGER ']' '(' e1=expression ')' {result=Evaluation.pastCycleIndexTimeArray($i1.text,-Integer.parseInt($index.text), $e1.ee);} + ; + +function returns [EvalExpression ee] + : (n=noArgFunction{ee=$n.ee;})|(a=argFunction{ee=$a.ee;}) + ; + +noArgFunction returns [EvalExpression ee] + : IDENT '(' ')' {ee=Evaluation.noArgFunction($IDENT.text);}; + +argFunction returns [EvalExpression ee] @init{ArrayList> eeArray = new ArrayList>(); ArrayList ee0Array=new ArrayList();} + : IDENT '(' (e1=expression {ArrayList eeArray1=new ArrayList(); eeArray1.add($e1.ee); eeArray.add(eeArray1);} + |t1=trunk_timeArray{eeArray.add($t1.eeArray);}) + (';' (e2=expression{ArrayList eeArray1=new ArrayList(); eeArray1.add($e2.ee); eeArray.add(eeArray1);} + |t2=trunk_timeArray{eeArray.add($t2.eeArray);}))* ')' ('(' e0=expression {ee0Array.add($e0.ee);} ')')? + { + if (ee0Array.size()==0){ + ee=Evaluation.argFunction($IDENT.text,eeArray,sumIndex); + }else{ + ee=Evaluation.pastTSFV($IDENT.text, $e0.ee, eeArray, prvs); + } + }; + +trunk_timeArray returns[ArrayList eeArray] @init{eeArray = new ArrayList(); IntDouble start=new IntDouble(1, true); IntDouble end=new IntDouble(1, true);} + : i0=IDENT '(' (n1=integer{start=ValueEvaluation.term_INTEGER($n1.text);}|i1=IDENT{start=ValueEvaluation.term_IDENT($i1.text, sumIndex);}) ':' (n2=integer{end=ValueEvaluation.term_INTEGER($n2.text);}|i2=IDENT{end=ValueEvaluation.term_IDENT($i2.text, sumIndex);}) ')' + { + eeArray=Evaluation.trunk_timeArray($i0.text, start, end); + } + ; + +unary returns [EvalExpression ee] + : (s=('+'|'-'))? term{ee=Evaluation.unary($s.text, $term.ee); + }; + +allnumber + : ('-')? number; + +mult returns [EvalExpression ee] + : (u1=unary {ee=$u1.ee;}) (s=('*'| '/') (u2=unary){ + if ($s.text.equals("*")){ + ee=Evaluation.mult(ee, $u2.ee); + }else{ + ee=Evaluation.divide(ee, $u2.ee); + } + })* + ; + +add returns [EvalExpression ee] + : (m1=mult {ee=$m1.ee;}) ((s=('+'|'-')) (m2=mult){ + if ($s.text.equals("+")){ + ee=Evaluation.add(ee, $m2.ee); + }else{ + ee=Evaluation.substract(ee, $m2.ee); + } + })* + ; + +expression returns [EvalExpression ee] + : i=add {$ee=$add.ee;} + ; + +relation + : '==' + | '<' + | '>' + | '>=' + | '<=' + ; + +whereStatement returns [String whereIdent, Number value] + : ((i=IDENT{$whereIdent=$i.text;})|(u=usedKeywords{$whereIdent=$u.text;})) '=' expression{$value=Evaluation.assignWhereStatement($expression.ee);} + ; + +conditionStatement returns [boolean result] + : ((r=relationUnary{result=$r.result;})|ALWAYS{result=true;}) + ; + +relationUnary returns [boolean result] + : (n=NOT)? r=relationOr{ + if ($n==null){ + return $r.result; + }else{ + if ($r.result){ + return false; + }else{ + return true; + } + } + } + ; + +relationOr returns [boolean result] + : r1=relationAnd {result=$r1.result;} + (s=OR r2=relationAnd {result=Evaluation.relationStatementSeries(result, $r2.result, $s.text);})* ; + +relationAnd returns [boolean result] + : r1=relationRangeStatement {result=$r1.result;} + (s=AND r2=relationRangeStatement {result=Evaluation.relationStatementSeries(result, $r2.result, $s.text);})* ; + +relationRangeStatement returns [boolean result] + : (r1=relationStatement{result=$r1.result;})|(r2=range_func{result=$r2.result;}) + ; + +relationStatement returns [boolean result] + : ( ( expression relation expression ) => (e1=expression) relation (e2=expression) {result=Evaluation.relationStatement($e1.ee, $e2.ee, $relation.text);} ) + | ( ( '('relationUnary')' ) => '('r2=relationUnary')' {result=$r2.result;} ) + ; + +constraintStatement returns [EvalConstraint ec] + : e1=expression ((s='=')|(s='>')|(s='<')) e2=expression{ec=Evaluation.constraintStatement($e1.ee, $e2.ee, $s.text);} + ; + +assignStatement returns [String assignIdent, Number value] + : IDENT '=' expression {$assignIdent=$IDENT.text; $value=Evaluation.assignWhereStatement($expression.ee);} + ; + +number + : INTEGER + | FLOAT + ; + +integer : integer_p|integer_n ; +integer_p : INTEGER ; +integer_n : '-' INTEGER ; + +MULTILINE_COMMENT : '/*' .* '*/' {$channel = HIDDEN;} ; + +fragment LETTER : ('a'..'z' | 'A'..'Z') ; +fragment DIGIT : '0'..'9'; +fragment SYMBOLS : '_'; + +BACKSLASH : '\\'; + +INTEGER : DIGIT+ ; +FLOAT : INTEGER? '.' INTEGER + | INTEGER '.' + ; + +//I: 'i'; +YEAR: 'wateryear'; +MONTH: 'month'; +DAY: 'day'; +MONTH_CONST: 'jan'|'feb'|'mar'|'apr'|'may'|'jun'|'jul'|'aug'|'sep'|'oct'|'nov'|'dec'; +MONTH_RANGE: MONTH_CONST MONTH_CONST; +ALL: 'all'; +PASTMONTH: 'prevjan'|'prevfeb'|'prevmar'|'prevapr'|'prevmay'|'prevjun'|'prevjul'|'prevaug'|'prevsep'|'prevoct'|'prevnov'|'prevdec'; +RANGE: 'range'; + +TAFCFS: 'taf_cfs'|'cfs_taf'|'cfs_af'|'af_cfs'; +DAYSIN: 'daysin'|'daysinmonth'; +DAYSINTIMESTEP: 'daysintimestep'; + +ARRAY_ITERATOR : '$m' ; + +AND: '.and.'; +OR: '.or.'; +NOT: '.not.'; + +SUM: 'sum'; +MAX : 'max'; +MIN : 'min'; +INT : 'int'; +REAL: 'real'; +ABS: 'abs'; +EXP: 'exp'; +LOG: 'log'; +LOG10: 'log10'; +POW: 'pow'; +MOD: 'mod'; +ROUND: 'round'; +SIN : 'sin'; +COS : 'cos'; +TAN : 'tan'; +COT : 'cot'; +ASIN : 'asin'; +ACOS : 'acos'; +ATAN : 'atan'; +ACOT : 'acot'; +EXCEEDANCE : 'exceedance'; +EXCEEDANCE_TSI : 'exceedance_tsi'; + +SELECT: 'select'; +FROM: 'from'; +GIVEN: 'given'; +USE: 'use'; +WHERE : 'where'; + +CONSTRAIN: 'constrain'; +ALWAYS: 'always'; + +NAME: 'name'; +DVAR: 'dvar'; +CYCLE: 'cycle'; +FILE: 'file'; +CONDITION: 'condition'; +INCLUDE: 'include'; +LOWERBOUND: 'lower_bound'; +UPPERBOUND: 'upper_bound'; +INTEGERTYPE: 'integer'; +UNITS: 'units'; +CONVERTUNITS: 'convert_to_units'; +TYPE: 'type'; +OUTPUT: 'output'; +CASE: 'case'; +ORDER: 'order'; +EXPRESSION: 'expression'; +LHSGTRHS: 'lhs_gt_rhs'; +LHSLTRHS: 'lhs_lt_rhs'; +WEIGHT: 'weight'; +FUNCTION: 'function'; +FROM_WRESL_FILE: 'from_wresl_file'; +UPPERUNBOUNDED: 'upper_unbounded'; +LOWERUNBOUNDED: 'lower_unbounded'; + +SVAR: '{' IDENT '}'; +IDENT : LETTER (LETTER | DIGIT | SYMBOLS )*; +IDENT1 : DIGIT (LETTER | DIGIT | SYMBOLS )*; +IDENT2 : SYMBOLS (LETTER | DIGIT | SYMBOLS )*; + +WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}; +COMMENT : '!' .* ('\n'|'\r') {$channel = HIDDEN;}; + + + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluator.g b/wrims-core/src/main/antlr/wrimsv2/evaluator/ValueEvaluator.g similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluator.g rename to wrims-core/src/main/antlr/wrimsv2/evaluator/ValueEvaluator.g index 517e026fc..818a7a4e3 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluator.g +++ b/wrims-core/src/main/antlr/wrimsv2/evaluator/ValueEvaluator.g @@ -1,552 +1,552 @@ -grammar ValueEvaluator; - -options { - language = Java; -} - -@header { - package wrimsv2.evaluator; - - import org.antlr.runtime.ANTLRFileStream; - import org.antlr.runtime.CharStream; - import org.antlr.runtime.CommonTokenStream; - import org.antlr.runtime.RecognitionException; - import org.antlr.runtime.TokenStream; - - import java.util.HashMap; - import wrimsv2.components.Error; - import wrimsv2.components.IntDouble; - import wrimsv2.parallel.ParallelVars; -} - -@lexer::header { - package wrimsv2.evaluator; -} - -@members { - public IntDouble evalValue; - public boolean evalCondition; - public ParallelVars prvs; - public Stack sumIndex= new Stack (); - - @Override - public void reportError(RecognitionException e) { - Error.addEvaluationError(getErrorMessage(e, tokenNames)); - } - - public void setParallelVars (ParallelVars prvs1) { - prvs=prvs1; - } - - public void setSumIndex(Stack sumIndex){ - this.sumIndex=sumIndex; - } -} - -evaluator returns [String result] - : expressionInput | - conditionInput - ; - -/////////////////// -/// input rules /// -/////////////////// - -expressionInput: 'v:' expressionCollection{evalValue=$expressionCollection.id;}; -conditionInput: 'c:' conditionStatement {evalCondition=$conditionStatement.result;}; - -/////////////////// -/// basic rules /// -/////////////////// -lhsrhs: expression|CONSTRAIN; - -//weight : (allnumber|(allnumber '*' TAFCFS)) (('+' allnumber)|('-' allnumber))?; - -units: IDENT|(IDENT '/' IDENT); - -fileName - : (':'|';'|'.'|'|'|SYMBOLS|'-'|'+'|BACKSLASH|IDENT|IDENT1|IDENT2|INTEGER|FLOAT|usedKeywords)+{ - } - ; - -externalFile - : (';'|'.'|'|'|SYMBOLS|'-'|'+'|INTEGER|FLOAT|IDENT|usedKeywords)+ - ; - -text : LETTER (LETTER | DIGIT )*; - -expressionCollection returns [IntDouble id] - :(expression{id=$expression.id;}) - |(tableSQL){id=$tableSQL.id;} - |(timeseriesWithUnits) - |((timeseries){id=$timeseries.id;}) - | sumExpression {id=$sumExpression.id;} - |(UPPERUNBOUNDED{id=new IntDouble(1e38,true);}) - |(LOWERUNBOUNDED{id=new IntDouble(-1e38,true);}) - ; - -func returns[IntDouble id]: - (max_func{id=$max_func.id;})| - (min_func{id=$min_func.id;})| - (int_func{id=$int_func.id;})| - (real_func{id=$real_func.id;})| - (abs_func{id=$abs_func.id;})| - (exp_func{id=$exp_func.id;})| - (log_func{id=$log_func.id;})| - (log10_func{id=$log10_func.id;})| - (pow_func{id=$pow_func.id;})| - (mod_func{id=$mod_func.id;})| - (round_func{id=$round_func.id;})| - (sin_func{id=$sin_func.id;})| - (cos_func{id=$cos_func.id;})| - (tan_func{id=$tan_func.id;})| - (cot_func{id=$cot_func.id;})| - (asin_func{id=$asin_func.id;})| - (acos_func{id=$acos_func.id;})| - (atan_func{id=$atan_func.id;})| - (acot_func{id=$acot_func.id;})| - (exceedFunc{id=$exceedFunc.id;})| - (exceedtsiFunc{id=$exceedtsiFunc.id;}); - -round_func returns[IntDouble id] - : ROUND '(' (e1=expression) ')'{ - id=ValueEvaluation.round($e1.id); - } - ; - -mod_func returns[IntDouble id] - : MOD '(' (e1=expression) (';' (e2=expression)) ')'{ - id=ValueEvaluation.mod($e1.id, $e2.id); - } - ; - -max_func returns[IntDouble id] - : MAX '(' (e1=expression){id=$e1.id;}(';' (e2=expression{ - id=ValueEvaluation.max(id, $e2.id); - }))+ ')' - ; - -min_func returns[IntDouble id] - : MIN '(' (e1=expression){id=$e1.id;}(';' (e2=expression{ - id=ValueEvaluation.min(id, $e2.id); - }))+ ')' - ; - -int_func returns[IntDouble id] - : INT '(' (e=expression) ')'{ - id=ValueEvaluation.intFunc($e.id); - } - ; - -real_func returns[IntDouble id] - : REAL '(' (e=expression) ')'{ - id=ValueEvaluation.realFunc($e.id); - } - ; - -abs_func returns[IntDouble id] - : ABS '(' (e=expression) ')'{ - id=ValueEvaluation.abs($e.id); - } - ; - -exp_func returns[IntDouble id] - : EXP '(' (e=expression) ')'{ - id=ValueEvaluation.exp($e.id); - } - ; - -log_func returns[IntDouble id] - : LOG '(' (e=expression) ')'{ - id=ValueEvaluation.log($e.id); - } - ; - -log10_func returns[IntDouble id] - : LOG10 '(' (e=expression) ')'{ - id=ValueEvaluation.log10($e.id); - } - ; - -pow_func returns[IntDouble id] - : POW '(' (e1=expression) (';' (e2=expression)) ')'{ - id=ValueEvaluation.pow($e1.id, $e2.id); - } - ; - -sin_func returns[IntDouble id] - : SIN '(' (e=expression) ')'{ - id=ValueEvaluation.sin($e.id); - } - ; - -cos_func returns[IntDouble id] - : COS '(' (e=expression) ')'{ - id=ValueEvaluation.cos($e.id); - } - ; - -tan_func returns[IntDouble id] - : TAN '(' (e=expression) ')'{ - id=ValueEvaluation.tan($e.id); - } - ; - -cot_func returns[IntDouble id] - : COT '(' (e=expression) ')'{ - id=ValueEvaluation.cot($e.id); - } - ; - -asin_func returns[IntDouble id] - : ASIN '(' (e=expression) ')'{ - id=ValueEvaluation.asin($e.id); - } - ; - -acos_func returns[IntDouble id] - : ACOS '(' (e=expression) ')'{ - id=ValueEvaluation.acos($e.id); - } - ; - -atan_func returns[IntDouble id] - : ATAN '(' (e=expression) ')'{ - id=ValueEvaluation.atan($e.id); - } - ; - -acot_func returns[IntDouble id] - : ACOT '(' (e=expression) ')'{ - id=ValueEvaluation.acot($e.id); - } - ; - -exceedFunc returns[IntDouble id] - : EXCEEDANCE '(' var=IDENT ';' exc=term ';' (mon=MONTH_CONST|mon=MONTH_RANGE|mon=ALL) ';' sy=INTEGER ';' sm=MONTH_CONST ';' sd=INTEGER ';' ey=INTEGER ';' em=MONTH_CONST ';' ed=INTEGER ')' { - id=ValueEvaluation.exceedance($var.text, $exc.id, $mon.text, $sy.text, $sm.text, $sd.text, $ey.text, $em.text, $ed.text); - } - ; - -exceedtsiFunc returns[IntDouble id] - : EXCEEDANCE_TSI '(' var=IDENT ';' exc=term ';' (mon=MONTH_CONST|mon=MONTH_RANGE|mon=ALL) ';' sy=INTEGER ';' sm=MONTH_CONST ';' sd=INTEGER ';' ey=INTEGER ';' em=MONTH_CONST ';' ed=INTEGER ')' { - id=ValueEvaluation.exceedance_tsi($var.text, $exc.id, $mon.text, $sy.text, $sm.text, $sd.text, $ey.text, $em.text, $ed.text); - } - ; - -range_func returns [boolean result] - : RANGE '(' MONTH ';' m1=MONTH_CONST ';' m2=MONTH_CONST ')' {result=ValueEvaluation.range($m1.text, $m2.text);}; - -timeseriesWithUnits - : 'timeseries' 'kind' '=' partC 'units' '=' IDENT - ; - -timeseries returns [IntDouble id] - : 'timeseries' {id=ValueEvaluation.timeseries();} - ; - - - -partC: (IDENT|IDENT1|usedKeywords) ('-' (IDENT|IDENT1|usedKeywords))*; - -usedKeywords: YEAR|MONTH|MONTH_CONST|MONTH_RANGE|DAY|PASTMONTH|RANGE|TAFCFS|DAYSIN|DAYSINTIMESTEP|SUM|MAX|MIN|INT|REAL|ABS|EXP|LOG|LOG10|POW|MOD|ROUND|SELECT|FROM|GIVEN|USE|WHERE -|CONSTRAIN|ALWAYS|NAME|DVAR|CYCLE|FILE|CONDITION|INCLUDE|LOWERBOUND|UPPERBOUND|INTEGERTYPE|UNITS|CONVERTUNITS|TYPE|OUTPUT -|CASE|ORDER|EXPRESSION|LHSGTRHS|LHSLTRHS|WEIGHT|FUNCTION|FROM_WRESL_FILE|UPPERUNBOUNDED|LOWERUNBOUNDED|AND|OR|NOT -|SIN|COS|TAN|COT|ASIN|ACOS|ATAN|ACOT|EXCEEDANCE|EXCEEDANCE_TSI|ALL; - -tableSQL returns [IntDouble id] @init{String table=null; String select=null; String use=null; HashMap given=null; HashMap where=null;} - : SELECT ((i1=IDENT{select=$i1.text;})|(u1=usedKeywords{select=$u1.text;})) FROM i2=IDENT{table=$i2.text;} - (GIVEN a=assignStatement{given=new HashMap(); given.put($a.assignIdent, $a.value);})? (USE i3=IDENT{use=$i3.text;})? - (where_items{where=$where_items.where;})? {id=ValueEvaluation.tableSQL(table, select, where, given, use);} - ; - -where_items returns [HashMap where] - : WHERE (r1=whereStatement{where=new HashMap(); where.put($r1.whereIdent, $r1.value);}) - (';' r=whereStatement{where.put($r.whereIdent, $r.value);})* - ; - - -upperbound: IDENT|allnumber|(allnumber '*' TAFCFS); - -lowerbound: IDENT|allnumber|(allnumber '*' TAFCFS); - -//sumExpression -// : SUM '(' I '=' e1=expression_sum ';' e2=expression_sum (';' (s='-')? INTEGER )? ')' e3=expression -// ; -//term_sum: (MONTH|MONTH_CONST|PASTMONTH|I|INTEGER|'(' expression_sum ')'); - -//unary_sum : ('-')? term_sum ; -//add_sum : unary_sum(('+' | '-') unary_sum)* ; -//expression_sum: add_sum ; - -//sumExpression was redesign. If not work, switch back to the original design above - -sumExpression returns [IntDouble id] @init{String s="";} - : SUM '(' IDENT{ValueEvaluation.sumExpression_IDENT($IDENT.text, sumIndex);} '=' e1=expression ';' e2=expression (';' (('-'{s=s+"-";})? INTEGER {s=s+$INTEGER.text;}))? (')'{ValueEvaluation.initSumExpression($e1.id, $e2.id, s, sumIndex);}) e3=expression{id=ValueEvaluation.sumExpression($e3.id, $e3.text, sumIndex);} - ; - -term returns [IntDouble id] - : (IDENT {id=ValueEvaluation.term_IDENT($IDENT.text, sumIndex);}) - | (FLOAT {id=ValueEvaluation.term_FLOAT($FLOAT.text);}) - | ('(' (e=expression) ')' {id=$e.id;}) - | (knownTS{id=ValueEvaluation.term_knownTS($knownTS.result);}) - | func{id=$func.id;} - | (INTEGER {id=ValueEvaluation.term_INTEGER($INTEGER.text);}) - | tafcfs_term{id=$tafcfs_term.id;} - | YEAR{id=ValueEvaluation.term_YEAR();} - | MONTH{id=ValueEvaluation.term_MONTH();} - | DAY {id=ValueEvaluation.term_DAY();} - | MONTH_CONST{id=ValueEvaluation.term_MONTH_CONST($MONTH_CONST.text);} - | PASTMONTH{id=ValueEvaluation.term_PASTMONTH($PASTMONTH.text);} - | DAYSIN{id=ValueEvaluation.daysIn();} - | DAYSINTIMESTEP{id=ValueEvaluation.daysInTimeStep();} - | (SVAR{id=ValueEvaluation.term_SVAR($SVAR.text.replace("{","").replace("}",""));}) - | ARRAY_ITERATOR{id=ValueEvaluation.term_ARRAY_ITERATOR(prvs);} - | '(' sumExpression ')' {id=$sumExpression.id;} - ; - -tafcfs_term returns [IntDouble id]: TAFCFS ('(' expression ')')? { - id=ValueEvaluation.tafcfs_term($TAFCFS.text, $expression.id); -}; - -knownTS returns [IntDouble result] - : (f=function{result=$f.result;})|(p=pastCycleValue {result=$p.result;}) - ; - -pastCycleValue returns [IntDouble result] - : (p1=pastCycleNoTimeArray{return $p1.result;})|(p2=pastCycleTimeArray{return $p2.result;})|(p3=pastCycleIndexNoTimeArray{return $p3.result;})|(p4=pastCycleIndexTimeArray{return $p4.result;}) - ; - -pastCycleNoTimeArray returns [IntDouble result] - : i1=IDENT '[' i2=IDENT ']'{result=ValueEvaluation.pastCycleNoTimeArray($i1.text,$i2.text);} - ; - -pastCycleTimeArray returns [IntDouble result] - : i1=IDENT '[' i2=IDENT ']' '(' e1=expression ')' {result=ValueEvaluation.pastCycleTimeArray($i1.text,$i2.text, $e1.id);} - ; - -pastCycleIndexNoTimeArray returns [IntDouble result] - : i1=IDENT '[' ('-' index=INTEGER) ']'{result=ValueEvaluation.pastCycleIndexNoTimeArray($i1.text, -Integer.parseInt($index.text));} - ; - -pastCycleIndexTimeArray returns [IntDouble result] - : i1=IDENT '[' '-' index=INTEGER ']' '(' e1=expression ')' {result=ValueEvaluation.pastCycleIndexTimeArray($i1.text,-Integer.parseInt($index.text), $e1.id);} - ; - -function returns [IntDouble result] - : (n=noArgFunction{result=$n.result;})|(a=argFunction{result=$a.result;}) - ; - -noArgFunction returns [IntDouble result] - : IDENT '(' ')' {result=ValueEvaluation.noArgFunction($IDENT.text);}; - -argFunction returns [IntDouble result] @init{ArrayList> idArray = new ArrayList>(); ArrayList id0Array=new ArrayList();} - : IDENT '(' (e1=expression {ArrayList idArray1=new ArrayList(); idArray1.add($e1.id); idArray.add(idArray1);} - | t1=trunk_timeArray{idArray.add($t1.idArray);}) - (';' (e2=expression{ArrayList idArray1=new ArrayList(); idArray1.add($e2.id); idArray.add(idArray1);} - |t2=trunk_timeArray{idArray.add($t2.idArray);}))* ')' ('(' e0=expression {id0Array.add($e0.id);} ')')? - { - if (id0Array.size()==0) { - result=ValueEvaluation.argFunction($IDENT.text,idArray); - }else{ - result=ValueEvaluation.pastTSFV($IDENT.text, $e0.id, idArray, prvs); - } - }; - -trunk_timeArray returns[ArrayList idArray] @init{idArray = new ArrayList(); IntDouble start=new IntDouble(1, true); IntDouble end=new IntDouble(1, true);} - : i0=IDENT '(' (n1=integer{start=ValueEvaluation.term_INTEGER($n1.text);}|i1=IDENT{start=ValueEvaluation.term_IDENT($i1.text, sumIndex);}) ':' (n2=integer{end=ValueEvaluation.term_INTEGER($n2.text);}|i2=IDENT{end=ValueEvaluation.term_IDENT($i2.text, sumIndex);}) ')' - { - idArray=ValueEvaluation.trunk_timeArray($i0.text, start, end); - } - ; - -unary returns [IntDouble id] - : (s=('+'|'-'))? term{id=ValueEvaluation.unary($s.text, $term.id); - }; - -allnumber - : ('-')? number; - -mult returns [IntDouble id] - : (u1=unary {id=$u1.id;}) (s=('*'| '/') (u2=unary){ - if ($s.text.equals("*")){ - id=ValueEvaluation.mult(id, $u2.id); - }else{ - id=ValueEvaluation.divide(id, $u2.id); - } - })* - ; - -add returns [IntDouble id] - : (m1=mult {id=$m1.id;}) ((s=('+'|'-')) (m2=mult){ - if ($s.text.equals("+")){ - id=ValueEvaluation.add(id, $m2.id); - }else{ - id=ValueEvaluation.substract(id, $m2.id); - } - })* - ; - -expression returns [IntDouble id] - : i=add {$id=$add.id;} - ; - -relation - : '==' - | '<' - | '>' - | '>=' - | '<=' - ; - -whereStatement returns [String whereIdent, Number value] - : ((i=IDENT{$whereIdent=$i.text;})|(u=usedKeywords{$whereIdent=$u.text;})) '=' expression{$value=ValueEvaluation.assignWhereStatement($expression.id);} - ; - -conditionStatement returns [boolean result] - : ((r=relationUnary{result=$r.result;})|ALWAYS{result=true;}) - ; - -relationUnary returns [boolean result] - : (n=NOT)? r=relationOr{ - if ($n==null){ - return $r.result; - }else{ - if ($r.result){ - return false; - }else{ - return true; - } - } - } - ; - -relationOr returns [boolean result] - : r1=relationAnd {result=$r1.result;} - (s=OR r2=relationAnd {result=ValueEvaluation.relationStatementSeries(result, $r2.result, $s.text);})* ; - -relationAnd returns [boolean result] - : r1=relationRangeStatement {result=$r1.result;} - (s=AND r2=relationRangeStatement {result=ValueEvaluation.relationStatementSeries(result, $r2.result, $s.text);})* ; - -relationRangeStatement returns [boolean result] - : (r1=relationStatement{result=$r1.result;})|(r2=range_func{result=$r2.result;}) - ; - -relationStatement returns [boolean result] - : ( ( expression relation expression) => e1=expression relation e2=expression {result=ValueEvaluation.relationStatement($e1.id, $e2.id, $relation.text);} ) - | ( ( '('relationUnary')' ) => '('r2=relationUnary')' {result=$r2.result;} ) - ; - -assignStatement returns [String assignIdent, Number value] - : IDENT '=' expression {$assignIdent=$IDENT.text; $value=ValueEvaluation.assignWhereStatement($expression.id);} - ; - -number - : INTEGER - | FLOAT - ; - -integer : integer_p|integer_n ; -integer_p : INTEGER ; -integer_n : '-' INTEGER ; - -MULTILINE_COMMENT : '/*' .* '*/' {$channel = HIDDEN;} ; - -fragment LETTER : ('a'..'z' | 'A'..'Z') ; -fragment DIGIT : '0'..'9'; -fragment SYMBOLS : '_'; - -BACKSLASH : '\\'; - -INTEGER : DIGIT+ ; -FLOAT : INTEGER? '.' INTEGER - | INTEGER '.' - ; - -//I: 'i'; -YEAR: 'wateryear'; -MONTH: 'month'; -DAY: 'day'; -MONTH_CONST: 'jan'|'feb'|'mar'|'apr'|'may'|'jun'|'jul'|'aug'|'sep'|'oct'|'nov'|'dec'; -MONTH_RANGE: MONTH_CONST MONTH_CONST; -ALL: 'all'; -PASTMONTH: 'prevjan'|'prevfeb'|'prevmar'|'prevapr'|'prevmay'|'prevjun'|'prevjul'|'prevaug'|'prevsep'|'prevoct'|'prevnov'|'prevdec'; -RANGE: 'range'; - -TAFCFS: 'taf_cfs'|'cfs_taf'|'cfs_af'|'af_cfs'; -DAYSIN: 'daysin'|'daysinmonth'; -DAYSINTIMESTEP: 'daysintimestep'; - -ARRAY_ITERATOR : '$m' ; - -AND: '.and.'; -OR: '.or.'; -NOT: '.not.'; - -SUM: 'sum'; -MAX : 'max'; -MIN : 'min'; -INT : 'int'; -REAL: 'real'; -ABS: 'abs'; -EXP: 'exp'; -LOG: 'log'; -LOG10: 'log10'; -POW: 'pow'; -MOD: 'mod'; -ROUND: 'round'; -SIN : 'sin'; -COS : 'cos'; -TAN : 'tan'; -COT : 'cot'; -ASIN : 'asin'; -ACOS : 'acos'; -ATAN : 'atan'; -ACOT : 'acot'; -EXCEEDANCE : 'exceedance'; -EXCEEDANCE_TSI : 'exceedance_tsi'; - -SELECT: 'select'; -FROM: 'from'; -GIVEN: 'given'; -USE: 'use'; -WHERE : 'where'; - -CONSTRAIN: 'constrain'; -ALWAYS: 'always'; - -NAME: 'name'; -DVAR: 'dvar'; -CYCLE: 'cycle'; -FILE: 'file'; -CONDITION: 'condition'; -INCLUDE: 'include'; -LOWERBOUND: 'lower_bound'; -UPPERBOUND: 'upper_bound'; -INTEGERTYPE: 'integer'; -UNITS: 'units'; -CONVERTUNITS: 'convert_to_units'; -TYPE: 'type'; -OUTPUT: 'output'; -CASE: 'case'; -ORDER: 'order'; -EXPRESSION: 'expression'; -LHSGTRHS: 'lhs_gt_rhs'; -LHSLTRHS: 'lhs_lt_rhs'; -WEIGHT: 'weight'; -FUNCTION: 'function'; -FROM_WRESL_FILE: 'from_wresl_file'; -UPPERUNBOUNDED: 'upper_unbounded'; -LOWERUNBOUNDED: 'lower_unbounded'; - -SVAR: '{' IDENT '}'; -IDENT : LETTER (LETTER | DIGIT | SYMBOLS )*; -IDENT1 : DIGIT (LETTER | DIGIT | SYMBOLS )*; -IDENT2 : SYMBOLS (LETTER | DIGIT | SYMBOLS )*; - -WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}; -COMMENT : '!' .* ('\n'|'\r') {$channel = HIDDEN;}; - - - +grammar ValueEvaluator; + +options { + language = Java; +} + +@header { + package wrimsv2.evaluator; + + import org.antlr.runtime.ANTLRFileStream; + import org.antlr.runtime.CharStream; + import org.antlr.runtime.CommonTokenStream; + import org.antlr.runtime.RecognitionException; + import org.antlr.runtime.TokenStream; + + import java.util.HashMap; + import wrimsv2.components.Error; + import wrimsv2.components.IntDouble; + import wrimsv2.parallel.ParallelVars; +} + +@lexer::header { + package wrimsv2.evaluator; +} + +@members { + public IntDouble evalValue; + public boolean evalCondition; + public ParallelVars prvs; + public Stack sumIndex= new Stack (); + + @Override + public void reportError(RecognitionException e) { + Error.addEvaluationError(getErrorMessage(e, tokenNames)); + } + + public void setParallelVars (ParallelVars prvs1) { + prvs=prvs1; + } + + public void setSumIndex(Stack sumIndex){ + this.sumIndex=sumIndex; + } +} + +evaluator returns [String result] + : expressionInput | + conditionInput + ; + +/////////////////// +/// input rules /// +/////////////////// + +expressionInput: 'v:' expressionCollection{evalValue=$expressionCollection.id;}; +conditionInput: 'c:' conditionStatement {evalCondition=$conditionStatement.result;}; + +/////////////////// +/// basic rules /// +/////////////////// +lhsrhs: expression|CONSTRAIN; + +//weight : (allnumber|(allnumber '*' TAFCFS)) (('+' allnumber)|('-' allnumber))?; + +units: IDENT|(IDENT '/' IDENT); + +fileName + : (':'|';'|'.'|'|'|SYMBOLS|'-'|'+'|BACKSLASH|IDENT|IDENT1|IDENT2|INTEGER|FLOAT|usedKeywords)+{ + } + ; + +externalFile + : (';'|'.'|'|'|SYMBOLS|'-'|'+'|INTEGER|FLOAT|IDENT|usedKeywords)+ + ; + +text : LETTER (LETTER | DIGIT )*; + +expressionCollection returns [IntDouble id] + :(expression{id=$expression.id;}) + |(tableSQL){id=$tableSQL.id;} + |(timeseriesWithUnits) + |((timeseries){id=$timeseries.id;}) + | sumExpression {id=$sumExpression.id;} + |(UPPERUNBOUNDED{id=new IntDouble(1e38,true);}) + |(LOWERUNBOUNDED{id=new IntDouble(-1e38,true);}) + ; + +func returns[IntDouble id]: + (max_func{id=$max_func.id;})| + (min_func{id=$min_func.id;})| + (int_func{id=$int_func.id;})| + (real_func{id=$real_func.id;})| + (abs_func{id=$abs_func.id;})| + (exp_func{id=$exp_func.id;})| + (log_func{id=$log_func.id;})| + (log10_func{id=$log10_func.id;})| + (pow_func{id=$pow_func.id;})| + (mod_func{id=$mod_func.id;})| + (round_func{id=$round_func.id;})| + (sin_func{id=$sin_func.id;})| + (cos_func{id=$cos_func.id;})| + (tan_func{id=$tan_func.id;})| + (cot_func{id=$cot_func.id;})| + (asin_func{id=$asin_func.id;})| + (acos_func{id=$acos_func.id;})| + (atan_func{id=$atan_func.id;})| + (acot_func{id=$acot_func.id;})| + (exceedFunc{id=$exceedFunc.id;})| + (exceedtsiFunc{id=$exceedtsiFunc.id;}); + +round_func returns[IntDouble id] + : ROUND '(' (e1=expression) ')'{ + id=ValueEvaluation.round($e1.id); + } + ; + +mod_func returns[IntDouble id] + : MOD '(' (e1=expression) (';' (e2=expression)) ')'{ + id=ValueEvaluation.mod($e1.id, $e2.id); + } + ; + +max_func returns[IntDouble id] + : MAX '(' (e1=expression){id=$e1.id;}(';' (e2=expression{ + id=ValueEvaluation.max(id, $e2.id); + }))+ ')' + ; + +min_func returns[IntDouble id] + : MIN '(' (e1=expression){id=$e1.id;}(';' (e2=expression{ + id=ValueEvaluation.min(id, $e2.id); + }))+ ')' + ; + +int_func returns[IntDouble id] + : INT '(' (e=expression) ')'{ + id=ValueEvaluation.intFunc($e.id); + } + ; + +real_func returns[IntDouble id] + : REAL '(' (e=expression) ')'{ + id=ValueEvaluation.realFunc($e.id); + } + ; + +abs_func returns[IntDouble id] + : ABS '(' (e=expression) ')'{ + id=ValueEvaluation.abs($e.id); + } + ; + +exp_func returns[IntDouble id] + : EXP '(' (e=expression) ')'{ + id=ValueEvaluation.exp($e.id); + } + ; + +log_func returns[IntDouble id] + : LOG '(' (e=expression) ')'{ + id=ValueEvaluation.log($e.id); + } + ; + +log10_func returns[IntDouble id] + : LOG10 '(' (e=expression) ')'{ + id=ValueEvaluation.log10($e.id); + } + ; + +pow_func returns[IntDouble id] + : POW '(' (e1=expression) (';' (e2=expression)) ')'{ + id=ValueEvaluation.pow($e1.id, $e2.id); + } + ; + +sin_func returns[IntDouble id] + : SIN '(' (e=expression) ')'{ + id=ValueEvaluation.sin($e.id); + } + ; + +cos_func returns[IntDouble id] + : COS '(' (e=expression) ')'{ + id=ValueEvaluation.cos($e.id); + } + ; + +tan_func returns[IntDouble id] + : TAN '(' (e=expression) ')'{ + id=ValueEvaluation.tan($e.id); + } + ; + +cot_func returns[IntDouble id] + : COT '(' (e=expression) ')'{ + id=ValueEvaluation.cot($e.id); + } + ; + +asin_func returns[IntDouble id] + : ASIN '(' (e=expression) ')'{ + id=ValueEvaluation.asin($e.id); + } + ; + +acos_func returns[IntDouble id] + : ACOS '(' (e=expression) ')'{ + id=ValueEvaluation.acos($e.id); + } + ; + +atan_func returns[IntDouble id] + : ATAN '(' (e=expression) ')'{ + id=ValueEvaluation.atan($e.id); + } + ; + +acot_func returns[IntDouble id] + : ACOT '(' (e=expression) ')'{ + id=ValueEvaluation.acot($e.id); + } + ; + +exceedFunc returns[IntDouble id] + : EXCEEDANCE '(' var=IDENT ';' exc=term ';' (mon=MONTH_CONST|mon=MONTH_RANGE|mon=ALL) ';' sy=INTEGER ';' sm=MONTH_CONST ';' sd=INTEGER ';' ey=INTEGER ';' em=MONTH_CONST ';' ed=INTEGER ')' { + id=ValueEvaluation.exceedance($var.text, $exc.id, $mon.text, $sy.text, $sm.text, $sd.text, $ey.text, $em.text, $ed.text); + } + ; + +exceedtsiFunc returns[IntDouble id] + : EXCEEDANCE_TSI '(' var=IDENT ';' exc=term ';' (mon=MONTH_CONST|mon=MONTH_RANGE|mon=ALL) ';' sy=INTEGER ';' sm=MONTH_CONST ';' sd=INTEGER ';' ey=INTEGER ';' em=MONTH_CONST ';' ed=INTEGER ')' { + id=ValueEvaluation.exceedance_tsi($var.text, $exc.id, $mon.text, $sy.text, $sm.text, $sd.text, $ey.text, $em.text, $ed.text); + } + ; + +range_func returns [boolean result] + : RANGE '(' MONTH ';' m1=MONTH_CONST ';' m2=MONTH_CONST ')' {result=ValueEvaluation.range($m1.text, $m2.text);}; + +timeseriesWithUnits + : 'timeseries' 'kind' '=' partC 'units' '=' IDENT + ; + +timeseries returns [IntDouble id] + : 'timeseries' {id=ValueEvaluation.timeseries();} + ; + + + +partC: (IDENT|IDENT1|usedKeywords) ('-' (IDENT|IDENT1|usedKeywords))*; + +usedKeywords: YEAR|MONTH|MONTH_CONST|MONTH_RANGE|DAY|PASTMONTH|RANGE|TAFCFS|DAYSIN|DAYSINTIMESTEP|SUM|MAX|MIN|INT|REAL|ABS|EXP|LOG|LOG10|POW|MOD|ROUND|SELECT|FROM|GIVEN|USE|WHERE +|CONSTRAIN|ALWAYS|NAME|DVAR|CYCLE|FILE|CONDITION|INCLUDE|LOWERBOUND|UPPERBOUND|INTEGERTYPE|UNITS|CONVERTUNITS|TYPE|OUTPUT +|CASE|ORDER|EXPRESSION|LHSGTRHS|LHSLTRHS|WEIGHT|FUNCTION|FROM_WRESL_FILE|UPPERUNBOUNDED|LOWERUNBOUNDED|AND|OR|NOT +|SIN|COS|TAN|COT|ASIN|ACOS|ATAN|ACOT|EXCEEDANCE|EXCEEDANCE_TSI|ALL; + +tableSQL returns [IntDouble id] @init{String table=null; String select=null; String use=null; HashMap given=null; HashMap where=null;} + : SELECT ((i1=IDENT{select=$i1.text;})|(u1=usedKeywords{select=$u1.text;})) FROM i2=IDENT{table=$i2.text;} + (GIVEN a=assignStatement{given=new HashMap(); given.put($a.assignIdent, $a.value);})? (USE i3=IDENT{use=$i3.text;})? + (where_items{where=$where_items.where;})? {id=ValueEvaluation.tableSQL(table, select, where, given, use);} + ; + +where_items returns [HashMap where] + : WHERE (r1=whereStatement{where=new HashMap(); where.put($r1.whereIdent, $r1.value);}) + (';' r=whereStatement{where.put($r.whereIdent, $r.value);})* + ; + + +upperbound: IDENT|allnumber|(allnumber '*' TAFCFS); + +lowerbound: IDENT|allnumber|(allnumber '*' TAFCFS); + +//sumExpression +// : SUM '(' I '=' e1=expression_sum ';' e2=expression_sum (';' (s='-')? INTEGER )? ')' e3=expression +// ; +//term_sum: (MONTH|MONTH_CONST|PASTMONTH|I|INTEGER|'(' expression_sum ')'); + +//unary_sum : ('-')? term_sum ; +//add_sum : unary_sum(('+' | '-') unary_sum)* ; +//expression_sum: add_sum ; + +//sumExpression was redesign. If not work, switch back to the original design above + +sumExpression returns [IntDouble id] @init{String s="";} + : SUM '(' IDENT{ValueEvaluation.sumExpression_IDENT($IDENT.text, sumIndex);} '=' e1=expression ';' e2=expression (';' (('-'{s=s+"-";})? INTEGER {s=s+$INTEGER.text;}))? (')'{ValueEvaluation.initSumExpression($e1.id, $e2.id, s, sumIndex);}) e3=expression{id=ValueEvaluation.sumExpression($e3.id, $e3.text, sumIndex);} + ; + +term returns [IntDouble id] + : (IDENT {id=ValueEvaluation.term_IDENT($IDENT.text, sumIndex);}) + | (FLOAT {id=ValueEvaluation.term_FLOAT($FLOAT.text);}) + | ('(' (e=expression) ')' {id=$e.id;}) + | (knownTS{id=ValueEvaluation.term_knownTS($knownTS.result);}) + | func{id=$func.id;} + | (INTEGER {id=ValueEvaluation.term_INTEGER($INTEGER.text);}) + | tafcfs_term{id=$tafcfs_term.id;} + | YEAR{id=ValueEvaluation.term_YEAR();} + | MONTH{id=ValueEvaluation.term_MONTH();} + | DAY {id=ValueEvaluation.term_DAY();} + | MONTH_CONST{id=ValueEvaluation.term_MONTH_CONST($MONTH_CONST.text);} + | PASTMONTH{id=ValueEvaluation.term_PASTMONTH($PASTMONTH.text);} + | DAYSIN{id=ValueEvaluation.daysIn();} + | DAYSINTIMESTEP{id=ValueEvaluation.daysInTimeStep();} + | (SVAR{id=ValueEvaluation.term_SVAR($SVAR.text.replace("{","").replace("}",""));}) + | ARRAY_ITERATOR{id=ValueEvaluation.term_ARRAY_ITERATOR(prvs);} + | '(' sumExpression ')' {id=$sumExpression.id;} + ; + +tafcfs_term returns [IntDouble id]: TAFCFS ('(' expression ')')? { + id=ValueEvaluation.tafcfs_term($TAFCFS.text, $expression.id); +}; + +knownTS returns [IntDouble result] + : (f=function{result=$f.result;})|(p=pastCycleValue {result=$p.result;}) + ; + +pastCycleValue returns [IntDouble result] + : (p1=pastCycleNoTimeArray{return $p1.result;})|(p2=pastCycleTimeArray{return $p2.result;})|(p3=pastCycleIndexNoTimeArray{return $p3.result;})|(p4=pastCycleIndexTimeArray{return $p4.result;}) + ; + +pastCycleNoTimeArray returns [IntDouble result] + : i1=IDENT '[' i2=IDENT ']'{result=ValueEvaluation.pastCycleNoTimeArray($i1.text,$i2.text);} + ; + +pastCycleTimeArray returns [IntDouble result] + : i1=IDENT '[' i2=IDENT ']' '(' e1=expression ')' {result=ValueEvaluation.pastCycleTimeArray($i1.text,$i2.text, $e1.id);} + ; + +pastCycleIndexNoTimeArray returns [IntDouble result] + : i1=IDENT '[' ('-' index=INTEGER) ']'{result=ValueEvaluation.pastCycleIndexNoTimeArray($i1.text, -Integer.parseInt($index.text));} + ; + +pastCycleIndexTimeArray returns [IntDouble result] + : i1=IDENT '[' '-' index=INTEGER ']' '(' e1=expression ')' {result=ValueEvaluation.pastCycleIndexTimeArray($i1.text,-Integer.parseInt($index.text), $e1.id);} + ; + +function returns [IntDouble result] + : (n=noArgFunction{result=$n.result;})|(a=argFunction{result=$a.result;}) + ; + +noArgFunction returns [IntDouble result] + : IDENT '(' ')' {result=ValueEvaluation.noArgFunction($IDENT.text);}; + +argFunction returns [IntDouble result] @init{ArrayList> idArray = new ArrayList>(); ArrayList id0Array=new ArrayList();} + : IDENT '(' (e1=expression {ArrayList idArray1=new ArrayList(); idArray1.add($e1.id); idArray.add(idArray1);} + | t1=trunk_timeArray{idArray.add($t1.idArray);}) + (';' (e2=expression{ArrayList idArray1=new ArrayList(); idArray1.add($e2.id); idArray.add(idArray1);} + |t2=trunk_timeArray{idArray.add($t2.idArray);}))* ')' ('(' e0=expression {id0Array.add($e0.id);} ')')? + { + if (id0Array.size()==0) { + result=ValueEvaluation.argFunction($IDENT.text,idArray); + }else{ + result=ValueEvaluation.pastTSFV($IDENT.text, $e0.id, idArray, prvs); + } + }; + +trunk_timeArray returns[ArrayList idArray] @init{idArray = new ArrayList(); IntDouble start=new IntDouble(1, true); IntDouble end=new IntDouble(1, true);} + : i0=IDENT '(' (n1=integer{start=ValueEvaluation.term_INTEGER($n1.text);}|i1=IDENT{start=ValueEvaluation.term_IDENT($i1.text, sumIndex);}) ':' (n2=integer{end=ValueEvaluation.term_INTEGER($n2.text);}|i2=IDENT{end=ValueEvaluation.term_IDENT($i2.text, sumIndex);}) ')' + { + idArray=ValueEvaluation.trunk_timeArray($i0.text, start, end); + } + ; + +unary returns [IntDouble id] + : (s=('+'|'-'))? term{id=ValueEvaluation.unary($s.text, $term.id); + }; + +allnumber + : ('-')? number; + +mult returns [IntDouble id] + : (u1=unary {id=$u1.id;}) (s=('*'| '/') (u2=unary){ + if ($s.text.equals("*")){ + id=ValueEvaluation.mult(id, $u2.id); + }else{ + id=ValueEvaluation.divide(id, $u2.id); + } + })* + ; + +add returns [IntDouble id] + : (m1=mult {id=$m1.id;}) ((s=('+'|'-')) (m2=mult){ + if ($s.text.equals("+")){ + id=ValueEvaluation.add(id, $m2.id); + }else{ + id=ValueEvaluation.substract(id, $m2.id); + } + })* + ; + +expression returns [IntDouble id] + : i=add {$id=$add.id;} + ; + +relation + : '==' + | '<' + | '>' + | '>=' + | '<=' + ; + +whereStatement returns [String whereIdent, Number value] + : ((i=IDENT{$whereIdent=$i.text;})|(u=usedKeywords{$whereIdent=$u.text;})) '=' expression{$value=ValueEvaluation.assignWhereStatement($expression.id);} + ; + +conditionStatement returns [boolean result] + : ((r=relationUnary{result=$r.result;})|ALWAYS{result=true;}) + ; + +relationUnary returns [boolean result] + : (n=NOT)? r=relationOr{ + if ($n==null){ + return $r.result; + }else{ + if ($r.result){ + return false; + }else{ + return true; + } + } + } + ; + +relationOr returns [boolean result] + : r1=relationAnd {result=$r1.result;} + (s=OR r2=relationAnd {result=ValueEvaluation.relationStatementSeries(result, $r2.result, $s.text);})* ; + +relationAnd returns [boolean result] + : r1=relationRangeStatement {result=$r1.result;} + (s=AND r2=relationRangeStatement {result=ValueEvaluation.relationStatementSeries(result, $r2.result, $s.text);})* ; + +relationRangeStatement returns [boolean result] + : (r1=relationStatement{result=$r1.result;})|(r2=range_func{result=$r2.result;}) + ; + +relationStatement returns [boolean result] + : ( ( expression relation expression) => e1=expression relation e2=expression {result=ValueEvaluation.relationStatement($e1.id, $e2.id, $relation.text);} ) + | ( ( '('relationUnary')' ) => '('r2=relationUnary')' {result=$r2.result;} ) + ; + +assignStatement returns [String assignIdent, Number value] + : IDENT '=' expression {$assignIdent=$IDENT.text; $value=ValueEvaluation.assignWhereStatement($expression.id);} + ; + +number + : INTEGER + | FLOAT + ; + +integer : integer_p|integer_n ; +integer_p : INTEGER ; +integer_n : '-' INTEGER ; + +MULTILINE_COMMENT : '/*' .* '*/' {$channel = HIDDEN;} ; + +fragment LETTER : ('a'..'z' | 'A'..'Z') ; +fragment DIGIT : '0'..'9'; +fragment SYMBOLS : '_'; + +BACKSLASH : '\\'; + +INTEGER : DIGIT+ ; +FLOAT : INTEGER? '.' INTEGER + | INTEGER '.' + ; + +//I: 'i'; +YEAR: 'wateryear'; +MONTH: 'month'; +DAY: 'day'; +MONTH_CONST: 'jan'|'feb'|'mar'|'apr'|'may'|'jun'|'jul'|'aug'|'sep'|'oct'|'nov'|'dec'; +MONTH_RANGE: MONTH_CONST MONTH_CONST; +ALL: 'all'; +PASTMONTH: 'prevjan'|'prevfeb'|'prevmar'|'prevapr'|'prevmay'|'prevjun'|'prevjul'|'prevaug'|'prevsep'|'prevoct'|'prevnov'|'prevdec'; +RANGE: 'range'; + +TAFCFS: 'taf_cfs'|'cfs_taf'|'cfs_af'|'af_cfs'; +DAYSIN: 'daysin'|'daysinmonth'; +DAYSINTIMESTEP: 'daysintimestep'; + +ARRAY_ITERATOR : '$m' ; + +AND: '.and.'; +OR: '.or.'; +NOT: '.not.'; + +SUM: 'sum'; +MAX : 'max'; +MIN : 'min'; +INT : 'int'; +REAL: 'real'; +ABS: 'abs'; +EXP: 'exp'; +LOG: 'log'; +LOG10: 'log10'; +POW: 'pow'; +MOD: 'mod'; +ROUND: 'round'; +SIN : 'sin'; +COS : 'cos'; +TAN : 'tan'; +COT : 'cot'; +ASIN : 'asin'; +ACOS : 'acos'; +ATAN : 'atan'; +ACOT : 'acot'; +EXCEEDANCE : 'exceedance'; +EXCEEDANCE_TSI : 'exceedance_tsi'; + +SELECT: 'select'; +FROM: 'from'; +GIVEN: 'given'; +USE: 'use'; +WHERE : 'where'; + +CONSTRAIN: 'constrain'; +ALWAYS: 'always'; + +NAME: 'name'; +DVAR: 'dvar'; +CYCLE: 'cycle'; +FILE: 'file'; +CONDITION: 'condition'; +INCLUDE: 'include'; +LOWERBOUND: 'lower_bound'; +UPPERBOUND: 'upper_bound'; +INTEGERTYPE: 'integer'; +UNITS: 'units'; +CONVERTUNITS: 'convert_to_units'; +TYPE: 'type'; +OUTPUT: 'output'; +CASE: 'case'; +ORDER: 'order'; +EXPRESSION: 'expression'; +LHSGTRHS: 'lhs_gt_rhs'; +LHSLTRHS: 'lhs_lt_rhs'; +WEIGHT: 'weight'; +FUNCTION: 'function'; +FROM_WRESL_FILE: 'from_wresl_file'; +UPPERUNBOUNDED: 'upper_unbounded'; +LOWERUNBOUNDED: 'lower_unbounded'; + +SVAR: '{' IDENT '}'; +IDENT : LETTER (LETTER | DIGIT | SYMBOLS )*; +IDENT1 : DIGIT (LETTER | DIGIT | SYMBOLS )*; +IDENT2 : SYMBOLS (LETTER | DIGIT | SYMBOLS )*; + +WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}; +COMMENT : '!' .* ('\n'|'\r') {$channel = HIDDEN;}; + + + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluatorTree.g b/wrims-core/src/main/antlr/wrimsv2/evaluator/ValueEvaluatorTree.g similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluatorTree.g rename to wrims-core/src/main/antlr/wrimsv2/evaluator/ValueEvaluatorTree.g index 613d74d91..374c36141 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluatorTree.g +++ b/wrims-core/src/main/antlr/wrimsv2/evaluator/ValueEvaluatorTree.g @@ -1,363 +1,363 @@ -grammar ValueEvaluatorTree; - -options { - language = Java; - output=AST; - ASTLabelType=CommonTree; -} - -@header { - package wrimsv2.evaluator; - - import org.antlr.runtime.ANTLRFileStream; - import org.antlr.runtime.CharStream; - import org.antlr.runtime.CommonTokenStream; - import org.antlr.runtime.RecognitionException; - import org.antlr.runtime.TokenStream; - - import java.util.HashMap; - import wrimsv2.components.Error; - import wrimsv2.components.IntDouble; -} - -@lexer::header { - package wrimsv2.evaluator; -} - -@members { - - @Override - public void reportError(RecognitionException e) { - Error.addEvaluationError(getErrorMessage(e, tokenNames)); - } -} - -evaluator - : expressionInput | - conditionInput - ; - -/////////////////// -/// input rules /// -/////////////////// - -expressionInput: 'v:' expressionCollection-> ^('v:' expressionCollection); -conditionInput: 'c:' conditionStatement-> ^('c:' conditionStatement); - -/////////////////// -/// basic rules /// -/////////////////// -lhsrhs: expression|CONSTRAIN; - -//weight : (allnumber|(allnumber '*' TAFCFS)) (('+' allnumber)|('-' allnumber))?; - -units: IDENT|(IDENT '/' IDENT); - -fileName - : (':'|';'|'.'|'|'|SYMBOLS|'-'|'+'|BACKSLASH|IDENT|IDENT1|IDENT2|INTEGER|FLOAT|usedKeywords)+{ - } - ; - -externalFile - : (';'|'.'|'|'|SYMBOLS|'-'|'+'|INTEGER|FLOAT|IDENT|usedKeywords)+ - ; - -text : LETTER (LETTER | DIGIT )*; - -conditionStatement - : ((r=relationStatementSeries->$r) |(ALWAYS->ALWAYS)) - ; - -relationStatementSeries - : r1=relationRangeStatement - (((s=('.and.'^|'.or.'^))) r2=relationRangeStatement)* ; - -relationRangeStatement - : (relationStatement -> relationStatement)|(range_func -> range_func) - ; - -relationStatement - : (e1=expression) relation (e2=expression) -> ^(relation $e1 $e2) - ; - -expressionCollection - :((expression->expression) - |(tableSQL->tableSQL) - |(timeseries->timeseries) - |(sumExpression->sumExpression) - |(UPPERUNBOUNDED ->UPPERUNBOUNDED) - |(LOWERUNBOUNDED ->LOWERUNBOUNDED)) - ; - -func: - (max_func| - min_func| - int_func| - real_func| - abs_func| - exp_func| - log_func| - log10_func| - pow_func); - -max_func - : MAX '(' (e1=expression) (';' (e2=expression))+ ')' -> ^(MAX $e1 $e2+) - ; - -min_func - : MIN '(' (e1=expression)(';' (e2=expression))+ ')' -> ^(MIN $e1 $e2+) - ; - -int_func - : INT '(' (e=expression) ')' -> ^(INT $e) - ; - -real_func - : REAL '(' (e=expression) ')' -> ^(REAL $e) - ; - -abs_func - : ABS '(' (e=expression) ')'-> ^(ABS $e) - ; - -exp_func - : EXP '(' (e=expression) ')' -> ^(EXP $e) - ; - -log_func - : LOG '(' (e=expression) ')' -> ^(LOG $e) - ; - -log10_func - : LOG10 '(' (e=expression) ')'-> ^(LOG10 $e) - ; - -pow_func - : POW '(' (e1=expression) (';' (e2=expression)) ')'-> ^(POW $e1 $e2) - ; - -range_func - : RANGE '(' MONTH ';' m1=MONTH_CONST ';' m2=MONTH_CONST ')' -> ^(RANGE MONTH $m1 $m2) - ; - -timeseries - : TIMESERIES ->TIMESERIES - ; - - - -partC: (IDENT|IDENT1|usedKeywords) ('-' (IDENT|IDENT1|usedKeywords))*; - -usedKeywords: YEAR|MONTH|MONTH_CONST|PASTMONTH|RANGE|TAFCFS|DAYSIN|SUM|MAX|MIN|INT|REAL|ABS|EXP|LOG|LOG10|POW|MOD|UNARY|SELECT|FROM|GIVEN|USE|WHERE -|TIMESERIES|CONSTRAIN|ALWAYS|NAME|DVAR|CYCLE|FILE|CONDITION|INCLUDE|LOWERBOUND|UPPERBOUND|INTEGERTYPE|UNITS|CONVERTUNITS|TYPE|OUTPUT -|CASE|ORDER|EXPRESSION|LHSGTRHS|LHSLTRHS|WEIGHT|FUNCTION|FROM_WRESL_FILE|UPPERUNBOUNDED|LOWERUNBOUNDED; - -tableSQL : SELECT selectName FROM i1=IDENT (GIVEN a=assignStatement)? (USE i2=IDENT)? (where_items)? -> ^(SELECT selectName $i1 assignStatement? $i2? where_items?) - ; - -selectName: (IDENT -> IDENT)|(usedKeywords -> usedKeywords); - -where_items - : WHERE (w1=whereStatement) - (addWhereStatement)* ->^(WHERE $w1 addWhereStatement*) - ; - -addWhereStatement - : ';' whereStatement -> whereStatement - ; - -//upperbound: (IDENT -> IDENT)|(allnumber->allnumber)|(((allnumber '*' TAFCFS) ->^('*' allnumber TAFCFS))); - -//lowerbound: (IDENT -> IDENT)|(allnumber->allnumber)|(((allnumber '*' TAFCFS) ->^('*' allnumber TAFCFS))); - -//sumExpression -// : SUM '(' I '=' e1=expression_sum ';' e2=expression_sum (';' (s='-')? INTEGER )? ')' e3=expression -// ; -//term_sum: (MONTH|MONTH_CONST|PASTMONTH|I|INTEGER|'(' expression_sum ')'); - -//unary_sum : ('-')? term_sum ; -//add_sum : unary_sum(('+' | '-') unary_sum)* ; -//expression_sum: add_sum ; - -//sumExpression was redesign. If not work, switch back to the original design above - -sumExpression - : SUM '(' IDENT '=' e1=expression ';' e2=expression (';' (('-')? INTEGER ))? ')' e3=expression - -> ^(SUM IDENT $e1 $e2 '-'? INTEGER? $e3) - ; - -term - : (IDENT -> IDENT) - | (FLOAT -> FLOAT) - | ('(' (expression) ')' -> expression) - | (knownTS -> knownTS) - | (func -> func) - | (INTEGER -> INTEGER) - | (tafcfs_term -> tafcfs_term) - | (YEAR ->YEAR) - | (MONTH ->MONTH) - | (MONTH_CONST ->MONTH_CONST) - | (PASTMONTH -> PASTMONTH) - | (DAYSIN -> DAYSIN) - | (SVAR -> SVAR) - ; - -tafcfs_term : TAFCFS ('(' expression ')')? -> ^(TAFCFS expression?) - ; - -knownTS - : (f=function -> $f)|(p=pastCycleDV ->$p) - ; - -//pastMonthTS -// : ((i1=IDENT)|TAFCFS) '(' ((p=PASTMONTH)|(i=I)|(pm=(MONTH_CONST '-' MONTH (('+'|'-') INTEGER)? ))|(mp=(MONTH '-' MONTH_CONST (('+'|'-') INTEGER)?))) ')' -// ; - -//preMonthTS -// : IDENT '(' (s='-')? INTEGER ')' -// ; - -pastCycleDV - : i1=IDENT '[' i2=IDENT ']' -> ^($i1 '[' $i2 ']') - ; - -function - : (n=noArgFunction-> $n)|(a=argFunction->$a) - ; - -noArgFunction - : IDENT '(' ')' -> ^(IDENT '(' ')'); - -argFunction - : IDENT '(' e1=expression addarg* ')' -> ^(IDENT '(' $e1 addarg* ')' ) - ; - -addarg - : ';' expression -> expression - ; - -unary - : (s='-')? term -> {s==null}? term - -> ^(UNARY term) - ; - -//allnumber -// : (s='-')? number -> {s==null}? number -// -> ^('-' number) -// ; - -mult - : (u1=unary) (s=('*'^| '/'^| MOD^) (u2=unary))* - ; - -add - : (m1=mult) ((s=('+'^|'-'^)) (m2=mult))* - ; - -expression - : add -> add - ; - -relation - : '==' - | '<' - | '>' - | '>=' - | '<=' - ; - -whereStatement - : whereName '=' expression -> ^(WHERE whereName expression) - ; - -whereName: (IDENT -> IDENT)|(usedKeywords -> usedKeywords); - -assignStatement - : IDENT '=' expression -> ^('=' IDENT expression) - ; - -number - : (INTEGER->INTEGER) - | (FLOAT->FLOAT) - ; - -MULTILINE_COMMENT : '/*' .* '*/' {$channel = HIDDEN;} ; - -fragment LETTER : ('a'..'z' | 'A'..'Z') ; -fragment DIGIT : '0'..'9'; -fragment SYMBOLS : '_'; - -BACKSLASH : '\\'; - -INTEGER : DIGIT+ ; -FLOAT : INTEGER? '.' INTEGER - | INTEGER '.' - ; - -//I: 'i'; -YEAR: 'wateryear'; -MONTH: 'month'; -MONTH_CONST: 'jan'|'feb'|'mar'|'apr'|'may'|'jun'|'jul'|'aug'|'sep'|'oct'|'nov'|'dec'; -PASTMONTH: 'prevjan'|'prevfeb'|'prevmar'|'prevapr'|'prevmay'|'prevjun'|'prevjul'|'prevaug'|'prevsep'|'prevoct'|'prevnov'|'prevdec'; -RANGE: 'range'; - -TAFCFS: 'taf_cfs'|'cfs_taf'|'cfs_af'|'af_cfs'; -DAYSIN: 'daysin'|'daysinmonth'; - -SUM: 'sum'; -MAX : 'max'; -MIN : 'min'; -INT : 'int'; -REAL: 'real'; -ABS: 'abs'; -EXP: 'exp'; -LOG: 'log'; -LOG10: 'log10'; -POW: 'pow'; -MOD: 'mod'; -UNARY: 'unary'; - -SELECT: 'select'; -FROM: 'from'; -GIVEN: 'given'; -USE: 'use'; -WHERE : 'where'; -TIMESERIES: 'timeseries'; - -CONSTRAIN: 'constrain'; -ALWAYS: 'always'; - -NAME: 'name'; -DVAR: 'dvar'; -CYCLE: 'cycle'; -FILE: 'file'; -CONDITION: 'condition'; -INCLUDE: 'include'; -LOWERBOUND: 'lower_bound'; -UPPERBOUND: 'upper_bound'; -INTEGERTYPE: 'integer'; -UNITS: 'units'; -CONVERTUNITS: 'convert_to_units'; -TYPE: 'type'; -OUTPUT: 'output'; -CASE: 'case'; -ORDER: 'order'; -EXPRESSION: 'expression'; -LHSGTRHS: 'lhs_gt_rhs'; -LHSLTRHS: 'lhs_lt_rhs'; -WEIGHT: 'weight'; -FUNCTION: 'function'; -FROM_WRESL_FILE: 'from_wresl_file'; -UPPERUNBOUNDED: 'upper_unbounded'; -LOWERUNBOUNDED: 'lower_unbounded'; - -SVAR: '{' IDENT '}'; -IDENT : LETTER (LETTER | DIGIT | SYMBOLS )*; -IDENT1 : DIGIT (LETTER | DIGIT | SYMBOLS )*; -IDENT2 : SYMBOLS (LETTER | DIGIT | SYMBOLS )*; - -WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}; -COMMENT : '!' .* ('\n'|'\r') {$channel = HIDDEN;}; - - - +grammar ValueEvaluatorTree; + +options { + language = Java; + output=AST; + ASTLabelType=CommonTree; +} + +@header { + package wrimsv2.evaluator; + + import org.antlr.runtime.ANTLRFileStream; + import org.antlr.runtime.CharStream; + import org.antlr.runtime.CommonTokenStream; + import org.antlr.runtime.RecognitionException; + import org.antlr.runtime.TokenStream; + + import java.util.HashMap; + import wrimsv2.components.Error; + import wrimsv2.components.IntDouble; +} + +@lexer::header { + package wrimsv2.evaluator; +} + +@members { + + @Override + public void reportError(RecognitionException e) { + Error.addEvaluationError(getErrorMessage(e, tokenNames)); + } +} + +evaluator + : expressionInput | + conditionInput + ; + +/////////////////// +/// input rules /// +/////////////////// + +expressionInput: 'v:' expressionCollection-> ^('v:' expressionCollection); +conditionInput: 'c:' conditionStatement-> ^('c:' conditionStatement); + +/////////////////// +/// basic rules /// +/////////////////// +lhsrhs: expression|CONSTRAIN; + +//weight : (allnumber|(allnumber '*' TAFCFS)) (('+' allnumber)|('-' allnumber))?; + +units: IDENT|(IDENT '/' IDENT); + +fileName + : (':'|';'|'.'|'|'|SYMBOLS|'-'|'+'|BACKSLASH|IDENT|IDENT1|IDENT2|INTEGER|FLOAT|usedKeywords)+{ + } + ; + +externalFile + : (';'|'.'|'|'|SYMBOLS|'-'|'+'|INTEGER|FLOAT|IDENT|usedKeywords)+ + ; + +text : LETTER (LETTER | DIGIT )*; + +conditionStatement + : ((r=relationStatementSeries->$r) |(ALWAYS->ALWAYS)) + ; + +relationStatementSeries + : r1=relationRangeStatement + (((s=('.and.'^|'.or.'^))) r2=relationRangeStatement)* ; + +relationRangeStatement + : (relationStatement -> relationStatement)|(range_func -> range_func) + ; + +relationStatement + : (e1=expression) relation (e2=expression) -> ^(relation $e1 $e2) + ; + +expressionCollection + :((expression->expression) + |(tableSQL->tableSQL) + |(timeseries->timeseries) + |(sumExpression->sumExpression) + |(UPPERUNBOUNDED ->UPPERUNBOUNDED) + |(LOWERUNBOUNDED ->LOWERUNBOUNDED)) + ; + +func: + (max_func| + min_func| + int_func| + real_func| + abs_func| + exp_func| + log_func| + log10_func| + pow_func); + +max_func + : MAX '(' (e1=expression) (';' (e2=expression))+ ')' -> ^(MAX $e1 $e2+) + ; + +min_func + : MIN '(' (e1=expression)(';' (e2=expression))+ ')' -> ^(MIN $e1 $e2+) + ; + +int_func + : INT '(' (e=expression) ')' -> ^(INT $e) + ; + +real_func + : REAL '(' (e=expression) ')' -> ^(REAL $e) + ; + +abs_func + : ABS '(' (e=expression) ')'-> ^(ABS $e) + ; + +exp_func + : EXP '(' (e=expression) ')' -> ^(EXP $e) + ; + +log_func + : LOG '(' (e=expression) ')' -> ^(LOG $e) + ; + +log10_func + : LOG10 '(' (e=expression) ')'-> ^(LOG10 $e) + ; + +pow_func + : POW '(' (e1=expression) (';' (e2=expression)) ')'-> ^(POW $e1 $e2) + ; + +range_func + : RANGE '(' MONTH ';' m1=MONTH_CONST ';' m2=MONTH_CONST ')' -> ^(RANGE MONTH $m1 $m2) + ; + +timeseries + : TIMESERIES ->TIMESERIES + ; + + + +partC: (IDENT|IDENT1|usedKeywords) ('-' (IDENT|IDENT1|usedKeywords))*; + +usedKeywords: YEAR|MONTH|MONTH_CONST|PASTMONTH|RANGE|TAFCFS|DAYSIN|SUM|MAX|MIN|INT|REAL|ABS|EXP|LOG|LOG10|POW|MOD|UNARY|SELECT|FROM|GIVEN|USE|WHERE +|TIMESERIES|CONSTRAIN|ALWAYS|NAME|DVAR|CYCLE|FILE|CONDITION|INCLUDE|LOWERBOUND|UPPERBOUND|INTEGERTYPE|UNITS|CONVERTUNITS|TYPE|OUTPUT +|CASE|ORDER|EXPRESSION|LHSGTRHS|LHSLTRHS|WEIGHT|FUNCTION|FROM_WRESL_FILE|UPPERUNBOUNDED|LOWERUNBOUNDED; + +tableSQL : SELECT selectName FROM i1=IDENT (GIVEN a=assignStatement)? (USE i2=IDENT)? (where_items)? -> ^(SELECT selectName $i1 assignStatement? $i2? where_items?) + ; + +selectName: (IDENT -> IDENT)|(usedKeywords -> usedKeywords); + +where_items + : WHERE (w1=whereStatement) + (addWhereStatement)* ->^(WHERE $w1 addWhereStatement*) + ; + +addWhereStatement + : ';' whereStatement -> whereStatement + ; + +//upperbound: (IDENT -> IDENT)|(allnumber->allnumber)|(((allnumber '*' TAFCFS) ->^('*' allnumber TAFCFS))); + +//lowerbound: (IDENT -> IDENT)|(allnumber->allnumber)|(((allnumber '*' TAFCFS) ->^('*' allnumber TAFCFS))); + +//sumExpression +// : SUM '(' I '=' e1=expression_sum ';' e2=expression_sum (';' (s='-')? INTEGER )? ')' e3=expression +// ; +//term_sum: (MONTH|MONTH_CONST|PASTMONTH|I|INTEGER|'(' expression_sum ')'); + +//unary_sum : ('-')? term_sum ; +//add_sum : unary_sum(('+' | '-') unary_sum)* ; +//expression_sum: add_sum ; + +//sumExpression was redesign. If not work, switch back to the original design above + +sumExpression + : SUM '(' IDENT '=' e1=expression ';' e2=expression (';' (('-')? INTEGER ))? ')' e3=expression + -> ^(SUM IDENT $e1 $e2 '-'? INTEGER? $e3) + ; + +term + : (IDENT -> IDENT) + | (FLOAT -> FLOAT) + | ('(' (expression) ')' -> expression) + | (knownTS -> knownTS) + | (func -> func) + | (INTEGER -> INTEGER) + | (tafcfs_term -> tafcfs_term) + | (YEAR ->YEAR) + | (MONTH ->MONTH) + | (MONTH_CONST ->MONTH_CONST) + | (PASTMONTH -> PASTMONTH) + | (DAYSIN -> DAYSIN) + | (SVAR -> SVAR) + ; + +tafcfs_term : TAFCFS ('(' expression ')')? -> ^(TAFCFS expression?) + ; + +knownTS + : (f=function -> $f)|(p=pastCycleDV ->$p) + ; + +//pastMonthTS +// : ((i1=IDENT)|TAFCFS) '(' ((p=PASTMONTH)|(i=I)|(pm=(MONTH_CONST '-' MONTH (('+'|'-') INTEGER)? ))|(mp=(MONTH '-' MONTH_CONST (('+'|'-') INTEGER)?))) ')' +// ; + +//preMonthTS +// : IDENT '(' (s='-')? INTEGER ')' +// ; + +pastCycleDV + : i1=IDENT '[' i2=IDENT ']' -> ^($i1 '[' $i2 ']') + ; + +function + : (n=noArgFunction-> $n)|(a=argFunction->$a) + ; + +noArgFunction + : IDENT '(' ')' -> ^(IDENT '(' ')'); + +argFunction + : IDENT '(' e1=expression addarg* ')' -> ^(IDENT '(' $e1 addarg* ')' ) + ; + +addarg + : ';' expression -> expression + ; + +unary + : (s='-')? term -> {s==null}? term + -> ^(UNARY term) + ; + +//allnumber +// : (s='-')? number -> {s==null}? number +// -> ^('-' number) +// ; + +mult + : (u1=unary) (s=('*'^| '/'^| MOD^) (u2=unary))* + ; + +add + : (m1=mult) ((s=('+'^|'-'^)) (m2=mult))* + ; + +expression + : add -> add + ; + +relation + : '==' + | '<' + | '>' + | '>=' + | '<=' + ; + +whereStatement + : whereName '=' expression -> ^(WHERE whereName expression) + ; + +whereName: (IDENT -> IDENT)|(usedKeywords -> usedKeywords); + +assignStatement + : IDENT '=' expression -> ^('=' IDENT expression) + ; + +number + : (INTEGER->INTEGER) + | (FLOAT->FLOAT) + ; + +MULTILINE_COMMENT : '/*' .* '*/' {$channel = HIDDEN;} ; + +fragment LETTER : ('a'..'z' | 'A'..'Z') ; +fragment DIGIT : '0'..'9'; +fragment SYMBOLS : '_'; + +BACKSLASH : '\\'; + +INTEGER : DIGIT+ ; +FLOAT : INTEGER? '.' INTEGER + | INTEGER '.' + ; + +//I: 'i'; +YEAR: 'wateryear'; +MONTH: 'month'; +MONTH_CONST: 'jan'|'feb'|'mar'|'apr'|'may'|'jun'|'jul'|'aug'|'sep'|'oct'|'nov'|'dec'; +PASTMONTH: 'prevjan'|'prevfeb'|'prevmar'|'prevapr'|'prevmay'|'prevjun'|'prevjul'|'prevaug'|'prevsep'|'prevoct'|'prevnov'|'prevdec'; +RANGE: 'range'; + +TAFCFS: 'taf_cfs'|'cfs_taf'|'cfs_af'|'af_cfs'; +DAYSIN: 'daysin'|'daysinmonth'; + +SUM: 'sum'; +MAX : 'max'; +MIN : 'min'; +INT : 'int'; +REAL: 'real'; +ABS: 'abs'; +EXP: 'exp'; +LOG: 'log'; +LOG10: 'log10'; +POW: 'pow'; +MOD: 'mod'; +UNARY: 'unary'; + +SELECT: 'select'; +FROM: 'from'; +GIVEN: 'given'; +USE: 'use'; +WHERE : 'where'; +TIMESERIES: 'timeseries'; + +CONSTRAIN: 'constrain'; +ALWAYS: 'always'; + +NAME: 'name'; +DVAR: 'dvar'; +CYCLE: 'cycle'; +FILE: 'file'; +CONDITION: 'condition'; +INCLUDE: 'include'; +LOWERBOUND: 'lower_bound'; +UPPERBOUND: 'upper_bound'; +INTEGERTYPE: 'integer'; +UNITS: 'units'; +CONVERTUNITS: 'convert_to_units'; +TYPE: 'type'; +OUTPUT: 'output'; +CASE: 'case'; +ORDER: 'order'; +EXPRESSION: 'expression'; +LHSGTRHS: 'lhs_gt_rhs'; +LHSLTRHS: 'lhs_lt_rhs'; +WEIGHT: 'weight'; +FUNCTION: 'function'; +FROM_WRESL_FILE: 'from_wresl_file'; +UPPERUNBOUNDED: 'upper_unbounded'; +LOWERUNBOUNDED: 'lower_unbounded'; + +SVAR: '{' IDENT '}'; +IDENT : LETTER (LETTER | DIGIT | SYMBOLS )*; +IDENT1 : DIGIT (LETTER | DIGIT | SYMBOLS )*; +IDENT2 : SYMBOLS (LETTER | DIGIT | SYMBOLS )*; + +WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}; +COMMENT : '!' .* ('\n'|'\r') {$channel = HIDDEN;}; + + + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluatorTreeWalker.g b/wrims-core/src/main/antlr/wrimsv2/evaluator/ValueEvaluatorTreeWalker.g similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluatorTreeWalker.g rename to wrims-core/src/main/antlr/wrimsv2/evaluator/ValueEvaluatorTreeWalker.g index 09a07bae8..c363e8031 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluatorTreeWalker.g +++ b/wrims-core/src/main/antlr/wrimsv2/evaluator/ValueEvaluatorTreeWalker.g @@ -1,292 +1,292 @@ -tree grammar ValueEvaluatorTreeWalker; - -options { - language = Java; - tokenVocab=ValueEvaluatorTree; - ASTLabelType=CommonTree; -} - -@header { - package wrimsv2.evaluator; - - import org.antlr.runtime.ANTLRFileStream; - import org.antlr.runtime.CharStream; - import org.antlr.runtime.CommonTokenStream; - import org.antlr.runtime.RecognitionException; - import org.antlr.runtime.TokenStream; - - import java.util.HashMap; - import wrimsv2.components.Error; - import wrimsv2.components.IntDouble; -} - -@members { - public static IntDouble evalValue; - public static boolean evalCondition; - public Stack sumIndex= new Stack (); - - @Override - public void reportError(RecognitionException e) { - Error.addEvaluationError(getErrorMessage(e, tokenNames)); - } -} - -evaluator - : expressionInput | - conditionInput - ; - -/////////////////// -/// input rules /// -/////////////////// - -expressionInput: ^('v:' expressionCollection){evalValue=$expressionCollection.id;}; -conditionInput: ^('c:' conditionStatement) {evalCondition=$conditionStatement.result;}; - -/////////////////// -/// basic rules /// -/////////////////// -lhsrhs: term|CONSTRAIN; - -//weight : (allnumber|(allnumber '*' TAFCFS)) (('+' allnumber)|('-' allnumber))?; - -units: IDENT|(IDENT '/' IDENT); - -fileName - : (':'|';'|'.'|'|'|SYMBOLS|'-'|'+'|BACKSLASH|IDENT|IDENT1|IDENT2|INTEGER|FLOAT|usedKeywords)+{ - } - ; - -externalFile - : (';'|'.'|'|'|SYMBOLS|'-'|'+'|INTEGER|FLOAT|IDENT|usedKeywords)+ - ; - -text : LETTER (LETTER | DIGIT )*; - -conditionStatement returns [boolean result] - : (r=relationStatementTerm{result=$r.result;})|ALWAYS{result=true;} - ; - -relationStatementTerm returns [boolean result] - : r0=relationRangeStatement{result=$r0.result;}|r1=relationStatementSeries{result=$r1.result;} - ; - -relationStatementSeries returns [boolean result] - : (^((s=('.and.'|'.or.')) r1=relationStatementTerm {result=$r1.result;} - (r2=relationStatementTerm {result=ValueEvaluation.relationStatementSeries(result, $r2.result, $s.text);}))) ; - -relationRangeStatement returns [boolean result] - : (r1=relationStatement{result=$r1.result;})|(r2=range_func{result=$r2.result;}) - ; - -relationStatement returns [boolean result] - : ^(s=relation e1=term e2=term){result=ValueEvaluation.relationStatement($e1.id, $e2.id, $s.text);} - ; - - -expressionCollection returns [IntDouble id] - :((term{id=$term.id;}) - |(tableSQL){id=$tableSQL.id;} - |(timeseriesWithUnits) - |((timeseries){id=$timeseries.id;}) - |(sumExpression{id=$sumExpression.id;})) - |(UPPERUNBOUNDED{id=new IntDouble(1e38,true);}) - |(LOWERUNBOUNDED{id=new IntDouble(-1e38,true);}) - ; - -func returns[IntDouble id]: - (max_func{id=$max_func.id;})| - (min_func{id=$min_func.id;})| - (int_func{id=$int_func.id;})| - (real_func{id=$real_func.id;})| - (abs_func{id=$abs_func.id;})| - (exp_func{id=$exp_func.id;})| - (log_func{id=$log_func.id;})| - (log10_func{id=$log10_func.id;})| - (pow_func{id=$pow_func.id;}); - -max_func returns[IntDouble id] - : ^(MAX (t1=term){id=$t1.id;} (t2=term{ - id=ValueEvaluation.max(id, $t2.id); - })) - ; - -min_func returns[IntDouble id] - : ^(MIN (t1=term){id=$t1.id;} (t2=term{ - id=ValueEvaluation.min(id, $t2.id); - })) - ; - -int_func returns[IntDouble id] - : ^(INT (t=term) { - id=ValueEvaluation.intFunc($t.id); - }) - ; - -real_func returns[IntDouble id] - : ^(REAL (t=term) { - id=ValueEvaluation.realFunc($t.id); - }) - ; - -abs_func returns[IntDouble id] - : ^(ABS (t=term) { - id=ValueEvaluation.abs($t.id); - }) - ; - -exp_func returns[IntDouble id] - : ^(EXP (t=term) { - id=ValueEvaluation.exp($t.id); - }) - ; - -log_func returns[IntDouble id] - : ^(LOG (t=term) { - id=ValueEvaluation.log($t.id); - }) - ; - -log10_func returns[IntDouble id] - : ^(LOG10 (t=term) { - id=ValueEvaluation.log10($t.id); - }) - ; - -pow_func returns[IntDouble id] - : ^(POW (t1=term) (t2=term) { - id=ValueEvaluation.pow($t1.id, $t2.id); - }) - ; - -range_func returns [boolean result] - : ^(RANGE MONTH m1=MONTH_CONST m2=MONTH_CONST ){result=ValueEvaluation.range($m1.text, $m2.text);}; - -timeseriesWithUnits - : TIMESERIES 'kind' '=' partC 'units' '=' IDENT - ; - -timeseries returns [IntDouble id] - : TIMESERIES {id=ValueEvaluation.timeseries();} - ; - - - -partC: (IDENT|IDENT1|usedKeywords) ('-' (IDENT|IDENT1|usedKeywords))*; - -usedKeywords: YEAR|MONTH|MONTH_CONST|PASTMONTH|RANGE|TAFCFS|DAYSIN|SUM|MAX|MIN|INT|ABS|LOG|LOG10|POW|MOD|SELECT|FROM|GIVEN|USE|WHERE -|CONSTRAIN|ALWAYS|NAME|DVAR|CYCLE|FILE|CONDITION|INCLUDE|LOWERBOUND|UPPERBOUND|INTEGERTYPE|UNITS|CONVERTUNITS|TYPE|OUTPUT -|CASE|ORDER|EXPRESSION|LHSGTRHS|LHSLTRHS|WEIGHT|FUNCTION|FROM_WRESL_FILE|UPPERUNBOUNDED|LOWERUNBOUNDED; - -tableSQL returns [IntDouble id] @init{String table=null; String select=null; String use=null; HashMap given=null; HashMap where=null;} - : ^(SELECT (selectName{select=$selectName.text;}) i1=IDENT{table=$i1.text;} - (a=assignStatement{given=new HashMap(); given.put($a.assignIdent, $a.value);})? (i2=IDENT{use=$i2.text;})? - (where_items{where=$where_items.where;})?) {id=ValueEvaluation.tableSQL(table, select, where, given, use);} - ; - -selectName: (IDENT |usedKeywords); - -where_items returns [HashMap where] - : ^(WHERE (r1=whereStatement{where=new HashMap(); where.put($r1.whereIdent, $r1.value);}) - (r=whereStatement{where.put($r.whereIdent, $r.value);})* ) - ; - - -//upperbound: IDENT|allnumber|^('*' allnumber TAFCFS); - -//lowerbound: IDENT|allnumber|^('*' allnumber TAFCFS); - -//sumExpression -// : SUM '(' I '=' e1=expression_sum ';' e2=expression_sum (';' (s='-')? INTEGER )? ')' e3=expression -// ; -//term_sum: (MONTH|MONTH_CONST|PASTMONTH|I|INTEGER|'(' expression_sum ')'); - -//unary_sum : ('-')? term_sum ; -//add_sum : unary_sum(('+' | '-') unary_sum)* ; -//expression_sum: add_sum ; - -//sumExpression was redesign. If not work, switch back to the original design above - -sumExpression returns [IntDouble id] @init{String s="";} - : ^(SUM IDENT{$id=new IntDouble(0, false);} t1=term t2=term ((('-'{s=s+"-";})? INTEGER {s=s+$INTEGER.text;}))? ({$id=new IntDouble(0, false);}) t3=term{$id=new IntDouble(0, false);}) - ; - -term returns [IntDouble id] - : (IDENT {$id=new IntDouble(0, false);}) - | (FLOAT {$id=ValueEvaluation.term_FLOAT($FLOAT.text);}) - | ( t=expression {$id=$t.id;}) - | ((knownTS{$id=ValueEvaluation.term_knownTS($knownTS.result);}) - | func{$id=$func.id;} - | (INTEGER {$id=ValueEvaluation.term_INTEGER($INTEGER.text);}) - | tafcfs_term{$id=$tafcfs_term.id;} - | YEAR{$id=ValueEvaluation.term_YEAR();} - | MONTH{$id=ValueEvaluation.term_MONTH();} - | MONTH_CONST{$id=ValueEvaluation.term_MONTH_CONST($MONTH_CONST.text);} - | PASTMONTH{$id=ValueEvaluation.term_PASTMONTH($PASTMONTH.text);} - | DAYSIN{$id=ValueEvaluation.daysIn();}) - | (SVAR{$id=ValueEvaluation.term_SVAR($SVAR.text.replace("{","").replace("}",""));}) - ; - -tafcfs_term returns [IntDouble id]: ^(TAFCFS term?) { - id=ValueEvaluation.tafcfs_term($TAFCFS.text, $term.id); -}; - -knownTS returns [IntDouble result] - : (f=function{result=$f.result;})|(p=pastCycleDV {result=$p.result;}) - ; - -//pastMonthTS -// : ((i1=IDENT)|TAFCFS) '(' ((p=PASTMONTH)|(i=I)|(pm=(MONTH_CONST '-' MONTH (('+'|'-') INTEGER)? ))|(mp=(MONTH '-' MONTH_CONST (('+'|'-') INTEGER)?))) ')' -// ; - -//preMonthTS -// : IDENT '(' (s='-')? INTEGER ')' -// ; - -pastCycleDV returns [IntDouble result] - : ^(i1=IDENT '[' i2=IDENT ']'{result=ValueEvaluation.pastCycleNoTimeArray($i1.text,$i2.text);}) - ; - -function returns [IntDouble result] - : (n=noArgFunction{result=$n.result;})|(a=argFunction{result=$a.result;}) - ; - -noArgFunction returns [IntDouble result] - : ^(IDENT '(' ')' {result=ValueEvaluation.noArgFunction($IDENT.text);}); - -argFunction returns [IntDouble result] @init{ArrayList> idArray = new ArrayList>();} - : ^(IDENT '(' (t1=term {ArrayList idArray1=new ArrayList();idArray1.add($t1.id);idArray.add(idArray1);}) ((t2=term{ArrayList idArray1=new ArrayList();idArray1.add($t2.id);idArray.add(idArray1);}))* ')'{result=ValueEvaluation.argFunction($IDENT.text,idArray);}); - -expression returns [IntDouble id] - : (^('+' t1=term t2=term{$id=ValueEvaluation.add($t1.id, $t2.id);}) - |^('-' t3=term t4=term{$id=ValueEvaluation.substract($t3.id, $t4.id);}) - |^('*' t5=term t6=term{$id=ValueEvaluation.mult($t5.id, $t6.id);}) - |^('/' t7=term t8=term{$id=ValueEvaluation.divide($t7.id, $t8.id);}) - |^(MOD t9=term t10=term{$id=ValueEvaluation.mod($t9.id, $t10.id);}) - |^(UNARY t11=term{$id=ValueEvaluation.unary("-", $t11.id);})) - ; - -relation returns [String text] - : '=='{text="==";} - | '<'{text="<";} - | '>'{text=">";} - | '>='{text=">=";} - | '<='{text="<=";} - ; - -whereStatement returns [String whereIdent, Number value] - : ^(WHERE ((i=IDENT{$whereIdent=$i.text;})|(u=usedKeywords{$whereIdent=$u.text;})) term{$value=ValueEvaluation.assignWhereStatement($term.id);}) - ; - -assignStatement returns [String assignIdent, Number value] - : ^('=' IDENT term {$assignIdent=$IDENT.text; $value=ValueEvaluation.assignWhereStatement($term.id);}) - ; - -number - : INTEGER - | FLOAT - ; - - - - +tree grammar ValueEvaluatorTreeWalker; + +options { + language = Java; + tokenVocab=ValueEvaluatorTree; + ASTLabelType=CommonTree; +} + +@header { + package wrimsv2.evaluator; + + import org.antlr.runtime.ANTLRFileStream; + import org.antlr.runtime.CharStream; + import org.antlr.runtime.CommonTokenStream; + import org.antlr.runtime.RecognitionException; + import org.antlr.runtime.TokenStream; + + import java.util.HashMap; + import wrimsv2.components.Error; + import wrimsv2.components.IntDouble; +} + +@members { + public static IntDouble evalValue; + public static boolean evalCondition; + public Stack sumIndex= new Stack (); + + @Override + public void reportError(RecognitionException e) { + Error.addEvaluationError(getErrorMessage(e, tokenNames)); + } +} + +evaluator + : expressionInput | + conditionInput + ; + +/////////////////// +/// input rules /// +/////////////////// + +expressionInput: ^('v:' expressionCollection){evalValue=$expressionCollection.id;}; +conditionInput: ^('c:' conditionStatement) {evalCondition=$conditionStatement.result;}; + +/////////////////// +/// basic rules /// +/////////////////// +lhsrhs: term|CONSTRAIN; + +//weight : (allnumber|(allnumber '*' TAFCFS)) (('+' allnumber)|('-' allnumber))?; + +units: IDENT|(IDENT '/' IDENT); + +fileName + : (':'|';'|'.'|'|'|SYMBOLS|'-'|'+'|BACKSLASH|IDENT|IDENT1|IDENT2|INTEGER|FLOAT|usedKeywords)+{ + } + ; + +externalFile + : (';'|'.'|'|'|SYMBOLS|'-'|'+'|INTEGER|FLOAT|IDENT|usedKeywords)+ + ; + +text : LETTER (LETTER | DIGIT )*; + +conditionStatement returns [boolean result] + : (r=relationStatementTerm{result=$r.result;})|ALWAYS{result=true;} + ; + +relationStatementTerm returns [boolean result] + : r0=relationRangeStatement{result=$r0.result;}|r1=relationStatementSeries{result=$r1.result;} + ; + +relationStatementSeries returns [boolean result] + : (^((s=('.and.'|'.or.')) r1=relationStatementTerm {result=$r1.result;} + (r2=relationStatementTerm {result=ValueEvaluation.relationStatementSeries(result, $r2.result, $s.text);}))) ; + +relationRangeStatement returns [boolean result] + : (r1=relationStatement{result=$r1.result;})|(r2=range_func{result=$r2.result;}) + ; + +relationStatement returns [boolean result] + : ^(s=relation e1=term e2=term){result=ValueEvaluation.relationStatement($e1.id, $e2.id, $s.text);} + ; + + +expressionCollection returns [IntDouble id] + :((term{id=$term.id;}) + |(tableSQL){id=$tableSQL.id;} + |(timeseriesWithUnits) + |((timeseries){id=$timeseries.id;}) + |(sumExpression{id=$sumExpression.id;})) + |(UPPERUNBOUNDED{id=new IntDouble(1e38,true);}) + |(LOWERUNBOUNDED{id=new IntDouble(-1e38,true);}) + ; + +func returns[IntDouble id]: + (max_func{id=$max_func.id;})| + (min_func{id=$min_func.id;})| + (int_func{id=$int_func.id;})| + (real_func{id=$real_func.id;})| + (abs_func{id=$abs_func.id;})| + (exp_func{id=$exp_func.id;})| + (log_func{id=$log_func.id;})| + (log10_func{id=$log10_func.id;})| + (pow_func{id=$pow_func.id;}); + +max_func returns[IntDouble id] + : ^(MAX (t1=term){id=$t1.id;} (t2=term{ + id=ValueEvaluation.max(id, $t2.id); + })) + ; + +min_func returns[IntDouble id] + : ^(MIN (t1=term){id=$t1.id;} (t2=term{ + id=ValueEvaluation.min(id, $t2.id); + })) + ; + +int_func returns[IntDouble id] + : ^(INT (t=term) { + id=ValueEvaluation.intFunc($t.id); + }) + ; + +real_func returns[IntDouble id] + : ^(REAL (t=term) { + id=ValueEvaluation.realFunc($t.id); + }) + ; + +abs_func returns[IntDouble id] + : ^(ABS (t=term) { + id=ValueEvaluation.abs($t.id); + }) + ; + +exp_func returns[IntDouble id] + : ^(EXP (t=term) { + id=ValueEvaluation.exp($t.id); + }) + ; + +log_func returns[IntDouble id] + : ^(LOG (t=term) { + id=ValueEvaluation.log($t.id); + }) + ; + +log10_func returns[IntDouble id] + : ^(LOG10 (t=term) { + id=ValueEvaluation.log10($t.id); + }) + ; + +pow_func returns[IntDouble id] + : ^(POW (t1=term) (t2=term) { + id=ValueEvaluation.pow($t1.id, $t2.id); + }) + ; + +range_func returns [boolean result] + : ^(RANGE MONTH m1=MONTH_CONST m2=MONTH_CONST ){result=ValueEvaluation.range($m1.text, $m2.text);}; + +timeseriesWithUnits + : TIMESERIES 'kind' '=' partC 'units' '=' IDENT + ; + +timeseries returns [IntDouble id] + : TIMESERIES {id=ValueEvaluation.timeseries();} + ; + + + +partC: (IDENT|IDENT1|usedKeywords) ('-' (IDENT|IDENT1|usedKeywords))*; + +usedKeywords: YEAR|MONTH|MONTH_CONST|PASTMONTH|RANGE|TAFCFS|DAYSIN|SUM|MAX|MIN|INT|ABS|LOG|LOG10|POW|MOD|SELECT|FROM|GIVEN|USE|WHERE +|CONSTRAIN|ALWAYS|NAME|DVAR|CYCLE|FILE|CONDITION|INCLUDE|LOWERBOUND|UPPERBOUND|INTEGERTYPE|UNITS|CONVERTUNITS|TYPE|OUTPUT +|CASE|ORDER|EXPRESSION|LHSGTRHS|LHSLTRHS|WEIGHT|FUNCTION|FROM_WRESL_FILE|UPPERUNBOUNDED|LOWERUNBOUNDED; + +tableSQL returns [IntDouble id] @init{String table=null; String select=null; String use=null; HashMap given=null; HashMap where=null;} + : ^(SELECT (selectName{select=$selectName.text;}) i1=IDENT{table=$i1.text;} + (a=assignStatement{given=new HashMap(); given.put($a.assignIdent, $a.value);})? (i2=IDENT{use=$i2.text;})? + (where_items{where=$where_items.where;})?) {id=ValueEvaluation.tableSQL(table, select, where, given, use);} + ; + +selectName: (IDENT |usedKeywords); + +where_items returns [HashMap where] + : ^(WHERE (r1=whereStatement{where=new HashMap(); where.put($r1.whereIdent, $r1.value);}) + (r=whereStatement{where.put($r.whereIdent, $r.value);})* ) + ; + + +//upperbound: IDENT|allnumber|^('*' allnumber TAFCFS); + +//lowerbound: IDENT|allnumber|^('*' allnumber TAFCFS); + +//sumExpression +// : SUM '(' I '=' e1=expression_sum ';' e2=expression_sum (';' (s='-')? INTEGER )? ')' e3=expression +// ; +//term_sum: (MONTH|MONTH_CONST|PASTMONTH|I|INTEGER|'(' expression_sum ')'); + +//unary_sum : ('-')? term_sum ; +//add_sum : unary_sum(('+' | '-') unary_sum)* ; +//expression_sum: add_sum ; + +//sumExpression was redesign. If not work, switch back to the original design above + +sumExpression returns [IntDouble id] @init{String s="";} + : ^(SUM IDENT{$id=new IntDouble(0, false);} t1=term t2=term ((('-'{s=s+"-";})? INTEGER {s=s+$INTEGER.text;}))? ({$id=new IntDouble(0, false);}) t3=term{$id=new IntDouble(0, false);}) + ; + +term returns [IntDouble id] + : (IDENT {$id=new IntDouble(0, false);}) + | (FLOAT {$id=ValueEvaluation.term_FLOAT($FLOAT.text);}) + | ( t=expression {$id=$t.id;}) + | ((knownTS{$id=ValueEvaluation.term_knownTS($knownTS.result);}) + | func{$id=$func.id;} + | (INTEGER {$id=ValueEvaluation.term_INTEGER($INTEGER.text);}) + | tafcfs_term{$id=$tafcfs_term.id;} + | YEAR{$id=ValueEvaluation.term_YEAR();} + | MONTH{$id=ValueEvaluation.term_MONTH();} + | MONTH_CONST{$id=ValueEvaluation.term_MONTH_CONST($MONTH_CONST.text);} + | PASTMONTH{$id=ValueEvaluation.term_PASTMONTH($PASTMONTH.text);} + | DAYSIN{$id=ValueEvaluation.daysIn();}) + | (SVAR{$id=ValueEvaluation.term_SVAR($SVAR.text.replace("{","").replace("}",""));}) + ; + +tafcfs_term returns [IntDouble id]: ^(TAFCFS term?) { + id=ValueEvaluation.tafcfs_term($TAFCFS.text, $term.id); +}; + +knownTS returns [IntDouble result] + : (f=function{result=$f.result;})|(p=pastCycleDV {result=$p.result;}) + ; + +//pastMonthTS +// : ((i1=IDENT)|TAFCFS) '(' ((p=PASTMONTH)|(i=I)|(pm=(MONTH_CONST '-' MONTH (('+'|'-') INTEGER)? ))|(mp=(MONTH '-' MONTH_CONST (('+'|'-') INTEGER)?))) ')' +// ; + +//preMonthTS +// : IDENT '(' (s='-')? INTEGER ')' +// ; + +pastCycleDV returns [IntDouble result] + : ^(i1=IDENT '[' i2=IDENT ']'{result=ValueEvaluation.pastCycleNoTimeArray($i1.text,$i2.text);}) + ; + +function returns [IntDouble result] + : (n=noArgFunction{result=$n.result;})|(a=argFunction{result=$a.result;}) + ; + +noArgFunction returns [IntDouble result] + : ^(IDENT '(' ')' {result=ValueEvaluation.noArgFunction($IDENT.text);}); + +argFunction returns [IntDouble result] @init{ArrayList> idArray = new ArrayList>();} + : ^(IDENT '(' (t1=term {ArrayList idArray1=new ArrayList();idArray1.add($t1.id);idArray.add(idArray1);}) ((t2=term{ArrayList idArray1=new ArrayList();idArray1.add($t2.id);idArray.add(idArray1);}))* ')'{result=ValueEvaluation.argFunction($IDENT.text,idArray);}); + +expression returns [IntDouble id] + : (^('+' t1=term t2=term{$id=ValueEvaluation.add($t1.id, $t2.id);}) + |^('-' t3=term t4=term{$id=ValueEvaluation.substract($t3.id, $t4.id);}) + |^('*' t5=term t6=term{$id=ValueEvaluation.mult($t5.id, $t6.id);}) + |^('/' t7=term t8=term{$id=ValueEvaluation.divide($t7.id, $t8.id);}) + |^(MOD t9=term t10=term{$id=ValueEvaluation.mod($t9.id, $t10.id);}) + |^(UNARY t11=term{$id=ValueEvaluation.unary("-", $t11.id);})) + ; + +relation returns [String text] + : '=='{text="==";} + | '<'{text="<";} + | '>'{text=">";} + | '>='{text=">=";} + | '<='{text="<=";} + ; + +whereStatement returns [String whereIdent, Number value] + : ^(WHERE ((i=IDENT{$whereIdent=$i.text;})|(u=usedKeywords{$whereIdent=$u.text;})) term{$value=ValueEvaluation.assignWhereStatement($term.id);}) + ; + +assignStatement returns [String assignIdent, Number value] + : ^('=' IDENT term {$assignIdent=$IDENT.text; $value=ValueEvaluation.assignWhereStatement($term.id);}) + ; + +number + : INTEGER + | FLOAT + ; + + + + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/grammar/WreslTree.g b/wrims-core/src/main/antlr/wrimsv2/wreslparser/grammar/WreslTree.g similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/grammar/WreslTree.g rename to wrims-core/src/main/antlr/wrimsv2/wreslparser/grammar/WreslTree.g index 5ceac676d..afb9aa6b4 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/grammar/WreslTree.g +++ b/wrims-core/src/main/antlr/wrimsv2/wreslparser/grammar/WreslTree.g @@ -1,752 +1,752 @@ - -grammar WreslTree; - -options { - language = Java; - output=AST; - ASTLabelType=CommonTree; -} -tokens { - NEGATION; - NEW_LINE; Op; Separator; Slack_Surplus; Sign; Constrain; Free; Simple; One; Two; - Weight_table; Assignment; External; - Local; Global; Scope; - Value; Case ; Dependants; VarInCycle; - Alias; Expression; - Dvar; Dvar_std; Dvar_nonStd; Dvar_std; Dvar_nonStd_local; Dvar_integer; - DvarTimeArray_std; DvarTimeArray_nonStd; - TimeArraySize; - SvarTimeArray_const; SvarTimeArray_case; - Svar_case; Svar_dss; Svar_const; Svar_sum; Sum_hdr; B_part; - Svar_table; Select; From; Where_content; Where_item_number; Given; Use; - Goal_simple; Goal_no_case; Goal_case ; Lhs_gt_rhs; Lhs_lt_rhs; Never; Penalty; - Lhs; Rhs; Weight; - Constraint_content; - Model; - Sequence; - Condition; - Order; - Kind; Units; - Lower='Lower'; Upper='Upper'; - Std='Std'; Unbounded='Unbounded'; - Exp='Exp'; - Include; - //Or='.Or.'; And='.And.'; Not='.Not.'; - Always; - LimitType; -} -@header { - package wrimsv2.wreslparser.grammar; - import wrimsv2.wreslparser.elements.LogUtils; - import wrimsv2.wreslparser.elements.Tools; - import wrimsv2.wreslplus.elements.VarCycleIndex; - import wrimsv2.commondata.wresldata.Param; - import java.util.Set; - import java.util.HashSet; - import java.util.Arrays; -} -@lexer::header { - package wrimsv2.wreslparser.grammar; - import wrimsv2.wreslparser.elements.LogUtils; - -} -@members { - - public String wresl_version = null; - public ArrayList model_in_sequence = new ArrayList(); - public ArrayList model_list = new ArrayList(); - - public CommonTree commonTree; - public String currentAbsolutePath; - public String currentAbsoluteParent; - public boolean sometest(String name) { - - return true; - } - - /// error message - public void displayRecognitionError(String[] tokenNames, - RecognitionException e) { - String hdr = getErrorHeader(e); - String msg = getErrorMessage(e, tokenNames); - LogUtils.errMsg(hdr + " " + msg); - } -} -@lexer::members { - List tokens = new ArrayList(); - public void emit(Token token) { - state.token = token; - tokens.add(token); - } - public Token nextToken() { - super.nextToken(); - if ( tokens.size()==0 ) { - return getEOFToken(); - } - return (Token)tokens.remove(0); - } - - /// error message - public void displayRecognitionError(String[] tokenNames, - RecognitionException e) { - String hdr = getErrorHeader(e); - String msg = getErrorMessage(e, tokenNames); - LogUtils.errMsg(hdr + " " + msg); - } -} - -mainFile - : sequence+ model+ - EOF! - ; - -version_tag : '[' 'wresl_version' vn=version_number ']' {wresl_version=$vn.text;} ; - -version_number : FLOAT; - -evaluator - : pattern+ - EOF! - ; - -pattern - : dvar | svar | goal | includeFile | alias | weight_table | external | integer - | svar_timeArray - ; - -integer - : integer_std | integer_nonStd | integer_timeArray_std | integer_timeArray_nonStd - ; - -// this is actually a binary -integer_std - : DEFINE ( '[' sc=LOCAL? ']' )? i=IDENT '{' INTEGER_WORD STD KIND k=STRING UNITS u=STRING '}' - -> ^(Dvar_integer Scope[$sc.text] $i Kind[$k.text] Units[$u.text]) - ; - -integer_nonStd - : DEFINE ( '[' sc=LOCAL? ']' )? i=IDENT '{' INTEGER_WORD lower_and_or_upper KIND k=STRING UNITS u=STRING '}' - -> ^(Dvar_integer Scope[$sc.text] $i lower_and_or_upper Kind[$k.text] Units[$u.text]) - ; - -integer_timeArray_std - : DEFINE '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' INTEGER_WORD STD KIND k=STRING UNITS u=STRING '}' - -> ^(Dvar_integer TimeArraySize[$ta.text] Scope[$sc.text] $i Kind[$k.text] Units[$u.text]) - ; - -integer_timeArray_nonStd - : DEFINE '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' INTEGER_WORD lower_and_or_upper KIND k=STRING UNITS u=STRING '}' - -> ^(Dvar_integer TimeArraySize[$ta.text] Scope[$sc.text] $i lower_and_or_upper Kind[$k.text] Units[$u.text]) - ; - -external : DEFINE ( '[' sc=LOCAL? ']' )? i=IDENT '{' EXTERNAL (e=DLL|e=F90) '}' --> ^(External Scope[$sc.text] $i Expression[$e.text] ) -; - - -weight_table - : OBJECTIVE ( '[' sc=LOCAL? ']' )? IDENT '=' '{' w+=weightItem+ '}' - -> ^(Weight_table Scope[$sc.text] $w+ ) - ; - -weightItem -@init{String r="0";} - : '[' IDENT ('(' ta=timeArraySize ')' { r = $ta.text;} )? ',' e=expression ']' (',')? - -> ^(IDENT TimeArraySize[r] Expression[$e.text]) - ; - -model -@init { String id = null;} - : MODEL i=IDENT '{' (pattern )+ '}' - {id = $i.text.toLowerCase(); - model_list.add(id);} - -> {model_in_sequence.contains(id)}? ^(Model IDENT[id] (pattern )+ ) - -> // ignore - ; -sequence -@init { String id = null;String timeStep=Param.undefined;} - : SEQUENCE s=IDENT '{' MODEL m=IDENT ( c=condition)? ORDER INTEGER (TIMESTEP t=TIMESTEPVALUE{timeStep=$t.text.toUpperCase();})? '}' - {id = $m.text.toLowerCase(); - model_in_sequence.add(id);} - -> ^(Sequence $s Model IDENT[id] Order INTEGER Condition[$c.text] TIMESTEP[timeStep]) - ; - -condition returns[String text, String dependants, String varInCycle] - : CONDITION - ( e=logical_expr {$text=$e.text; $dependants=$e.dependants; $varInCycle=$e.strVarInCycle;} - | ALWAYS {$text = Param.always; } - ) - ; - -includeFile - : INCLUDE ( '[' sc=LOCAL? ']' )? FILE_PATH - -> ^(Include Scope[$sc.text] FILE_PATH) - ; - -alias: DEFINE! (alias_simple|alias_timeArray_simple); - -alias_simple : ( '[' sc=LOCAL? ']' )? i=IDENT '{' ALIAS e=expression (KIND k=STRING)? (UNITS u=STRING)? '}' - -> ^(Alias Scope[$sc.text] $i Expression[$e.text] Kind[$k.text] Units[$u.text] Dependants[$e.dependants] VarInCycle[$e.strVarInCycle]) - ; - -alias_timeArray_simple : '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' ALIAS e=expression (KIND k=STRING)? (UNITS u=STRING)? '}' - -> ^(Alias TimeArraySize[$ta.text] Scope[$sc.text] $i Expression[$e.text] Kind[$k.text] Units[$u.text] Dependants[$e.dependants] VarInCycle[$e.strVarInCycle]) - ; - -goal -scope { String goalName; String caseName; int caseNumber;} -@init{ $goal::caseNumber = 0; } - : GOAL! (goal_simple | goal_case_or_nocase | goal_timeArray_simple | goal_timeArray_case_or_nocase ) - ; - -goal_simple - : ( '[' sc=LOCAL? ']' )? i=IDENT '{' v=constraint_statement '}' --> ^(Goal_simple Scope[$sc.text] $i Dependants[$v.dependants] Constraint_content[Tools.replace_ignoreChar($v.text)] VarInCycle[$v.varInCycle]) - ; - -goal_timeArray_simple - : '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' v=constraint_statement '}' --> ^(Goal_simple TimeArraySize[$ta.text] Scope[$sc.text] $i Dependants[$v.dependants+" "+$ta.dependant] Constraint_content[Tools.replace_ignoreChar($v.text)] VarInCycle[$v.varInCycle]) - ; - -goal_case_or_nocase - : ( '[' s=LOCAL? ']' )? i=IDENT { $goal::goalName = $i.text; } - '{' LHS l=expression - ( - ( goal_no_case_content[$l.text, $l.dependants, $l.strVarInCycle] -> ^( Goal_no_case Scope[$s.text] $i goal_no_case_content ) ) - | ( goal_case_content[$l.text, $l.dependants, $l.strVarInCycle]+ -> ^( Goal_case Scope[$s.text] $i goal_case_content+ ) ) - ) '}' - ; - -goal_timeArray_case_or_nocase - : '(' ta=timeArraySize ')' ( '[' s=LOCAL? ']' )? i=IDENT { $goal::goalName = $i.text; } - '{' LHS l=expression - ( - ( goal_no_case_content[$l.text, $ta.dependant+" "+$l.dependants, $l.strVarInCycle] -> ^( Goal_no_case TimeArraySize[$ta.text] Scope[$s.text] $i goal_no_case_content ) ) - | ( goal_case_content[$l.text, $ta.dependant+" "+$l.dependants, $l.strVarInCycle]+ -> ^( Goal_case TimeArraySize[$ta.text] Scope[$s.text] $i goal_case_content+ ) ) - ) '}' - ; - -goal_case_content[String l, String d, String vc] -@init{ String varInCycle_nullsRemoved = null; String dependants_nullsRemoved = null; } - : CASE i=IDENT { $goal::caseName = $i.text; $goal::caseNumber++; } - '{' c=condition RHS r=expression (s=sub_content[$l,$r.text])? '}' - { varInCycle_nullsRemoved = Tools.remove_nulls($vc+" "+$r.strVarInCycle+" "+$c.varInCycle); - dependants_nullsRemoved = Tools.remove_nulls($d+" "+$r.dependants+" "+$c.dependants); - } - -> {s!=null}? ^( Case $i Condition[$c.text] Dependants[dependants_nullsRemoved] VarInCycle[varInCycle_nullsRemoved] $s ) - -> ^( Case $i Condition[$c.text] Dependants[dependants_nullsRemoved] VarInCycle[varInCycle_nullsRemoved] Simple Lhs[$l] Op["="] Rhs[$r.text] ) - ; - -goal_no_case_content[String l, String d, String vc] -@init{ $goal::caseName = "default"; $goal::caseNumber=1;} - : RHS r=expression (s=sub_content[$l,$r.text])? - -> {s!=null}? Dependants[$d+" "+$r.dependants] VarInCycle[$vc+" "+$r.strVarInCycle] $s - -> Dependants[$d+" "+$r.dependants] VarInCycle[$vc+" "+$r.strVarInCycle] Simple Lhs[$l] Op["="] Rhs[$r.text] - ; - -sub_content[String l, String r] - : ( a=lhs_gt_rhs[$l,$r] ( b=lhs_lt_rhs[$l,$r])? - -> {b==null}? One[$a.type] $a - -> Two[$a.type+$b.type] $a $b - ) - - | ( c=lhs_lt_rhs[$l,$r] ( d=lhs_gt_rhs[$l,$r] -> Two[$c.type+$d.type] $c $d )? - -> {d==null}? One[$c.type] $c - -> Two[$c.type+$d.type] $c $d - ) - ; - -lhs_gt_rhs[String l, String r] returns[String type] -@init{ String penalty2Weight = "";} - : -LHS '>' RHS - ( ( CONSTRAIN { $type = "c"; } -> Constrain Lhs[$l] Op["<"] Rhs[$r] ) - | ( p=penalty { - if ($p.isZero) { $type = "f"; } - else if ($p.isNegative) { $type = "p"; penalty2Weight = $p.w; } - else { $type = "p"; penalty2Weight = "-"+$p.w; } - } - -> {$p.isZero}? Free Lhs[$l] Op[">"] Rhs[$r] - -> Penalty Lhs[$l] Op["="] Rhs[$r] Sign["-"] Kind["surplus"] Slack_Surplus["surplus__"+$goal::goalName+"_"+Integer.toString($goal::caseNumber)] Weight[penalty2Weight] - //-> Penalty Lhs[$l] Op["="] Rhs[$r] Sign["-"] Kind["surplus"] Slack_Surplus["surplus_"+$goal::goalName+"_"+$goal::caseName] Weight["-"+$p.w] - ) - ); - -lhs_lt_rhs[String l, String r] returns[String type] -@init{ String penalty2Weight = "";} - : -LHS '<' RHS - ( ( CONSTRAIN { $type = "c"; } -> Constrain Lhs[$l] Op[">"] Rhs[$r]) - | ( p=penalty { - if ($p.isZero) { $type = "f"; } - else if ($p.isNegative) { $type = "p"; penalty2Weight = $p.w; } - else { $type = "p"; penalty2Weight = "-"+$p.w; } - } - -> {$p.isZero}? Free Lhs[$l] Op["<"] Rhs[$r] - -> Penalty Lhs[$l] Op["="] Rhs[$r] Sign["+"] Kind["slack"] Slack_Surplus["slack__"+$goal::goalName+"_"+Integer.toString($goal::caseNumber)] Weight[penalty2Weight] - //-> Penalty Lhs[$l] Op["="] Rhs[$r] Sign["+"] Kind["slack"] Slack_Surplus["slack_"+$goal::goalName+"_"+$goal::caseName] Weight["-"+$p.w] - ) - ); - -penalty returns[String w, boolean isZero, boolean isNegative] - : PENALTY n=expression - { $w=$n.text; - $isZero = false; - $isNegative = false; - - try { - double p = Double.parseDouble($n.text); - if ( p == 0 ) { $isZero = true; $w = "0";} - else if ( p < 0 ) { $isNegative = true; $w = $n.text.replace("-","");} - else { $w = $n.text;} - } - catch (Exception e) { - - $w = "("+$n.text+")"; -// String ptext=$n.text; -// Integer lineNumber=$pt.getLine(); -// Integer columnNumber=$pt.getCharPositionInLine(); -// if (ptext.substring(0,1).equals("-")) { -// $isNegative = true; -// $w = ptext.substring(1,ptext.length()); -// } - } - } ; - -svar : DEFINE! (svar_dss | svar_expr | svar_sum | svar_table | svar_case ) ; - -svar_timeArray : DEFINE! ( svar_timeArray_expr | svar_timeArray_case| svar_timeArray_table | svar_timeArray_sum ) ; - -dvar : DEFINE! (dvar_std | dvar_nonStd ) ; - -svar_case : ( '[' sc=LOCAL? ']' )? i=IDENT '{' case_content+ '}' --> ^(Svar_case Scope[$sc.text] $i case_content+ ) ; - -svar_timeArray_case : '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' case_content+ '}' --> ^(SvarTimeArray_case TimeArraySize[$ta.text] Dependants[$ta.dependant] Scope[$sc.text] $i case_content+ ) ; - -case_content -@init{ String dependants_nullsRemoved = ""; String varInCycle_nullsRemoved = ""; } - : CASE i=IDENT '{' c=condition - { varInCycle_nullsRemoved = Tools.remove_nulls($c.varInCycle); - dependants_nullsRemoved = Tools.remove_nulls($c.dependants); } - - ( table_content - -> ^(Case $i Condition[$c.text] Dependants[dependants_nullsRemoved] VarInCycle[varInCycle_nullsRemoved] table_content ) - - | value_content - -> ^(Case $i Condition[$c.text] Dependants[dependants_nullsRemoved] VarInCycle[varInCycle_nullsRemoved] value_content ) - - | sum_content - -> ^(Case $i Condition[$c.text] Dependants[dependants_nullsRemoved] VarInCycle[varInCycle_nullsRemoved] sum_content ) - -) '}' -; - -value_content : VALUE e=expression -> Value[$e.text] Dependants[$e.dependants] VarInCycle[$e.strVarInCycle]; - -svar_table : - ( '[' sc=LOCAL? ']' )? i=IDENT '{' table_content '}' --> ^(Svar_table Scope[$sc.text] $i table_content ) - ; - -svar_timeArray_table : - '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' table_content '}' --> ^(Svar_table TimeArraySize[$ta.text] Scope[$sc.text] $i table_content ) - ; - -table_content : SELECT s=IDENT FROM f=IDENT - (GIVEN g=assignment USE u=IDENT)? - (WHERE w=where_items)? - --> ^( SELECT $s FROM $f (GIVEN $g Dependants[$g.dependants] VarInCycle[$g.varInCycle] USE $u)? (WHERE $w Dependants[$w.dependants])? ) -; - -where_items returns[String dependants] - : ai=assignment (',' a=assignment {$dependants =$dependants + " " + $a.dependants; } )* - {$dependants =$dependants + " " + $ai.dependants; } - ; - -svar_expr : - ( '[' sc=LOCAL ']' )? IDENT '{' VALUE e=expression'}' - -> ^(Svar_const Scope[$sc.text] IDENT Expression[$e.text] Dependants[$e.dependants] VarInCycle[$e.strVarInCycle]) - ; - -svar_timeArray_expr : - '(' ta=timeArraySize ')' ( '[' sc=LOCAL ']' )? IDENT '{' VALUE e=expression'}' - -> ^(SvarTimeArray_const TimeArraySize[$ta.text] Scope[$sc.text] IDENT Expression[$e.text] Dependants[$e.dependants+" "+$ta.dependant] VarInCycle[$e.strVarInCycle]) - ; - -svar_sum : ( '[' sc=LOCAL ']' )? IDENT '{' sum_content '}' - -> ^(Svar_sum Scope[$sc.text] IDENT sum_content ) - ; - -svar_timeArray_sum : '(' ta=timeArraySize ')' ( '[' sc=LOCAL ']' )? IDENT '{' sum_content '}' - -> ^(Svar_sum TimeArraySize[$ta.text] Scope[$sc.text] IDENT sum_content ) - ; - -sum_content returns[Set setVarInCycle] :SUM hdr=sum_header e=expression -{ - $setVarInCycle = $e.setVarInCycle; -} --> ^( Sum_hdr[$hdr.text] Expression[$e.text] Dependants[$hdr.dependants+" "+$e.dependants] VarInCycle[$e.strVarInCycle]) -; - -sum_header returns[String dependants] - : ( '(' 'i=' e1=expression ',' e2=expression (',' '-'? INTEGER )? ')' ) - {$dependants = $e1.dependants + " " +$e2.dependants;} - ; - -svar_dss : - ( '[' sc=LOCAL ']' )? IDENT '{' TIMESERIES b=STRING? KIND k=STRING UNITS u=STRING (CONVERT c=STRING)? '}' - -> ^(Svar_dss Scope[$sc.text] IDENT B_part[$b.text] Kind $k Units $u CONVERT[$c.text]) - ; - -timeArraySize -returns[String dependant] -@init { String dependant = ""; } - : INTEGER - | ( i=IDENT { $dependant=$i.text; } ) - ; - -dvar_std : - ( '(' ta=timeArraySize ')')? ( '[' sc=LOCAL ']' )? IDENT '{' STD KIND k=STRING UNITS u=STRING '}' - -> {ta==null}? ^(Dvar_std Scope[$sc.text] IDENT Kind $k Units $u) - -> ^(DvarTimeArray_std TimeArraySize[$ta.text] Scope[$sc.text] IDENT Kind $k Units $u) - ; - -dvar_nonStd : - ( '(' ta=timeArraySize ')')? ( '[' sc=LOCAL ']' )? IDENT '{' lower_and_or_upper KIND k=STRING UNITS u=STRING '}' - -> {ta==null}? ^(Dvar_nonStd Scope[$sc.text] IDENT lower_and_or_upper Kind $k Units $u) - -> ^(DvarTimeArray_nonStd TimeArraySize[$ta.text] Scope[$sc.text] IDENT lower_and_or_upper Kind $k Units $u) - ; - -lower_and_or_upper : lower_upper - | upper_lower ; - -lower_upper : lower (u=upper)? - -> {u==null}? lower Upper LimitType[Param.upper_unbounded] - -> lower $u - ; -upper_lower : upper (l=lower)? - -> {l==null}? Lower LimitType["0"] upper - -> $l upper - ; - -lower: LOWER ( UNBOUNDED -> Lower LimitType[Param.lower_unbounded] | e=expression -> Lower LimitType[$e.tree.toStringTree().replaceAll("\\s+", "")] ) ; -upper: UPPER ( UNBOUNDED -> Upper LimitType[Param.upper_unbounded] | e=expression -> Upper LimitType[$e.tree.toStringTree().replaceAll("\\s+", "")] ) ; - - -/// IDENT =, <, > /// - - -constraint_statement returns[String text, String dependants, String varInCycle] - : c=constraint_statement_preprocessed - - { $text = Tools.replace_ignoreChar($c.text); - $text = Tools.replace_seperator($text); - $dependants = $c.dependants; - $varInCycle = $c.varInCycle; - }; - -constraint_statement_preprocessed returns[String dependants, String varInCycle] - : c=expression ( '<' | '>' | '=' ) d=expression - { $dependants = $c.dependants + " " + $d.dependants; - $varInCycle = $c.strVarInCycle + " " + $d.strVarInCycle; - } - - ; - - -assignment returns[String dependants, String varInCycle] - : t=term_simple '=' e=expression - { $dependants = Tools.remove_nulls($e.dependants); - $varInCycle = Tools.remove_nulls($e.strVarInCycle);} - -> Assignment[$t.text+"="+$e.text] - ; - -lt_or_gt : term_simple ( '<' | '>' ) expression ; -le_or_ge : term_simple ( '<=' | '>=' ) expression ; -equal_statement : term_simple '==' expression ; - -/// Expression /// -number : INTEGER | FLOAT ; - -term_simple : ident | number | function ; - -ident: IDENT ; - -array_iterator : '$m' ; - -term : i=ident {$expression::SV.add($i.text.toLowerCase());} - | array_iterator - | number - | function - | '(' e=expression ')' {$expression::SV.addAll($e.members);$expression::varInCycle.addAll($e.setVarInCycle);} - | '(' s=sum_content ')' {$expression::varInCycle.addAll($s.setVarInCycle);} - ; - -unary : ('+'! | negation)? term ; - -negation : '-' -> NEGATION["-"] ; - -mult : unary (('*' | '/' ) unary)* ; - -add : mult (('+' | '-') mult)* ; - -logical_expr returns[Set members, String dependants, Set setVarInCycle, String strVarInCycle] -scope { Set SV; Set varInCycle } -@init { $logical_expr::SV = new HashSet(); - $logical_expr::varInCycle = new HashSet(); - String dependants = null; - String strVarInCycle = null; } - : c_unary ( bin c_unary )* - - { - //$logical_expr::SV.removeAll(reservedSet); - $members = $logical_expr::SV; - for (String s : $logical_expr::SV) { - - $dependants = $dependants +" "+s; - } - - $setVarInCycle = $logical_expr::varInCycle; - for (String s : $logical_expr::varInCycle) { - - $strVarInCycle = $strVarInCycle +" "+s; - } - }; - -expression returns[String text, Set members, String dependants, Set setVarInCycle, String strVarInCycle] -scope { Set SV; Set varInCycle } -@init { $expression::SV = new HashSet(); - $expression::varInCycle = new HashSet(); - String dependants = ""; - String strVarInCycle = ""; } - : - add - { $text = Tools.replace_ignoreChar($add.text); - $text = Tools.replace_seperator($text); - - //$expression::SV.removeAll(reservedSet); - $members = $expression::SV; - for (String s : $expression::SV) { - - $dependants = $dependants +" "+s; - } - - $setVarInCycle = $expression::varInCycle; - for (String s : $expression::varInCycle) { - - $strVarInCycle = $strVarInCycle +" "+s; - } - }; - -c_term - : ( expression relation expression ) => e1=expression relation e2=expression - { - $logical_expr::SV.addAll($e1.members); - $logical_expr::SV.addAll($e2.members); - $logical_expr::varInCycle.addAll($e1.setVarInCycle); - $logical_expr::varInCycle.addAll($e2.setVarInCycle); - } - | function_logical - | ( '(' logical_expr ')' ) => '(' e=logical_expr ')' - { - $logical_expr::SV.addAll($e.members); - $logical_expr::varInCycle.addAll($e.setVarInCycle); - } - ; - -c_unary : (c_negation)? c_term ; - -c_negation : NOT -> NOT[".NOT."] ; - - - -relation : '>' | '<' | '>=' | '<=' | '==' | '/=' ; - -bin : OR -> OR[".OR."] | AND -> AND[".AND."] ; - -/// End Expression /// - -/// Intrinsic functions /// - -//range_func -// : RANGE '(' MONTH ',' MONTH_CONST ',' MONTH_CONST ')' ; - -function : external_func | max_func | min_func | int_func | round_func | var_model ; - -function_logical : range_func ; - -var_model: var_model_noTimeArray|var_model_timeArray|var_modelindex_noTimeArray|var_modelindex_TimeArray - ; - -var_model_noTimeArray - : varName=IDENT '[' cycleName = IDENT ']' - { $expression::varInCycle.add($varName.text+'['+$cycleName.text+']' );} ; //{ $expression::DV.add($i.text.toLowerCase());} ; - -var_model_timeArray - : varName=IDENT '[' cycleName = IDENT ']' '(' e=expression ')' - { $expression::varInCycle.add($varName.text+'['+$cycleName.text+']'+'(' + $e.text +')' );} ; //{ $expression::DV.add($i.text.toLowerCase());} ; - -var_modelindex_noTimeArray - : varName=IDENT '[' cycleIndex=('-' INTEGER) ']' { - if (!VarCycleIndex.varCycleIndexList.contains(varName)){ - VarCycleIndex.varCycleIndexList.add($varName.text.toLowerCase()); - } - }; - -var_modelindex_TimeArray - : varName=IDENT '[' cycleIndex=('-' INTEGER) ']' '(' e=expression ')' { - if (!VarCycleIndex.varCycleIndexList.contains(varName)){ - VarCycleIndex.varCycleIndexList.add($varName.text.toLowerCase()); - } - }; - -external_func // this could be timeseries function - : i=IDENT {$expression::SV.add($i.text);} '(' ie=expression (',' e=expression {$expression::SV.addAll($e.members);$expression::varInCycle.addAll($e.setVarInCycle);} )* ')' - { $expression::SV.addAll($ie.members);$expression::varInCycle.addAll($ie.setVarInCycle);} // $expression::EX.add($i.text.toLowerCase()); - - ; - -range_func : RANGE '(' IDENT ',' ( IDENT | number ) ',' ( IDENT | number ) ')' ; - -max_func - : MAX '(' ie=expression (',' e=expression - { - $expression::SV.addAll($e.members); - $expression::varInCycle.addAll($e.setVarInCycle); - } - - )+ ')' - - { - $expression::SV.addAll($ie.members); - $expression::varInCycle.addAll($ie.setVarInCycle); - } - ; - -min_func - : MIN '(' ie=expression (',' e=expression - { - $expression::SV.addAll($e.members); - $expression::varInCycle.addAll($e.setVarInCycle); - } - - )+ ')' - - { - $expression::SV.addAll($ie.members); - $expression::varInCycle.addAll($ie.setVarInCycle); - } - ; - -int_func - : INT '(' e=expression ')' - { - $expression::SV.addAll($e.members); - $expression::varInCycle.addAll($e.setVarInCycle); - } - ; - -round_func - : ROUND '(' e=expression ')' - { - $expression::SV.addAll($e.members); - $expression::varInCycle.addAll($e.setVarInCycle); - } - ; - -/// End Intrinsic functions /// - -COMMENT : ('!'|'#') .* ('\n'|'\r') {skip();}; //{$channel = HIDDEN;}; -MULTILINE_COMMENT : '/*' .* '*/' {skip();}; //{$channel = HIDDEN;}; - -fragment LETTER : ('a'..'z' | 'A'..'Z') ; -fragment DIGIT : '0'..'9'; -INTEGER : DIGIT+ ; -FLOAT : (INTEGER? '.' INTEGER) | (INTEGER '.') ; - - -/// logical /// -AND : '.and.' | '.AND.' ; -OR : '.or.' | '.OR.' ; -NOT : '.not.' | '.NOT.' ; - -/// reserved keywords /// -PENALTY : 'penalty' | 'PENALTY' | 'Penalty'; -CONSTRAIN : 'constrain' | 'CONSTRAIN' | 'Constrain'; -INT : 'int' | 'INT' | 'Int' ; -ROUND : 'round' | 'ROUND' | 'Round' ; -SUM : 'sum' | 'SUM' | 'Sum' ; -RANGE : 'range' | 'RANGE' | 'Range' ; -MAX : 'max' | 'MAX' | 'Max' ; -MIN : 'min' | 'MIN' | 'Min' ; -VALUE : 'value' | 'VALUE' | 'Value' ; -LOCAL : 'local'| 'LOCAL' | 'Local' ; -OBJECTIVE: 'objective' | 'Objective' | 'OBJECTIVE'; -TIMESERIES: 'timeseries' | 'TIMESERIES' | 'Timeseries'; -SELECT : 'select' | 'Select' | 'SELECT' ; -FROM: 'from' | 'From' | 'FROM' ; -WHERE : 'where' | 'Where' | 'WHERE'; -GIVEN: 'given' | 'Given' | 'GIVEN' ; -USE: 'use' | 'Use' | 'USE' ; -CASE : 'case' | 'Case' | 'CASE' ; -LHS: 'lhs' | 'LHS' ; -RHS: 'rhs' | 'RHS' ; -EXTERNAL : 'EXTERNAL' | 'external' | 'External' ; -F90 : 'f90' | 'F90' ; -DLL : IDENT ('.dll' | '.DLL' ); -INTEGER_WORD: 'integer' | 'INTEGER' | 'Integer' ; -STD : 'std' | 'STD' ; -UNITS : 'units' | 'UNITS' | 'Units' ; -CONVERT : 'convert' | 'CONVERT' | 'Convert'; -ALIAS : 'alias' | 'ALIAS' | 'Alias'; -KIND : 'kind' | 'KIND' | 'Kind'; -GOAL : 'goal' | 'GOAL' | 'Goal'; -DEFINE :'define' | 'DEFINE' | 'Define' ; -ALWAYS :'always' | 'ALWAYS' | 'Always' ; -CONDITION : 'condition' | 'CONDITION' | 'Condition' ; -SEQUENCE : 'sequence' | 'SEQUENCE' | 'Sequence'; -MODEL : 'model' | 'MODEL' | 'Model'; -ORDER : 'order' | 'ORDER' | 'Order'; -TIMESTEP : 'timestep'|'TIMESTEP'|'TimeStep'; -TIMESTEPVALUE: '1mon'|'1MON'|'1day'|'1DAY'; -INCLUDE : 'include' | 'INCLUDE' | 'Include'; -LOWER : 'lower' | 'LOWER' | 'Lower' ; -UPPER : 'upper' | 'UPPER' | 'Upper' ; -UNBOUNDED : 'unbounded' | 'Unbounded' | 'UNBOUNDED'; - -/// include file path /// -FILE_PATH : '\'' DIR_SPLIT? (DIR_ELEMENT | DIR_UP)* WRESL_FILE '\'' ; -fragment WRESL_EXT : '.wresl' | '.WRESL' ; -fragment WRESL_FILE : (LETTER | DIGIT | '_' |'-' )+ WRESL_EXT ; -fragment DIR_ELEMENT : (LETTER | DIGIT | '_' | '-' )+ '\\' ; -fragment DIR_UP : ('..') '\\' ; -fragment DIR_SPLIT : '\\' ; - - -STRING : '\'' IDENT( '-' | '/' | IDENT )* '\''; - -IDENT_FOLLOWED_BY_LOGICAL - : i=IDENT{$i.setType(IDENT); emit($i);} - ( a=AND { $a.setType(AND); emit($a);} - | a=OR { $a.setType(OR); emit($a);} - | a=NOT { $a.setType(NOT); emit($a);} - ); - -INTEGER_FOLLOWED_BY_LOGICAL - : i=INTEGER{$i.setType(INTEGER); emit($i);} - ( a=AND { $a.setType(AND); emit($a);} - | a=OR { $a.setType(OR); emit($a);} - | a=NOT { $a.setType(NOT); emit($a);} - ); - -IDENT : LETTER (LETTER | DIGIT | '_')*; - -WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}; - -COMMENT_LAST_LINE : ('!'|'#') (~('\n' | '\r'))* {skip();}; -//IGNORE : . {skip();}; + +grammar WreslTree; + +options { + language = Java; + output=AST; + ASTLabelType=CommonTree; +} +tokens { + NEGATION; + NEW_LINE; Op; Separator; Slack_Surplus; Sign; Constrain; Free; Simple; One; Two; + Weight_table; Assignment; External; + Local; Global; Scope; + Value; Case ; Dependants; VarInCycle; + Alias; Expression; + Dvar; Dvar_std; Dvar_nonStd; Dvar_std; Dvar_nonStd_local; Dvar_integer; + DvarTimeArray_std; DvarTimeArray_nonStd; + TimeArraySize; + SvarTimeArray_const; SvarTimeArray_case; + Svar_case; Svar_dss; Svar_const; Svar_sum; Sum_hdr; B_part; + Svar_table; Select; From; Where_content; Where_item_number; Given; Use; + Goal_simple; Goal_no_case; Goal_case ; Lhs_gt_rhs; Lhs_lt_rhs; Never; Penalty; + Lhs; Rhs; Weight; + Constraint_content; + Model; + Sequence; + Condition; + Order; + Kind; Units; + Lower='Lower'; Upper='Upper'; + Std='Std'; Unbounded='Unbounded'; + Exp='Exp'; + Include; + //Or='.Or.'; And='.And.'; Not='.Not.'; + Always; + LimitType; +} +@header { + package wrimsv2.wreslparser.grammar; + import wrimsv2.wreslparser.elements.LogUtils; + import wrimsv2.wreslparser.elements.Tools; + import wrimsv2.wreslplus.elements.VarCycleIndex; + import wrimsv2.commondata.wresldata.Param; + import java.util.Set; + import java.util.HashSet; + import java.util.Arrays; +} +@lexer::header { + package wrimsv2.wreslparser.grammar; + import wrimsv2.wreslparser.elements.LogUtils; + +} +@members { + + public String wresl_version = null; + public ArrayList model_in_sequence = new ArrayList(); + public ArrayList model_list = new ArrayList(); + + public CommonTree commonTree; + public String currentAbsolutePath; + public String currentAbsoluteParent; + public boolean sometest(String name) { + + return true; + } + + /// error message + public void displayRecognitionError(String[] tokenNames, + RecognitionException e) { + String hdr = getErrorHeader(e); + String msg = getErrorMessage(e, tokenNames); + LogUtils.errMsg(hdr + " " + msg); + } +} +@lexer::members { + List tokens = new ArrayList(); + public void emit(Token token) { + state.token = token; + tokens.add(token); + } + public Token nextToken() { + super.nextToken(); + if ( tokens.size()==0 ) { + return getEOFToken(); + } + return (Token)tokens.remove(0); + } + + /// error message + public void displayRecognitionError(String[] tokenNames, + RecognitionException e) { + String hdr = getErrorHeader(e); + String msg = getErrorMessage(e, tokenNames); + LogUtils.errMsg(hdr + " " + msg); + } +} + +mainFile + : sequence+ model+ + EOF! + ; + +version_tag : '[' 'wresl_version' vn=version_number ']' {wresl_version=$vn.text;} ; + +version_number : FLOAT; + +evaluator + : pattern+ + EOF! + ; + +pattern + : dvar | svar | goal | includeFile | alias | weight_table | external | integer + | svar_timeArray + ; + +integer + : integer_std | integer_nonStd | integer_timeArray_std | integer_timeArray_nonStd + ; + +// this is actually a binary +integer_std + : DEFINE ( '[' sc=LOCAL? ']' )? i=IDENT '{' INTEGER_WORD STD KIND k=STRING UNITS u=STRING '}' + -> ^(Dvar_integer Scope[$sc.text] $i Kind[$k.text] Units[$u.text]) + ; + +integer_nonStd + : DEFINE ( '[' sc=LOCAL? ']' )? i=IDENT '{' INTEGER_WORD lower_and_or_upper KIND k=STRING UNITS u=STRING '}' + -> ^(Dvar_integer Scope[$sc.text] $i lower_and_or_upper Kind[$k.text] Units[$u.text]) + ; + +integer_timeArray_std + : DEFINE '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' INTEGER_WORD STD KIND k=STRING UNITS u=STRING '}' + -> ^(Dvar_integer TimeArraySize[$ta.text] Scope[$sc.text] $i Kind[$k.text] Units[$u.text]) + ; + +integer_timeArray_nonStd + : DEFINE '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' INTEGER_WORD lower_and_or_upper KIND k=STRING UNITS u=STRING '}' + -> ^(Dvar_integer TimeArraySize[$ta.text] Scope[$sc.text] $i lower_and_or_upper Kind[$k.text] Units[$u.text]) + ; + +external : DEFINE ( '[' sc=LOCAL? ']' )? i=IDENT '{' EXTERNAL (e=DLL|e=F90) '}' +-> ^(External Scope[$sc.text] $i Expression[$e.text] ) +; + + +weight_table + : OBJECTIVE ( '[' sc=LOCAL? ']' )? IDENT '=' '{' w+=weightItem+ '}' + -> ^(Weight_table Scope[$sc.text] $w+ ) + ; + +weightItem +@init{String r="0";} + : '[' IDENT ('(' ta=timeArraySize ')' { r = $ta.text;} )? ',' e=expression ']' (',')? + -> ^(IDENT TimeArraySize[r] Expression[$e.text]) + ; + +model +@init { String id = null;} + : MODEL i=IDENT '{' (pattern )+ '}' + {id = $i.text.toLowerCase(); + model_list.add(id);} + -> {model_in_sequence.contains(id)}? ^(Model IDENT[id] (pattern )+ ) + -> // ignore + ; +sequence +@init { String id = null;String timeStep=Param.undefined;} + : SEQUENCE s=IDENT '{' MODEL m=IDENT ( c=condition)? ORDER INTEGER (TIMESTEP t=TIMESTEPVALUE{timeStep=$t.text.toUpperCase();})? '}' + {id = $m.text.toLowerCase(); + model_in_sequence.add(id);} + -> ^(Sequence $s Model IDENT[id] Order INTEGER Condition[$c.text] TIMESTEP[timeStep]) + ; + +condition returns[String text, String dependants, String varInCycle] + : CONDITION + ( e=logical_expr {$text=$e.text; $dependants=$e.dependants; $varInCycle=$e.strVarInCycle;} + | ALWAYS {$text = Param.always; } + ) + ; + +includeFile + : INCLUDE ( '[' sc=LOCAL? ']' )? FILE_PATH + -> ^(Include Scope[$sc.text] FILE_PATH) + ; + +alias: DEFINE! (alias_simple|alias_timeArray_simple); + +alias_simple : ( '[' sc=LOCAL? ']' )? i=IDENT '{' ALIAS e=expression (KIND k=STRING)? (UNITS u=STRING)? '}' + -> ^(Alias Scope[$sc.text] $i Expression[$e.text] Kind[$k.text] Units[$u.text] Dependants[$e.dependants] VarInCycle[$e.strVarInCycle]) + ; + +alias_timeArray_simple : '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' ALIAS e=expression (KIND k=STRING)? (UNITS u=STRING)? '}' + -> ^(Alias TimeArraySize[$ta.text] Scope[$sc.text] $i Expression[$e.text] Kind[$k.text] Units[$u.text] Dependants[$e.dependants] VarInCycle[$e.strVarInCycle]) + ; + +goal +scope { String goalName; String caseName; int caseNumber;} +@init{ $goal::caseNumber = 0; } + : GOAL! (goal_simple | goal_case_or_nocase | goal_timeArray_simple | goal_timeArray_case_or_nocase ) + ; + +goal_simple + : ( '[' sc=LOCAL? ']' )? i=IDENT '{' v=constraint_statement '}' +-> ^(Goal_simple Scope[$sc.text] $i Dependants[$v.dependants] Constraint_content[Tools.replace_ignoreChar($v.text)] VarInCycle[$v.varInCycle]) + ; + +goal_timeArray_simple + : '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' v=constraint_statement '}' +-> ^(Goal_simple TimeArraySize[$ta.text] Scope[$sc.text] $i Dependants[$v.dependants+" "+$ta.dependant] Constraint_content[Tools.replace_ignoreChar($v.text)] VarInCycle[$v.varInCycle]) + ; + +goal_case_or_nocase + : ( '[' s=LOCAL? ']' )? i=IDENT { $goal::goalName = $i.text; } + '{' LHS l=expression + ( + ( goal_no_case_content[$l.text, $l.dependants, $l.strVarInCycle] -> ^( Goal_no_case Scope[$s.text] $i goal_no_case_content ) ) + | ( goal_case_content[$l.text, $l.dependants, $l.strVarInCycle]+ -> ^( Goal_case Scope[$s.text] $i goal_case_content+ ) ) + ) '}' + ; + +goal_timeArray_case_or_nocase + : '(' ta=timeArraySize ')' ( '[' s=LOCAL? ']' )? i=IDENT { $goal::goalName = $i.text; } + '{' LHS l=expression + ( + ( goal_no_case_content[$l.text, $ta.dependant+" "+$l.dependants, $l.strVarInCycle] -> ^( Goal_no_case TimeArraySize[$ta.text] Scope[$s.text] $i goal_no_case_content ) ) + | ( goal_case_content[$l.text, $ta.dependant+" "+$l.dependants, $l.strVarInCycle]+ -> ^( Goal_case TimeArraySize[$ta.text] Scope[$s.text] $i goal_case_content+ ) ) + ) '}' + ; + +goal_case_content[String l, String d, String vc] +@init{ String varInCycle_nullsRemoved = null; String dependants_nullsRemoved = null; } + : CASE i=IDENT { $goal::caseName = $i.text; $goal::caseNumber++; } + '{' c=condition RHS r=expression (s=sub_content[$l,$r.text])? '}' + { varInCycle_nullsRemoved = Tools.remove_nulls($vc+" "+$r.strVarInCycle+" "+$c.varInCycle); + dependants_nullsRemoved = Tools.remove_nulls($d+" "+$r.dependants+" "+$c.dependants); + } + -> {s!=null}? ^( Case $i Condition[$c.text] Dependants[dependants_nullsRemoved] VarInCycle[varInCycle_nullsRemoved] $s ) + -> ^( Case $i Condition[$c.text] Dependants[dependants_nullsRemoved] VarInCycle[varInCycle_nullsRemoved] Simple Lhs[$l] Op["="] Rhs[$r.text] ) + ; + +goal_no_case_content[String l, String d, String vc] +@init{ $goal::caseName = "default"; $goal::caseNumber=1;} + : RHS r=expression (s=sub_content[$l,$r.text])? + -> {s!=null}? Dependants[$d+" "+$r.dependants] VarInCycle[$vc+" "+$r.strVarInCycle] $s + -> Dependants[$d+" "+$r.dependants] VarInCycle[$vc+" "+$r.strVarInCycle] Simple Lhs[$l] Op["="] Rhs[$r.text] + ; + +sub_content[String l, String r] + : ( a=lhs_gt_rhs[$l,$r] ( b=lhs_lt_rhs[$l,$r])? + -> {b==null}? One[$a.type] $a + -> Two[$a.type+$b.type] $a $b + ) + + | ( c=lhs_lt_rhs[$l,$r] ( d=lhs_gt_rhs[$l,$r] -> Two[$c.type+$d.type] $c $d )? + -> {d==null}? One[$c.type] $c + -> Two[$c.type+$d.type] $c $d + ) + ; + +lhs_gt_rhs[String l, String r] returns[String type] +@init{ String penalty2Weight = "";} + : +LHS '>' RHS + ( ( CONSTRAIN { $type = "c"; } -> Constrain Lhs[$l] Op["<"] Rhs[$r] ) + | ( p=penalty { + if ($p.isZero) { $type = "f"; } + else if ($p.isNegative) { $type = "p"; penalty2Weight = $p.w; } + else { $type = "p"; penalty2Weight = "-"+$p.w; } + } + -> {$p.isZero}? Free Lhs[$l] Op[">"] Rhs[$r] + -> Penalty Lhs[$l] Op["="] Rhs[$r] Sign["-"] Kind["surplus"] Slack_Surplus["surplus__"+$goal::goalName+"_"+Integer.toString($goal::caseNumber)] Weight[penalty2Weight] + //-> Penalty Lhs[$l] Op["="] Rhs[$r] Sign["-"] Kind["surplus"] Slack_Surplus["surplus_"+$goal::goalName+"_"+$goal::caseName] Weight["-"+$p.w] + ) + ); + +lhs_lt_rhs[String l, String r] returns[String type] +@init{ String penalty2Weight = "";} + : +LHS '<' RHS + ( ( CONSTRAIN { $type = "c"; } -> Constrain Lhs[$l] Op[">"] Rhs[$r]) + | ( p=penalty { + if ($p.isZero) { $type = "f"; } + else if ($p.isNegative) { $type = "p"; penalty2Weight = $p.w; } + else { $type = "p"; penalty2Weight = "-"+$p.w; } + } + -> {$p.isZero}? Free Lhs[$l] Op["<"] Rhs[$r] + -> Penalty Lhs[$l] Op["="] Rhs[$r] Sign["+"] Kind["slack"] Slack_Surplus["slack__"+$goal::goalName+"_"+Integer.toString($goal::caseNumber)] Weight[penalty2Weight] + //-> Penalty Lhs[$l] Op["="] Rhs[$r] Sign["+"] Kind["slack"] Slack_Surplus["slack_"+$goal::goalName+"_"+$goal::caseName] Weight["-"+$p.w] + ) + ); + +penalty returns[String w, boolean isZero, boolean isNegative] + : PENALTY n=expression + { $w=$n.text; + $isZero = false; + $isNegative = false; + + try { + double p = Double.parseDouble($n.text); + if ( p == 0 ) { $isZero = true; $w = "0";} + else if ( p < 0 ) { $isNegative = true; $w = $n.text.replace("-","");} + else { $w = $n.text;} + } + catch (Exception e) { + + $w = "("+$n.text+")"; +// String ptext=$n.text; +// Integer lineNumber=$pt.getLine(); +// Integer columnNumber=$pt.getCharPositionInLine(); +// if (ptext.substring(0,1).equals("-")) { +// $isNegative = true; +// $w = ptext.substring(1,ptext.length()); +// } + } + } ; + +svar : DEFINE! (svar_dss | svar_expr | svar_sum | svar_table | svar_case ) ; + +svar_timeArray : DEFINE! ( svar_timeArray_expr | svar_timeArray_case| svar_timeArray_table | svar_timeArray_sum ) ; + +dvar : DEFINE! (dvar_std | dvar_nonStd ) ; + +svar_case : ( '[' sc=LOCAL? ']' )? i=IDENT '{' case_content+ '}' +-> ^(Svar_case Scope[$sc.text] $i case_content+ ) ; + +svar_timeArray_case : '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' case_content+ '}' +-> ^(SvarTimeArray_case TimeArraySize[$ta.text] Dependants[$ta.dependant] Scope[$sc.text] $i case_content+ ) ; + +case_content +@init{ String dependants_nullsRemoved = ""; String varInCycle_nullsRemoved = ""; } + : CASE i=IDENT '{' c=condition + { varInCycle_nullsRemoved = Tools.remove_nulls($c.varInCycle); + dependants_nullsRemoved = Tools.remove_nulls($c.dependants); } + + ( table_content + -> ^(Case $i Condition[$c.text] Dependants[dependants_nullsRemoved] VarInCycle[varInCycle_nullsRemoved] table_content ) + + | value_content + -> ^(Case $i Condition[$c.text] Dependants[dependants_nullsRemoved] VarInCycle[varInCycle_nullsRemoved] value_content ) + + | sum_content + -> ^(Case $i Condition[$c.text] Dependants[dependants_nullsRemoved] VarInCycle[varInCycle_nullsRemoved] sum_content ) + +) '}' +; + +value_content : VALUE e=expression -> Value[$e.text] Dependants[$e.dependants] VarInCycle[$e.strVarInCycle]; + +svar_table : + ( '[' sc=LOCAL? ']' )? i=IDENT '{' table_content '}' +-> ^(Svar_table Scope[$sc.text] $i table_content ) + ; + +svar_timeArray_table : + '(' ta=timeArraySize ')' ( '[' sc=LOCAL? ']' )? i=IDENT '{' table_content '}' +-> ^(Svar_table TimeArraySize[$ta.text] Scope[$sc.text] $i table_content ) + ; + +table_content : SELECT s=IDENT FROM f=IDENT + (GIVEN g=assignment USE u=IDENT)? + (WHERE w=where_items)? + +-> ^( SELECT $s FROM $f (GIVEN $g Dependants[$g.dependants] VarInCycle[$g.varInCycle] USE $u)? (WHERE $w Dependants[$w.dependants])? ) +; + +where_items returns[String dependants] + : ai=assignment (',' a=assignment {$dependants =$dependants + " " + $a.dependants; } )* + {$dependants =$dependants + " " + $ai.dependants; } + ; + +svar_expr : + ( '[' sc=LOCAL ']' )? IDENT '{' VALUE e=expression'}' + -> ^(Svar_const Scope[$sc.text] IDENT Expression[$e.text] Dependants[$e.dependants] VarInCycle[$e.strVarInCycle]) + ; + +svar_timeArray_expr : + '(' ta=timeArraySize ')' ( '[' sc=LOCAL ']' )? IDENT '{' VALUE e=expression'}' + -> ^(SvarTimeArray_const TimeArraySize[$ta.text] Scope[$sc.text] IDENT Expression[$e.text] Dependants[$e.dependants+" "+$ta.dependant] VarInCycle[$e.strVarInCycle]) + ; + +svar_sum : ( '[' sc=LOCAL ']' )? IDENT '{' sum_content '}' + -> ^(Svar_sum Scope[$sc.text] IDENT sum_content ) + ; + +svar_timeArray_sum : '(' ta=timeArraySize ')' ( '[' sc=LOCAL ']' )? IDENT '{' sum_content '}' + -> ^(Svar_sum TimeArraySize[$ta.text] Scope[$sc.text] IDENT sum_content ) + ; + +sum_content returns[Set setVarInCycle] :SUM hdr=sum_header e=expression +{ + $setVarInCycle = $e.setVarInCycle; +} +-> ^( Sum_hdr[$hdr.text] Expression[$e.text] Dependants[$hdr.dependants+" "+$e.dependants] VarInCycle[$e.strVarInCycle]) +; + +sum_header returns[String dependants] + : ( '(' 'i=' e1=expression ',' e2=expression (',' '-'? INTEGER )? ')' ) + {$dependants = $e1.dependants + " " +$e2.dependants;} + ; + +svar_dss : + ( '[' sc=LOCAL ']' )? IDENT '{' TIMESERIES b=STRING? KIND k=STRING UNITS u=STRING (CONVERT c=STRING)? '}' + -> ^(Svar_dss Scope[$sc.text] IDENT B_part[$b.text] Kind $k Units $u CONVERT[$c.text]) + ; + +timeArraySize +returns[String dependant] +@init { String dependant = ""; } + : INTEGER + | ( i=IDENT { $dependant=$i.text; } ) + ; + +dvar_std : + ( '(' ta=timeArraySize ')')? ( '[' sc=LOCAL ']' )? IDENT '{' STD KIND k=STRING UNITS u=STRING '}' + -> {ta==null}? ^(Dvar_std Scope[$sc.text] IDENT Kind $k Units $u) + -> ^(DvarTimeArray_std TimeArraySize[$ta.text] Scope[$sc.text] IDENT Kind $k Units $u) + ; + +dvar_nonStd : + ( '(' ta=timeArraySize ')')? ( '[' sc=LOCAL ']' )? IDENT '{' lower_and_or_upper KIND k=STRING UNITS u=STRING '}' + -> {ta==null}? ^(Dvar_nonStd Scope[$sc.text] IDENT lower_and_or_upper Kind $k Units $u) + -> ^(DvarTimeArray_nonStd TimeArraySize[$ta.text] Scope[$sc.text] IDENT lower_and_or_upper Kind $k Units $u) + ; + +lower_and_or_upper : lower_upper + | upper_lower ; + +lower_upper : lower (u=upper)? + -> {u==null}? lower Upper LimitType[Param.upper_unbounded] + -> lower $u + ; +upper_lower : upper (l=lower)? + -> {l==null}? Lower LimitType["0"] upper + -> $l upper + ; + +lower: LOWER ( UNBOUNDED -> Lower LimitType[Param.lower_unbounded] | e=expression -> Lower LimitType[$e.tree.toStringTree().replaceAll("\\s+", "")] ) ; +upper: UPPER ( UNBOUNDED -> Upper LimitType[Param.upper_unbounded] | e=expression -> Upper LimitType[$e.tree.toStringTree().replaceAll("\\s+", "")] ) ; + + +/// IDENT =, <, > /// + + +constraint_statement returns[String text, String dependants, String varInCycle] + : c=constraint_statement_preprocessed + + { $text = Tools.replace_ignoreChar($c.text); + $text = Tools.replace_seperator($text); + $dependants = $c.dependants; + $varInCycle = $c.varInCycle; + }; + +constraint_statement_preprocessed returns[String dependants, String varInCycle] + : c=expression ( '<' | '>' | '=' ) d=expression + { $dependants = $c.dependants + " " + $d.dependants; + $varInCycle = $c.strVarInCycle + " " + $d.strVarInCycle; + } + + ; + + +assignment returns[String dependants, String varInCycle] + : t=term_simple '=' e=expression + { $dependants = Tools.remove_nulls($e.dependants); + $varInCycle = Tools.remove_nulls($e.strVarInCycle);} + -> Assignment[$t.text+"="+$e.text] + ; + +lt_or_gt : term_simple ( '<' | '>' ) expression ; +le_or_ge : term_simple ( '<=' | '>=' ) expression ; +equal_statement : term_simple '==' expression ; + +/// Expression /// +number : INTEGER | FLOAT ; + +term_simple : ident | number | function ; + +ident: IDENT ; + +array_iterator : '$m' ; + +term : i=ident {$expression::SV.add($i.text.toLowerCase());} + | array_iterator + | number + | function + | '(' e=expression ')' {$expression::SV.addAll($e.members);$expression::varInCycle.addAll($e.setVarInCycle);} + | '(' s=sum_content ')' {$expression::varInCycle.addAll($s.setVarInCycle);} + ; + +unary : ('+'! | negation)? term ; + +negation : '-' -> NEGATION["-"] ; + +mult : unary (('*' | '/' ) unary)* ; + +add : mult (('+' | '-') mult)* ; + +logical_expr returns[Set members, String dependants, Set setVarInCycle, String strVarInCycle] +scope { Set SV; Set varInCycle } +@init { $logical_expr::SV = new HashSet(); + $logical_expr::varInCycle = new HashSet(); + String dependants = null; + String strVarInCycle = null; } + : c_unary ( bin c_unary )* + + { + //$logical_expr::SV.removeAll(reservedSet); + $members = $logical_expr::SV; + for (String s : $logical_expr::SV) { + + $dependants = $dependants +" "+s; + } + + $setVarInCycle = $logical_expr::varInCycle; + for (String s : $logical_expr::varInCycle) { + + $strVarInCycle = $strVarInCycle +" "+s; + } + }; + +expression returns[String text, Set members, String dependants, Set setVarInCycle, String strVarInCycle] +scope { Set SV; Set varInCycle } +@init { $expression::SV = new HashSet(); + $expression::varInCycle = new HashSet(); + String dependants = ""; + String strVarInCycle = ""; } + : + add + { $text = Tools.replace_ignoreChar($add.text); + $text = Tools.replace_seperator($text); + + //$expression::SV.removeAll(reservedSet); + $members = $expression::SV; + for (String s : $expression::SV) { + + $dependants = $dependants +" "+s; + } + + $setVarInCycle = $expression::varInCycle; + for (String s : $expression::varInCycle) { + + $strVarInCycle = $strVarInCycle +" "+s; + } + }; + +c_term + : ( expression relation expression ) => e1=expression relation e2=expression + { + $logical_expr::SV.addAll($e1.members); + $logical_expr::SV.addAll($e2.members); + $logical_expr::varInCycle.addAll($e1.setVarInCycle); + $logical_expr::varInCycle.addAll($e2.setVarInCycle); + } + | function_logical + | ( '(' logical_expr ')' ) => '(' e=logical_expr ')' + { + $logical_expr::SV.addAll($e.members); + $logical_expr::varInCycle.addAll($e.setVarInCycle); + } + ; + +c_unary : (c_negation)? c_term ; + +c_negation : NOT -> NOT[".NOT."] ; + + + +relation : '>' | '<' | '>=' | '<=' | '==' | '/=' ; + +bin : OR -> OR[".OR."] | AND -> AND[".AND."] ; + +/// End Expression /// + +/// Intrinsic functions /// + +//range_func +// : RANGE '(' MONTH ',' MONTH_CONST ',' MONTH_CONST ')' ; + +function : external_func | max_func | min_func | int_func | round_func | var_model ; + +function_logical : range_func ; + +var_model: var_model_noTimeArray|var_model_timeArray|var_modelindex_noTimeArray|var_modelindex_TimeArray + ; + +var_model_noTimeArray + : varName=IDENT '[' cycleName = IDENT ']' + { $expression::varInCycle.add($varName.text+'['+$cycleName.text+']' );} ; //{ $expression::DV.add($i.text.toLowerCase());} ; + +var_model_timeArray + : varName=IDENT '[' cycleName = IDENT ']' '(' e=expression ')' + { $expression::varInCycle.add($varName.text+'['+$cycleName.text+']'+'(' + $e.text +')' );} ; //{ $expression::DV.add($i.text.toLowerCase());} ; + +var_modelindex_noTimeArray + : varName=IDENT '[' cycleIndex=('-' INTEGER) ']' { + if (!VarCycleIndex.varCycleIndexList.contains(varName)){ + VarCycleIndex.varCycleIndexList.add($varName.text.toLowerCase()); + } + }; + +var_modelindex_TimeArray + : varName=IDENT '[' cycleIndex=('-' INTEGER) ']' '(' e=expression ')' { + if (!VarCycleIndex.varCycleIndexList.contains(varName)){ + VarCycleIndex.varCycleIndexList.add($varName.text.toLowerCase()); + } + }; + +external_func // this could be timeseries function + : i=IDENT {$expression::SV.add($i.text);} '(' ie=expression (',' e=expression {$expression::SV.addAll($e.members);$expression::varInCycle.addAll($e.setVarInCycle);} )* ')' + { $expression::SV.addAll($ie.members);$expression::varInCycle.addAll($ie.setVarInCycle);} // $expression::EX.add($i.text.toLowerCase()); + + ; + +range_func : RANGE '(' IDENT ',' ( IDENT | number ) ',' ( IDENT | number ) ')' ; + +max_func + : MAX '(' ie=expression (',' e=expression + { + $expression::SV.addAll($e.members); + $expression::varInCycle.addAll($e.setVarInCycle); + } + + )+ ')' + + { + $expression::SV.addAll($ie.members); + $expression::varInCycle.addAll($ie.setVarInCycle); + } + ; + +min_func + : MIN '(' ie=expression (',' e=expression + { + $expression::SV.addAll($e.members); + $expression::varInCycle.addAll($e.setVarInCycle); + } + + )+ ')' + + { + $expression::SV.addAll($ie.members); + $expression::varInCycle.addAll($ie.setVarInCycle); + } + ; + +int_func + : INT '(' e=expression ')' + { + $expression::SV.addAll($e.members); + $expression::varInCycle.addAll($e.setVarInCycle); + } + ; + +round_func + : ROUND '(' e=expression ')' + { + $expression::SV.addAll($e.members); + $expression::varInCycle.addAll($e.setVarInCycle); + } + ; + +/// End Intrinsic functions /// + +COMMENT : ('!'|'#') .* ('\n'|'\r') {skip();}; //{$channel = HIDDEN;}; +MULTILINE_COMMENT : '/*' .* '*/' {skip();}; //{$channel = HIDDEN;}; + +fragment LETTER : ('a'..'z' | 'A'..'Z') ; +fragment DIGIT : '0'..'9'; +INTEGER : DIGIT+ ; +FLOAT : (INTEGER? '.' INTEGER) | (INTEGER '.') ; + + +/// logical /// +AND : '.and.' | '.AND.' ; +OR : '.or.' | '.OR.' ; +NOT : '.not.' | '.NOT.' ; + +/// reserved keywords /// +PENALTY : 'penalty' | 'PENALTY' | 'Penalty'; +CONSTRAIN : 'constrain' | 'CONSTRAIN' | 'Constrain'; +INT : 'int' | 'INT' | 'Int' ; +ROUND : 'round' | 'ROUND' | 'Round' ; +SUM : 'sum' | 'SUM' | 'Sum' ; +RANGE : 'range' | 'RANGE' | 'Range' ; +MAX : 'max' | 'MAX' | 'Max' ; +MIN : 'min' | 'MIN' | 'Min' ; +VALUE : 'value' | 'VALUE' | 'Value' ; +LOCAL : 'local'| 'LOCAL' | 'Local' ; +OBJECTIVE: 'objective' | 'Objective' | 'OBJECTIVE'; +TIMESERIES: 'timeseries' | 'TIMESERIES' | 'Timeseries'; +SELECT : 'select' | 'Select' | 'SELECT' ; +FROM: 'from' | 'From' | 'FROM' ; +WHERE : 'where' | 'Where' | 'WHERE'; +GIVEN: 'given' | 'Given' | 'GIVEN' ; +USE: 'use' | 'Use' | 'USE' ; +CASE : 'case' | 'Case' | 'CASE' ; +LHS: 'lhs' | 'LHS' ; +RHS: 'rhs' | 'RHS' ; +EXTERNAL : 'EXTERNAL' | 'external' | 'External' ; +F90 : 'f90' | 'F90' ; +DLL : IDENT ('.dll' | '.DLL' ); +INTEGER_WORD: 'integer' | 'INTEGER' | 'Integer' ; +STD : 'std' | 'STD' ; +UNITS : 'units' | 'UNITS' | 'Units' ; +CONVERT : 'convert' | 'CONVERT' | 'Convert'; +ALIAS : 'alias' | 'ALIAS' | 'Alias'; +KIND : 'kind' | 'KIND' | 'Kind'; +GOAL : 'goal' | 'GOAL' | 'Goal'; +DEFINE :'define' | 'DEFINE' | 'Define' ; +ALWAYS :'always' | 'ALWAYS' | 'Always' ; +CONDITION : 'condition' | 'CONDITION' | 'Condition' ; +SEQUENCE : 'sequence' | 'SEQUENCE' | 'Sequence'; +MODEL : 'model' | 'MODEL' | 'Model'; +ORDER : 'order' | 'ORDER' | 'Order'; +TIMESTEP : 'timestep'|'TIMESTEP'|'TimeStep'; +TIMESTEPVALUE: '1mon'|'1MON'|'1day'|'1DAY'; +INCLUDE : 'include' | 'INCLUDE' | 'Include'; +LOWER : 'lower' | 'LOWER' | 'Lower' ; +UPPER : 'upper' | 'UPPER' | 'Upper' ; +UNBOUNDED : 'unbounded' | 'Unbounded' | 'UNBOUNDED'; + +/// include file path /// +FILE_PATH : '\'' DIR_SPLIT? (DIR_ELEMENT | DIR_UP)* WRESL_FILE '\'' ; +fragment WRESL_EXT : '.wresl' | '.WRESL' ; +fragment WRESL_FILE : (LETTER | DIGIT | '_' |'-' )+ WRESL_EXT ; +fragment DIR_ELEMENT : (LETTER | DIGIT | '_' | '-' )+ '\\' ; +fragment DIR_UP : ('..') '\\' ; +fragment DIR_SPLIT : '\\' ; + + +STRING : '\'' IDENT( '-' | '/' | IDENT )* '\''; + +IDENT_FOLLOWED_BY_LOGICAL + : i=IDENT{$i.setType(IDENT); emit($i);} + ( a=AND { $a.setType(AND); emit($a);} + | a=OR { $a.setType(OR); emit($a);} + | a=NOT { $a.setType(NOT); emit($a);} + ); + +INTEGER_FOLLOWED_BY_LOGICAL + : i=INTEGER{$i.setType(INTEGER); emit($i);} + ( a=AND { $a.setType(AND); emit($a);} + | a=OR { $a.setType(OR); emit($a);} + | a=NOT { $a.setType(NOT); emit($a);} + ); + +IDENT : LETTER (LETTER | DIGIT | '_')*; + +WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;}; + +COMMENT_LAST_LINE : ('!'|'#') (~('\n' | '\r'))* {skip();}; +//IGNORE : . {skip();}; diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/grammar/WreslTreeWalker.g b/wrims-core/src/main/antlr/wrimsv2/wreslparser/grammar/WreslTreeWalker.g similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/grammar/WreslTreeWalker.g rename to wrims-core/src/main/antlr/wrimsv2/wreslparser/grammar/WreslTreeWalker.g index e7214a184..61dc91bf0 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/grammar/WreslTreeWalker.g +++ b/wrims-core/src/main/antlr/wrimsv2/wreslparser/grammar/WreslTreeWalker.g @@ -1,520 +1,520 @@ -tree grammar WreslTreeWalker; -options { - language = Java; - tokenVocab = WreslTree; - ASTLabelType = CommonTree; -} -@header { - package wrimsv2.wreslparser.grammar; - import java.util.Map; - import java.util.HashMap; - import wrimsv2.wreslparser.elements.StructTree; - import wrimsv2.wreslparser.elements.SimulationDataSet; - import wrimsv2.wreslparser.elements.Tools; - import wrimsv2.wreslparser.elements.LogUtils; - import wrimsv2.commondata.wresldata.Param; - import wrimsv2.commondata.wresldata.Goal; - import wrimsv2.commondata.wresldata.Svar; -} -@members { - - public int result; - public CommonTree commonTree; - public String currentAbsolutePath; - public String currentAbsoluteParent; - - public StructTree F = new StructTree(); - public SimulationDataSet thisFileDataSet = new SimulationDataSet(); - private SimulationDataSet S; - - public Map modelDataMap = new HashMap(); - /// error message - public void displayRecognitionError(String[] tokenNames, - RecognitionException e) { - String hdr = getErrorHeader(e); - String msg = getErrorMessage(e, tokenNames); - LogUtils.errMsg(hdr + " " + msg); - } -} -evaluator -@init { - F.S = thisFileDataSet; - F.S.currentAbsolutePath = currentAbsolutePath; - F.S.currentAbsoluteParent = currentAbsoluteParent; - } - : - ( pattern+ - | ( sequence+ model+ ) - ) - EOF - ; - -pattern - : dvar | svar | goal | includeFile | alias | weight_table | external | integer - | svar_timeArray - ; - -integer - : integer_std | integer_nonStd | integer_timeArray_std | integer_timeArray_nonStd - ; - -integer_std - : ^(Dvar_integer sc=Scope i=IDENT k=Kind u=Units ) - {F.dvarStd($i.text, $sc.text, "integer", Tools.strip($k.text), Tools.strip($u.text)); } - ; - -integer_nonStd - : ^(Dvar_integer sc=Scope i=IDENT Lower lowerbound=LimitType Upper upperbound=LimitType k=Kind u=Units ) - {F.dvarNonStd($i.text, $sc.text, "integer", Tools.strip($k.text), Tools.strip($u.text), $lowerbound.text, $upperbound.text); } - ; - -integer_timeArray_std - : ^(Dvar_integer ta=TimeArraySize sc=Scope i=IDENT k=Kind u=Units ) - {F.dvarStd($i.text, $sc.text, "integer", Tools.strip($k.text), Tools.strip($u.text), $ta.text); } - ; - -integer_timeArray_nonStd - : ^(Dvar_integer ta=TimeArraySize sc=Scope i=IDENT Lower lowerbound=LimitType Upper upperbound=LimitType k=Kind u=Units ) - {F.dvarNonStd($i.text, $sc.text, "integer", Tools.strip($k.text), Tools.strip($u.text), $lowerbound.text, $upperbound.text, $ta.text); } - ; - -external - : ^(External sc=Scope i=IDENT e=Expression ) - {F.external($i.text, $sc.text, $e.text);} - ; - -sequence - : ^(Sequence s=IDENT Model m=IDENT Order i=INTEGER c=Condition t=TIMESTEP) - { - F.sequenceOrder($s.text, $i.text, $m.text, $c.text, $t.text); - - SimulationDataSet M = new SimulationDataSet(); - M.currentAbsolutePath=currentAbsolutePath; - M.currentAbsoluteParent=currentAbsoluteParent; - modelDataMap.put($m.text.toLowerCase(), M); - } - - - ; - -model -@after{ F.S = thisFileDataSet; } - : ^(Model i=IDENT - { - F.S = thisFileDataSet; F.modelList($i.text.toLowerCase()); - - F.S = modelDataMap.get($i.text.toLowerCase()); - } - - (pattern )+ ) - ; - -includeFile - : ^(Include sc=Scope f=FILE_PATH) {F.includeFile(Tools.strip($f.text), $sc.text);} - ; - -weight_table - : ^(Weight_table sc=Scope ( ^(i=IDENT ta=TimeArraySize e=Expression - { - F.mergeWeightTable($i.text, $e.text, $sc.text, $ta.text); - } - ) )+ ) - ; - - -//assignment -// : ^(':=' IDENT e=expression) -// { variables.put($IDENT.text, e); } -// ; -goal -scope { String ta; String scop ; Goal gl; String case_condition; int caseNumber; Map dvarWeightMap; ArrayList dvarSlackSurplus;} -@init { $goal::ta=null; $goal::scop = null; $goal::gl = new Goal(); $goal::caseNumber=0; $goal::case_condition="always";} -: goal_simple | goal_nocase | goal_case ; - -dvar : dvar_std | dvar_nonStd | dvar_timeArray_std | dvar_timeArray_nonStd ; - -svar : svar_dss | svar_expr | svar_sum | svar_table | svar_case; - -svar_timeArray : svar_timeArray_expr | svar_timeArray_case |svar_timeArray_table | svar_timeArray_sum; - -svar_timeArray_case -@init { Svar sv = new Svar(); String dependants=null; String varInCycle=null;} - : ^(SvarTimeArray_case ta=TimeArraySize tad=Dependants sc=Scope i=IDENT ( c=case_content - { - sv.caseName.add($c.name.toLowerCase()); - sv.caseCondition.add( Tools.add_space_between_logical( $c.condition.toLowerCase() ) ); - sv.caseExpression.add($c.expression.toLowerCase()); - dependants = dependants + " " + $c.dependants; - varInCycle = varInCycle + " " + $c.varInCycle; - } - - )+ - ) - { - F.svarCase($i.text, $sc.text, sv, dependants+" "+$tad.text, varInCycle, $ta.text); } -; - -svar_case -@init { Svar sv = new Svar(); String dependants=null; String varInCycle=null;} - : ^(Svar_case sc=Scope i=IDENT ( c=case_content - { - sv.caseName.add($c.name.toLowerCase()); - sv.caseCondition.add( Tools.add_space_between_logical( $c.condition.toLowerCase() ) ); - sv.caseExpression.add($c.expression.toLowerCase()); - dependants = dependants + " " + $c.dependants; - varInCycle = varInCycle + " " + $c.varInCycle; - } - - )+ - ) - { - F.svarCase($i.text, $sc.text, sv, dependants, varInCycle); } -; - - -case_content returns[String name, String condition, String expression, String dependants, String varInCycle] -@init{ String expr = null;} : -^(Case i=IDENT c=Condition d=Dependants cvc=VarInCycle - - ( t=table_content {expr =$t.text;} // todo: add dependants - | v=Value vd=Dependants vvc=VarInCycle {expr =$v.text; } - | sum=sum_content {expr =$sum.hdr+" "+$sum.expr; } - ) ) - -{ $name = $i.text; $condition =$c.text; $expression = expr; - $dependants = $d.text + " " + $t.dependants + " " + $vd.text + " " + $sum.dependants; - $varInCycle = $cvc.text + " "+ $t.varInCycle + " " + $sum.varInCycle + " " + $vvc.text; - -} - - -; - - -//table_content returns[String text] : -//^( s=Select f=From (g=Given u=Use)? wc=Where_content ) -//{ $text = "SELECT "+$s.text+" FROM "+$f.text+" GIVEN "+$g.text+" USE "+$u.text+ -// " WHERE "+ Tools.replace_ignoreChar(Tools.replace_seperator($wc.text)); } -//; - -table_content returns[String text, String dependants, String varInCycle] - : - ^( SELECT s=IDENT FROM f=IDENT {$text = "select "+$s.text+" from "+$f.text; } - (GIVEN g=Assignment d=Dependants vc=VarInCycle USE u=IDENT {$text = $text+" given "+$g.text+" use "+$u.text;} )? - (WHERE w=where_items wd=Dependants {$text = $text+" where "+ Tools.replace_ignoreChar(Tools.replace_seperator($w.text)); } )? - ) - {$dependants = $d.text +" " + $wd.text; $varInCycle = $vc.text; } - ; - -where_items returns[String text] - : a=Assignment {$text = $a.text;} (',' b=Assignment {$text = $text+","+$b.text;})* - ; - - -alias : (alias_simple|alias_timeArray_simple); - -alias_simple: ^(Alias sc=Scope i=IDENT e=Expression k=Kind u=Units d=Dependants vc=VarInCycle) - { F.alias($i.text, $sc.text, Tools.strip($k.text), Tools.strip($u.text), $e.text, $d.text, $vc.text ); } - ; - -alias_timeArray_simple: ^(Alias ta=TimeArraySize sc=Scope i=IDENT e=Expression k=Kind u=Units d=Dependants vc=VarInCycle) - { F.alias($i.text, $sc.text, Tools.strip($k.text), Tools.strip($u.text), $e.text, $d.text, $vc.text, $ta.text); } - ; - -goal_simple - : ^(Goal_simple (ta=TimeArraySize{$goal::ta=$ta.text;})? sc=Scope {$goal::scop = $sc.text;} i=IDENT d=Dependants v=Constraint_content vc=VarInCycle) - { - if ($ta==null){ - F.goalSimple($i.text, $sc.text, $v.text, $d.text, $vc.text); - }else{ - F.goalSimple($i.text, $sc.text, $v.text, $d.text, $vc.text, $ta.text); - } - } - ; - -goal_nocase - @init { $goal::gl = new Goal(); $goal::caseNumber=0; $goal::case_condition="always";} - : ^( Goal_no_case (ta=TimeArraySize{$goal::ta=$ta.text;})? sc=Scope {$goal::scop = $sc.text;} i=IDENT d=Dependants vc=VarInCycle - { - if ($ta==null){ - $goal::gl = F.goalSimple($i.text, $sc.text, "", $d.text, $vc.text); - }else{ - $goal::gl = F.goalSimple($i.text, $sc.text, "", $d.text, $vc.text, $ta.text); - } - $goal::gl.dvarWeightMapList.add(null); - $goal::gl.dvarSlackSurplusList.add(null); - $goal::dvarWeightMap = new HashMap(); - $goal::dvarSlackSurplus = new ArrayList(); - //$goal::gl.dvarName.add(""); $goal::gl.dvarWeight.add(""); - } - c=goal_contents ) - - { - $goal::gl.caseExpression.set(0, $c.str.toLowerCase()); - } -; - -goal_case - @init { $goal::gl = new Goal(); $goal::caseNumber=0; $goal::case_condition=Param.conditional; } - : ^( Goal_case (ta=TimeArraySize{$goal::ta=$ta.text;})? sc=Scope {$goal::scop = $sc.text;} i=IDENT - ( - { $goal::gl.dvarWeightMapList.add(null); - $goal::gl.dvarSlackSurplusList.add(null); - $goal::dvarWeightMap = new HashMap(); - $goal::dvarSlackSurplus = new ArrayList(); - //$goal::gl.dvarName.add(""); $goal::gl.dvarWeight.add(""); - } - - ^( Case n=IDENT c=Condition d=Dependants vc=VarInCycle e=goal_contents - { $goal::caseNumber++; - $goal::dvarWeightMap = new HashMap(); - $goal::dvarSlackSurplus = new ArrayList(); - $goal::gl.caseName.add($n.text.toLowerCase()); - $goal::gl.caseCondition.add( Tools.add_space_between_logical( $c.text.toLowerCase() ) ); - $goal::gl.caseExpression.add($e.str.toLowerCase()); - if (d != null) { - String dependants = $d.text.toLowerCase(); - $goal::gl.expressionDependants.addAll(Tools.convertStrToSet(dependants)); - $goal::gl.expressionDependants.removeAll(Param.reservedSet); - } - if (vc != null) { - String varInCycle = $vc.text.toLowerCase(); - $goal::gl.neededVarInCycleSet.addAll(Tools.convertStrToSet(varInCycle)); - $goal::gl.needVarFromEarlierCycle = true; - } - } - ) )+ - ) - { - if ($ta==null){ - F.goalCase($i.text, $sc.text, $goal::gl); - }else{ - F.goalCase($i.text, $sc.text, $goal::gl, $ta.text); - } - } -; - -goal_contents returns[String str] - : ( g=goal_contents_process_2 |g=goal_contents_process_1 | g=goal_content_simple ) - - {$str = $g.str;} - ; - -goal_contents_process_1 returns[String str] : t=One c1=goal_content - { - // c -> = - // f -> f - // p -> = - - if ( $t.text.equals("c") ) { - - $str = $c1.lhs + "=" + $c1.rhs ; - - } else if ( $t.text.equals("f") ) { - - $str = $c1.str ; - - } else { - - $str = $c1.lhs + $c1.ss + "=" + $c1.rhs ; - - } - - } - ; - -goal_contents_process_2 returns[String str] : t=Two c1=goal_content c2=goal_content - { - // p: penalty f: free c: constrain - // pp -> = - // pc or cp -> = - // pf or fp -> f - // fc or cf -> f (same as c) - // cc -> = (simple string) - // ff -> error - - - if ( $t.text.equals("pp") ) { - - $str = $c1.lhs + $c1.ss + $c2.ss + "=" + $c1.rhs ; - - } else if ( $t.text.equals("pc") ) { - - $str = $c1.lhs + $c1.ss + "=" + $c1.rhs ; - - } else if ( $t.text.equals("cp") ) { - - $str = $c2.lhs + $c2.ss + "=" + $c2.rhs; - - } else if ( $t.text.equals("pf") ) { - - $str = $c1.lhs + $c1.ss + $c2.op + $c1.rhs ; - - } else if ( $t.text.equals("fp")) { - - $str = $c2.lhs + $c2.ss + $c1.op + $c2.rhs; - - } else if ( $t.text.equals("fc")) { - - $str = $c1.lhs + $c1.op + $c1.rhs ; - - } else if ( $t.text.equals("cf")) { - - $str = $c1.lhs + $c2.op + $c1.rhs ; - - - } else if ( $t.text.equals("cc")) { - - $str = $c1.lhs+"="+$c1.rhs ; - - } else { // ff - - $str = " 1 > 0 "; // do something - } - - - - } - ; - -goal_content returns[boolean hasDvar, String str, String ss, String weight, String lhs, String rhs, String type, String op] -@init{$hasDvar=false; String kind=null; $type="constrain";} - : - ( Constrain | Free | Penalty ) l=Lhs o=Op r=Rhs ( Sign Kind s=Slack_Surplus w=Weight )? - - { $str = $l.text + $o.text + $r.text; - - if (s!=null) { - - if ($goal::case_condition.equalsIgnoreCase(Param.conditional)){ - - $goal::dvarWeightMap.put($s.text.toLowerCase(), $w.text.toLowerCase()); - $goal::dvarSlackSurplus.add($s.text.toLowerCase()); - $goal::gl.dvarWeightMapList.set($goal::caseNumber,$goal::dvarWeightMap); - $goal::gl.dvarSlackSurplusList.set($goal::caseNumber,$goal::dvarSlackSurplus); - } - //System.out.println($s.text.toLowerCase()+": "+$w.text.toLowerCase()); - //$goal::gl.dvarName.set($goal::caseNumber, $s.text.toLowerCase()); - //$goal::gl.dvarWeight.set($goal::caseNumber, $w.text.toLowerCase()); - //F.dvarStd($s.text, $goal::scop, null, $Kind.text, ""); - if ($goal::ta==null){ - $ss = $Sign.text + $s.text; - F.dvarSlackSurplus($s.text, $goal::scop, $Kind.text, "", $goal::case_condition, "0"); - F.mergeSlackSurplusIntoWeightTable($s.text, $w.text, $goal::scop, $goal::case_condition, "0"); - }else if ($goal::ta.equals("0")){ - $ss = $Sign.text + $s.text; - F.dvarSlackSurplus($s.text, $goal::scop, $Kind.text, "", $goal::case_condition, "0"); - F.mergeSlackSurplusIntoWeightTable($s.text, $w.text, $goal::scop, $goal::case_condition, "0"); - }else{ - $ss = $Sign.text + $s.text+"(\$m)"; - F.dvarSlackSurplus($s.text, $goal::scop, $Kind.text, "", $goal::case_condition, $goal::ta); - F.mergeSlackSurplusIntoWeightTable($s.text, $w.text, $goal::scop, $goal::case_condition, $goal::ta); - } - $hasDvar = true; - $weight = $w.text; } - //} else { - - $lhs = $l.text; $rhs = $r.text; $op = $o.text; - //} - } - ; - -goal_content_simple returns[String str] - : - Simple l=Lhs o=Op r=Rhs - { $str = $l.text + $o.text + $r.text; } - ; - -svar_table : - ^( Svar_table sc=Scope i=IDENT t=table_content ) - { F.svarTable($i.text, $sc.text, $t.text, $t.dependants, $t.varInCycle); } - ; - -svar_timeArray_table : - ^( Svar_table ta=TimeArraySize sc=Scope i=IDENT t=table_content ) - { F.svarTable($i.text, $sc.text, $t.text, $t.dependants, $t.varInCycle, $ta.text); } - ; - -svar_sum : - ^(Svar_sum sc=Scope i=IDENT sum=sum_content ) - { F.svarSum($i.text, $sc.text, $sum.hdr, $sum.expr, $sum.dependants, $sum.varInCycle ); } - ; - -svar_timeArray_sum : - ^(Svar_sum ta=TimeArraySize sc=Scope i=IDENT sum=sum_content ) - { F.svarSum($i.text, $sc.text, $sum.hdr, $sum.expr, $sum.dependants, $sum.varInCycle, $ta.text ); } - ; - -sum_content returns[String hdr, String expr, String dependants, String varInCycle]: -^(h=Sum_hdr e=Expression d=Dependants vc=VarInCycle) - { - $hdr="SUM"+Tools.replace_ignoreChar( Tools.replace_seperator($h.text)); - $expr = $e.text; - $dependants = $d.text; - $varInCycle = $vc.text; - } -; - -svar_expr : - ^(Svar_const sc=Scope i=IDENT v=Expression d=Dependants vc=VarInCycle) - { F.svarExpression($i.text, $sc.text, Tools.replace_seperator($v.text), $d.text, $vc.text ); } - ; - -svar_timeArray_expr : - ^(SvarTimeArray_const ta=TimeArraySize sc=Scope i=IDENT v=Expression d=Dependants vc=VarInCycle) - { F.svarExpression($i.text, $sc.text, Tools.replace_seperator($v.text), $d.text, $vc.text, $ta.text ); } - ; - -svar_dss : - ^(Svar_dss sc=Scope i=IDENT b=B_part Kind k=STRING Units u=STRING c=CONVERT ) - { F.timeseriesDss($i.text, $sc.text, Tools.strip($b.text), Tools.strip($k.text), Tools.strip($u.text), Tools.strip($c.text)); } - ; - -dvar_std : - ^(Dvar_std sc=Scope i=IDENT Kind k=STRING Units u=STRING) - { F.dvarStd($i.text, $sc.text, null, Tools.strip($k.text), Tools.strip($u.text)); } - ; - -dvar_nonStd : - ^(Dvar_nonStd sc=Scope i=IDENT Lower lowerbound=LimitType Upper upperbound=LimitType Kind k=STRING Units u=STRING) - {F.dvarNonStd($i.text, $sc.text, null, Tools.strip($k.text), Tools.strip($u.text), $lowerbound.text, $upperbound.text);} - ; - -dvar_timeArray_std : - ^(DvarTimeArray_std ta=TimeArraySize sc=Scope i=IDENT Kind k=STRING Units u=STRING) - { F.dvarStd($i.text, $sc.text, null, Tools.strip($k.text), Tools.strip($u.text), $ta.text ); } - ; - -dvar_timeArray_nonStd : - ^(DvarTimeArray_nonStd ta=TimeArraySize sc=Scope i=IDENT Lower lowerbound=LimitType Upper upperbound=LimitType Kind k=STRING Units u=STRING) - {F.dvarNonStd($i.text, $sc.text, null, Tools.strip($k.text), Tools.strip($u.text), $lowerbound.text, $upperbound.text, $ta.text);} - ; - -/// Expression /// -term - : IDENT - | '(' expression ')' - | INTEGER - ; - -unary : NEGATION? term ; - -mult : unary (('*' | '/' ) unary)* ; - -expression : mult (('+' | '-') mult)* ; - -c_term - : ( expression relation expression ) => expression relation expression - | ( '(' logical ')' ) => '(' logical ')' - ; - -c_unary : NOT? c_term ; - -logical : c_unary ( bin c_unary )* ; - -relation : '>' | '<' | '>=' | '<=' | '==' | '/=' ; - -bin : OR | AND ; - -/// End Expression /// - +tree grammar WreslTreeWalker; +options { + language = Java; + tokenVocab = WreslTree; + ASTLabelType = CommonTree; +} +@header { + package wrimsv2.wreslparser.grammar; + import java.util.Map; + import java.util.HashMap; + import wrimsv2.wreslparser.elements.StructTree; + import wrimsv2.wreslparser.elements.SimulationDataSet; + import wrimsv2.wreslparser.elements.Tools; + import wrimsv2.wreslparser.elements.LogUtils; + import wrimsv2.commondata.wresldata.Param; + import wrimsv2.commondata.wresldata.Goal; + import wrimsv2.commondata.wresldata.Svar; +} +@members { + + public int result; + public CommonTree commonTree; + public String currentAbsolutePath; + public String currentAbsoluteParent; + + public StructTree F = new StructTree(); + public SimulationDataSet thisFileDataSet = new SimulationDataSet(); + private SimulationDataSet S; + + public Map modelDataMap = new HashMap(); + /// error message + public void displayRecognitionError(String[] tokenNames, + RecognitionException e) { + String hdr = getErrorHeader(e); + String msg = getErrorMessage(e, tokenNames); + LogUtils.errMsg(hdr + " " + msg); + } +} +evaluator +@init { + F.S = thisFileDataSet; + F.S.currentAbsolutePath = currentAbsolutePath; + F.S.currentAbsoluteParent = currentAbsoluteParent; + } + : + ( pattern+ + | ( sequence+ model+ ) + ) + EOF + ; + +pattern + : dvar | svar | goal | includeFile | alias | weight_table | external | integer + | svar_timeArray + ; + +integer + : integer_std | integer_nonStd | integer_timeArray_std | integer_timeArray_nonStd + ; + +integer_std + : ^(Dvar_integer sc=Scope i=IDENT k=Kind u=Units ) + {F.dvarStd($i.text, $sc.text, "integer", Tools.strip($k.text), Tools.strip($u.text)); } + ; + +integer_nonStd + : ^(Dvar_integer sc=Scope i=IDENT Lower lowerbound=LimitType Upper upperbound=LimitType k=Kind u=Units ) + {F.dvarNonStd($i.text, $sc.text, "integer", Tools.strip($k.text), Tools.strip($u.text), $lowerbound.text, $upperbound.text); } + ; + +integer_timeArray_std + : ^(Dvar_integer ta=TimeArraySize sc=Scope i=IDENT k=Kind u=Units ) + {F.dvarStd($i.text, $sc.text, "integer", Tools.strip($k.text), Tools.strip($u.text), $ta.text); } + ; + +integer_timeArray_nonStd + : ^(Dvar_integer ta=TimeArraySize sc=Scope i=IDENT Lower lowerbound=LimitType Upper upperbound=LimitType k=Kind u=Units ) + {F.dvarNonStd($i.text, $sc.text, "integer", Tools.strip($k.text), Tools.strip($u.text), $lowerbound.text, $upperbound.text, $ta.text); } + ; + +external + : ^(External sc=Scope i=IDENT e=Expression ) + {F.external($i.text, $sc.text, $e.text);} + ; + +sequence + : ^(Sequence s=IDENT Model m=IDENT Order i=INTEGER c=Condition t=TIMESTEP) + { + F.sequenceOrder($s.text, $i.text, $m.text, $c.text, $t.text); + + SimulationDataSet M = new SimulationDataSet(); + M.currentAbsolutePath=currentAbsolutePath; + M.currentAbsoluteParent=currentAbsoluteParent; + modelDataMap.put($m.text.toLowerCase(), M); + } + + + ; + +model +@after{ F.S = thisFileDataSet; } + : ^(Model i=IDENT + { + F.S = thisFileDataSet; F.modelList($i.text.toLowerCase()); + + F.S = modelDataMap.get($i.text.toLowerCase()); + } + + (pattern )+ ) + ; + +includeFile + : ^(Include sc=Scope f=FILE_PATH) {F.includeFile(Tools.strip($f.text), $sc.text);} + ; + +weight_table + : ^(Weight_table sc=Scope ( ^(i=IDENT ta=TimeArraySize e=Expression + { + F.mergeWeightTable($i.text, $e.text, $sc.text, $ta.text); + } + ) )+ ) + ; + + +//assignment +// : ^(':=' IDENT e=expression) +// { variables.put($IDENT.text, e); } +// ; +goal +scope { String ta; String scop ; Goal gl; String case_condition; int caseNumber; Map dvarWeightMap; ArrayList dvarSlackSurplus;} +@init { $goal::ta=null; $goal::scop = null; $goal::gl = new Goal(); $goal::caseNumber=0; $goal::case_condition="always";} +: goal_simple | goal_nocase | goal_case ; + +dvar : dvar_std | dvar_nonStd | dvar_timeArray_std | dvar_timeArray_nonStd ; + +svar : svar_dss | svar_expr | svar_sum | svar_table | svar_case; + +svar_timeArray : svar_timeArray_expr | svar_timeArray_case |svar_timeArray_table | svar_timeArray_sum; + +svar_timeArray_case +@init { Svar sv = new Svar(); String dependants=null; String varInCycle=null;} + : ^(SvarTimeArray_case ta=TimeArraySize tad=Dependants sc=Scope i=IDENT ( c=case_content + { + sv.caseName.add($c.name.toLowerCase()); + sv.caseCondition.add( Tools.add_space_between_logical( $c.condition.toLowerCase() ) ); + sv.caseExpression.add($c.expression.toLowerCase()); + dependants = dependants + " " + $c.dependants; + varInCycle = varInCycle + " " + $c.varInCycle; + } + + )+ + ) + { + F.svarCase($i.text, $sc.text, sv, dependants+" "+$tad.text, varInCycle, $ta.text); } +; + +svar_case +@init { Svar sv = new Svar(); String dependants=null; String varInCycle=null;} + : ^(Svar_case sc=Scope i=IDENT ( c=case_content + { + sv.caseName.add($c.name.toLowerCase()); + sv.caseCondition.add( Tools.add_space_between_logical( $c.condition.toLowerCase() ) ); + sv.caseExpression.add($c.expression.toLowerCase()); + dependants = dependants + " " + $c.dependants; + varInCycle = varInCycle + " " + $c.varInCycle; + } + + )+ + ) + { + F.svarCase($i.text, $sc.text, sv, dependants, varInCycle); } +; + + +case_content returns[String name, String condition, String expression, String dependants, String varInCycle] +@init{ String expr = null;} : +^(Case i=IDENT c=Condition d=Dependants cvc=VarInCycle + + ( t=table_content {expr =$t.text;} // todo: add dependants + | v=Value vd=Dependants vvc=VarInCycle {expr =$v.text; } + | sum=sum_content {expr =$sum.hdr+" "+$sum.expr; } + ) ) + +{ $name = $i.text; $condition =$c.text; $expression = expr; + $dependants = $d.text + " " + $t.dependants + " " + $vd.text + " " + $sum.dependants; + $varInCycle = $cvc.text + " "+ $t.varInCycle + " " + $sum.varInCycle + " " + $vvc.text; + +} + + +; + + +//table_content returns[String text] : +//^( s=Select f=From (g=Given u=Use)? wc=Where_content ) +//{ $text = "SELECT "+$s.text+" FROM "+$f.text+" GIVEN "+$g.text+" USE "+$u.text+ +// " WHERE "+ Tools.replace_ignoreChar(Tools.replace_seperator($wc.text)); } +//; + +table_content returns[String text, String dependants, String varInCycle] + : + ^( SELECT s=IDENT FROM f=IDENT {$text = "select "+$s.text+" from "+$f.text; } + (GIVEN g=Assignment d=Dependants vc=VarInCycle USE u=IDENT {$text = $text+" given "+$g.text+" use "+$u.text;} )? + (WHERE w=where_items wd=Dependants {$text = $text+" where "+ Tools.replace_ignoreChar(Tools.replace_seperator($w.text)); } )? + ) + {$dependants = $d.text +" " + $wd.text; $varInCycle = $vc.text; } + ; + +where_items returns[String text] + : a=Assignment {$text = $a.text;} (',' b=Assignment {$text = $text+","+$b.text;})* + ; + + +alias : (alias_simple|alias_timeArray_simple); + +alias_simple: ^(Alias sc=Scope i=IDENT e=Expression k=Kind u=Units d=Dependants vc=VarInCycle) + { F.alias($i.text, $sc.text, Tools.strip($k.text), Tools.strip($u.text), $e.text, $d.text, $vc.text ); } + ; + +alias_timeArray_simple: ^(Alias ta=TimeArraySize sc=Scope i=IDENT e=Expression k=Kind u=Units d=Dependants vc=VarInCycle) + { F.alias($i.text, $sc.text, Tools.strip($k.text), Tools.strip($u.text), $e.text, $d.text, $vc.text, $ta.text); } + ; + +goal_simple + : ^(Goal_simple (ta=TimeArraySize{$goal::ta=$ta.text;})? sc=Scope {$goal::scop = $sc.text;} i=IDENT d=Dependants v=Constraint_content vc=VarInCycle) + { + if ($ta==null){ + F.goalSimple($i.text, $sc.text, $v.text, $d.text, $vc.text); + }else{ + F.goalSimple($i.text, $sc.text, $v.text, $d.text, $vc.text, $ta.text); + } + } + ; + +goal_nocase + @init { $goal::gl = new Goal(); $goal::caseNumber=0; $goal::case_condition="always";} + : ^( Goal_no_case (ta=TimeArraySize{$goal::ta=$ta.text;})? sc=Scope {$goal::scop = $sc.text;} i=IDENT d=Dependants vc=VarInCycle + { + if ($ta==null){ + $goal::gl = F.goalSimple($i.text, $sc.text, "", $d.text, $vc.text); + }else{ + $goal::gl = F.goalSimple($i.text, $sc.text, "", $d.text, $vc.text, $ta.text); + } + $goal::gl.dvarWeightMapList.add(null); + $goal::gl.dvarSlackSurplusList.add(null); + $goal::dvarWeightMap = new HashMap(); + $goal::dvarSlackSurplus = new ArrayList(); + //$goal::gl.dvarName.add(""); $goal::gl.dvarWeight.add(""); + } + c=goal_contents ) + + { + $goal::gl.caseExpression.set(0, $c.str.toLowerCase()); + } +; + +goal_case + @init { $goal::gl = new Goal(); $goal::caseNumber=0; $goal::case_condition=Param.conditional; } + : ^( Goal_case (ta=TimeArraySize{$goal::ta=$ta.text;})? sc=Scope {$goal::scop = $sc.text;} i=IDENT + ( + { $goal::gl.dvarWeightMapList.add(null); + $goal::gl.dvarSlackSurplusList.add(null); + $goal::dvarWeightMap = new HashMap(); + $goal::dvarSlackSurplus = new ArrayList(); + //$goal::gl.dvarName.add(""); $goal::gl.dvarWeight.add(""); + } + + ^( Case n=IDENT c=Condition d=Dependants vc=VarInCycle e=goal_contents + { $goal::caseNumber++; + $goal::dvarWeightMap = new HashMap(); + $goal::dvarSlackSurplus = new ArrayList(); + $goal::gl.caseName.add($n.text.toLowerCase()); + $goal::gl.caseCondition.add( Tools.add_space_between_logical( $c.text.toLowerCase() ) ); + $goal::gl.caseExpression.add($e.str.toLowerCase()); + if (d != null) { + String dependants = $d.text.toLowerCase(); + $goal::gl.expressionDependants.addAll(Tools.convertStrToSet(dependants)); + $goal::gl.expressionDependants.removeAll(Param.reservedSet); + } + if (vc != null) { + String varInCycle = $vc.text.toLowerCase(); + $goal::gl.neededVarInCycleSet.addAll(Tools.convertStrToSet(varInCycle)); + $goal::gl.needVarFromEarlierCycle = true; + } + } + ) )+ + ) + { + if ($ta==null){ + F.goalCase($i.text, $sc.text, $goal::gl); + }else{ + F.goalCase($i.text, $sc.text, $goal::gl, $ta.text); + } + } +; + +goal_contents returns[String str] + : ( g=goal_contents_process_2 |g=goal_contents_process_1 | g=goal_content_simple ) + + {$str = $g.str;} + ; + +goal_contents_process_1 returns[String str] : t=One c1=goal_content + { + // c -> = + // f -> f + // p -> = + + if ( $t.text.equals("c") ) { + + $str = $c1.lhs + "=" + $c1.rhs ; + + } else if ( $t.text.equals("f") ) { + + $str = $c1.str ; + + } else { + + $str = $c1.lhs + $c1.ss + "=" + $c1.rhs ; + + } + + } + ; + +goal_contents_process_2 returns[String str] : t=Two c1=goal_content c2=goal_content + { + // p: penalty f: free c: constrain + // pp -> = + // pc or cp -> = + // pf or fp -> f + // fc or cf -> f (same as c) + // cc -> = (simple string) + // ff -> error + + + if ( $t.text.equals("pp") ) { + + $str = $c1.lhs + $c1.ss + $c2.ss + "=" + $c1.rhs ; + + } else if ( $t.text.equals("pc") ) { + + $str = $c1.lhs + $c1.ss + "=" + $c1.rhs ; + + } else if ( $t.text.equals("cp") ) { + + $str = $c2.lhs + $c2.ss + "=" + $c2.rhs; + + } else if ( $t.text.equals("pf") ) { + + $str = $c1.lhs + $c1.ss + $c2.op + $c1.rhs ; + + } else if ( $t.text.equals("fp")) { + + $str = $c2.lhs + $c2.ss + $c1.op + $c2.rhs; + + } else if ( $t.text.equals("fc")) { + + $str = $c1.lhs + $c1.op + $c1.rhs ; + + } else if ( $t.text.equals("cf")) { + + $str = $c1.lhs + $c2.op + $c1.rhs ; + + + } else if ( $t.text.equals("cc")) { + + $str = $c1.lhs+"="+$c1.rhs ; + + } else { // ff + + $str = " 1 > 0 "; // do something + } + + + + } + ; + +goal_content returns[boolean hasDvar, String str, String ss, String weight, String lhs, String rhs, String type, String op] +@init{$hasDvar=false; String kind=null; $type="constrain";} + : + ( Constrain | Free | Penalty ) l=Lhs o=Op r=Rhs ( Sign Kind s=Slack_Surplus w=Weight )? + + { $str = $l.text + $o.text + $r.text; + + if (s!=null) { + + if ($goal::case_condition.equalsIgnoreCase(Param.conditional)){ + + $goal::dvarWeightMap.put($s.text.toLowerCase(), $w.text.toLowerCase()); + $goal::dvarSlackSurplus.add($s.text.toLowerCase()); + $goal::gl.dvarWeightMapList.set($goal::caseNumber,$goal::dvarWeightMap); + $goal::gl.dvarSlackSurplusList.set($goal::caseNumber,$goal::dvarSlackSurplus); + } + //System.out.println($s.text.toLowerCase()+": "+$w.text.toLowerCase()); + //$goal::gl.dvarName.set($goal::caseNumber, $s.text.toLowerCase()); + //$goal::gl.dvarWeight.set($goal::caseNumber, $w.text.toLowerCase()); + //F.dvarStd($s.text, $goal::scop, null, $Kind.text, ""); + if ($goal::ta==null){ + $ss = $Sign.text + $s.text; + F.dvarSlackSurplus($s.text, $goal::scop, $Kind.text, "", $goal::case_condition, "0"); + F.mergeSlackSurplusIntoWeightTable($s.text, $w.text, $goal::scop, $goal::case_condition, "0"); + }else if ($goal::ta.equals("0")){ + $ss = $Sign.text + $s.text; + F.dvarSlackSurplus($s.text, $goal::scop, $Kind.text, "", $goal::case_condition, "0"); + F.mergeSlackSurplusIntoWeightTable($s.text, $w.text, $goal::scop, $goal::case_condition, "0"); + }else{ + $ss = $Sign.text + $s.text+"(\$m)"; + F.dvarSlackSurplus($s.text, $goal::scop, $Kind.text, "", $goal::case_condition, $goal::ta); + F.mergeSlackSurplusIntoWeightTable($s.text, $w.text, $goal::scop, $goal::case_condition, $goal::ta); + } + $hasDvar = true; + $weight = $w.text; } + //} else { + + $lhs = $l.text; $rhs = $r.text; $op = $o.text; + //} + } + ; + +goal_content_simple returns[String str] + : + Simple l=Lhs o=Op r=Rhs + { $str = $l.text + $o.text + $r.text; } + ; + +svar_table : + ^( Svar_table sc=Scope i=IDENT t=table_content ) + { F.svarTable($i.text, $sc.text, $t.text, $t.dependants, $t.varInCycle); } + ; + +svar_timeArray_table : + ^( Svar_table ta=TimeArraySize sc=Scope i=IDENT t=table_content ) + { F.svarTable($i.text, $sc.text, $t.text, $t.dependants, $t.varInCycle, $ta.text); } + ; + +svar_sum : + ^(Svar_sum sc=Scope i=IDENT sum=sum_content ) + { F.svarSum($i.text, $sc.text, $sum.hdr, $sum.expr, $sum.dependants, $sum.varInCycle ); } + ; + +svar_timeArray_sum : + ^(Svar_sum ta=TimeArraySize sc=Scope i=IDENT sum=sum_content ) + { F.svarSum($i.text, $sc.text, $sum.hdr, $sum.expr, $sum.dependants, $sum.varInCycle, $ta.text ); } + ; + +sum_content returns[String hdr, String expr, String dependants, String varInCycle]: +^(h=Sum_hdr e=Expression d=Dependants vc=VarInCycle) + { + $hdr="SUM"+Tools.replace_ignoreChar( Tools.replace_seperator($h.text)); + $expr = $e.text; + $dependants = $d.text; + $varInCycle = $vc.text; + } +; + +svar_expr : + ^(Svar_const sc=Scope i=IDENT v=Expression d=Dependants vc=VarInCycle) + { F.svarExpression($i.text, $sc.text, Tools.replace_seperator($v.text), $d.text, $vc.text ); } + ; + +svar_timeArray_expr : + ^(SvarTimeArray_const ta=TimeArraySize sc=Scope i=IDENT v=Expression d=Dependants vc=VarInCycle) + { F.svarExpression($i.text, $sc.text, Tools.replace_seperator($v.text), $d.text, $vc.text, $ta.text ); } + ; + +svar_dss : + ^(Svar_dss sc=Scope i=IDENT b=B_part Kind k=STRING Units u=STRING c=CONVERT ) + { F.timeseriesDss($i.text, $sc.text, Tools.strip($b.text), Tools.strip($k.text), Tools.strip($u.text), Tools.strip($c.text)); } + ; + +dvar_std : + ^(Dvar_std sc=Scope i=IDENT Kind k=STRING Units u=STRING) + { F.dvarStd($i.text, $sc.text, null, Tools.strip($k.text), Tools.strip($u.text)); } + ; + +dvar_nonStd : + ^(Dvar_nonStd sc=Scope i=IDENT Lower lowerbound=LimitType Upper upperbound=LimitType Kind k=STRING Units u=STRING) + {F.dvarNonStd($i.text, $sc.text, null, Tools.strip($k.text), Tools.strip($u.text), $lowerbound.text, $upperbound.text);} + ; + +dvar_timeArray_std : + ^(DvarTimeArray_std ta=TimeArraySize sc=Scope i=IDENT Kind k=STRING Units u=STRING) + { F.dvarStd($i.text, $sc.text, null, Tools.strip($k.text), Tools.strip($u.text), $ta.text ); } + ; + +dvar_timeArray_nonStd : + ^(DvarTimeArray_nonStd ta=TimeArraySize sc=Scope i=IDENT Lower lowerbound=LimitType Upper upperbound=LimitType Kind k=STRING Units u=STRING) + {F.dvarNonStd($i.text, $sc.text, null, Tools.strip($k.text), Tools.strip($u.text), $lowerbound.text, $upperbound.text, $ta.text);} + ; + +/// Expression /// +term + : IDENT + | '(' expression ')' + | INTEGER + ; + +unary : NEGATION? term ; + +mult : unary (('*' | '/' ) unary)* ; + +expression : mult (('+' | '-') mult)* ; + +c_term + : ( expression relation expression ) => expression relation expression + | ( '(' logical ')' ) => '(' logical ')' + ; + +c_unary : NOT? c_term ; + +logical : c_unary ( bin c_unary )* ; + +relation : '>' | '<' | '>=' | '<=' | '==' | '/=' ; + +bin : OR | AND ; + +/// End Expression /// + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/grammar/IncFileFinder.g b/wrims-core/src/main/antlr/wrimsv2/wreslplus/grammar/IncFileFinder.g similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/grammar/IncFileFinder.g rename to wrims-core/src/main/antlr/wrimsv2/wreslplus/grammar/IncFileFinder.g index dcdd48e8f..a0a8eaf6f 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/grammar/IncFileFinder.g +++ b/wrims-core/src/main/antlr/wrimsv2/wreslplus/grammar/IncFileFinder.g @@ -1,132 +1,132 @@ -grammar IncFileFinder; -//import CommonLexer; - -options { - language = Java; - //output=AST; - //ASTLabelType=CommonTree; -} - -@header { - package wrimsv2.wreslplus.grammar; - import wrimsv2.wreslparser.elements.LogUtils; - import wrimsv2.wreslplus.elements.IncFileSimple; - import wrimsv2.wreslplus.elements.LookupTableSimple; - import java.util.HashMap; - import java.util.Set; - import java.util.HashSet; - import java.util.LinkedHashSet; - import java.io.File; -} -@lexer::header { - package wrimsv2.wreslplus.grammar; - import wrimsv2.wreslparser.elements.LogUtils; -} - -@members { - //public ArrayList incFileList; - public ArrayList incFileSimpleList; - public ArrayList lookupTableSimpleList; - //public CommonTree commonTree; - public String currentAbsolutePath; - public String currentAbsoluteParent; - public int number_of_errors = 0; - public int line=1; - - /// error message - public void displayRecognitionError(String[] tokenNames, - RecognitionException e) { - String hdr = getErrorHeader(e); - String msg = getErrorMessage(e, tokenNames); - //LogUtils.errMsg("@parser "+ hdr + " " + msg); - LogUtils.errMsgLocation(currentAbsolutePath, e.line, msg); - number_of_errors++; - } -} - -@lexer::members { - - public String currentAbsolutePath; - public int number_of_errors = 0; - /// error message - public void displayRecognitionError(String[] tokenNames, - RecognitionException e) { - String hdr = getErrorHeader(e); - String msg = getErrorMessage(e, tokenNames); - LogUtils.errMsgLocation(currentAbsolutePath, e.line, msg); - number_of_errors++; - } -} - - -wreslFile -@init{ //incFileList = new ArrayList(); - incFileSimpleList = new ArrayList(); - lookupTableSimpleList = new ArrayList(); } - : .* ( - ( f=include_file - { //incFileList.add(new File(currentAbsoluteParent, $f.fp_string).toString()); - $f.incFileObj.absPath=new File(currentAbsoluteParent, $f.fp_string).toString(); - incFileSimpleList.add($f.incFileObj); - } - | include_group - | include_model - | l=lookup - { lookupTableSimpleList.add($l.lookupTableObj); - }) - .* ) * ; - -include_group : INCLUDE GROUP ID ; -include_model : INCLUDE MODEL ID ; -include_file returns[String fp_string, IncFileSimple incFileObj] -@init {$incFileObj = new IncFileSimple(); - $incFileObj.fromWresl = this.currentAbsolutePath; - } - -@after{$incFileObj.line=line; - } - : i=INCLUDE{line=$i.line;}(local_deprecated)? fp=file_path {$fp_string = $fp.text.substring(1,$fp.text.length()-1);} - ; - -file_path : QUOTE ; - -local_deprecated - : '[' LOCAL ']' ; - - -lookup returns[String tp_string, LookupTableSimple lookupTableObj] -@init {$lookupTableObj = new LookupTableSimple(); - $lookupTableObj.fromWresl = this.currentAbsolutePath; - } - -@after{$lookupTableObj.line=line; - } -: SELECT ID i=FROM {line=$i.line;} ft=fromTable {$lookupTableObj.tableName=$ft.text;} ; - -fromTable : -ID ; - -QUOTE : '\'' (Letter | Digit | '\\' | '_' | '.' | '-' | '/' )+ '\'' ; - -ML_COMMENT : '/*' .* '*/' {skip();}; - -SL_COMMENT : ('#'|'!') ~('\r'|'\n')* '\r'? ( '\n' | EOF ) {skip();}; //{$channel=HIDDEN;} ; - -INCLUDE : 'include' | 'INCLUDE' | 'Include' ; -LOCAL : 'local' | 'LOCAL' | 'Local' ; -MODEL : 'model' | 'MODEL' | 'Model' ; -GROUP : 'group' | 'GROUP' | 'Group' ; -SELECT : 'select'|'SELECT'|'Select'; -FROM : 'from'|'FROM'|'From'; -WHERE: 'where'|'WHERE'|'Where'; - -WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {skip();}; //{$channel = HIDDEN;}; - -ID : Letter ( Letter | Digit | '_' )* ; -N : Digit+ {skip();}; - -fragment Letter : 'a'..'z' | 'A'..'Z'; - -fragment Digit : '0'..'9'; - -Others : '{'|'}'|'\\'|'.'|'='|'('|')'|'\r'|'\n'|'<'|'>'|'+'|'-'|'*'|'/'|','|'$' {skip();}; +grammar IncFileFinder; +//import CommonLexer; + +options { + language = Java; + //output=AST; + //ASTLabelType=CommonTree; +} + +@header { + package wrimsv2.wreslplus.grammar; + import wrimsv2.wreslparser.elements.LogUtils; + import wrimsv2.wreslplus.elements.IncFileSimple; + import wrimsv2.wreslplus.elements.LookupTableSimple; + import java.util.HashMap; + import java.util.Set; + import java.util.HashSet; + import java.util.LinkedHashSet; + import java.io.File; +} +@lexer::header { + package wrimsv2.wreslplus.grammar; + import wrimsv2.wreslparser.elements.LogUtils; +} + +@members { + //public ArrayList incFileList; + public ArrayList incFileSimpleList; + public ArrayList lookupTableSimpleList; + //public CommonTree commonTree; + public String currentAbsolutePath; + public String currentAbsoluteParent; + public int number_of_errors = 0; + public int line=1; + + /// error message + public void displayRecognitionError(String[] tokenNames, + RecognitionException e) { + String hdr = getErrorHeader(e); + String msg = getErrorMessage(e, tokenNames); + //LogUtils.errMsg("@parser "+ hdr + " " + msg); + LogUtils.errMsgLocation(currentAbsolutePath, e.line, msg); + number_of_errors++; + } +} + +@lexer::members { + + public String currentAbsolutePath; + public int number_of_errors = 0; + /// error message + public void displayRecognitionError(String[] tokenNames, + RecognitionException e) { + String hdr = getErrorHeader(e); + String msg = getErrorMessage(e, tokenNames); + LogUtils.errMsgLocation(currentAbsolutePath, e.line, msg); + number_of_errors++; + } +} + + +wreslFile +@init{ //incFileList = new ArrayList(); + incFileSimpleList = new ArrayList(); + lookupTableSimpleList = new ArrayList(); } + : .* ( + ( f=include_file + { //incFileList.add(new File(currentAbsoluteParent, $f.fp_string).toString()); + $f.incFileObj.absPath=new File(currentAbsoluteParent, $f.fp_string).toString(); + incFileSimpleList.add($f.incFileObj); + } + | include_group + | include_model + | l=lookup + { lookupTableSimpleList.add($l.lookupTableObj); + }) + .* ) * ; + +include_group : INCLUDE GROUP ID ; +include_model : INCLUDE MODEL ID ; +include_file returns[String fp_string, IncFileSimple incFileObj] +@init {$incFileObj = new IncFileSimple(); + $incFileObj.fromWresl = this.currentAbsolutePath; + } + +@after{$incFileObj.line=line; + } + : i=INCLUDE{line=$i.line;}(local_deprecated)? fp=file_path {$fp_string = $fp.text.substring(1,$fp.text.length()-1);} + ; + +file_path : QUOTE ; + +local_deprecated + : '[' LOCAL ']' ; + + +lookup returns[String tp_string, LookupTableSimple lookupTableObj] +@init {$lookupTableObj = new LookupTableSimple(); + $lookupTableObj.fromWresl = this.currentAbsolutePath; + } + +@after{$lookupTableObj.line=line; + } +: SELECT ID i=FROM {line=$i.line;} ft=fromTable {$lookupTableObj.tableName=$ft.text;} ; + +fromTable : +ID ; + +QUOTE : '\'' (Letter | Digit | '\\' | '_' | '.' | '-' | '/' )+ '\'' ; + +ML_COMMENT : '/*' .* '*/' {skip();}; + +SL_COMMENT : ('#'|'!') ~('\r'|'\n')* '\r'? ( '\n' | EOF ) {skip();}; //{$channel=HIDDEN;} ; + +INCLUDE : 'include' | 'INCLUDE' | 'Include' ; +LOCAL : 'local' | 'LOCAL' | 'Local' ; +MODEL : 'model' | 'MODEL' | 'Model' ; +GROUP : 'group' | 'GROUP' | 'Group' ; +SELECT : 'select'|'SELECT'|'Select'; +FROM : 'from'|'FROM'|'From'; +WHERE: 'where'|'WHERE'|'Where'; + +WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {skip();}; //{$channel = HIDDEN;}; + +ID : Letter ( Letter | Digit | '_' )* ; +N : Digit+ {skip();}; + +fragment Letter : 'a'..'z' | 'A'..'Z'; + +fragment Digit : '0'..'9'; + +Others : '{'|'}'|'\\'|'.'|'='|'('|')'|'\r'|'\n'|'<'|'>'|'+'|'-'|'*'|'/'|','|'$' {skip();}; diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/grammar/WreslPlus.g b/wrims-core/src/main/antlr/wrimsv2/wreslplus/grammar/WreslPlus.g similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/grammar/WreslPlus.g rename to wrims-core/src/main/antlr/wrimsv2/wreslplus/grammar/WreslPlus.g index 77d17b3e2..fcd54a817 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/grammar/WreslPlus.g +++ b/wrims-core/src/main/antlr/wrimsv2/wreslplus/grammar/WreslPlus.g @@ -1,1208 +1,1208 @@ -grammar WreslPlus; -//import CommonLexer; - -options { - language = Java; - output=AST; - ASTLabelType=CommonTree; -} - -@header { - package wrimsv2.wreslplus.grammar; - import wrimsv2.wreslparser.elements.LogUtils; - import java.util.HashMap; - import java.util.LinkedHashMap; - import java.util.Set; - import java.util.HashSet; - import java.util.LinkedHashSet; - import wrimsv2.wreslplus.elements.Tools; - import wrimsv2.wreslplus.elements.IncFileTemp; - import wrimsv2.wreslplus.elements.IfIncItemGroup; - import wrimsv2.wreslplus.elements.TimeseriesTemp; - import wrimsv2.wreslplus.elements.ExternalTemp; - import wrimsv2.wreslplus.elements.DvarTemp; - import wrimsv2.wreslplus.elements.SvarTemp; - import wrimsv2.wreslplus.elements.ParamTemp; - import wrimsv2.wreslplus.elements.WeightTable; - import wrimsv2.wreslplus.elements.WeightSubgroup; - import wrimsv2.wreslplus.elements.AliasTemp; - import wrimsv2.wreslplus.elements.GoalTemp; - import wrimsv2.wreslplus.elements.GoalHS; - import wrimsv2.wreslplus.elements.GoalCase; - import wrimsv2.wreslplus.elements.ModelTemp; - import wrimsv2.wreslplus.elements.SequenceTemp; - import wrimsv2.wreslplus.elements.StudyTemp; - import wrimsv2.wreslplus.elements.VarCycleIndex; - import wrimsv2.commondata.wresldata.Param; -} -@lexer::header { - package wrimsv2.wreslplus.grammar; - import wrimsv2.wreslparser.elements.LogUtils; -} - -@members { - public CommonTree commonTree; - public String currentAbsolutePath; - public String currentAbsoluteParent; - public String pathRelativeToRunDir; - public StudyTemp styObj; - public ModelTemp mObj; - public Set dependants; - public Set dependantTypes; - public Set dependants_notAllowed; - public Set varInCycle; - public Map> neededCycleVarMap; - boolean addDep = true; - boolean isParameter = false; - public int number_of_errors = 0; - public int line=1; - - /// error message - public void displayRecognitionError(String[] tokenNames, - RecognitionException e) { - String hdr = getErrorHeader(e); - String msg = getErrorMessage(e, tokenNames); - //LogUtils.errMsg("@parser "+ hdr + " " + msg); - LogUtils.errMsgLocation(currentAbsolutePath, e.line, msg); - number_of_errors++; - } -} - -@lexer::members { - - public int number_of_errors = 0; - /// error message - public void displayRecognitionError(String[] tokenNames, - RecognitionException e) { - String hdr = getErrorHeader(e); - String msg = getErrorMessage(e, tokenNames); - LogUtils.errMsg("@lexer "+ hdr + " " + msg); - number_of_errors++; - } -} -//wreslPlusMain : study template* sequence+ model+; - - -wreslFile -@after{ mObj = $t.modelObj;} - : ('{' t=mt '}' EOF ) | ( t=mt EOF ); - -wreslMain -scope { StudyTemp sty;} -@init { $wreslMain::sty = new StudyTemp();} -@after{ styObj = $wreslMain::sty; } - - : - initial? - ( seq=sequence { $wreslMain::sty.seqList.add($seq.id); $wreslMain::sty.seqMap.put($seq.id,$seq.seqObj); } )+ - ( g=group { $wreslMain::sty.modelList.add($g.id); $wreslMain::sty.modelMap.put($g.id, $g.modelObj); } )* - ( m=model { $wreslMain::sty.modelList.add($m.id); $wreslMain::sty.modelMap.put($m.id, $m.modelObj); } )+ - EOF ; - -local_deprecated - : '[' LOCAL ']' ; - //{LogUtils.warningMsg("\"[local]\" is deprecated. All variables are by default local.");}; - -initial -@init { isParameter=true; } -@after{ isParameter=false; } - : - Initial '{' - //config* - ( - ( c=constant {$wreslMain::sty.parameterList.add($c.id); $wreslMain::sty.parameterConstList.add($c.id); $wreslMain::sty.parameterMap.put($c.id, $c.ptObj);} ) - | ( s=svar_initial {$wreslMain::sty.parameterList.add($s.id); $wreslMain::sty.parameterMap.put($s.id, $s.svObj);} ) - )+ - '}'; - -//config : CONFIG SORTING '{' VALUE (TRUE | (FALSE {$wreslMain::sty.isSort=false;}))'}' ; - -constant returns[String id, SvarTemp ptObj] -@init{ $ptObj = new SvarTemp(); - dependants = new LinkedHashSet(); } - : Const i=ID '{' n=number '}' //n=expr_add_simple - - { - $id = $i.text; - $ptObj.id = $i.text; - $ptObj.caseName.add(Param.defaultCaseName); - $ptObj.caseCondition.add(Param.always); - $ptObj.caseExpression.add($n.text); - $ptObj.dependants = dependants; - - }; - -svar_initial returns[String id, SvarTemp svObj] -@init{ dependants = new LinkedHashSet(); - dependantTypes = new LinkedHashSet(); - dependants_notAllowed = new LinkedHashSet(); } - : SVAR svar_g { $id=$svar_g.id; $svObj=$svar_g.svObj; $svObj.dependants_notAllowed=dependants_notAllowed; } ; - - - -expression_simple -@init{ dependants = new LinkedHashSet(); } - : expr_add_simple ; - - - -//study : 'study' ID '{' include_template* include_sequence+ '}' ; -// -// -//include_template : INCLUDE 'template' ( ID | include_file ) ; -//include_sequence : INCLUDE SEQUENCE ID ; - - - -template : TEMPLATE ID '{' ( template_svar | template_dvar | template_dvar_array )* '}' ; - -template_dvar : '%dvar' varID '{' dvar_trunk '}' ; - -template_dvar_array : '%dvar' dimension varID '{' dvar_trunk '}' ; - -template_svar : '%svar' varID svar_trunk ; - -sequence returns[String id, SequenceTemp seqObj] -@init {$seqObj = new SequenceTemp(); - dependants = new LinkedHashSet(); - $seqObj.fromWresl = this.currentAbsolutePath; - - // for condition expression if previous cycle var is used - neededCycleVarMap = new HashMap>(); - } - -@after{$seqObj.model=$m.text; $seqObj.order=$o.text; - $seqObj.dependants= dependants; $seqObj.line=line; - $seqObj.neededCycleVarMap = neededCycleVarMap; - } - - : SEQUENCE i=ID {$id=$i.text; $seqObj.id=$i.text;} - '{' MODEL m=ID - (( CONDITION cc=logical_main {$seqObj.condition=$cc.text;} ORDER o=INT )| - ( ORDER o=INT (CONDITION cc=logical_main {$seqObj.condition=$cc.text;})? ) ) - ( TIMESTEP t=TIMESTEPVALUE {$seqObj.timeStep=$t.text.toUpperCase();} )? - '}' - ; - - - -group returns[String id, ModelTemp modelObj] -: GROUP i=ID {$id=$i.text;} '{' t=mt '}' {$modelObj =$t.modelObj; $modelObj.id=$id;} ; - - - -model_standalone : model ; - -model returns[String id, ModelTemp modelObj] -: MODEL i=modelName {$id=$i.text;} - '{' t=mt '}' - {$modelObj =$t.modelObj; $modelObj.id=$id;} - ; - -modelName: ID; - -//model trunk -mt returns[ModelTemp modelObj] - -scope { ModelTemp m_;} -@init{ neededCycleVarMap = new HashMap>(); - $mt::m_ = new ModelTemp(); - $mt::m_.absPath = currentAbsolutePath; - $mt::m_.parentAbsPath = currentAbsoluteParent; } -@after{$modelObj =$mt::m_; - $modelObj.neededCycleVarMap = neededCycleVarMap; - $modelObj.id=Param.legacywresl;} -: - ( fi=include_file {$mt::m_.itemTypeList.add(Param.incFileType); $mt::m_.itemList.add($fi.id); $mt::m_.incFileIDList.add($fi.id); $mt::m_.incFileMap.put($fi.id, $fi.incFileObj); } - | ts=timeseries {$mt::m_.itemTypeList.add(Param.tsType);$mt::m_.itemList.add($ts.id); $mt::m_.tsList.add($ts.id); $mt::m_.tsMap.put($ts.id, $ts.tsObj); } - | sv=svar_group {$mt::m_.itemTypeList.add(Param.svType);$mt::m_.itemList.add($sv.id); $mt::m_.svList.add($sv.id); $mt::m_.svMap.put($sv.id, $sv.svObj); } - | dv=dvar_g {$mt::m_.itemTypeList.add(Param.dvType);$mt::m_.itemList.add($dv.id); $mt::m_.dvList.add($dv.id); $mt::m_.dvMap.put($dv.id, $dv.dvObj); } - | ex=ex_g {$mt::m_.itemTypeList.add(Param.exType);$mt::m_.itemList.add($ex.id); $mt::m_.exList.add($ex.id); $mt::m_.exMap.put($ex.id, $ex.exObj); } - | as=alias {$mt::m_.itemTypeList.add(Param.asType);$mt::m_.itemList.add($as.id); $mt::m_.asList.add($as.id); $mt::m_.asMap.put($as.id, $as.asObj); } - | gl1=goal_s {$mt::m_.itemTypeList.add(Param.gl1Type);$mt::m_.itemList.add($gl1.id);$mt::m_.glList.add($gl1.id);$mt::m_.glMap.put($gl1.id, $gl1.glObj); } - | gl2=goal_hs {$mt::m_.itemTypeList.add(Param.gl2Type);$mt::m_.itemList.add($gl2.id);$mt::m_.glList.add($gl2.id);$mt::m_.glMap.put($gl2.id, $gl2.glObj); $mt::m_.gl2List.add($gl2.id); } - | network - | wt=weight {$mt::m_.wTableObjList.add($wt.wtObj);} - | im=include_model {$mt::m_.itemTypeList.add(Param.incModelType);$mt::m_.itemList.add(Param.model_label+$im.id); $mt::m_.incModelList.add($im.id); - $mt::m_.incFileIDList.add($im.id); $mt::m_.incFileMap.put($im.id, null); - } - | ifig=if_inc_items {$mt::m_.itemTypeList.add(Param.ifIncItemGroupType); $mt::m_.itemList.add($ifig.id); $mt::m_.ifIncItemGroupIDList.add($ifig.id); $mt::m_.ifIncItemGroupMap.put($ifig.id, $ifig.ifIncItemGroupObj); } - )+ - ; - -if_inc_items returns[String id, IfIncItemGroup ifIncItemGroupObj] -scope { IfIncItemGroup incg_; - ArrayList _arr; - HashMap _incfmap; - HashMap _incSvarMap; - HashMap _incDvarMap; - LinkedHashMap _incAliasMap; - HashMap _incTimeseriesMap; - HashMap _incGoalSimpleMap; - HashMap _incGoalComplexMap; - HashMap _incWeightTableMap; - } -@init{ $if_inc_items::incg_ = new IfIncItemGroup(); - $if_inc_items::incg_.id = "__item__"+Integer.toString($mt::m_.ifIncItemGroupIDList.size()); - $id = $if_inc_items::incg_.id; - $ifIncItemGroupObj = $if_inc_items::incg_; - //dependants = new LinkedHashSet(); - $if_inc_items::incg_.dependants = new HashSet(); - // $incg_.id = "__incfilegroup__"+Integer.toString($mt::m_.incFileGroupIDList.size()); - - } -@after{ - // reserve space - $mt::m_.svList.add($if_inc_items::incg_.id); - $mt::m_.dvList.add($if_inc_items::incg_.id); - $mt::m_.asList.add($if_inc_items::incg_.id); - $mt::m_.tsList.add($if_inc_items::incg_.id); - $mt::m_.glList.add($if_inc_items::incg_.id); - $mt::m_.gl2List.add($if_inc_items::incg_.id); - //$if_inc_items::incg_.dependants = dependants; - $if_inc_items::incg_.fromWresl = this.currentAbsolutePath; - $if_inc_items::incg_.line=line; - // $mt::m_.wTableObjList.add($if_inc_items::incg_.id); - -} - : if_ elseif_* else_? ; - -if_ -@init{ dependants = new LinkedHashSet(); } - : - If{line=$If.line;} e=logical_main {$if_inc_items::incg_.dependants.addAll(dependants);} - '{' include_item_group '}' - {$if_inc_items::incg_.conditionList.add($e.text);}; - -elseif_ -@init{ dependants = new LinkedHashSet(); } - : - Elseif e=logical_main {$if_inc_items::incg_.dependants.addAll(dependants);} - '{' include_item_group '}' - {$if_inc_items::incg_.conditionList.add($e.text);}; - -else_ : - Else '{' include_item_group '}' - {$if_inc_items::incg_.conditionList.add(Param.always);}; - -include_item_group -@init{ $if_inc_items::_arr = new ArrayList(); - $if_inc_items::_incfmap = new HashMap(); - $if_inc_items::_incSvarMap = new HashMap(); - $if_inc_items::_incDvarMap = new HashMap(); - $if_inc_items::_incAliasMap = new LinkedHashMap(); - $if_inc_items::_incTimeseriesMap = new HashMap(); - $if_inc_items::_incGoalSimpleMap = new HashMap(); - $if_inc_items::_incGoalComplexMap = new HashMap(); - $if_inc_items::_incWeightTableMap = new HashMap(); -} -@after { - $if_inc_items::incg_.inc_item_list.add($if_inc_items::_arr); - $if_inc_items::incg_.inc_files_map_list.add($if_inc_items::_incfmap); - $if_inc_items::incg_.inc_svar_map_list.add($if_inc_items::_incSvarMap); - $if_inc_items::incg_.inc_dvar_map_list.add($if_inc_items::_incDvarMap); - $if_inc_items::incg_.inc_alias_map_list.add($if_inc_items::_incAliasMap); - $if_inc_items::incg_.inc_timeseries_map_list.add($if_inc_items::_incTimeseriesMap); - $if_inc_items::incg_.inc_goalSimple_map_list.add($if_inc_items::_incGoalSimpleMap); - $if_inc_items::incg_.inc_goalComplex_map_list.add($if_inc_items::_incGoalComplexMap); - $if_inc_items::incg_.inc_weightTable_map_list.add($if_inc_items::_incWeightTableMap); -} -: - ( - ( fi=include_file { - $if_inc_items::_arr.add($fi.id); - $if_inc_items::_incfmap.put($fi.id, $fi.incFileObj); - $mt::m_.incFileIDList.add($if_inc_items::incg_.id); - }) - | ( si=svar_group { - $if_inc_items::_arr.add($si.id); - $if_inc_items::_incSvarMap.put($si.id, $si.svObj); - }) - | ( di=dvar_g { - $if_inc_items::_arr.add($di.id); - $if_inc_items::_incDvarMap.put($di.id, $di.dvObj); - }) - | ( ai=alias { - $if_inc_items::_arr.add($ai.id); - $if_inc_items::_incAliasMap.put($ai.id, $ai.asObj); - }) - | ( ti=timeseries { - $if_inc_items::_arr.add($ti.id); - $if_inc_items::_incTimeseriesMap.put($ti.id, $ti.tsObj); - }) - | ( gsi=goal_s { - $if_inc_items::_arr.add($gsi.id); - $if_inc_items::_incGoalSimpleMap.put($gsi.id, $gsi.glObj); - }) - | ( ghi=goal_hs { - $if_inc_items::_arr.add($ghi.id); - $if_inc_items::_incGoalComplexMap.put($ghi.id, $ghi.glObj); - }) - | ( wti=weight { - $if_inc_items::_incWeightTableMap.put($wti.id, $wti.wtObj); - }) - )+ ; - - -///// external -// -//external returns[String id, ExternalTemp exObj] -//scope { ExternalTemp ex_;} -//@init{ $external::ex_ = new ExternalTemp(); -// $external::ex_.fromWresl = this.currentAbsolutePath; -// dependants = new LinkedHashSet(); -// } -//@after{ $id = $external::ex_.id; $exObj=$external::ex_;} -// : external_old -// ; -// -//external_old : DEFINE ('[' LOCAL ']')? externalID '{' EXTERNAL external_fileName '}' ; -// -// -//external_fileName : f=fileName {$external::ex_.fileName=$f.text;} ; -//fileName : ID ('.' ID)? ; -//externalID : i=ID {$external::ex_.id=$i.text;} ; - - -weight returns[String id, WeightTable wtObj] -scope { WeightTable wt_; - String id_; - } -@init{ $weight::wt_ = new WeightTable(); - $weight::wt_.fromWresl = this.currentAbsolutePath; - $weight::wt_.line = line; - dependants = new LinkedHashSet(); - } -@after{ $id = $weight::wt_.id_lowcase; $wtObj=$weight::wt_; $wtObj.dependants= dependants;} - : weight_legacy | weight_new ; - -weight_legacy : OBJECTIVE{line=$OBJECTIVE.line;} (local_deprecated)? objGroupName '='? '{' weight_legacy_unit+ '}' ; - -//obj : 'obj' | 'Obj' | 'OBJ' ; -objGroupName : i=ID {$weight::wt_.id_lowcase=$i.text.toLowerCase(); - $weight::wt_.id_raw=$i.text;} ; - -weight_legacy_unit - : '[' i=ID{line=$i.line;} (ta=weightTimeArray {$weight::wt_.varTimeArraySizeMap.put($i.text,$ta.text);})? ',' e=expr_add ']' ','? - {$weight::wt_.varList.add($i.text); - $weight::wt_.varWeightMap.put($i.text,$e.text); - $weight::wt_.varLineMap.put($i.text, line);}; - -weightTimeArray : '(' d=( INT | ID ) ')'; // this is a repetition. The time array should be known when dvar is declared. - -weight_new : OBJECTIVE{line=$OBJECTIVE.line;} weightTableID '{' weight_group '}' ; - -weightTableID : i=ID {$weight::wt_.id_lowcase=$i.text.toLowerCase(); - $weight::wt_.id_raw=$i.text; - $weight::wt_.line=$i.getLine();} ; - -weight_group -@init{ $weight::wt_.isWeightGroup=true; } - : WEIGHT w=expr_add {$weight::wt_.commonWeight=$w.text;} - weight_trunk - ; - -weight_trunk - : ( DeviationPenalty p=expr_add {$weight::wt_.deviationPenalty=$p.text;} )? - ( DeviationTolerance t=expr_add {$weight::wt_.deviationTolerance=$t.text;} )? - VARIABLE ( weight_group_unit | weight_subgroup )+ - ; - -weight_group_unit : i=ID {$weight::wt_.varList.add($i.text);} ; - -weight_subgroup -scope { WeightSubgroup sub_;} -@init{ $weight_subgroup::sub_ = new WeightSubgroup(); } -@after{ $weight_subgroup::sub_.id=$i.text; - $weight::wt_.subgroupMap.put($i.text,$weight_subgroup::sub_); - //$weight::wt_.varList.add($i.text); - //System.out.println("subgroup: "+$weight::wt_.subgroupMap.keySet()); - } - : i=ID //{$weight::wt_.subgroupMap.put($i.text.toLowerCase(),$weight_subgroup::sub_);} - '{' weight_subgroup_trunk '}' - ; - -weight_subgroup_trunk - : ( DeviationPenalty p=expr_add {$weight_subgroup::sub_.deviationPenalty=$p.text;} )? - ( DeviationTolerance t=expr_add {$weight_subgroup::sub_.deviationTolerance=$t.text;} )? - VARIABLE ( weight_subgroup_unit+ ) // | weight_subgroup )+ - ; - -weight_subgroup_unit : i=ID {$weight_subgroup::sub_.varList.add($i.text);} ; - - -include_model returns[String id] : INCLUDE (MODEL|GROUP) i=ID {$id=$i.text;} ; - -include_file returns[String id, IncFileTemp incFileObj] -@init{ $incFileObj = new IncFileTemp(); - $incFileObj.id = "__file__"+Integer.toString($mt::m_.incFileIDList.size()); - $id = $incFileObj.id; - } - : INCLUDE (local_deprecated)? fp=file_path {$incFileObj.rawPath=Tools.strip($fp.text);} ; - -file_path : QUOTE ; - - -/// goal simple -goal_s returns[String id, GoalTemp glObj] -scope { GoalTemp gl_; - String id_; - } -@init{ $goal_s::gl_ = new GoalTemp(); - $goal_s::gl_.fromWresl = this.currentAbsolutePath; - $goal_s::gl_.hasCase = false; - dependants = new LinkedHashSet(); - varInCycle = new LinkedHashSet(); - } -@after{ $id = $goal_s::gl_.id; - $glObj=$goal_s::gl_; - $glObj.dependants= dependants; - $glObj.neededVarInCycleSet= varInCycle; - $glObj.needVarFromEarlierCycle = (varInCycle!=null); - $glObj.line=line;} - - : GOAL{line=$GOAL.line;} (local_deprecated)? (goalSimpleArray|goalSimpleTimeArray)? i=ID '{' ( e=expr_constraint )'}' - {$goal_s::gl_.id=$i.text; - $goal_s::gl_.caseCondition.add(Param.always); - $goal_s::gl_.caseName.add(Param.defaultCaseName); - $goal_s::gl_.caseExpression.add($e.text);}; - -goalSimpleArray : '[' d=( INT | ID ) ']' {$goal_s::gl_.arraySize=$d.text; }; -goalSimpleTimeArray : '(' d=( INT | ID ) ')' {$goal_s::gl_.timeArraySize=$d.text; }; - - -/// goal hs -goal_hs returns[String id, GoalTemp glObj] -scope { GoalTemp gl_; - String id_; - } -@init{ $goal_hs::gl_ = new GoalTemp(); - $goal_hs::gl_.fromWresl = this.currentAbsolutePath; - dependants = new LinkedHashSet(); - varInCycle = new LinkedHashSet(); - $goal_hs::gl_.hasLhs=true; - } -@after{ $id = $goal_hs::gl_.id; - $glObj=$goal_hs::gl_; - $glObj.dependants= dependants; - $glObj.neededVarInCycleSet= varInCycle; - $glObj.needVarFromEarlierCycle = (varInCycle!=null); - $glObj.line=line;} - : GOAL{line=$GOAL.line;} (local_deprecated)? (goalHsArray|goalHsTimeArray)? i=ID {$goal_hs::gl_.id=$i.text;} - '{' lhs - ( goal_hs_nocase - | goal_hs_cases - ) '}'; - -goalHsArray : '[' d=( INT | ID ) ']' {$goal_hs::gl_.arraySize=$d.text; }; -goalHsTimeArray : '(' d=( INT | ID ) ')' {$goal_hs::gl_.timeArraySize=$d.text; }; - -goal_hs_nocase -@after{ $t.gc.id = Param.defaultCaseName; - $goal_hs::gl_.caseName.add($t.gc.id); - $goal_hs::gl_.caseMap.put($t.gc.id, $t.gc); - $goal_hs::gl_.hasCase = false; - } - : t=goal_hs_trunk ; - -goal_hs_trunk returns[GoalCase gc] -scope { GoalCase gc_; } -@init { $goal_hs_trunk::gc_ = new GoalCase();} -@after{ $gc=$goal_hs_trunk::gc_;} - : rhs ((lhs_gt_rhs lhs_lt_rhs?) | (lhs_lt_rhs lhs_gt_rhs?))? ; - -goal_hs_cases : goal_hs_case+ ; - -goal_hs_case -@after{ $t.gc.id = $ci.text; - $t.gc.condition = $cc.text; - $goal_hs::gl_.caseName.add($t.gc.id); - $goal_hs::gl_.caseMap.put($t.gc.id, $t.gc); - $goal_hs::gl_.hasCase = true;} - : CASE ci=ID '{' CONDITION cc=logical_main t=goal_hs_trunk '}'; - - -lhs : LHS e=expr_add {$goal_hs::gl_.lhs=$e.text;} ; -rhs : RHS e=expr_add {$goal_hs_trunk::gc_.rhs=$e.text;} ; -lhs_gt_rhs : LHS '>' RHS ( PENALTY p=expr_add {$goal_hs_trunk::gc_.lhs_gt_rhs=$p.text;} | constrain ) ; -lhs_lt_rhs : LHS '<' RHS ( PENALTY p=expr_add {$goal_hs_trunk::gc_.lhs_lt_rhs=$p.text;} | constrain ) ; - -constrain : 'constrain' ; - -/// alias - -alias returns[String id, AliasTemp asObj] -scope { AliasTemp as_;} -@init{ $alias::as_ = new AliasTemp(); - $alias::as_.fromWresl = this.currentAbsolutePath; - dependants = new LinkedHashSet(); - varInCycle = new LinkedHashSet(); - } -@after{ $id = $alias::as_.id; - $asObj=$alias::as_; - $asObj.dependants= dependants; - $asObj.neededVarInCycleSet= varInCycle; - $asObj.needVarFromEarlierCycle = (varInCycle!=null); - $asObj.line=line;} - : alias_new | alias_old - ; - -alias_old : DEFINE{line=$DEFINE.line;} (local_deprecated)? (aliasArray|aliasTimeArray)? aliasID '{' ALIAS aliasExpresion aliasKind? aliasUnits? aliasNoSolver? '}' ; -alias_new : ALIAS{line=$ALIAS.line;} (aliasArray|aliasTimeArray)? aliasID '{' aliasExpresion aliasKind? aliasUnits? aliasNoSolver? '}' ; - -aliasExpresion : e=expr_add {$alias::as_.expression=$e.text;}; -aliasID : i=ID {$alias::as_.id=$i.text;}; -aliasUnits: UNITS s=QUOTE {$alias::as_.units=Tools.strip($s.text);}; -aliasKind: KIND s=QUOTE {$alias::as_.kind=Tools.strip($s.text);}; -aliasNoSolver : NoSolver {$alias::as_.noSolver=true;}; - -aliasArray : '[' d=( INT | ID ) ']' {$alias::as_.arraySize=$d.text; }; -aliasTimeArray : '(' d=( INT | ID ) ')' {$alias::as_.timeArraySize=$d.text; }; - -/// svar - -svar_group returns[String id, SvarTemp svObj] - : ( SVAR{line=$SVAR.line;} | DEFINE{line=$DEFINE.line;} (local_deprecated)? ) svar_g { $id=$svar_g.id; $svObj=$svar_g.svObj; $svObj.line=line;} ; - - -svar_g returns[String id, SvarTemp svObj] -scope { SvarTemp sv_; - String id_; - } -@init{ $svar_g::sv_ = new SvarTemp(); - $svar_g::sv_.fromWresl = this.currentAbsolutePath; - dependants = new LinkedHashSet(); - varInCycle = new LinkedHashSet(); - - } -@after{ $id = $svar_g::sv_.id; - $svObj=$svar_g::sv_; - $svObj.dependants= dependants; - $svObj.neededVarInCycleSet= varInCycle; - $svObj.needVarFromEarlierCycle = (varInCycle!=null); - } - : ( svar | svar_array | svar_timeArray ) ; - - -svarID : i=ID {$svar_g::sv_.id =$i.text;} ; - -svar: svarID '{' svar_trunk '}' ; - -svar_array: svarArray svar; - -svar_timeArray: svarTimeArray svar ; - -svarArray : '[' d=( INT | ID ) ']' {$svar_g::sv_.arraySize=$d.text; }; -svarTimeArray : '(' d=( INT | ID ) ')' {$svar_g::sv_.timeArraySize=$d.text; }; - -/// svar trunk - -svar_trunk - : ( svar_noCase | svar_case+ ) ( svarKind svarUnits )? ; - -svarUnits: UNITS QUOTE ; -svarKind: KIND QUOTE ; - -svar_noCase - @after {$svar_g::sv_.caseName.add(Param.defaultCaseName); $svar_g::sv_.caseCondition.add(Param.always);} - : svar_value | svar_sum | svar_table - ; - -svar_case - @after {$svar_g::sv_.caseName.add($ci.text); $svar_g::sv_.caseCondition.add($cc.text);} - : CASE ci=ID '{' CONDITION cc=logical_main ( svar_value | svar_sum | svar_table ) '}' ; - -svar_value - : VALUE e=expr_add - { $svar_g::sv_.caseExpression.add($e.text); }; - -svar_sum - : h=sum_header c=sum_content - { $svar_g::sv_.caseExpression.add($h.text+" "+$c.text); }; - -sum_header - : SUM '(' 'i' '=' e1=expr_add ',' e2=expr_add (',' integer)? ')' - ; - -sum_content - : e=expr_add ; - -svar_table - : t1=svar_table_1 { $svar_g::sv_.caseExpression.add($t1.text); - //System.out.println($t1.text); - } - | svar_table_2 ; - -svar_table_1 - : s=SELECT { $s.setText("select ");} (ID|reservedID) - f=FROM { $f.setText(" from ");} ID - (g=GIVEN { $g.setText(" given ");} expr_assign - u=USE { $u.setText(" use ");} ID)? - (w=WHERE { $w.setText(" where ");} where)? - ; - -where: expr_assign (',' expr_assign)* ; - -svar_table_2 - : 'table' '(' ')' ; - - -// common rules - -dimension : '[' ( INT | ID ) ']' ; - -dimension_time : '(' ( INT | ID ) ')' ; - -//typeNumber: 'integer' | 'real' | 'binary' ; - -//value : 'value' expr_add; - -//sum: 'sum' '(' 'i' '=' INT ',' expr_add ',' INT ')' '(' expr_add ')'; - -//table : 'select' ID 'from' ID 'where' expr_assign (',' expr_assign)* ; - -// end common rules - - - -//timeseries: 'timeseries' ID '{' 'kind' '\'' .+ '\'' 'units' '\'' id_with_dash '\'' '}'; -timeseries returns[String id, TimeseriesTemp tsObj] -scope { TimeseriesTemp ts_; - String id_; - } -@init{ $timeseries::ts_ = new TimeseriesTemp(); - $timeseries::ts_.fromWresl = this.currentAbsolutePath; - } -@after{ $id = $timeseries::ts_.id; - $tsObj = $timeseries::ts_; - $tsObj.line = line; - } - : timeseries_new | timeseries_old ; - -timeseries_new : TIMESERIES{line=$TIMESERIES.line;} tsID '{' (NAME bpart_id)? tsKind tsUnits convert? '}' ; -timeseries_old : DEFINE{line=$DEFINE.line;} (local_deprecated)? tsID '{' TIMESERIES bpart_id? tsKind tsUnits convert? '}' ; - -tsID : i=ID {$timeseries::ts_.id=$i.text;$timeseries::ts_.dssBPart=$i.text;} ; -tsUnits: UNITS s=QUOTE {$timeseries::ts_.units=Tools.strip($s.text);} ; -tsKind: KIND s=QUOTE {$timeseries::ts_.kind=Tools.strip($s.text);} ; -bpart_id : s=QUOTE {$timeseries::ts_.dssBPart=Tools.strip($s.text);}; -convert : CONVERT s=QUOTE {$timeseries::ts_.convertToUnits=Tools.strip($s.text);}; - -/// network -network : NETWORK ID '{' node? connection+ '}'; - -//inlet: 'inlet' ID ( ',' ID)* ; -//outlet: 'outlet' ID ( ',' ID)* ; -node: NODE ID ( ',' ID)* ; - -connection: branch | branch_short ; - -inlet : INFLOW element ; -outlet : element OUTFLOW ; -inoutlet : INFLOW element OUTFLOW ; - -branch_short : inoutlet ; - -branch : (elements | inlet) FLOW (element FLOW)* (elements | outlet) ; - -elements : element ( ',' element)* ; - -element : ID ('.' ID)? ; - - -//branch: ( id_with_port arrow_type )+ id_with_port ; -// -//id_with_port: inlet_port? id outlet_port? ; -// -//id_with_inlet : inlet_port? id ; -// -//id_with_outlet : id outlet_port? ; -// -//inlet_port : '(' ID ':)' ; -//outlet_port : '(:' ID ')' ; - - -/// external - -ex_g returns[String id, ExternalTemp exObj] -scope { ExternalTemp ex_; - String id_; - } -@init{ $ex_g::ex_ = new ExternalTemp(); - $ex_g::ex_.fromWresl = this.currentAbsolutePath; - } -@after{ $id = $ex_g::ex_.id; - $exObj = $ex_g::ex_; - $exObj.line=line; - } - : ex_old ; //| ex_new ; - -ex_id : i=ID {$ex_g::ex_.id=$i.text;} ; - -ex_old : DEFINE{line=$DEFINE.line;} (local_deprecated)? ex_id '{' EXTERNAL f=ex_fileName {$ex_g::ex_.fileName=$f.text;} '}' ; - -ex_fileName : ID ('.' ID)? ; - -//ex_new : EXTERNAL ex_id '{' ( ex_fortran | ex_java ) '}' ; - -//ex_fortran : 'language' 'fortran' '{' fortran_var+ fortran_return '}' ; - -//fortran_var : VARIABLE ID '{' 'type' 'intent' '}' ; -//fortran_return : 'return' ; - -//ex_java : 'language' 'java' ; - - -/// dvar -dvar_g returns[String id, DvarTemp dvObj] -scope { DvarTemp dvar_; - String id_; - } -@init{ $dvar_g::dvar_ = new DvarTemp(); - $dvar_g::dvar_.fromWresl = this.currentAbsolutePath; - } -@after{ $id= $dvar_g::id_; $dvObj= $dvar_g::dvar_; $dvObj.line=line; } - : ( dvar_group_new | dvar_group_old ) - ; - -dvarID : i=ID { $dvar_g::dvar_.id=$i.text; $dvar_g::id_=$i.text; }; - -dvar_group_old: DEFINE{line=$DEFINE.line;} (local_deprecated)? dvar ; -dvar_group_new: DVAR{line=$DVAR.line;} dvar ; - -dvar: (dvarArray|dvarTimeArray)? dvarID '{' dvar_trunk '}' ; - -dvarArray : '[' d=( INT | ID ) ']' {$dvar_g::dvar_.arraySize=$d.text; }; -dvarTimeArray : '(' d=( INT | ID ) ')' {$dvar_g::dvar_.timeArraySize=$d.text; }; - -//dvar_array : dimension dvarID '{' dvar_trunk '}' ; -// -//dvar_timeArray: dimension_time dvarID '{' dvar_trunk '}' ; - -dvar_trunk - : - // TODO: remove addDep. this is to match wreslparser result. - ( ( ( dvarIsInteger? ( std | ( {addDep = false;} lower_upper {addDep = true;} ) ) ) - | dvarIsBinary ) - dvKindUnits ) - | ('<' ID '>') ; - -//dvar_array_trunk : ( index_assign? '{' dvar_trunk '}' )+ ; -//dvar_timeArray_trunk : ( timeIndex_assign? '{' dvar_trunk '}' )+ ; - -dvarIsInteger : INTEGER {$dvar_g::dvar_.isInteger=true; $dvar_g::dvar_.upperBound="1";$dvar_g::dvar_.lowerBound="0";} ; -dvarIsBinary : BINARY {$dvar_g::dvar_.isInteger=true; $dvar_g::dvar_.upperBound="1";$dvar_g::dvar_.lowerBound="0";} ; -index_assign : '[' INT (':' INT)? ']' ; -timeIndex_assign : '(' INT (':' INT)? ')' ; - -lower_upper : lower upper? | upper lower? ; -upper: UPPER ( e=expr_limited {$dvar_g::dvar_.upperBound=$e.text;} | UNBOUNDED {$dvar_g::dvar_.upperBound=Param.upper_unbounded;}) ; -lower: LOWER ( e=expr_limited {$dvar_g::dvar_.lowerBound=$e.text;} | UNBOUNDED {$dvar_g::dvar_.lowerBound=Param.lower_unbounded;}) ; - -expr_limited: expr_add ; //number ( ('*' | '/') unitFunc )? ; - -std: STD ; - -dvKindUnits : dvKind dvUnits | dvUnits dvKind ; -dvKind: KIND s=QUOTE {$dvar_g::dvar_.kind=Tools.strip($s.text);}; -dvUnits: UNITS s=QUOTE {$dvar_g::dvar_.units=Tools.strip($s.text);}; - - - - - - - -//================ begin logical ==============// - -logical_main: logical_or | ALWAYS ; - -logical_or - : logical_and - ( o=OR {$o.setText(" .or. ");} logical_and )* - ; - -logical_and - : logical_unary - ( a=AND {$a.setText(" .and. ");} logical_unary )* - ; - -logical_unary : NOT? logical_term; - -logical_term - : ( logical_relation ) => logical_relation - | ( logical_or_p ) => logical_or_p - | logical_relation_p - | logicalFunc - ; - -logical_or_p : '(' logical_or ')' ; - -logical_relation_p - : '(' logical_relation ')' - ; - -logical_relation - : expr_add relation_token expr_add - ; - -logicalFunc - : RANGE '(' expr_add ',' expr_add ',' expr_add ')' ; -//================ end logical ==============// - - -/// constraint expr -constraint_token : '>' | '<' | '>=' | '<=' | '=' ; - -expr_constraint - : expr_add constraint_token expr_add - ; - -// comparison expr -relation_token: '>' | '<' | '>=' | '<=' | '==' | '/=' ; - -expr_relation - : expr_add relation_token expr_add - ; - -// ignore dependants in the lhs -expr_assign -@init{ Set backup = new LinkedHashSet(dependants);} - : expr_add {dependants = backup;} '=' expr_add - ; -//================ begin simple expr_add ==============// -expr_add_simple - : expr_mult_simple ( ( '+' | '-' ) expr_mult_simple )* - ; - -expr_mult_simple - : expr_unary_simple ( ( '*' | '/' ) expr_unary_simple )* - ; - -expr_unary_simple: '-'? expr_term_simple ; - -expr_term_simple - : atom_simple - | '(' expr_add_simple ')' - ; - -atom_simple - : number_p - | v=varID {dependants.add($v.text);} - | intrinsicFunc_simple - ; - -intrinsicFunc_simple - : mathFunc_simple - | multiInputFunc_simple - | unitFunc_simple - ; - -mathFunc_simple - : LOG '(' expr_add_simple ')' - | INT_word '(' expr_add_simple ')' - | ROUND '(' expr_add_simple ')' - | MOD '(' expr_add_simple ',' expr_add_simple ')' - | SIN '(' expr_add_simple ')' - | COS '(' expr_add_simple ')' - | TAN '(' expr_add_simple ')' - | COT '(' expr_add_simple ')' - | ASIN '(' expr_add_simple ')' - | ACOS '(' expr_add_simple ')' - | ATAN '(' expr_add_simple ')' - | ACOT '(' expr_add_simple ')' - | exceedFunc - | exceedtsiFunc - ; - -unitFunc_simple - : ( CFS_TAF | TAF_CFS ) ('(' expr_add_simple ')')? ; - -multiInputFunc_simple - : ( MIN | MAX ) '(' expr_add_simple ( ',' expr_add_simple )* ')' ; - -//================ end simple expr_add ==============// - -//================ begin expr_add ==============// -expr_add - : expr_mult ( ( '+' | '-' ) expr_mult )* - ; - -expr_mult - : expr_unary ( ( '*' | '/' ) expr_unary )* - ; - -expr_unary: ('-'|'+')? expr_term ; - -expr_term - : atom - | '(' expr_add ')' - ; -//================ end expr_add ==============// - -atom - : number_p - | v=varID {if (addDep) dependants.add($v.text);} - | intrinsicFunc - // | r=reservedID {if (isParameter) dependants_notAllowed.add($r.text);} - | s=specialVar {if (isParameter) dependants_notAllowed.add($s.text);} - | externalFunc - | vf=varFunc {if (isParameter) dependants_notAllowed.add($vf.text);} - | p=preCycleVar {if (isParameter) dependants_notAllowed.add($p.text);} - ; - -specialVar : 'i' | '$m' | '$M'; - -preCycleVar - : p1=preCycleVar_old {varInCycle.add($p1.text);} | p2=preCycleVarIndex {varInCycle.add($p2.text);} - ; - -preCycleVar_old : var=ID '[' cycle=ID ']' ('(' e=expr_add ')')? -{ - // TODO: don't convert to lower case here! - if (!isParameter){ - String cnl = $cycle.text.toLowerCase(); - String vl = $var.text.toLowerCase(); - if (neededCycleVarMap.keySet().contains(cnl)) { - neededCycleVarMap.get(cnl).add(vl); - } else { - HashSet t = new HashSet(); - t.add(vl); - neededCycleVarMap.put(cnl, t); - } - } -} ; - -preCycleVarIndex : var=ID '[' '-' INT ']' ('(' e=expr_add ')')? { - if (!VarCycleIndex.varCycleIndexList.contains($var.text)){ - VarCycleIndex.varCycleIndexList.add($var.text.toLowerCase()); - } -}; - -externalFunc - : 'extern:(' ID '(' expr_add ')' ')' - ; -intrinsicFunc - : mathFunc - | multiInputFunc - | unitFunc - | tableFunc - | timeFunc - | sumFunc - ; - -sumFunc: '(' sum_header sum_content ')'; - -timeFunc: ( DAY | MONTH | WATERYEAR ) ( '(' expr_add ')' )? ; - -tableFunc : 'table' '(' tableName ',' columnNumber ',' rowNumber ')' ; - -tableName : ID ; -columnNumber : INT ; -rowNumber : INT ; - -varFunc - : v=varID '(' func_arg (',' func_arg )* ')' ('(' expr_add ')')? - {dependants.add($v.text); - //System.out.println(dependants); - } - ; - -varID : ID ; - -func_arg: expr_add|trunk_timeArray; - -trunk_timeArray - : v1=varID '(' (integer|v2=varID{dependants.add($v2.text);}) ':' (integer|v3=varID{dependants.add($v3.text);}) ')'; - -number : integer | real ; -number_p : integer_p | real_p ; - -integer : integer_p|integer_n ; -real : real_p|real_n ; - -integer_p : INT ; -integer_n : '-' INT ; -real_p : REAL ; -real_n : '-' REAL ; - - -id_domain : ( ID '.' )? ID ; - - - -mathFunc - : LOG '(' expr_add ')' - | INT_word '(' expr_add ')' - | ROUND '(' expr_add ')' - | MOD '(' expr_add ',' expr_add ')' - | SIN '(' expr_add ')' - | COS '(' expr_add ')' - | TAN '(' expr_add ')' - | COT '(' expr_add ')' - | ASIN '(' expr_add ')' - | ACOS '(' expr_add ')' - | ATAN '(' expr_add ')' - | ACOT '(' expr_add ')' - | exceedFunc - | exceedtsiFunc - ; - -unitFunc - : ( CFS_TAF | TAF_CFS ) ('(' expr_add ')')? ; - -multiInputFunc - : ( MIN | MAX ) '(' expr_add ( ',' expr_add )* ')' ; - -//exceedance(FOLSM_INFLOW, 0.9,ALL/OCT,1921,OCT,31,2015,SEP,30) -exceedFunc - : EXCEEDANCE '(' varID ',' number_p ',' varID ',' integer_p ',' varID ',' integer ',' integer_p ',' varID ',' integer ')' - ; - -exceedtsiFunc - : EXCEEDANCE_TSI '(' varID ',' number_p ',' varID ',' integer_p ',' varID ',' integer ',' integer_p ',' varID ',' integer ')' - ; - -// -//// reserved ID -//DaysIn: 'daysin'; -//Int: 'int'; -//Real: 'real'; - - -reservedID : DAY | MONTH | WATERYEAR ; //| MonthID ; - -QUOTE : '\'' .* '\'' ; - -ML_COMMENT : '/*' .* '*/' {skip();}; - -SL_COMMENT : ('#'|'!') ~('\r'|'\n')* {skip();}; //{$channel=HIDDEN;} ; - -AND : '&&' | '.and.' | '.AND.' ; -OR : '||' | '.or.' | '.OR.' ; -NOT : '.not.' | '.NOT.' ; -NOT_EQUAL : '.ne.' | '.NE.' ; - -DAY: 'day'|'Day'|'DAY'; -MONTH : 'month' | 'Month' | 'MONTH' ; -WATERYEAR : 'wateryear' | 'Wateryear' | 'WaterYear' | 'WATERYEAR' ; -//MonthID : 'jan'|'feb'|'mar'|'apr'|'may'|'jun'|'jul'|'aug'|'sep'|'oct'|'nov'|'dec'; - - -REAL : ( Digit+ '.' Digit* ) | ( '.' Digit+ ) ; -INT : Digit+ ; - -OBJECTIVE : 'objective' | 'OBJECTIVE' | 'Objective' ; -//OBJ : 'obj' | 'Obj' | 'OBJ' ; -MODEL : 'model' | 'MODEL' | 'Model' ; -GROUP : 'group' | 'Group' | 'GROUP'; -SEQUENCE : 'sequence' | 'Sequence' | 'SEQUENCE' ; - -ORDER : 'order' | 'ORDER' | 'Order' ; -TIMESTEP : 'timestep'|'TIMESTEP'|'TimeStep'; -TIMESTEPVALUE: '1mon'|'1day'; -INCLUDE : 'include' | 'INCLUDE' | 'Include' ; -CASE : 'case' | 'CASE' | 'Case' ; -CONDITION : 'condition' | 'CONDITION' | 'Condition' ; -GOAL : 'goal' | 'GOAL' | 'Goal' ; -VALUE : 'value' | 'VALUE' | 'Value'; -PENALTY : 'penalty' | 'PENALTY' | 'Penalty' ; -DeviationPenalty : 'deviationpenalty' | 'DEVIATIONPENALTY' | 'DeviationPenalty' | 'deviationPenalty' | 'Deviationpenalty' ; -DeviationTolerance : 'deviationtolerance' | 'DEVIATIONTOLERANCE' | 'DeviationTolerance' | 'deviationTolerance' | 'Deviationtolerance' ; -WEIGHT : 'weight' | 'WEIGHT' | 'Weight' ; -//ITEM : 'item' | 'ITEM' | 'Item' ; - -CONFIG : 'config' | 'CONFIG' | 'Config'; -SORTING : 'sorting' | 'SORTING' | 'Sorting' ; -TRUE : 'true' | 'TRUE' | 'True' ; -FALSE : 'false' | 'FALSE' | 'False' ; -LABEL : 'label' ; -NAME : 'name' ; - -Initial : 'initial' | 'Initial' | 'INITIAL' ; -//Parameter : 'parameter' | 'Parameter' | 'PARAMETER' ; -Const : 'const' | 'Const' | 'CONST' ; - -If : 'If' | 'IF' | 'if' ; -Elseif : 'Elseif' | 'ELSEIF' | 'elseif' | 'ElseIf' ; -Else : 'Else' | 'ELSE' | 'else' ; - -// deprecated keyword -DEFINE : 'define' | 'DEFINE' | 'Define' ; -LOCAL : 'local' | 'LOCAL' | 'Local' ; -/////////////////////////////// - -STD : 'std' | 'STD' | 'Std' ; -DVAR : 'dvar' | 'DVAR' | 'Dvar' ; -SVAR : 'svar' | 'SVAR' | 'Svar' ; -VARIABLE : 'variable' | 'VARIABLE' | 'Variable' ; -ALIAS : 'alias' | 'ALIAS' | 'Alias'; -TIMESERIES : 'timeseries' | 'TIMESERIES' | 'Timeseries' ; -EXTERNAL : 'external' | 'EXTERNAL' | 'External' ; -TEMPLATE : 'template' ; - - -SUM : 'sum' | 'SUM' | 'Sum'; -KIND : 'kind' | 'KIND' | 'Kind'; -UNITS : 'units' | 'UNITS' | 'Units' ; -NoSolver : 'NoSolver' | 'Nosolver' | 'NOSOLVER' | 'nosolver' | 'noSolver'; -CONVERT : 'convert' | 'CONVERT' |'Convert' ; -UPPER : 'upper' | 'UPPER' | 'Upper'; -LOWER : 'lower' | 'LOWER' | 'Lower'; - -UNBOUNDED : 'unbounded'|'UNBOUNDED' ; - -ALWAYS: 'always'|'ALWAYS'|'Always' ; -INTEGER : 'integer'|'INTEGER'|'Integer'; -BINARY : 'binary'|'BINARY'|'Binary'; - -SELECT : 'select' | 'SELECT'|'Select' ; -FROM : 'from' | 'FROM'|'From' ; -WHERE : 'where' | 'WHERE'|'Where' ; -GIVEN : 'given' | 'GIVEN'|'Given' ; -USE : 'use' | 'USE'|'Use' ; - -LHS : 'lhs' | 'LHS' ; -RHS : 'rhs' | 'RHS' ; - -// special function -RANGE : 'range' | 'RANGE' | 'Range' ; - -// intrinsic function -INT_word : 'int' | 'INT' ; -ROUND : 'round' | 'ROUND' ; -LOG : 'log' | 'LOG' ; -MAX : 'max' | 'MAX' ; -MIN : 'min' | 'MIN' ; -MOD : 'mod' | 'MOD' ; -SIN : 'sin' | 'SIN' ; -COS : 'cos' | 'COS' ; -TAN : 'tan' | 'TAN' ; -COT : 'cot' | 'COT' ; -ASIN : 'asin' | 'ASIN' ; -ACOS : 'acos' | 'ACOS' ; -ATAN : 'atan' | 'ATAN' ; -ACOT : 'acot' | 'ACOT' ; -EXCEEDANCE : 'exceedance' | 'EXCEEDANCE' ; -EXCEEDANCE_TSI : 'exceedance_tsi' | 'EXCEEDANCE_TSI' ; -CFS_TAF : 'cfs_taf' | 'CFS_TAF' ; -TAF_CFS : 'taf_cfs' | 'TAF_CFS' ; - -// network -NETWORK : 'network' | 'NETWORK' | 'Network' ; -NODE : 'node' | 'NODE' | 'Node' ; -INFLOW : '*>>' ; -OUTFLOW : '>>*' ; -FLOW : '>>' ; - -//ID : ('a'..'z'|'A'..'Z')('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ; -ID : Letter ( Letter | Digit | '_' )*; - - -fragment Letter : 'a'..'z' | 'A'..'Z'; - -fragment Digit : '0'..'9'; - -WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {skip();}; //{$channel = HIDDEN;}; -//WS : ( '\t' | '\n' | '\r' | '\f')+ {skip();}; //{$channel = HIDDEN;}; -//WS2 : ( ' ' )+ {$channel = HIDDEN;}; +grammar WreslPlus; +//import CommonLexer; + +options { + language = Java; + output=AST; + ASTLabelType=CommonTree; +} + +@header { + package wrimsv2.wreslplus.grammar; + import wrimsv2.wreslparser.elements.LogUtils; + import java.util.HashMap; + import java.util.LinkedHashMap; + import java.util.Set; + import java.util.HashSet; + import java.util.LinkedHashSet; + import wrimsv2.wreslplus.elements.Tools; + import wrimsv2.wreslplus.elements.IncFileTemp; + import wrimsv2.wreslplus.elements.IfIncItemGroup; + import wrimsv2.wreslplus.elements.TimeseriesTemp; + import wrimsv2.wreslplus.elements.ExternalTemp; + import wrimsv2.wreslplus.elements.DvarTemp; + import wrimsv2.wreslplus.elements.SvarTemp; + import wrimsv2.wreslplus.elements.ParamTemp; + import wrimsv2.wreslplus.elements.WeightTable; + import wrimsv2.wreslplus.elements.WeightSubgroup; + import wrimsv2.wreslplus.elements.AliasTemp; + import wrimsv2.wreslplus.elements.GoalTemp; + import wrimsv2.wreslplus.elements.GoalHS; + import wrimsv2.wreslplus.elements.GoalCase; + import wrimsv2.wreslplus.elements.ModelTemp; + import wrimsv2.wreslplus.elements.SequenceTemp; + import wrimsv2.wreslplus.elements.StudyTemp; + import wrimsv2.wreslplus.elements.VarCycleIndex; + import wrimsv2.commondata.wresldata.Param; +} +@lexer::header { + package wrimsv2.wreslplus.grammar; + import wrimsv2.wreslparser.elements.LogUtils; +} + +@members { + public CommonTree commonTree; + public String currentAbsolutePath; + public String currentAbsoluteParent; + public String pathRelativeToRunDir; + public StudyTemp styObj; + public ModelTemp mObj; + public Set dependants; + public Set dependantTypes; + public Set dependants_notAllowed; + public Set varInCycle; + public Map> neededCycleVarMap; + boolean addDep = true; + boolean isParameter = false; + public int number_of_errors = 0; + public int line=1; + + /// error message + public void displayRecognitionError(String[] tokenNames, + RecognitionException e) { + String hdr = getErrorHeader(e); + String msg = getErrorMessage(e, tokenNames); + //LogUtils.errMsg("@parser "+ hdr + " " + msg); + LogUtils.errMsgLocation(currentAbsolutePath, e.line, msg); + number_of_errors++; + } +} + +@lexer::members { + + public int number_of_errors = 0; + /// error message + public void displayRecognitionError(String[] tokenNames, + RecognitionException e) { + String hdr = getErrorHeader(e); + String msg = getErrorMessage(e, tokenNames); + LogUtils.errMsg("@lexer "+ hdr + " " + msg); + number_of_errors++; + } +} +//wreslPlusMain : study template* sequence+ model+; + + +wreslFile +@after{ mObj = $t.modelObj;} + : ('{' t=mt '}' EOF ) | ( t=mt EOF ); + +wreslMain +scope { StudyTemp sty;} +@init { $wreslMain::sty = new StudyTemp();} +@after{ styObj = $wreslMain::sty; } + + : + initial? + ( seq=sequence { $wreslMain::sty.seqList.add($seq.id); $wreslMain::sty.seqMap.put($seq.id,$seq.seqObj); } )+ + ( g=group { $wreslMain::sty.modelList.add($g.id); $wreslMain::sty.modelMap.put($g.id, $g.modelObj); } )* + ( m=model { $wreslMain::sty.modelList.add($m.id); $wreslMain::sty.modelMap.put($m.id, $m.modelObj); } )+ + EOF ; + +local_deprecated + : '[' LOCAL ']' ; + //{LogUtils.warningMsg("\"[local]\" is deprecated. All variables are by default local.");}; + +initial +@init { isParameter=true; } +@after{ isParameter=false; } + : + Initial '{' + //config* + ( + ( c=constant {$wreslMain::sty.parameterList.add($c.id); $wreslMain::sty.parameterConstList.add($c.id); $wreslMain::sty.parameterMap.put($c.id, $c.ptObj);} ) + | ( s=svar_initial {$wreslMain::sty.parameterList.add($s.id); $wreslMain::sty.parameterMap.put($s.id, $s.svObj);} ) + )+ + '}'; + +//config : CONFIG SORTING '{' VALUE (TRUE | (FALSE {$wreslMain::sty.isSort=false;}))'}' ; + +constant returns[String id, SvarTemp ptObj] +@init{ $ptObj = new SvarTemp(); + dependants = new LinkedHashSet(); } + : Const i=ID '{' n=number '}' //n=expr_add_simple + + { + $id = $i.text; + $ptObj.id = $i.text; + $ptObj.caseName.add(Param.defaultCaseName); + $ptObj.caseCondition.add(Param.always); + $ptObj.caseExpression.add($n.text); + $ptObj.dependants = dependants; + + }; + +svar_initial returns[String id, SvarTemp svObj] +@init{ dependants = new LinkedHashSet(); + dependantTypes = new LinkedHashSet(); + dependants_notAllowed = new LinkedHashSet(); } + : SVAR svar_g { $id=$svar_g.id; $svObj=$svar_g.svObj; $svObj.dependants_notAllowed=dependants_notAllowed; } ; + + + +expression_simple +@init{ dependants = new LinkedHashSet(); } + : expr_add_simple ; + + + +//study : 'study' ID '{' include_template* include_sequence+ '}' ; +// +// +//include_template : INCLUDE 'template' ( ID | include_file ) ; +//include_sequence : INCLUDE SEQUENCE ID ; + + + +template : TEMPLATE ID '{' ( template_svar | template_dvar | template_dvar_array )* '}' ; + +template_dvar : '%dvar' varID '{' dvar_trunk '}' ; + +template_dvar_array : '%dvar' dimension varID '{' dvar_trunk '}' ; + +template_svar : '%svar' varID svar_trunk ; + +sequence returns[String id, SequenceTemp seqObj] +@init {$seqObj = new SequenceTemp(); + dependants = new LinkedHashSet(); + $seqObj.fromWresl = this.currentAbsolutePath; + + // for condition expression if previous cycle var is used + neededCycleVarMap = new HashMap>(); + } + +@after{$seqObj.model=$m.text; $seqObj.order=$o.text; + $seqObj.dependants= dependants; $seqObj.line=line; + $seqObj.neededCycleVarMap = neededCycleVarMap; + } + + : SEQUENCE i=ID {$id=$i.text; $seqObj.id=$i.text;} + '{' MODEL m=ID + (( CONDITION cc=logical_main {$seqObj.condition=$cc.text;} ORDER o=INT )| + ( ORDER o=INT (CONDITION cc=logical_main {$seqObj.condition=$cc.text;})? ) ) + ( TIMESTEP t=TIMESTEPVALUE {$seqObj.timeStep=$t.text.toUpperCase();} )? + '}' + ; + + + +group returns[String id, ModelTemp modelObj] +: GROUP i=ID {$id=$i.text;} '{' t=mt '}' {$modelObj =$t.modelObj; $modelObj.id=$id;} ; + + + +model_standalone : model ; + +model returns[String id, ModelTemp modelObj] +: MODEL i=modelName {$id=$i.text;} + '{' t=mt '}' + {$modelObj =$t.modelObj; $modelObj.id=$id;} + ; + +modelName: ID; + +//model trunk +mt returns[ModelTemp modelObj] + +scope { ModelTemp m_;} +@init{ neededCycleVarMap = new HashMap>(); + $mt::m_ = new ModelTemp(); + $mt::m_.absPath = currentAbsolutePath; + $mt::m_.parentAbsPath = currentAbsoluteParent; } +@after{$modelObj =$mt::m_; + $modelObj.neededCycleVarMap = neededCycleVarMap; + $modelObj.id=Param.legacywresl;} +: + ( fi=include_file {$mt::m_.itemTypeList.add(Param.incFileType); $mt::m_.itemList.add($fi.id); $mt::m_.incFileIDList.add($fi.id); $mt::m_.incFileMap.put($fi.id, $fi.incFileObj); } + | ts=timeseries {$mt::m_.itemTypeList.add(Param.tsType);$mt::m_.itemList.add($ts.id); $mt::m_.tsList.add($ts.id); $mt::m_.tsMap.put($ts.id, $ts.tsObj); } + | sv=svar_group {$mt::m_.itemTypeList.add(Param.svType);$mt::m_.itemList.add($sv.id); $mt::m_.svList.add($sv.id); $mt::m_.svMap.put($sv.id, $sv.svObj); } + | dv=dvar_g {$mt::m_.itemTypeList.add(Param.dvType);$mt::m_.itemList.add($dv.id); $mt::m_.dvList.add($dv.id); $mt::m_.dvMap.put($dv.id, $dv.dvObj); } + | ex=ex_g {$mt::m_.itemTypeList.add(Param.exType);$mt::m_.itemList.add($ex.id); $mt::m_.exList.add($ex.id); $mt::m_.exMap.put($ex.id, $ex.exObj); } + | as=alias {$mt::m_.itemTypeList.add(Param.asType);$mt::m_.itemList.add($as.id); $mt::m_.asList.add($as.id); $mt::m_.asMap.put($as.id, $as.asObj); } + | gl1=goal_s {$mt::m_.itemTypeList.add(Param.gl1Type);$mt::m_.itemList.add($gl1.id);$mt::m_.glList.add($gl1.id);$mt::m_.glMap.put($gl1.id, $gl1.glObj); } + | gl2=goal_hs {$mt::m_.itemTypeList.add(Param.gl2Type);$mt::m_.itemList.add($gl2.id);$mt::m_.glList.add($gl2.id);$mt::m_.glMap.put($gl2.id, $gl2.glObj); $mt::m_.gl2List.add($gl2.id); } + | network + | wt=weight {$mt::m_.wTableObjList.add($wt.wtObj);} + | im=include_model {$mt::m_.itemTypeList.add(Param.incModelType);$mt::m_.itemList.add(Param.model_label+$im.id); $mt::m_.incModelList.add($im.id); + $mt::m_.incFileIDList.add($im.id); $mt::m_.incFileMap.put($im.id, null); + } + | ifig=if_inc_items {$mt::m_.itemTypeList.add(Param.ifIncItemGroupType); $mt::m_.itemList.add($ifig.id); $mt::m_.ifIncItemGroupIDList.add($ifig.id); $mt::m_.ifIncItemGroupMap.put($ifig.id, $ifig.ifIncItemGroupObj); } + )+ + ; + +if_inc_items returns[String id, IfIncItemGroup ifIncItemGroupObj] +scope { IfIncItemGroup incg_; + ArrayList _arr; + HashMap _incfmap; + HashMap _incSvarMap; + HashMap _incDvarMap; + LinkedHashMap _incAliasMap; + HashMap _incTimeseriesMap; + HashMap _incGoalSimpleMap; + HashMap _incGoalComplexMap; + HashMap _incWeightTableMap; + } +@init{ $if_inc_items::incg_ = new IfIncItemGroup(); + $if_inc_items::incg_.id = "__item__"+Integer.toString($mt::m_.ifIncItemGroupIDList.size()); + $id = $if_inc_items::incg_.id; + $ifIncItemGroupObj = $if_inc_items::incg_; + //dependants = new LinkedHashSet(); + $if_inc_items::incg_.dependants = new HashSet(); + // $incg_.id = "__incfilegroup__"+Integer.toString($mt::m_.incFileGroupIDList.size()); + + } +@after{ + // reserve space + $mt::m_.svList.add($if_inc_items::incg_.id); + $mt::m_.dvList.add($if_inc_items::incg_.id); + $mt::m_.asList.add($if_inc_items::incg_.id); + $mt::m_.tsList.add($if_inc_items::incg_.id); + $mt::m_.glList.add($if_inc_items::incg_.id); + $mt::m_.gl2List.add($if_inc_items::incg_.id); + //$if_inc_items::incg_.dependants = dependants; + $if_inc_items::incg_.fromWresl = this.currentAbsolutePath; + $if_inc_items::incg_.line=line; + // $mt::m_.wTableObjList.add($if_inc_items::incg_.id); + +} + : if_ elseif_* else_? ; + +if_ +@init{ dependants = new LinkedHashSet(); } + : + If{line=$If.line;} e=logical_main {$if_inc_items::incg_.dependants.addAll(dependants);} + '{' include_item_group '}' + {$if_inc_items::incg_.conditionList.add($e.text);}; + +elseif_ +@init{ dependants = new LinkedHashSet(); } + : + Elseif e=logical_main {$if_inc_items::incg_.dependants.addAll(dependants);} + '{' include_item_group '}' + {$if_inc_items::incg_.conditionList.add($e.text);}; + +else_ : + Else '{' include_item_group '}' + {$if_inc_items::incg_.conditionList.add(Param.always);}; + +include_item_group +@init{ $if_inc_items::_arr = new ArrayList(); + $if_inc_items::_incfmap = new HashMap(); + $if_inc_items::_incSvarMap = new HashMap(); + $if_inc_items::_incDvarMap = new HashMap(); + $if_inc_items::_incAliasMap = new LinkedHashMap(); + $if_inc_items::_incTimeseriesMap = new HashMap(); + $if_inc_items::_incGoalSimpleMap = new HashMap(); + $if_inc_items::_incGoalComplexMap = new HashMap(); + $if_inc_items::_incWeightTableMap = new HashMap(); +} +@after { + $if_inc_items::incg_.inc_item_list.add($if_inc_items::_arr); + $if_inc_items::incg_.inc_files_map_list.add($if_inc_items::_incfmap); + $if_inc_items::incg_.inc_svar_map_list.add($if_inc_items::_incSvarMap); + $if_inc_items::incg_.inc_dvar_map_list.add($if_inc_items::_incDvarMap); + $if_inc_items::incg_.inc_alias_map_list.add($if_inc_items::_incAliasMap); + $if_inc_items::incg_.inc_timeseries_map_list.add($if_inc_items::_incTimeseriesMap); + $if_inc_items::incg_.inc_goalSimple_map_list.add($if_inc_items::_incGoalSimpleMap); + $if_inc_items::incg_.inc_goalComplex_map_list.add($if_inc_items::_incGoalComplexMap); + $if_inc_items::incg_.inc_weightTable_map_list.add($if_inc_items::_incWeightTableMap); +} +: + ( + ( fi=include_file { + $if_inc_items::_arr.add($fi.id); + $if_inc_items::_incfmap.put($fi.id, $fi.incFileObj); + $mt::m_.incFileIDList.add($if_inc_items::incg_.id); + }) + | ( si=svar_group { + $if_inc_items::_arr.add($si.id); + $if_inc_items::_incSvarMap.put($si.id, $si.svObj); + }) + | ( di=dvar_g { + $if_inc_items::_arr.add($di.id); + $if_inc_items::_incDvarMap.put($di.id, $di.dvObj); + }) + | ( ai=alias { + $if_inc_items::_arr.add($ai.id); + $if_inc_items::_incAliasMap.put($ai.id, $ai.asObj); + }) + | ( ti=timeseries { + $if_inc_items::_arr.add($ti.id); + $if_inc_items::_incTimeseriesMap.put($ti.id, $ti.tsObj); + }) + | ( gsi=goal_s { + $if_inc_items::_arr.add($gsi.id); + $if_inc_items::_incGoalSimpleMap.put($gsi.id, $gsi.glObj); + }) + | ( ghi=goal_hs { + $if_inc_items::_arr.add($ghi.id); + $if_inc_items::_incGoalComplexMap.put($ghi.id, $ghi.glObj); + }) + | ( wti=weight { + $if_inc_items::_incWeightTableMap.put($wti.id, $wti.wtObj); + }) + )+ ; + + +///// external +// +//external returns[String id, ExternalTemp exObj] +//scope { ExternalTemp ex_;} +//@init{ $external::ex_ = new ExternalTemp(); +// $external::ex_.fromWresl = this.currentAbsolutePath; +// dependants = new LinkedHashSet(); +// } +//@after{ $id = $external::ex_.id; $exObj=$external::ex_;} +// : external_old +// ; +// +//external_old : DEFINE ('[' LOCAL ']')? externalID '{' EXTERNAL external_fileName '}' ; +// +// +//external_fileName : f=fileName {$external::ex_.fileName=$f.text;} ; +//fileName : ID ('.' ID)? ; +//externalID : i=ID {$external::ex_.id=$i.text;} ; + + +weight returns[String id, WeightTable wtObj] +scope { WeightTable wt_; + String id_; + } +@init{ $weight::wt_ = new WeightTable(); + $weight::wt_.fromWresl = this.currentAbsolutePath; + $weight::wt_.line = line; + dependants = new LinkedHashSet(); + } +@after{ $id = $weight::wt_.id_lowcase; $wtObj=$weight::wt_; $wtObj.dependants= dependants;} + : weight_legacy | weight_new ; + +weight_legacy : OBJECTIVE{line=$OBJECTIVE.line;} (local_deprecated)? objGroupName '='? '{' weight_legacy_unit+ '}' ; + +//obj : 'obj' | 'Obj' | 'OBJ' ; +objGroupName : i=ID {$weight::wt_.id_lowcase=$i.text.toLowerCase(); + $weight::wt_.id_raw=$i.text;} ; + +weight_legacy_unit + : '[' i=ID{line=$i.line;} (ta=weightTimeArray {$weight::wt_.varTimeArraySizeMap.put($i.text,$ta.text);})? ',' e=expr_add ']' ','? + {$weight::wt_.varList.add($i.text); + $weight::wt_.varWeightMap.put($i.text,$e.text); + $weight::wt_.varLineMap.put($i.text, line);}; + +weightTimeArray : '(' d=( INT | ID ) ')'; // this is a repetition. The time array should be known when dvar is declared. + +weight_new : OBJECTIVE{line=$OBJECTIVE.line;} weightTableID '{' weight_group '}' ; + +weightTableID : i=ID {$weight::wt_.id_lowcase=$i.text.toLowerCase(); + $weight::wt_.id_raw=$i.text; + $weight::wt_.line=$i.getLine();} ; + +weight_group +@init{ $weight::wt_.isWeightGroup=true; } + : WEIGHT w=expr_add {$weight::wt_.commonWeight=$w.text;} + weight_trunk + ; + +weight_trunk + : ( DeviationPenalty p=expr_add {$weight::wt_.deviationPenalty=$p.text;} )? + ( DeviationTolerance t=expr_add {$weight::wt_.deviationTolerance=$t.text;} )? + VARIABLE ( weight_group_unit | weight_subgroup )+ + ; + +weight_group_unit : i=ID {$weight::wt_.varList.add($i.text);} ; + +weight_subgroup +scope { WeightSubgroup sub_;} +@init{ $weight_subgroup::sub_ = new WeightSubgroup(); } +@after{ $weight_subgroup::sub_.id=$i.text; + $weight::wt_.subgroupMap.put($i.text,$weight_subgroup::sub_); + //$weight::wt_.varList.add($i.text); + //System.out.println("subgroup: "+$weight::wt_.subgroupMap.keySet()); + } + : i=ID //{$weight::wt_.subgroupMap.put($i.text.toLowerCase(),$weight_subgroup::sub_);} + '{' weight_subgroup_trunk '}' + ; + +weight_subgroup_trunk + : ( DeviationPenalty p=expr_add {$weight_subgroup::sub_.deviationPenalty=$p.text;} )? + ( DeviationTolerance t=expr_add {$weight_subgroup::sub_.deviationTolerance=$t.text;} )? + VARIABLE ( weight_subgroup_unit+ ) // | weight_subgroup )+ + ; + +weight_subgroup_unit : i=ID {$weight_subgroup::sub_.varList.add($i.text);} ; + + +include_model returns[String id] : INCLUDE (MODEL|GROUP) i=ID {$id=$i.text;} ; + +include_file returns[String id, IncFileTemp incFileObj] +@init{ $incFileObj = new IncFileTemp(); + $incFileObj.id = "__file__"+Integer.toString($mt::m_.incFileIDList.size()); + $id = $incFileObj.id; + } + : INCLUDE (local_deprecated)? fp=file_path {$incFileObj.rawPath=Tools.strip($fp.text);} ; + +file_path : QUOTE ; + + +/// goal simple +goal_s returns[String id, GoalTemp glObj] +scope { GoalTemp gl_; + String id_; + } +@init{ $goal_s::gl_ = new GoalTemp(); + $goal_s::gl_.fromWresl = this.currentAbsolutePath; + $goal_s::gl_.hasCase = false; + dependants = new LinkedHashSet(); + varInCycle = new LinkedHashSet(); + } +@after{ $id = $goal_s::gl_.id; + $glObj=$goal_s::gl_; + $glObj.dependants= dependants; + $glObj.neededVarInCycleSet= varInCycle; + $glObj.needVarFromEarlierCycle = (varInCycle!=null); + $glObj.line=line;} + + : GOAL{line=$GOAL.line;} (local_deprecated)? (goalSimpleArray|goalSimpleTimeArray)? i=ID '{' ( e=expr_constraint )'}' + {$goal_s::gl_.id=$i.text; + $goal_s::gl_.caseCondition.add(Param.always); + $goal_s::gl_.caseName.add(Param.defaultCaseName); + $goal_s::gl_.caseExpression.add($e.text);}; + +goalSimpleArray : '[' d=( INT | ID ) ']' {$goal_s::gl_.arraySize=$d.text; }; +goalSimpleTimeArray : '(' d=( INT | ID ) ')' {$goal_s::gl_.timeArraySize=$d.text; }; + + +/// goal hs +goal_hs returns[String id, GoalTemp glObj] +scope { GoalTemp gl_; + String id_; + } +@init{ $goal_hs::gl_ = new GoalTemp(); + $goal_hs::gl_.fromWresl = this.currentAbsolutePath; + dependants = new LinkedHashSet(); + varInCycle = new LinkedHashSet(); + $goal_hs::gl_.hasLhs=true; + } +@after{ $id = $goal_hs::gl_.id; + $glObj=$goal_hs::gl_; + $glObj.dependants= dependants; + $glObj.neededVarInCycleSet= varInCycle; + $glObj.needVarFromEarlierCycle = (varInCycle!=null); + $glObj.line=line;} + : GOAL{line=$GOAL.line;} (local_deprecated)? (goalHsArray|goalHsTimeArray)? i=ID {$goal_hs::gl_.id=$i.text;} + '{' lhs + ( goal_hs_nocase + | goal_hs_cases + ) '}'; + +goalHsArray : '[' d=( INT | ID ) ']' {$goal_hs::gl_.arraySize=$d.text; }; +goalHsTimeArray : '(' d=( INT | ID ) ')' {$goal_hs::gl_.timeArraySize=$d.text; }; + +goal_hs_nocase +@after{ $t.gc.id = Param.defaultCaseName; + $goal_hs::gl_.caseName.add($t.gc.id); + $goal_hs::gl_.caseMap.put($t.gc.id, $t.gc); + $goal_hs::gl_.hasCase = false; + } + : t=goal_hs_trunk ; + +goal_hs_trunk returns[GoalCase gc] +scope { GoalCase gc_; } +@init { $goal_hs_trunk::gc_ = new GoalCase();} +@after{ $gc=$goal_hs_trunk::gc_;} + : rhs ((lhs_gt_rhs lhs_lt_rhs?) | (lhs_lt_rhs lhs_gt_rhs?))? ; + +goal_hs_cases : goal_hs_case+ ; + +goal_hs_case +@after{ $t.gc.id = $ci.text; + $t.gc.condition = $cc.text; + $goal_hs::gl_.caseName.add($t.gc.id); + $goal_hs::gl_.caseMap.put($t.gc.id, $t.gc); + $goal_hs::gl_.hasCase = true;} + : CASE ci=ID '{' CONDITION cc=logical_main t=goal_hs_trunk '}'; + + +lhs : LHS e=expr_add {$goal_hs::gl_.lhs=$e.text;} ; +rhs : RHS e=expr_add {$goal_hs_trunk::gc_.rhs=$e.text;} ; +lhs_gt_rhs : LHS '>' RHS ( PENALTY p=expr_add {$goal_hs_trunk::gc_.lhs_gt_rhs=$p.text;} | constrain ) ; +lhs_lt_rhs : LHS '<' RHS ( PENALTY p=expr_add {$goal_hs_trunk::gc_.lhs_lt_rhs=$p.text;} | constrain ) ; + +constrain : 'constrain' ; + +/// alias + +alias returns[String id, AliasTemp asObj] +scope { AliasTemp as_;} +@init{ $alias::as_ = new AliasTemp(); + $alias::as_.fromWresl = this.currentAbsolutePath; + dependants = new LinkedHashSet(); + varInCycle = new LinkedHashSet(); + } +@after{ $id = $alias::as_.id; + $asObj=$alias::as_; + $asObj.dependants= dependants; + $asObj.neededVarInCycleSet= varInCycle; + $asObj.needVarFromEarlierCycle = (varInCycle!=null); + $asObj.line=line;} + : alias_new | alias_old + ; + +alias_old : DEFINE{line=$DEFINE.line;} (local_deprecated)? (aliasArray|aliasTimeArray)? aliasID '{' ALIAS aliasExpresion aliasKind? aliasUnits? aliasNoSolver? '}' ; +alias_new : ALIAS{line=$ALIAS.line;} (aliasArray|aliasTimeArray)? aliasID '{' aliasExpresion aliasKind? aliasUnits? aliasNoSolver? '}' ; + +aliasExpresion : e=expr_add {$alias::as_.expression=$e.text;}; +aliasID : i=ID {$alias::as_.id=$i.text;}; +aliasUnits: UNITS s=QUOTE {$alias::as_.units=Tools.strip($s.text);}; +aliasKind: KIND s=QUOTE {$alias::as_.kind=Tools.strip($s.text);}; +aliasNoSolver : NoSolver {$alias::as_.noSolver=true;}; + +aliasArray : '[' d=( INT | ID ) ']' {$alias::as_.arraySize=$d.text; }; +aliasTimeArray : '(' d=( INT | ID ) ')' {$alias::as_.timeArraySize=$d.text; }; + +/// svar + +svar_group returns[String id, SvarTemp svObj] + : ( SVAR{line=$SVAR.line;} | DEFINE{line=$DEFINE.line;} (local_deprecated)? ) svar_g { $id=$svar_g.id; $svObj=$svar_g.svObj; $svObj.line=line;} ; + + +svar_g returns[String id, SvarTemp svObj] +scope { SvarTemp sv_; + String id_; + } +@init{ $svar_g::sv_ = new SvarTemp(); + $svar_g::sv_.fromWresl = this.currentAbsolutePath; + dependants = new LinkedHashSet(); + varInCycle = new LinkedHashSet(); + + } +@after{ $id = $svar_g::sv_.id; + $svObj=$svar_g::sv_; + $svObj.dependants= dependants; + $svObj.neededVarInCycleSet= varInCycle; + $svObj.needVarFromEarlierCycle = (varInCycle!=null); + } + : ( svar | svar_array | svar_timeArray ) ; + + +svarID : i=ID {$svar_g::sv_.id =$i.text;} ; + +svar: svarID '{' svar_trunk '}' ; + +svar_array: svarArray svar; + +svar_timeArray: svarTimeArray svar ; + +svarArray : '[' d=( INT | ID ) ']' {$svar_g::sv_.arraySize=$d.text; }; +svarTimeArray : '(' d=( INT | ID ) ')' {$svar_g::sv_.timeArraySize=$d.text; }; + +/// svar trunk + +svar_trunk + : ( svar_noCase | svar_case+ ) ( svarKind svarUnits )? ; + +svarUnits: UNITS QUOTE ; +svarKind: KIND QUOTE ; + +svar_noCase + @after {$svar_g::sv_.caseName.add(Param.defaultCaseName); $svar_g::sv_.caseCondition.add(Param.always);} + : svar_value | svar_sum | svar_table + ; + +svar_case + @after {$svar_g::sv_.caseName.add($ci.text); $svar_g::sv_.caseCondition.add($cc.text);} + : CASE ci=ID '{' CONDITION cc=logical_main ( svar_value | svar_sum | svar_table ) '}' ; + +svar_value + : VALUE e=expr_add + { $svar_g::sv_.caseExpression.add($e.text); }; + +svar_sum + : h=sum_header c=sum_content + { $svar_g::sv_.caseExpression.add($h.text+" "+$c.text); }; + +sum_header + : SUM '(' 'i' '=' e1=expr_add ',' e2=expr_add (',' integer)? ')' + ; + +sum_content + : e=expr_add ; + +svar_table + : t1=svar_table_1 { $svar_g::sv_.caseExpression.add($t1.text); + //System.out.println($t1.text); + } + | svar_table_2 ; + +svar_table_1 + : s=SELECT { $s.setText("select ");} (ID|reservedID) + f=FROM { $f.setText(" from ");} ID + (g=GIVEN { $g.setText(" given ");} expr_assign + u=USE { $u.setText(" use ");} ID)? + (w=WHERE { $w.setText(" where ");} where)? + ; + +where: expr_assign (',' expr_assign)* ; + +svar_table_2 + : 'table' '(' ')' ; + + +// common rules + +dimension : '[' ( INT | ID ) ']' ; + +dimension_time : '(' ( INT | ID ) ')' ; + +//typeNumber: 'integer' | 'real' | 'binary' ; + +//value : 'value' expr_add; + +//sum: 'sum' '(' 'i' '=' INT ',' expr_add ',' INT ')' '(' expr_add ')'; + +//table : 'select' ID 'from' ID 'where' expr_assign (',' expr_assign)* ; + +// end common rules + + + +//timeseries: 'timeseries' ID '{' 'kind' '\'' .+ '\'' 'units' '\'' id_with_dash '\'' '}'; +timeseries returns[String id, TimeseriesTemp tsObj] +scope { TimeseriesTemp ts_; + String id_; + } +@init{ $timeseries::ts_ = new TimeseriesTemp(); + $timeseries::ts_.fromWresl = this.currentAbsolutePath; + } +@after{ $id = $timeseries::ts_.id; + $tsObj = $timeseries::ts_; + $tsObj.line = line; + } + : timeseries_new | timeseries_old ; + +timeseries_new : TIMESERIES{line=$TIMESERIES.line;} tsID '{' (NAME bpart_id)? tsKind tsUnits convert? '}' ; +timeseries_old : DEFINE{line=$DEFINE.line;} (local_deprecated)? tsID '{' TIMESERIES bpart_id? tsKind tsUnits convert? '}' ; + +tsID : i=ID {$timeseries::ts_.id=$i.text;$timeseries::ts_.dssBPart=$i.text;} ; +tsUnits: UNITS s=QUOTE {$timeseries::ts_.units=Tools.strip($s.text);} ; +tsKind: KIND s=QUOTE {$timeseries::ts_.kind=Tools.strip($s.text);} ; +bpart_id : s=QUOTE {$timeseries::ts_.dssBPart=Tools.strip($s.text);}; +convert : CONVERT s=QUOTE {$timeseries::ts_.convertToUnits=Tools.strip($s.text);}; + +/// network +network : NETWORK ID '{' node? connection+ '}'; + +//inlet: 'inlet' ID ( ',' ID)* ; +//outlet: 'outlet' ID ( ',' ID)* ; +node: NODE ID ( ',' ID)* ; + +connection: branch | branch_short ; + +inlet : INFLOW element ; +outlet : element OUTFLOW ; +inoutlet : INFLOW element OUTFLOW ; + +branch_short : inoutlet ; + +branch : (elements | inlet) FLOW (element FLOW)* (elements | outlet) ; + +elements : element ( ',' element)* ; + +element : ID ('.' ID)? ; + + +//branch: ( id_with_port arrow_type )+ id_with_port ; +// +//id_with_port: inlet_port? id outlet_port? ; +// +//id_with_inlet : inlet_port? id ; +// +//id_with_outlet : id outlet_port? ; +// +//inlet_port : '(' ID ':)' ; +//outlet_port : '(:' ID ')' ; + + +/// external + +ex_g returns[String id, ExternalTemp exObj] +scope { ExternalTemp ex_; + String id_; + } +@init{ $ex_g::ex_ = new ExternalTemp(); + $ex_g::ex_.fromWresl = this.currentAbsolutePath; + } +@after{ $id = $ex_g::ex_.id; + $exObj = $ex_g::ex_; + $exObj.line=line; + } + : ex_old ; //| ex_new ; + +ex_id : i=ID {$ex_g::ex_.id=$i.text;} ; + +ex_old : DEFINE{line=$DEFINE.line;} (local_deprecated)? ex_id '{' EXTERNAL f=ex_fileName {$ex_g::ex_.fileName=$f.text;} '}' ; + +ex_fileName : ID ('.' ID)? ; + +//ex_new : EXTERNAL ex_id '{' ( ex_fortran | ex_java ) '}' ; + +//ex_fortran : 'language' 'fortran' '{' fortran_var+ fortran_return '}' ; + +//fortran_var : VARIABLE ID '{' 'type' 'intent' '}' ; +//fortran_return : 'return' ; + +//ex_java : 'language' 'java' ; + + +/// dvar +dvar_g returns[String id, DvarTemp dvObj] +scope { DvarTemp dvar_; + String id_; + } +@init{ $dvar_g::dvar_ = new DvarTemp(); + $dvar_g::dvar_.fromWresl = this.currentAbsolutePath; + } +@after{ $id= $dvar_g::id_; $dvObj= $dvar_g::dvar_; $dvObj.line=line; } + : ( dvar_group_new | dvar_group_old ) + ; + +dvarID : i=ID { $dvar_g::dvar_.id=$i.text; $dvar_g::id_=$i.text; }; + +dvar_group_old: DEFINE{line=$DEFINE.line;} (local_deprecated)? dvar ; +dvar_group_new: DVAR{line=$DVAR.line;} dvar ; + +dvar: (dvarArray|dvarTimeArray)? dvarID '{' dvar_trunk '}' ; + +dvarArray : '[' d=( INT | ID ) ']' {$dvar_g::dvar_.arraySize=$d.text; }; +dvarTimeArray : '(' d=( INT | ID ) ')' {$dvar_g::dvar_.timeArraySize=$d.text; }; + +//dvar_array : dimension dvarID '{' dvar_trunk '}' ; +// +//dvar_timeArray: dimension_time dvarID '{' dvar_trunk '}' ; + +dvar_trunk + : + // TODO: remove addDep. this is to match wreslparser result. + ( ( ( dvarIsInteger? ( std | ( {addDep = false;} lower_upper {addDep = true;} ) ) ) + | dvarIsBinary ) + dvKindUnits ) + | ('<' ID '>') ; + +//dvar_array_trunk : ( index_assign? '{' dvar_trunk '}' )+ ; +//dvar_timeArray_trunk : ( timeIndex_assign? '{' dvar_trunk '}' )+ ; + +dvarIsInteger : INTEGER {$dvar_g::dvar_.isInteger=true; $dvar_g::dvar_.upperBound="1";$dvar_g::dvar_.lowerBound="0";} ; +dvarIsBinary : BINARY {$dvar_g::dvar_.isInteger=true; $dvar_g::dvar_.upperBound="1";$dvar_g::dvar_.lowerBound="0";} ; +index_assign : '[' INT (':' INT)? ']' ; +timeIndex_assign : '(' INT (':' INT)? ')' ; + +lower_upper : lower upper? | upper lower? ; +upper: UPPER ( e=expr_limited {$dvar_g::dvar_.upperBound=$e.text;} | UNBOUNDED {$dvar_g::dvar_.upperBound=Param.upper_unbounded;}) ; +lower: LOWER ( e=expr_limited {$dvar_g::dvar_.lowerBound=$e.text;} | UNBOUNDED {$dvar_g::dvar_.lowerBound=Param.lower_unbounded;}) ; + +expr_limited: expr_add ; //number ( ('*' | '/') unitFunc )? ; + +std: STD ; + +dvKindUnits : dvKind dvUnits | dvUnits dvKind ; +dvKind: KIND s=QUOTE {$dvar_g::dvar_.kind=Tools.strip($s.text);}; +dvUnits: UNITS s=QUOTE {$dvar_g::dvar_.units=Tools.strip($s.text);}; + + + + + + + +//================ begin logical ==============// + +logical_main: logical_or | ALWAYS ; + +logical_or + : logical_and + ( o=OR {$o.setText(" .or. ");} logical_and )* + ; + +logical_and + : logical_unary + ( a=AND {$a.setText(" .and. ");} logical_unary )* + ; + +logical_unary : NOT? logical_term; + +logical_term + : ( logical_relation ) => logical_relation + | ( logical_or_p ) => logical_or_p + | logical_relation_p + | logicalFunc + ; + +logical_or_p : '(' logical_or ')' ; + +logical_relation_p + : '(' logical_relation ')' + ; + +logical_relation + : expr_add relation_token expr_add + ; + +logicalFunc + : RANGE '(' expr_add ',' expr_add ',' expr_add ')' ; +//================ end logical ==============// + + +/// constraint expr +constraint_token : '>' | '<' | '>=' | '<=' | '=' ; + +expr_constraint + : expr_add constraint_token expr_add + ; + +// comparison expr +relation_token: '>' | '<' | '>=' | '<=' | '==' | '/=' ; + +expr_relation + : expr_add relation_token expr_add + ; + +// ignore dependants in the lhs +expr_assign +@init{ Set backup = new LinkedHashSet(dependants);} + : expr_add {dependants = backup;} '=' expr_add + ; +//================ begin simple expr_add ==============// +expr_add_simple + : expr_mult_simple ( ( '+' | '-' ) expr_mult_simple )* + ; + +expr_mult_simple + : expr_unary_simple ( ( '*' | '/' ) expr_unary_simple )* + ; + +expr_unary_simple: '-'? expr_term_simple ; + +expr_term_simple + : atom_simple + | '(' expr_add_simple ')' + ; + +atom_simple + : number_p + | v=varID {dependants.add($v.text);} + | intrinsicFunc_simple + ; + +intrinsicFunc_simple + : mathFunc_simple + | multiInputFunc_simple + | unitFunc_simple + ; + +mathFunc_simple + : LOG '(' expr_add_simple ')' + | INT_word '(' expr_add_simple ')' + | ROUND '(' expr_add_simple ')' + | MOD '(' expr_add_simple ',' expr_add_simple ')' + | SIN '(' expr_add_simple ')' + | COS '(' expr_add_simple ')' + | TAN '(' expr_add_simple ')' + | COT '(' expr_add_simple ')' + | ASIN '(' expr_add_simple ')' + | ACOS '(' expr_add_simple ')' + | ATAN '(' expr_add_simple ')' + | ACOT '(' expr_add_simple ')' + | exceedFunc + | exceedtsiFunc + ; + +unitFunc_simple + : ( CFS_TAF | TAF_CFS ) ('(' expr_add_simple ')')? ; + +multiInputFunc_simple + : ( MIN | MAX ) '(' expr_add_simple ( ',' expr_add_simple )* ')' ; + +//================ end simple expr_add ==============// + +//================ begin expr_add ==============// +expr_add + : expr_mult ( ( '+' | '-' ) expr_mult )* + ; + +expr_mult + : expr_unary ( ( '*' | '/' ) expr_unary )* + ; + +expr_unary: ('-'|'+')? expr_term ; + +expr_term + : atom + | '(' expr_add ')' + ; +//================ end expr_add ==============// + +atom + : number_p + | v=varID {if (addDep) dependants.add($v.text);} + | intrinsicFunc + // | r=reservedID {if (isParameter) dependants_notAllowed.add($r.text);} + | s=specialVar {if (isParameter) dependants_notAllowed.add($s.text);} + | externalFunc + | vf=varFunc {if (isParameter) dependants_notAllowed.add($vf.text);} + | p=preCycleVar {if (isParameter) dependants_notAllowed.add($p.text);} + ; + +specialVar : 'i' | '$m' | '$M'; + +preCycleVar + : p1=preCycleVar_old {varInCycle.add($p1.text);} | p2=preCycleVarIndex {varInCycle.add($p2.text);} + ; + +preCycleVar_old : var=ID '[' cycle=ID ']' ('(' e=expr_add ')')? +{ + // TODO: don't convert to lower case here! + if (!isParameter){ + String cnl = $cycle.text.toLowerCase(); + String vl = $var.text.toLowerCase(); + if (neededCycleVarMap.keySet().contains(cnl)) { + neededCycleVarMap.get(cnl).add(vl); + } else { + HashSet t = new HashSet(); + t.add(vl); + neededCycleVarMap.put(cnl, t); + } + } +} ; + +preCycleVarIndex : var=ID '[' '-' INT ']' ('(' e=expr_add ')')? { + if (!VarCycleIndex.varCycleIndexList.contains($var.text)){ + VarCycleIndex.varCycleIndexList.add($var.text.toLowerCase()); + } +}; + +externalFunc + : 'extern:(' ID '(' expr_add ')' ')' + ; +intrinsicFunc + : mathFunc + | multiInputFunc + | unitFunc + | tableFunc + | timeFunc + | sumFunc + ; + +sumFunc: '(' sum_header sum_content ')'; + +timeFunc: ( DAY | MONTH | WATERYEAR ) ( '(' expr_add ')' )? ; + +tableFunc : 'table' '(' tableName ',' columnNumber ',' rowNumber ')' ; + +tableName : ID ; +columnNumber : INT ; +rowNumber : INT ; + +varFunc + : v=varID '(' func_arg (',' func_arg )* ')' ('(' expr_add ')')? + {dependants.add($v.text); + //System.out.println(dependants); + } + ; + +varID : ID ; + +func_arg: expr_add|trunk_timeArray; + +trunk_timeArray + : v1=varID '(' (integer|v2=varID{dependants.add($v2.text);}) ':' (integer|v3=varID{dependants.add($v3.text);}) ')'; + +number : integer | real ; +number_p : integer_p | real_p ; + +integer : integer_p|integer_n ; +real : real_p|real_n ; + +integer_p : INT ; +integer_n : '-' INT ; +real_p : REAL ; +real_n : '-' REAL ; + + +id_domain : ( ID '.' )? ID ; + + + +mathFunc + : LOG '(' expr_add ')' + | INT_word '(' expr_add ')' + | ROUND '(' expr_add ')' + | MOD '(' expr_add ',' expr_add ')' + | SIN '(' expr_add ')' + | COS '(' expr_add ')' + | TAN '(' expr_add ')' + | COT '(' expr_add ')' + | ASIN '(' expr_add ')' + | ACOS '(' expr_add ')' + | ATAN '(' expr_add ')' + | ACOT '(' expr_add ')' + | exceedFunc + | exceedtsiFunc + ; + +unitFunc + : ( CFS_TAF | TAF_CFS ) ('(' expr_add ')')? ; + +multiInputFunc + : ( MIN | MAX ) '(' expr_add ( ',' expr_add )* ')' ; + +//exceedance(FOLSM_INFLOW, 0.9,ALL/OCT,1921,OCT,31,2015,SEP,30) +exceedFunc + : EXCEEDANCE '(' varID ',' number_p ',' varID ',' integer_p ',' varID ',' integer ',' integer_p ',' varID ',' integer ')' + ; + +exceedtsiFunc + : EXCEEDANCE_TSI '(' varID ',' number_p ',' varID ',' integer_p ',' varID ',' integer ',' integer_p ',' varID ',' integer ')' + ; + +// +//// reserved ID +//DaysIn: 'daysin'; +//Int: 'int'; +//Real: 'real'; + + +reservedID : DAY | MONTH | WATERYEAR ; //| MonthID ; + +QUOTE : '\'' .* '\'' ; + +ML_COMMENT : '/*' .* '*/' {skip();}; + +SL_COMMENT : ('#'|'!') ~('\r'|'\n')* {skip();}; //{$channel=HIDDEN;} ; + +AND : '&&' | '.and.' | '.AND.' ; +OR : '||' | '.or.' | '.OR.' ; +NOT : '.not.' | '.NOT.' ; +NOT_EQUAL : '.ne.' | '.NE.' ; + +DAY: 'day'|'Day'|'DAY'; +MONTH : 'month' | 'Month' | 'MONTH' ; +WATERYEAR : 'wateryear' | 'Wateryear' | 'WaterYear' | 'WATERYEAR' ; +//MonthID : 'jan'|'feb'|'mar'|'apr'|'may'|'jun'|'jul'|'aug'|'sep'|'oct'|'nov'|'dec'; + + +REAL : ( Digit+ '.' Digit* ) | ( '.' Digit+ ) ; +INT : Digit+ ; + +OBJECTIVE : 'objective' | 'OBJECTIVE' | 'Objective' ; +//OBJ : 'obj' | 'Obj' | 'OBJ' ; +MODEL : 'model' | 'MODEL' | 'Model' ; +GROUP : 'group' | 'Group' | 'GROUP'; +SEQUENCE : 'sequence' | 'Sequence' | 'SEQUENCE' ; + +ORDER : 'order' | 'ORDER' | 'Order' ; +TIMESTEP : 'timestep'|'TIMESTEP'|'TimeStep'; +TIMESTEPVALUE: '1mon'|'1day'; +INCLUDE : 'include' | 'INCLUDE' | 'Include' ; +CASE : 'case' | 'CASE' | 'Case' ; +CONDITION : 'condition' | 'CONDITION' | 'Condition' ; +GOAL : 'goal' | 'GOAL' | 'Goal' ; +VALUE : 'value' | 'VALUE' | 'Value'; +PENALTY : 'penalty' | 'PENALTY' | 'Penalty' ; +DeviationPenalty : 'deviationpenalty' | 'DEVIATIONPENALTY' | 'DeviationPenalty' | 'deviationPenalty' | 'Deviationpenalty' ; +DeviationTolerance : 'deviationtolerance' | 'DEVIATIONTOLERANCE' | 'DeviationTolerance' | 'deviationTolerance' | 'Deviationtolerance' ; +WEIGHT : 'weight' | 'WEIGHT' | 'Weight' ; +//ITEM : 'item' | 'ITEM' | 'Item' ; + +CONFIG : 'config' | 'CONFIG' | 'Config'; +SORTING : 'sorting' | 'SORTING' | 'Sorting' ; +TRUE : 'true' | 'TRUE' | 'True' ; +FALSE : 'false' | 'FALSE' | 'False' ; +LABEL : 'label' ; +NAME : 'name' ; + +Initial : 'initial' | 'Initial' | 'INITIAL' ; +//Parameter : 'parameter' | 'Parameter' | 'PARAMETER' ; +Const : 'const' | 'Const' | 'CONST' ; + +If : 'If' | 'IF' | 'if' ; +Elseif : 'Elseif' | 'ELSEIF' | 'elseif' | 'ElseIf' ; +Else : 'Else' | 'ELSE' | 'else' ; + +// deprecated keyword +DEFINE : 'define' | 'DEFINE' | 'Define' ; +LOCAL : 'local' | 'LOCAL' | 'Local' ; +/////////////////////////////// + +STD : 'std' | 'STD' | 'Std' ; +DVAR : 'dvar' | 'DVAR' | 'Dvar' ; +SVAR : 'svar' | 'SVAR' | 'Svar' ; +VARIABLE : 'variable' | 'VARIABLE' | 'Variable' ; +ALIAS : 'alias' | 'ALIAS' | 'Alias'; +TIMESERIES : 'timeseries' | 'TIMESERIES' | 'Timeseries' ; +EXTERNAL : 'external' | 'EXTERNAL' | 'External' ; +TEMPLATE : 'template' ; + + +SUM : 'sum' | 'SUM' | 'Sum'; +KIND : 'kind' | 'KIND' | 'Kind'; +UNITS : 'units' | 'UNITS' | 'Units' ; +NoSolver : 'NoSolver' | 'Nosolver' | 'NOSOLVER' | 'nosolver' | 'noSolver'; +CONVERT : 'convert' | 'CONVERT' |'Convert' ; +UPPER : 'upper' | 'UPPER' | 'Upper'; +LOWER : 'lower' | 'LOWER' | 'Lower'; + +UNBOUNDED : 'unbounded'|'UNBOUNDED' ; + +ALWAYS: 'always'|'ALWAYS'|'Always' ; +INTEGER : 'integer'|'INTEGER'|'Integer'; +BINARY : 'binary'|'BINARY'|'Binary'; + +SELECT : 'select' | 'SELECT'|'Select' ; +FROM : 'from' | 'FROM'|'From' ; +WHERE : 'where' | 'WHERE'|'Where' ; +GIVEN : 'given' | 'GIVEN'|'Given' ; +USE : 'use' | 'USE'|'Use' ; + +LHS : 'lhs' | 'LHS' ; +RHS : 'rhs' | 'RHS' ; + +// special function +RANGE : 'range' | 'RANGE' | 'Range' ; + +// intrinsic function +INT_word : 'int' | 'INT' ; +ROUND : 'round' | 'ROUND' ; +LOG : 'log' | 'LOG' ; +MAX : 'max' | 'MAX' ; +MIN : 'min' | 'MIN' ; +MOD : 'mod' | 'MOD' ; +SIN : 'sin' | 'SIN' ; +COS : 'cos' | 'COS' ; +TAN : 'tan' | 'TAN' ; +COT : 'cot' | 'COT' ; +ASIN : 'asin' | 'ASIN' ; +ACOS : 'acos' | 'ACOS' ; +ATAN : 'atan' | 'ATAN' ; +ACOT : 'acot' | 'ACOT' ; +EXCEEDANCE : 'exceedance' | 'EXCEEDANCE' ; +EXCEEDANCE_TSI : 'exceedance_tsi' | 'EXCEEDANCE_TSI' ; +CFS_TAF : 'cfs_taf' | 'CFS_TAF' ; +TAF_CFS : 'taf_cfs' | 'TAF_CFS' ; + +// network +NETWORK : 'network' | 'NETWORK' | 'Network' ; +NODE : 'node' | 'NODE' | 'Node' ; +INFLOW : '*>>' ; +OUTFLOW : '>>*' ; +FLOW : '>>' ; + +//ID : ('a'..'z'|'A'..'Z')('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ; +ID : Letter ( Letter | Digit | '_' )*; + + +fragment Letter : 'a'..'z' | 'A'..'Z'; + +fragment Digit : '0'..'9'; + +WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {skip();}; //{$channel = HIDDEN;}; +//WS : ( '\t' | '\n' | '\r' | '\f')+ {skip();}; //{$channel = HIDDEN;}; +//WS2 : ( ' ' )+ {$channel = HIDDEN;}; diff --git a/wrims_v2/wrims_v2/src/main/BatchRun.java b/wrims-core/src/main/java/main/BatchRun.java similarity index 93% rename from wrims_v2/wrims_v2/src/main/BatchRun.java rename to wrims-core/src/main/java/main/BatchRun.java index 26296189d..75eb4d51b 100644 --- a/wrims_v2/wrims_v2/src/main/BatchRun.java +++ b/wrims-core/src/main/java/main/BatchRun.java @@ -1,12 +1,12 @@ -package main; - -import wrimsv2.components.ControllerBatch; - -public class BatchRun { - - public static void main(String[] args) { - - new ControllerBatch(args); - - } -} +package main; + +import wrimsv2.components.ControllerBatch; + +public class BatchRun { + + public static void main(String[] args) { + + new ControllerBatch(args); + + } +} diff --git a/wrims_v2/wrims_v2/src/main/WreslCheck.java b/wrims-core/src/main/java/main/WreslCheck.java similarity index 94% rename from wrims_v2/wrims_v2/src/main/WreslCheck.java rename to wrims-core/src/main/java/main/WreslCheck.java index 15be5d3d5..206d48518 100644 --- a/wrims_v2/wrims_v2/src/main/WreslCheck.java +++ b/wrims-core/src/main/java/main/WreslCheck.java @@ -1,16 +1,16 @@ -package main; - -import java.io.IOException; -import org.antlr.runtime.RecognitionException; - -import wrimsv2.wreslparser.elements.StudyUtils; - -public class WreslCheck { - - public static void main(String[] args) throws RecognitionException, IOException { - - StudyUtils.checkStudy(args[0]); - - } - -} +package main; + +import java.io.IOException; +import org.antlr.runtime.RecognitionException; + +import wrimsv2.wreslparser.elements.StudyUtils; + +public class WreslCheck { + + public static void main(String[] args) throws RecognitionException, IOException { + + StudyUtils.checkStudy(args[0]); + + } + +} diff --git a/wrims_v2/wrims_v2/src/main/WreslCheckGUI.java b/wrims-core/src/main/java/main/WreslCheckGUI.java similarity index 100% rename from wrims_v2/wrims_v2/src/main/WreslCheckGUI.java rename to wrims-core/src/main/java/main/WreslCheckGUI.java diff --git a/wrims_v2/wrims_v2/src/serial/SerialXml.java b/wrims-core/src/main/java/serial/SerialXml.java similarity index 94% rename from wrims_v2/wrims_v2/src/serial/SerialXml.java rename to wrims-core/src/main/java/serial/SerialXml.java index 706b1b858..03d810a36 100644 --- a/wrims_v2/wrims_v2/src/serial/SerialXml.java +++ b/wrims-core/src/main/java/serial/SerialXml.java @@ -1,46 +1,46 @@ -package serial; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import wrimsv2.wreslplus.elements.ModelTemp; -import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.io.xml.CompactWriter; - -public class SerialXml { - - public static void writeModelTemp(ModelTemp m, String xPath) { - - FileWriter writer = null; - - try { - writer = new FileWriter(xPath); - - } - catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - CompactWriter cw = new CompactWriter(writer); - - XStream xstream = new XStream(); - xstream.marshal(m, cw); - - cw.close(); - - } - - public static ModelTemp readModelTemp(String xPath) { - - File file = new File(xPath); - - XStream xstream = new XStream(); - - ModelTemp out = (ModelTemp) xstream.fromXML(file); - - return out; - - } - -} +package serial; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import wrimsv2.wreslplus.elements.ModelTemp; +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.io.xml.CompactWriter; + +public class SerialXml { + + public static void writeModelTemp(ModelTemp m, String xPath) { + + FileWriter writer = null; + + try { + writer = new FileWriter(xPath); + + } + catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + CompactWriter cw = new CompactWriter(writer); + + XStream xstream = new XStream(); + xstream.marshal(m, cw); + + cw.close(); + + } + + public static ModelTemp readModelTemp(String xPath) { + + File file = new File(xPath); + + XStream xstream = new XStream(); + + ModelTemp out = (ModelTemp) xstream.fromXML(file); + + return out; + + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/solverdata/SolverData.java b/wrims-core/src/main/java/wrimsv2/commondata/solverdata/SolverData.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/solverdata/SolverData.java rename to wrims-core/src/main/java/wrimsv2/commondata/solverdata/SolverData.java index 2165076a5..b921dfcd1 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/solverdata/SolverData.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/solverdata/SolverData.java @@ -1,50 +1,50 @@ -package wrimsv2.commondata.solverdata; - -import java.util.HashMap; -import java.util.Map; -import java.util.ArrayList; -import java.util.concurrent.ConcurrentHashMap; - -import wrimsv2.evaluator.EvalConstraint; -import wrimsv2.evaluator.EvalExpression; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.WeightElement; - -public class SolverData { - private static ConcurrentHashMap constraintDataMap=new ConcurrentHashMap(); - private static ConcurrentHashMap dvarMap= new ConcurrentHashMap(); - private static ConcurrentHashMap weightMap = new ConcurrentHashMap(); - private static ConcurrentHashMap weightSlackSurplusMap = new ConcurrentHashMap(); - - public static ConcurrentHashMap getWeightMap(){ - return weightMap; - } - - public static void clearWeightMap(){ - weightMap=new ConcurrentHashMap(); - } - - public static ConcurrentHashMap getWeightSlackSurplusMap(){ - return weightSlackSurplusMap; - } - - public static void clearWeightSlackSurplusMap(){ - weightSlackSurplusMap=new ConcurrentHashMap(); - } - - public static ConcurrentHashMap getDvarMap(){ - return dvarMap; - } - - public static void clearDvarMap(){ - dvarMap=new ConcurrentHashMap(); - } - - public static ConcurrentHashMap getConstraintDataMap(){ - return constraintDataMap; - } - - public static void clearConstraintDataMap(){ - constraintDataMap=new ConcurrentHashMap(); - } -} +package wrimsv2.commondata.solverdata; + +import java.util.HashMap; +import java.util.Map; +import java.util.ArrayList; +import java.util.concurrent.ConcurrentHashMap; + +import wrimsv2.evaluator.EvalConstraint; +import wrimsv2.evaluator.EvalExpression; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.WeightElement; + +public class SolverData { + private static ConcurrentHashMap constraintDataMap=new ConcurrentHashMap(); + private static ConcurrentHashMap dvarMap= new ConcurrentHashMap(); + private static ConcurrentHashMap weightMap = new ConcurrentHashMap(); + private static ConcurrentHashMap weightSlackSurplusMap = new ConcurrentHashMap(); + + public static ConcurrentHashMap getWeightMap(){ + return weightMap; + } + + public static void clearWeightMap(){ + weightMap=new ConcurrentHashMap(); + } + + public static ConcurrentHashMap getWeightSlackSurplusMap(){ + return weightSlackSurplusMap; + } + + public static void clearWeightSlackSurplusMap(){ + weightSlackSurplusMap=new ConcurrentHashMap(); + } + + public static ConcurrentHashMap getDvarMap(){ + return dvarMap; + } + + public static void clearDvarMap(){ + dvarMap=new ConcurrentHashMap(); + } + + public static ConcurrentHashMap getConstraintDataMap(){ + return constraintDataMap; + } + + public static void clearConstraintDataMap(){ + constraintDataMap=new ConcurrentHashMap(); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Alias.java b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/Alias.java similarity index 93% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Alias.java rename to wrims-core/src/main/java/wrimsv2/commondata/tabledata/Alias.java index dd1252d1c..24d33ca37 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Alias.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/Alias.java @@ -1,38 +1,38 @@ -package wrimsv2.commondata.tabledata; - -public class Alias { - - private String type; - private String units; - private String expression; - - public Alias(){ - type="undefined"; - units="undefined"; - } - - public void setType(String type){ - this.type=type; - } - - public void setUnits(String units){ - this.units=units; - } - - public void setExpression(String expression){ - this.expression=expression; - } - - public String getType(){ - return type; - } - - public String getUnits(){ - return units; - } - - public String getExpression(){ - return expression; - } -} - +package wrimsv2.commondata.tabledata; + +public class Alias { + + private String type; + private String units; + private String expression; + + public Alias(){ + type="undefined"; + units="undefined"; + } + + public void setType(String type){ + this.type=type; + } + + public void setUnits(String units){ + this.units=units; + } + + public void setExpression(String expression){ + this.expression=expression; + } + + public String getType(){ + return type; + } + + public String getUnits(){ + return units; + } + + public String getExpression(){ + return expression; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Constraint.java b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/Constraint.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Constraint.java rename to wrims-core/src/main/java/wrimsv2/commondata/tabledata/Constraint.java index d29760b81..0ff19f691 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Constraint.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/Constraint.java @@ -1,33 +1,33 @@ -package wrimsv2.commondata.tabledata; - -import java.util.ArrayList; - -public class Constraint { - - private String constraintName; - private ArrayList caseCondition; - private ArrayList caseExpression; - - - public Constraint(){ - caseCondition = new ArrayList(); - caseExpression = new ArrayList(); - } - - public void setCaseCondition(ArrayList caseCondition){ - this.caseCondition=caseCondition; - } - - public void setCaseExpression(ArrayList caseExpression){ - this.caseExpression=caseExpression; - } - - public ArrayList getCaseCondition(){ - return caseCondition; - } - - public ArrayList getCaseExpression(){ - return caseExpression; - } -} - +package wrimsv2.commondata.tabledata; + +import java.util.ArrayList; + +public class Constraint { + + private String constraintName; + private ArrayList caseCondition; + private ArrayList caseExpression; + + + public Constraint(){ + caseCondition = new ArrayList(); + caseExpression = new ArrayList(); + } + + public void setCaseCondition(ArrayList caseCondition){ + this.caseCondition=caseCondition; + } + + public void setCaseExpression(ArrayList caseExpression){ + this.caseExpression=caseExpression; + } + + public ArrayList getCaseCondition(){ + return caseCondition; + } + + public ArrayList getCaseExpression(){ + return caseExpression; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Dvar.java b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/Dvar.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Dvar.java rename to wrims-core/src/main/java/wrimsv2/commondata/tabledata/Dvar.java index f551fe0e8..0badcb7d3 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Dvar.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/Dvar.java @@ -1,97 +1,97 @@ -package wrimsv2.commondata.tabledata; - -public class Dvar { - - private String type; - private String units; - private String lowerBound; - private String upperBound; - private boolean integerType; - private String sourceFile; - private int lineNumber; - private int posLowerBound; - private int posUpperBound; - - public Dvar(){ - type="undefined"; - units="undefined"; - integerType=false; - } - - public void setType(String type){ - this.type=type; - } - - public void setUnits(String units){ - this.units=units; - } - - public void setLowerBound(String lowerBound){ - this.lowerBound=lowerBound; - } - - public void setUpperBound(String upperBound){ - this.upperBound=upperBound; - } - - public void setIntegerType(boolean isInteger){ - integerType=isInteger; - } - - public void setSourceFileName(String fileName){ - sourceFile=fileName; - } - - public void setLineNumber(int number){ - lineNumber=number; - } - - public void setPosLowerBound(int pos){ - posLowerBound=pos; - } - - public void setPosUpperBound(int pos){ - posUpperBound=pos; - } - - public String getLowerBound(){ - return lowerBound; - } - - public String getUpperBound(){ - return upperBound; - } - - public String getUnits(){ - return units; - } - - public String getType(){ - return type; - } - - public String getIntegerType(){ - if (integerType){ - return "true"; - }else{ - return "false"; - } - } - - public String getSourceFileName(){ - return sourceFile; - } - - public int getLineNumber(){ - return lineNumber; - } - - public int getPosLowerBound(){ - return posLowerBound; - } - - public int getPosUpperBound(){ - return posUpperBound; - } -} - +package wrimsv2.commondata.tabledata; + +public class Dvar { + + private String type; + private String units; + private String lowerBound; + private String upperBound; + private boolean integerType; + private String sourceFile; + private int lineNumber; + private int posLowerBound; + private int posUpperBound; + + public Dvar(){ + type="undefined"; + units="undefined"; + integerType=false; + } + + public void setType(String type){ + this.type=type; + } + + public void setUnits(String units){ + this.units=units; + } + + public void setLowerBound(String lowerBound){ + this.lowerBound=lowerBound; + } + + public void setUpperBound(String upperBound){ + this.upperBound=upperBound; + } + + public void setIntegerType(boolean isInteger){ + integerType=isInteger; + } + + public void setSourceFileName(String fileName){ + sourceFile=fileName; + } + + public void setLineNumber(int number){ + lineNumber=number; + } + + public void setPosLowerBound(int pos){ + posLowerBound=pos; + } + + public void setPosUpperBound(int pos){ + posUpperBound=pos; + } + + public String getLowerBound(){ + return lowerBound; + } + + public String getUpperBound(){ + return upperBound; + } + + public String getUnits(){ + return units; + } + + public String getType(){ + return type; + } + + public String getIntegerType(){ + if (integerType){ + return "true"; + }else{ + return "false"; + } + } + + public String getSourceFileName(){ + return sourceFile; + } + + public int getLineNumber(){ + return lineNumber; + } + + public int getPosLowerBound(){ + return posLowerBound; + } + + public int getPosUpperBound(){ + return posUpperBound; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/IlpData.java b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/IlpData.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/IlpData.java rename to wrims-core/src/main/java/wrimsv2/commondata/tabledata/IlpData.java index 62015c00e..eca0d6b49 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/IlpData.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/IlpData.java @@ -1,90 +1,90 @@ -package wrimsv2.commondata.tabledata; - -import java.util.ArrayList; -import java.util.Map; - -public class IlpData { - private static ArrayList>> nodeArray = new ArrayList>>(); - private static ArrayList> dvarArray = new ArrayList>(); - private static ArrayList> svarArray = new ArrayList>(); - private static ArrayList> outputSvarArray = new ArrayList>(); - private static ArrayList> weightArray = new ArrayList>(); - private static ArrayList> fileArray = new ArrayList>(); - private static ArrayList> constraintArray = new ArrayList> (); - private static ArrayList> lgrArray = new ArrayList>(); - private static ArrayList> rglArray = new ArrayList>(); - private static ArrayList> functionArray = new ArrayList>(); - private static ArrayList> aliasArray = new ArrayList>(); - - public static ArrayList> getDvarArray(){ - return dvarArray; - } - - public static void addDvarToArray(Map dvar){ - dvarArray.add(dvar); - } - - public static ArrayList> getSvarArray(){ - return svarArray; - } - - public static void addSvarToArray(Map svar){ - svarArray.add(svar); - } - - public static ArrayList> getOutputSvarArray(){ - return outputSvarArray; - } - - public static void addOutputSvarToArray(ArrayList outputSvar){ - outputSvarArray.add(outputSvar); - } - - public static ArrayList> getWeightArray(){ - return weightArray; - } - - public static void addWeightToArray(Map weight){ - weightArray.add(weight); - } - - public static ArrayList> getConstraintArray(){ - return constraintArray; - } - - public static void addConstraintToArray(Map constraint){ - constraintArray.add(constraint); - } - - public static ArrayList> getLgrArray(){ - return lgrArray; - } - - public static void addLgrToArray(Map lgr){ - lgrArray.add(lgr); - } - - public static ArrayList> getRglArray(){ - return rglArray; - } - - public static void addRglToArray(Map rgl){ - rglArray.add(rgl); - } - - public static ArrayList> getFunctionArray (){ - return functionArray; - } - - public static void addFunctionToArray (Map function){ - functionArray.add(function); - } - - public static ArrayList> getAliasArray(){ - return aliasArray; - } - - public static void addAliasToArray(Map alias){ - aliasArray.add(alias); - } +package wrimsv2.commondata.tabledata; + +import java.util.ArrayList; +import java.util.Map; + +public class IlpData { + private static ArrayList>> nodeArray = new ArrayList>>(); + private static ArrayList> dvarArray = new ArrayList>(); + private static ArrayList> svarArray = new ArrayList>(); + private static ArrayList> outputSvarArray = new ArrayList>(); + private static ArrayList> weightArray = new ArrayList>(); + private static ArrayList> fileArray = new ArrayList>(); + private static ArrayList> constraintArray = new ArrayList> (); + private static ArrayList> lgrArray = new ArrayList>(); + private static ArrayList> rglArray = new ArrayList>(); + private static ArrayList> functionArray = new ArrayList>(); + private static ArrayList> aliasArray = new ArrayList>(); + + public static ArrayList> getDvarArray(){ + return dvarArray; + } + + public static void addDvarToArray(Map dvar){ + dvarArray.add(dvar); + } + + public static ArrayList> getSvarArray(){ + return svarArray; + } + + public static void addSvarToArray(Map svar){ + svarArray.add(svar); + } + + public static ArrayList> getOutputSvarArray(){ + return outputSvarArray; + } + + public static void addOutputSvarToArray(ArrayList outputSvar){ + outputSvarArray.add(outputSvar); + } + + public static ArrayList> getWeightArray(){ + return weightArray; + } + + public static void addWeightToArray(Map weight){ + weightArray.add(weight); + } + + public static ArrayList> getConstraintArray(){ + return constraintArray; + } + + public static void addConstraintToArray(Map constraint){ + constraintArray.add(constraint); + } + + public static ArrayList> getLgrArray(){ + return lgrArray; + } + + public static void addLgrToArray(Map lgr){ + lgrArray.add(lgr); + } + + public static ArrayList> getRglArray(){ + return rglArray; + } + + public static void addRglToArray(Map rgl){ + rglArray.add(rgl); + } + + public static ArrayList> getFunctionArray (){ + return functionArray; + } + + public static void addFunctionToArray (Map function){ + functionArray.add(function); + } + + public static ArrayList> getAliasArray(){ + return aliasArray; + } + + public static void addAliasToArray(Map alias){ + aliasArray.add(alias); + } } \ No newline at end of file diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/LRWeight.java b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/LRWeight.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/LRWeight.java rename to wrims-core/src/main/java/wrimsv2/commondata/tabledata/LRWeight.java index b9c9df775..4499222fb 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/LRWeight.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/LRWeight.java @@ -1,43 +1,43 @@ -package wrimsv2.commondata.tabledata; - -import java.util.ArrayList; - -public class LRWeight { - - private String constraintName; - private ArrayList caseCondition; - private ArrayList caseExpression; - private ArrayList caseWeight; - - - public LRWeight(){ - caseCondition = new ArrayList(); - caseExpression = new ArrayList(); - caseWeight = new ArrayList(); - } - - public void setCaseCondition(ArrayList caseCondition){ - this.caseCondition=caseCondition; - } - - public void setCaseExpression(ArrayList caseExpression){ - this.caseExpression=caseExpression; - } - - public void setCaseWeight(ArrayList weight){ - this.caseWeight=weight; - } - - public ArrayList getCaseCondition(){ - return caseCondition; - } - - public ArrayList getCaseExpression(){ - return caseExpression; - } - - public ArrayList getCaseWeight(){ - return caseWeight; - } -} - +package wrimsv2.commondata.tabledata; + +import java.util.ArrayList; + +public class LRWeight { + + private String constraintName; + private ArrayList caseCondition; + private ArrayList caseExpression; + private ArrayList caseWeight; + + + public LRWeight(){ + caseCondition = new ArrayList(); + caseExpression = new ArrayList(); + caseWeight = new ArrayList(); + } + + public void setCaseCondition(ArrayList caseCondition){ + this.caseCondition=caseCondition; + } + + public void setCaseExpression(ArrayList caseExpression){ + this.caseExpression=caseExpression; + } + + public void setCaseWeight(ArrayList weight){ + this.caseWeight=weight; + } + + public ArrayList getCaseCondition(){ + return caseCondition; + } + + public ArrayList getCaseExpression(){ + return caseExpression; + } + + public ArrayList getCaseWeight(){ + return caseWeight; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Svar.java b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/Svar.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Svar.java rename to wrims-core/src/main/java/wrimsv2/commondata/tabledata/Svar.java index 50d831e5d..24e63c036 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/tabledata/Svar.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/tabledata/Svar.java @@ -1,60 +1,60 @@ -package wrimsv2.commondata.tabledata; - -import java.util.ArrayList; - -public class Svar { - - private String type; - private String units; - private String convertUnits; - private ArrayList caseCondition; - private ArrayList> caseExpression; - - public Svar(){ - type="undefined"; - units="undefined"; - caseCondition = new ArrayList(); - caseExpression = new ArrayList> (); - } - - public void setType(String type){ - this.type=type; - } - - public void setUnits(String units){ - this.units=units; - } - - public void setConvertUnits(String convertUnits){ - this.convertUnits=convertUnits; - } - - public void setCaseCondition(ArrayList caseCondition){ - this.caseCondition=caseCondition; - } - - public void setCaseExpression(ArrayList> caseExpression){ - this.caseExpression=caseExpression; - } - - public ArrayList getCaseCondition(){ - return caseCondition; - } - - public ArrayList> getCaseExpression(){ - return caseExpression; - } - - public String getType(){ - return type; - } - - public String getUnits(){ - return units; - } - - public String getConvertUnits(){ - return convertUnits; - } -} - +package wrimsv2.commondata.tabledata; + +import java.util.ArrayList; + +public class Svar { + + private String type; + private String units; + private String convertUnits; + private ArrayList caseCondition; + private ArrayList> caseExpression; + + public Svar(){ + type="undefined"; + units="undefined"; + caseCondition = new ArrayList(); + caseExpression = new ArrayList> (); + } + + public void setType(String type){ + this.type=type; + } + + public void setUnits(String units){ + this.units=units; + } + + public void setConvertUnits(String convertUnits){ + this.convertUnits=convertUnits; + } + + public void setCaseCondition(ArrayList caseCondition){ + this.caseCondition=caseCondition; + } + + public void setCaseExpression(ArrayList> caseExpression){ + this.caseExpression=caseExpression; + } + + public ArrayList getCaseCondition(){ + return caseCondition; + } + + public ArrayList> getCaseExpression(){ + return caseExpression; + } + + public String getType(){ + return type; + } + + public String getUnits(){ + return units; + } + + public String getConvertUnits(){ + return convertUnits; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Alias.java b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Alias.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Alias.java rename to wrims-core/src/main/java/wrimsv2/commondata/wresldata/Alias.java index 54c6a0157..907640ebf 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Alias.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Alias.java @@ -1,58 +1,58 @@ -package wrimsv2.commondata.wresldata; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.ValueEvaluatorParser; - - -public class Alias implements Serializable { - - private static final long serialVersionUID = 1L; - public String condition; - public String scope; - public String kind; - public String units; - public String expression; - public ValueEvaluatorParser expressionParser; - public String fromWresl; - public int line=1; - public IntDouble data; - public Set dependants; - public Set neededVarInCycleSet; - public boolean needVarFromEarlierCycle; - public boolean noSolver; - - // default is zero - public String timeArraySize; - public ValueEvaluatorParser timeArraySizeParser; - - - public Alias(){ - condition=Param.always; - scope=Param.undefined; - kind=Param.undefined; - units=Param.undefined; - expression=Param.undefined; - fromWresl=Param.undefined; - dependants = new HashSet(); - expressionParser = null; - data = null; - neededVarInCycleSet = new HashSet(); - needVarFromEarlierCycle = false; - noSolver = false; - - timeArraySize = "0"; // default has no future time array - } - - public void setData(IntDouble data){ - this.data=data; - } - - public IntDouble getData(){ - return data; - } -} - +package wrimsv2.commondata.wresldata; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.ValueEvaluatorParser; + + +public class Alias implements Serializable { + + private static final long serialVersionUID = 1L; + public String condition; + public String scope; + public String kind; + public String units; + public String expression; + public ValueEvaluatorParser expressionParser; + public String fromWresl; + public int line=1; + public IntDouble data; + public Set dependants; + public Set neededVarInCycleSet; + public boolean needVarFromEarlierCycle; + public boolean noSolver; + + // default is zero + public String timeArraySize; + public ValueEvaluatorParser timeArraySizeParser; + + + public Alias(){ + condition=Param.always; + scope=Param.undefined; + kind=Param.undefined; + units=Param.undefined; + expression=Param.undefined; + fromWresl=Param.undefined; + dependants = new HashSet(); + expressionParser = null; + data = null; + neededVarInCycleSet = new HashSet(); + needVarFromEarlierCycle = false; + noSolver = false; + + timeArraySize = "0"; // default has no future time array + } + + public void setData(IntDouble data){ + this.data=data; + } + + public IntDouble getData(){ + return data; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Dvar.java b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Dvar.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Dvar.java rename to wrims-core/src/main/java/wrimsv2/commondata/wresldata/Dvar.java index b36be0d73..de7a4f8fd 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Dvar.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Dvar.java @@ -1,68 +1,68 @@ -package wrimsv2.commondata.wresldata; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.ValueEvaluatorParser; - - -public class Dvar implements Serializable { - - private static final long serialVersionUID = 1L; - - public String fromWresl; - public int line=1; - public String scope; - public String integer; - public String format; - public String kind; - public String units; - public String lowerBound; - public ValueEvaluatorParser lowerBoundParser; - public String upperBound; - public ValueEvaluatorParser upperBoundParser; - public String condition; - public Number upperBoundValue; - public Number lowerBoundValue; - public String expression; - public Set dependants; - public IntDouble data; - - // default is zero - public String timeArraySize; - public ValueEvaluatorParser timeArraySizeParser; - - - public Dvar(){ - scope=Param.undefined; - integer=Param.no; - format=Param.undefined; - kind=Param.undefined; - units=Param.undefined; - lowerBound=Param.undefined; - upperBound=Param.undefined; - condition = Param.always; - fromWresl=Param.undefined; - expression=Param.undefined; - dependants = new HashSet(); - - lowerBoundParser = null; - upperBoundParser = null; - data = null; - upperBoundValue = null; - lowerBoundValue = null; - - timeArraySize = "0"; // default has no future time array - } - - public void setData(IntDouble data){ - this.data=data; - } - - public IntDouble getData(){ - return data; - } -} - +package wrimsv2.commondata.wresldata; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.ValueEvaluatorParser; + + +public class Dvar implements Serializable { + + private static final long serialVersionUID = 1L; + + public String fromWresl; + public int line=1; + public String scope; + public String integer; + public String format; + public String kind; + public String units; + public String lowerBound; + public ValueEvaluatorParser lowerBoundParser; + public String upperBound; + public ValueEvaluatorParser upperBoundParser; + public String condition; + public Number upperBoundValue; + public Number lowerBoundValue; + public String expression; + public Set dependants; + public IntDouble data; + + // default is zero + public String timeArraySize; + public ValueEvaluatorParser timeArraySizeParser; + + + public Dvar(){ + scope=Param.undefined; + integer=Param.no; + format=Param.undefined; + kind=Param.undefined; + units=Param.undefined; + lowerBound=Param.undefined; + upperBound=Param.undefined; + condition = Param.always; + fromWresl=Param.undefined; + expression=Param.undefined; + dependants = new HashSet(); + + lowerBoundParser = null; + upperBoundParser = null; + data = null; + upperBoundValue = null; + lowerBoundValue = null; + + timeArraySize = "0"; // default has no future time array + } + + public void setData(IntDouble data){ + this.data=data; + } + + public IntDouble getData(){ + return data; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/External.java b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/External.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/External.java rename to wrims-core/src/main/java/wrimsv2/commondata/wresldata/External.java index 35d32b4fd..e8a0bbf98 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/External.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/External.java @@ -1,21 +1,21 @@ -package wrimsv2.commondata.wresldata; - -import java.io.Serializable; - - -public class External implements Serializable { - - private static final long serialVersionUID = 1L; - public String scope; - public String type; - public String fromWresl; - public int line=1; - - public External(){ - scope=Param.undefined; - type=Param.undefined; - fromWresl=Param.undefined; - - } -} - +package wrimsv2.commondata.wresldata; + +import java.io.Serializable; + + +public class External implements Serializable { + + private static final long serialVersionUID = 1L; + public String scope; + public String type; + public String fromWresl; + public int line=1; + + public External(){ + scope=Param.undefined; + type=Param.undefined; + fromWresl=Param.undefined; + + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Goal.java b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Goal.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Goal.java rename to wrims-core/src/main/java/wrimsv2/commondata/wresldata/Goal.java index bbf07b8a1..9080c7e49 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Goal.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Goal.java @@ -1,58 +1,58 @@ -package wrimsv2.commondata.wresldata; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.evaluator.EvaluatorParser; -import wrimsv2.evaluator.ValueEvaluatorParser; - - -public class Goal implements Serializable { - - private static final long serialVersionUID = 1L; - public String scope; - public String lhs; - public ArrayList caseName; - - // ArrayList< Map< dvarName, Weight > > - public ArrayList> dvarWeightMapList; - public ArrayList> dvarSlackSurplusList; - public ArrayList dvarName; // from slack or surplus - public ArrayList dvarWeight; // for the slack or surplus. Negative penalty leads to positive weight - public ArrayList caseCondition; - public ArrayList caseConditionParsers; - public ArrayList caseExpression; - public Set expressionDependants; - public ArrayList caseExpressionParsers; - public String fromWresl; - public int line=1; - public Set neededVarInCycleSet; - public boolean needVarFromEarlierCycle; - - // default is zero - public String timeArraySize; - public ValueEvaluatorParser timeArraySizeParser; - - - public Goal(){ - scope=Param.undefined; - lhs=Param.undefined; - caseName = new ArrayList(); - dvarWeightMapList = new ArrayList>(); // ArrayList< Map< dvarName, Weight > > - dvarSlackSurplusList = new ArrayList>(); // ArrayList< ArrayList< dvarName > > - dvarName = new ArrayList(); - dvarWeight = new ArrayList(); - caseCondition = new ArrayList(); - caseExpression = new ArrayList(); - expressionDependants = new HashSet(); - fromWresl = Param.undefined; - neededVarInCycleSet = new HashSet(); - needVarFromEarlierCycle = false; - - timeArraySize = "0"; // default has no future time array - } -} - +package wrimsv2.commondata.wresldata; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.evaluator.EvaluatorParser; +import wrimsv2.evaluator.ValueEvaluatorParser; + + +public class Goal implements Serializable { + + private static final long serialVersionUID = 1L; + public String scope; + public String lhs; + public ArrayList caseName; + + // ArrayList< Map< dvarName, Weight > > + public ArrayList> dvarWeightMapList; + public ArrayList> dvarSlackSurplusList; + public ArrayList dvarName; // from slack or surplus + public ArrayList dvarWeight; // for the slack or surplus. Negative penalty leads to positive weight + public ArrayList caseCondition; + public ArrayList caseConditionParsers; + public ArrayList caseExpression; + public Set expressionDependants; + public ArrayList caseExpressionParsers; + public String fromWresl; + public int line=1; + public Set neededVarInCycleSet; + public boolean needVarFromEarlierCycle; + + // default is zero + public String timeArraySize; + public ValueEvaluatorParser timeArraySizeParser; + + + public Goal(){ + scope=Param.undefined; + lhs=Param.undefined; + caseName = new ArrayList(); + dvarWeightMapList = new ArrayList>(); // ArrayList< Map< dvarName, Weight > > + dvarSlackSurplusList = new ArrayList>(); // ArrayList< ArrayList< dvarName > > + dvarName = new ArrayList(); + dvarWeight = new ArrayList(); + caseCondition = new ArrayList(); + caseExpression = new ArrayList(); + expressionDependants = new HashSet(); + fromWresl = Param.undefined; + neededVarInCycleSet = new HashSet(); + needVarFromEarlierCycle = false; + + timeArraySize = "0"; // default has no future time array + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/ModelDataSet.java b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/ModelDataSet.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/ModelDataSet.java rename to wrims-core/src/main/java/wrimsv2/commondata/wresldata/ModelDataSet.java index 135b88846..4ef69041d 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/ModelDataSet.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/ModelDataSet.java @@ -1,662 +1,654 @@ -package wrimsv2.commondata.wresldata; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ForkJoinPool; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.components.ControlData; -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.DataTimeSeries; -import wrimsv2.evaluator.DssDataSetFixLength; -import wrimsv2.evaluator.DssOperation; -import wrimsv2.evaluator.EvalConstraint; -import wrimsv2.evaluator.Evaluation; -import wrimsv2.evaluator.EvaluatorParser; -import wrimsv2.evaluator.TimeOperation; -import wrimsv2.evaluator.ValueEvaluatorLexer; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.evaluator.WeightEval; -import wrimsv2.parallel.ParallelVars; -import wrimsv2.parallel.ProcessConstraint; -import wrimsv2.parallel.ProcessDvar; -import wrimsv2.parallel.ProcessTimeseries; -import wrimsv2.parallel.ProcessWeight; -import wrimsv2.parallel.ProcessWeightSurplusSlack; -import wrimsv2.tools.General; - -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; - -import wrimsv2.components.Error; - - -public class ModelDataSet implements Serializable { - - private static final long serialVersionUID = 1L; - // / weight table // > - public ArrayList wtList = new ArrayList(); - public ArrayList wtTimeArrayList = new ArrayList(); - public ArrayList wtSlackSurplusList = new ArrayList(); - public CopyOnWriteArrayList usedWtSlackSurplusList = new CopyOnWriteArrayList(); - public CopyOnWriteArrayList usedWtSlackSurplusDvList = new CopyOnWriteArrayList(); - -// public ArrayList wtList_global = new ArrayList(); -// public ArrayList wtList_local = new ArrayList(); - public Map wtMap = new HashMap(); - public Map wtSlackSurplusMap = new HashMap(); - - // / external function structure - public ArrayList exList = new ArrayList(); - public ArrayList exList_global = new ArrayList(); - public ArrayList exList_local = new ArrayList(); - public Map exMap = new HashMap(); - - -// // / sv, ts, and dv list -// public ArrayList svTsDvList = new ArrayList(); -// -// // / sv and ts list -// public ArrayList svTsList = new ArrayList(); - - // / svar timeseries data structure - public ArrayList tsList = new ArrayList(); - public ArrayList tsList_global = new ArrayList(); - public ArrayList tsList_local = new ArrayList(); - public Map tsMap = new HashMap(); - - // / svar data structure - public Set svSet_unknown = new HashSet(); - public ArrayList svList = new ArrayList(); - public ArrayList svList_global = new ArrayList(); - public ArrayList svList_local = new ArrayList(); - public Map svMap = new HashMap(); - public Map svFutMap = new HashMap(); - - // / dvar data structure - public ArrayList dvList = new ArrayList(); - public ArrayList dvList_deviationSlackSurplus = new ArrayList(); - public Map deviationSlackSurplus_toleranceMap = new HashMap(); - public ArrayList dvTimeArrayList = new ArrayList(); - public ArrayList timeArrayDvList = new ArrayList(); - public ArrayList dvSlackSurplusList = new ArrayList(); - public ArrayList dvList_global = new ArrayList(); - public ArrayList dvList_local = new ArrayList(); - public Map dvMap = new HashMap(); - public Map dvSlackSurplusMap = new HashMap(); - - // / alias data structure - public Set asSet_unknown = new HashSet(); - public ArrayList asList = new ArrayList(); - public ArrayList asList_global = new ArrayList(); - public ArrayList asList_local = new ArrayList(); - public Map asMap = new HashMap(); - public Map asFutMap = new HashMap(); - - // / goal data structure - public ArrayList gList = new ArrayList(); - public ArrayList gTimeArrayList = new ArrayList(); - public ArrayList gList_global = new ArrayList(); - public ArrayList gList_local = new ArrayList(); - public Map gMap = new HashMap(); - - public ArrayList incFileList=new ArrayList(); - public ArrayList incFileList_global=new ArrayList(); - public ArrayList incFileList_local=new ArrayList(); - - public Set varUsedByLaterCycle = new HashSet(); - - public Set dvarUsedByLaterCycle = new HashSet(); - public Set dvarTimeArrayUsedByLaterCycle = new HashSet(); - public Set svarUsedByLaterCycle = new HashSet(); - public Set aliasUsedByLaterCycle = new HashSet(); - - public void processModel(){ - resetSlackSurplusWeight(); // this clears slack and surplus vars - long t1 = Calendar.getInstance().getTimeInMillis(); - processTimeseries(); - if (ControlData.showRunTimeMessage) System.out.println("Process Timeseries Done."); - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_ts=ControlData.t_ts+(int) (t2-t1); - processSvar(); - if (ControlData.showRunTimeMessage) System.out.println("Process Svar Done."); - long t3 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_svar=ControlData.t_svar+(int) (t3-t2); - processDvar(); - if (ControlData.showRunTimeMessage) System.out.println("Process Dvar Done."); - long t4 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_dvar=ControlData.t_dvar+(int) (t4-t3); - processGoal(); - if (ControlData.showRunTimeMessage) System.out.println("Process Goal Done."); - long t5 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_goal=ControlData.t_goal+(int) (t5-t4); - processWeight(); - if (ControlData.showRunTimeMessage) System.out.println("Process Weight Done."); - long t6 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_wt=ControlData.t_wt+(int) (t6-t5); - processWeightSlackSurplus(); - if (ControlData.showRunTimeMessage) System.out.println("Process Weight Slack Surplus Done."); - long t7 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_wtss=ControlData.t_wtss+(int) (t7-t6); - } - - public void resetSlackSurplusWeight(){ - usedWtSlackSurplusList = new CopyOnWriteArrayList(); - } - - public void processWeight(){ - ModelDataSet mds=ControlData.currModelDataSet; - ArrayList wtList = mds.wtList; - Map wtMap =mds.wtMap; - SolverData.clearWeightMap(); - ConcurrentHashMap solverWtMap=SolverData.getWeightMap(); - ControlData.currEvalTypeIndex=7; - wtTimeArrayList = new ArrayList(); - ProcessWeight pw = new ProcessWeight(wtList, wtMap, solverWtMap, wtTimeArrayList, 0, wtList.size()-1); - ForkJoinPool pool = new ForkJoinPool(); - pool.invoke(pw); - } - - public void processWeightSlackSurplus(){ - ModelDataSet mds=ControlData.currModelDataSet; - CopyOnWriteArrayList usedWtSlackSurplusList = mds.usedWtSlackSurplusList; - Map wtSlackSurplusMap =mds.wtSlackSurplusMap; - SolverData.clearWeightSlackSurplusMap(); - ConcurrentHashMap solverWeightSlackSurplusMap=SolverData.getWeightSlackSurplusMap(); - ControlData.currEvalTypeIndex=7; - ProcessWeightSurplusSlack pwss = new ProcessWeightSurplusSlack(usedWtSlackSurplusDvList, wtSlackSurplusMap, solverWeightSlackSurplusMap, 0, usedWtSlackSurplusDvList.size()-1); - ForkJoinPool pool = new ForkJoinPool(); - pool.invoke(pwss); - } - - public void processSvar(){ - StudyDataSet sds = ControlData.currStudyDataSet; - ModelDataSet mds=ControlData.currModelDataSet; - ArrayList svList = mds.svList; - Map svMap =mds.svMap; - ControlData.currEvalTypeIndex=0; - Map> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); - Map> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); - Set svarUsedByLaterCycle = mds.svarUsedByLaterCycle; - ArrayList varCycleIndexList = sds.getVarCycleIndexList(); - Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); - String model=ControlData.currCycleName; - for (String svName: svList){ - ControlData.currEvalName=svName; - if (ControlData.showRunTimeMessage) System.out.println("Processing svar "+svName); - Svar svar=svMap.get(svName); - ArrayList caseConditions=svar.caseConditionParsers; - ParallelVars prvs = new ParallelVars(); - prvs.timeArrayIndex=0; - boolean condition=false; - int i=-1; - while(!condition && i<=caseConditions.size()-2){ - i=i+1; - ValueEvaluatorParser caseCondition=caseConditions.get(i); - caseCondition.setParallelVars(prvs); - try{ - caseCondition.evaluator(); - condition=caseCondition.evalCondition; - }catch (Exception e){ - Error.addEvaluationError("Case condition evaluation has error."); - condition=false; - } - caseCondition.reset(); - } - if (condition){ - ArrayList caseExpressions=svar.caseExpressionParsers; - ValueEvaluatorParser caseExpression=caseExpressions.get(i); - caseExpression.setParallelVars(prvs); - try { - caseExpression.evaluator(); - IntDouble evalValue=caseExpression.evalValue.copyOf(); - svar.setData(evalValue); - if (svarUsedByLaterCycle.contains(svName)){ - varCycleValueMap.get(svName).put(model, evalValue); - } - if (varCycleIndexList.contains(svName)){ - if (varCycleIndexValueMap.containsKey(svName)){ - varCycleIndexValueMap.get(svName).put(model, evalValue); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, evalValue); - varCycleIndexValueMap.put(svName, cycleValue); - } - } - } catch (RecognitionException e) { - Error.addEvaluationError("Case expression evaluation has error."); - IntDouble evalValue=new IntDouble(1.0, false); - svar.setData(evalValue); - if (svarUsedByLaterCycle.contains(svName)){ - varCycleValueMap.get(svName).put(model, evalValue); - } - if (varCycleIndexList.contains(svName)){ - if (varCycleIndexValueMap.containsKey(svName)){ - varCycleIndexValueMap.get(svName).put(model, evalValue); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, evalValue); - varCycleIndexValueMap.put(svName, cycleValue); - } - } - } - caseExpression.reset(); - }else{ - Error.addEvaluationError("None of the case conditions is satisfied."); - svar.setData(new IntDouble(1.0, false)); - } - - int timeArraySize=new TimeArray().getTimeArraySize(svar.timeArraySizeParser); - for (prvs.timeArrayIndex=1; prvs.timeArrayIndex<=timeArraySize; prvs.timeArrayIndex++){ - condition=false; - i=-1; - while(!condition && i<=caseConditions.size()-2){ - i=i+1; - ValueEvaluatorParser caseCondition=caseConditions.get(i); - caseCondition.setParallelVars(prvs); - try{ - caseCondition.evaluator(); - condition=caseCondition.evalCondition; - }catch (Exception e){ - Error.addEvaluationError("Case condition evaluation has error."); - condition=false; - } - caseCondition.reset(); - } - if (condition){ - ArrayList caseExpressions=svar.caseExpressionParsers; - ValueEvaluatorParser caseExpression=caseExpressions.get(i); - caseExpression.setParallelVars(prvs); - try { - caseExpression.evaluator(); - IntDouble evalValue=caseExpression.evalValue.copyOf(); - Svar newSvar=new Svar(); - String newSvName=svName+"__fut__"+prvs.timeArrayIndex; - newSvar.setData(evalValue); - svFutMap.put(newSvName, newSvar); - if (svarUsedByLaterCycle.contains(svName)){ - if (varTimeArrayCycleValueMap.containsKey(newSvName)){ - varTimeArrayCycleValueMap.get(newSvName).put(model, evalValue); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, evalValue); - varTimeArrayCycleValueMap.put(newSvName, cycleValue); - } - } - if (varCycleIndexList.contains(svName)){ - if (varCycleIndexValueMap.containsKey(newSvName)){ - varCycleIndexValueMap.get(newSvName).put(model, evalValue); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, evalValue); - varCycleIndexValueMap.put(newSvName, cycleValue); - } - } - } catch (RecognitionException e) { - Error.addEvaluationError("Case expression evaluation has error."); - IntDouble evalValue=new IntDouble(1.0, false); - Svar newSvar=new Svar(); - String newSvName=svName+"__fut__"+prvs.timeArrayIndex; - newSvar.setData(evalValue); - svFutMap.put(newSvName, newSvar); - if (svarUsedByLaterCycle.contains(svName)){ - if (varTimeArrayCycleValueMap.containsKey(newSvName)){ - varTimeArrayCycleValueMap.get(newSvName).put(model, evalValue); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, evalValue); - varTimeArrayCycleValueMap.put(newSvName, cycleValue); - } - } - if (varCycleIndexList.contains(svName)){ - if (varCycleIndexValueMap.containsKey(newSvName)){ - varCycleIndexValueMap.get(newSvName).put(model, evalValue); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, evalValue); - varCycleIndexValueMap.put(newSvName, cycleValue); - } - } - } - caseExpression.reset(); - }else{ - Error.addEvaluationError("None of the case conditions is satisfied."); - IntDouble evalValue=new IntDouble(1.0, false); - Svar newSvar=new Svar(); - String newSvName=svName+"__fut__"+prvs.timeArrayIndex; - newSvar.setData(evalValue); - svFutMap.put(newSvName, newSvar); - } - } - } - } - - public void processTimeseries(){ - ModelDataSet mds=ControlData.currModelDataSet; - ArrayList tsList = mds.tsList; - Map tsMap =mds.tsMap; - ControlData.currEvalTypeIndex=5; - ProcessTimeseries pt = new ProcessTimeseries(tsList, tsMap, 0, tsList.size()-1); - ForkJoinPool pool = new ForkJoinPool(); - pool.invoke(pt); - } - - public void processDvar(){ - ModelDataSet mds=ControlData.currModelDataSet; - ArrayList dvList = mds.dvList; - Map dvMap =mds.dvMap; - SolverData.clearDvarMap(); - ConcurrentHashMap solverDvarMap=SolverData.getDvarMap(); - ControlData.currDvMap=dvMap; - ControlData.currEvalTypeIndex=1; - dvTimeArrayList = new ArrayList(); - timeArrayDvList = new ArrayList(); - dvarTimeArrayUsedByLaterCycle = new HashSet(); - StudyDataSet sds = ControlData.currStudyDataSet; - ArrayList varCycleIndexList = sds.getVarCycleIndexList(); - ArrayList dvarTimeArrayCycleIndexList = sds.getDvarTimeArrayCycleIndexList(); - ProcessDvar pd = new ProcessDvar(dvList, dvMap, solverDvarMap, timeArrayDvList, dvTimeArrayList, dvarUsedByLaterCycle, dvarTimeArrayUsedByLaterCycle, varCycleIndexList, dvarTimeArrayCycleIndexList, 0, dvList.size()-1); - ForkJoinPool pool = new ForkJoinPool(); - pool.invoke(pd); - } - - public void processGoal(){ - ModelDataSet mds=ControlData.currModelDataSet; - ArrayList gList = mds.gList; - Map gMap =mds.gMap; - ControlData.currEvalTypeIndex=3; - SolverData.clearConstraintDataMap(); - ConcurrentHashMap solverGMap=SolverData.getConstraintDataMap(); - gTimeArrayList = new ArrayList(); - ProcessConstraint pc = new ProcessConstraint(gList, gMap, solverGMap, gTimeArrayList, usedWtSlackSurplusList, usedWtSlackSurplusDvList, 0, gList.size()-1); - ForkJoinPool pool = new ForkJoinPool(); - pool.invoke(pc); - } - - public void processAlias(){ - long t1 = Calendar.getInstance().getTimeInMillis(); - StudyDataSet sds = ControlData.currStudyDataSet; - ModelDataSet mds=ControlData.currModelDataSet; - ArrayList asList = mds.asList; - Map asMap =mds.asMap; - ControlData.currEvalTypeIndex=2; - Map> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); - Map> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); - Set aliasUsedByLaterCycle = mds.aliasUsedByLaterCycle; - ArrayList varCycleIndexList = sds.getVarCycleIndexList(); - Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); - String model=ControlData.currCycleName; - for (String asName: asList){ - ControlData.currEvalName=asName; - if (ControlData.showRunTimeMessage) System.out.println("Processing alias "+asName); - Alias alias=asMap.get(asName); - - ValueEvaluatorParser evaluator = alias.expressionParser; - ParallelVars prvs = new ParallelVars(); - evaluator.setParallelVars(prvs); - prvs.timeArrayIndex=0; - try { - evaluator.evaluator(); - IntDouble id=evaluator.evalValue; - alias.data=id.copyOf(); - if (aliasUsedByLaterCycle.contains(asName)){ - varCycleValueMap.get(asName).put(model, alias.data); - } - if (varCycleIndexList.contains(asName)){ - if (varCycleIndexValueMap.containsKey(asName)){ - varCycleIndexValueMap.get(asName).put(model, alias.data); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, alias.data); - varCycleIndexValueMap.put(asName, cycleValue); - } - } - String entryNameTS=DssOperation.entryNameTS(asName, ControlData.timeStep); - if (!DataTimeSeries.dvAliasTS.containsKey(entryNameTS)){ - DssDataSetFixLength dds=new DssDataSetFixLength(); - double[] data=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; - dds.setData(data); - dds.setTimeStep(ControlData.partE); - dds.setStartTime(ControlData.memStartDate); - dds.setUnits(alias.units); - dds.setKind(alias.kind); - DataTimeSeries.dvAliasTS.put(entryNameTS,dds); - } - DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); - double[] dataList=ddsfl.getData(); - //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=id.getData().doubleValue(); - //Date memStartDate = new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int index=TimeOperation.getNumberOfTimestep(ControlData.memStartDate, currDate, ddsfl.getTimeStep())-1; - dataList[index]=id.getData().doubleValue(); - - //if (ControlData.outputCycleToDss){ - HashMap dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(ControlData.currCycleIndex); - if (!dvAliasTSCycle.containsKey(entryNameTS)){ - DssDataSetFixLength dds1=new DssDataSetFixLength(); - double[] data1=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; - dds1.setData(data1); - dds1.setTimeStep(ControlData.partE); - dds1.setStartTime(ControlData.memStartDate); - dds1.setUnits(alias.units); - dds1.setKind(alias.kind); - dvAliasTSCycle.put(entryNameTS,dds1); - } - double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); - //dataList1[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=id.getData().doubleValue(); - dataList1[index]=id.getData().doubleValue(); - //} - } catch (RecognitionException e) { - Error.addEvaluationError("Alias evaluation has error."); - IntDouble id=new IntDouble(-901.0,false); - alias.data=id; - if (aliasUsedByLaterCycle.contains(asName)){ - varCycleValueMap.get(asName).put(model, id); - } - if (varCycleIndexList.contains(asName)){ - if (varCycleIndexValueMap.containsKey(asName)){ - varCycleIndexValueMap.get(asName).put(model, alias.data); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, alias.data); - varCycleIndexValueMap.put(asName, cycleValue); - } - } - String entryNameTS=DssOperation.entryNameTS(asName, ControlData.timeStep); - DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); - double[] dataList=ddsfl.getData(); - //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=-901.0; - //Date memStartDate = new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int index=TimeOperation.getNumberOfTimestep(ControlData.memStartDate, currDate, ddsfl.getTimeStep())-1; - dataList[index]=-901.0; - - //if (ControlData.outputCycleToDss){ - HashMap dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(ControlData.currCycleIndex); - double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); - //dataList1[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=-901.0; - dataList1[index]=-901.0; - //} - } - evaluator.reset(); - - if (!alias.timeArraySize.equals("0")){ - String newAsName=asName+"__fut__0"; - String entryNameTS=DssOperation.entryNameTS(newAsName, ControlData.timeStep); - if (!DataTimeSeries.dvAliasTS.containsKey(entryNameTS)){ - DssDataSetFixLength dds=new DssDataSetFixLength(); - double[] data=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; - dds.setData(data); - dds.setTimeStep(ControlData.partE); - dds.setStartTime(ControlData.memStartDate); - dds.setUnits(alias.units); - dds.setKind(alias.kind); - DataTimeSeries.dvAliasTS.put(entryNameTS,dds); - } - DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); - double[] dataList=ddsfl.getData(); - //Date memStartDate = new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int index=TimeOperation.getNumberOfTimestep(ControlData.memStartDate, currDate, ddsfl.getTimeStep())-1; - //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=alias.data.getData().doubleValue(); - dataList[index]=alias.data.getData().doubleValue(); - - //if (ControlData.outputCycleToDss){ - HashMap dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(ControlData.currCycleIndex); - if (!dvAliasTSCycle.containsKey(entryNameTS)){ - DssDataSetFixLength dds1=new DssDataSetFixLength(); - double[] data1=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; - dds1.setData(data1); - dds1.setTimeStep(ControlData.partE); - dds1.setStartTime(ControlData.memStartDate); - dds1.setUnits(alias.units); - dds1.setKind(alias.kind); - dvAliasTSCycle.put(entryNameTS,dds1); - } - double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); - //dataList1[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=alias.data.getData().doubleValue(); - dataList1[index]=alias.data.getData().doubleValue(); - //} - } - - int timeArraySize=new TimeArray().getTimeArraySize(alias.timeArraySizeParser); - for (prvs.timeArrayIndex=1; prvs.timeArrayIndex<=timeArraySize; prvs.timeArrayIndex++){ - String newAsName=asName+"__fut__"+prvs.timeArrayIndex; - try { - evaluator.evaluator(); - IntDouble id=evaluator.evalValue; - Alias newAlias=new Alias(); - newAlias.data=id.copyOf(); - asFutMap.put(newAsName, newAlias); - if (aliasUsedByLaterCycle.contains(asName)){ - if (varTimeArrayCycleValueMap.containsKey(newAsName)){ - varTimeArrayCycleValueMap.get(newAsName).put(model, newAlias.data); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, newAlias.data); - varTimeArrayCycleValueMap.put(newAsName, cycleValue); - } - } - if (varCycleIndexList.contains(asName)){ - if (varCycleIndexValueMap.containsKey(newAsName)){ - varCycleIndexValueMap.get(newAsName).put(model, newAlias.data); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, newAlias.data); - varCycleIndexValueMap.put(newAsName, cycleValue); - } - } - String entryNameTS=DssOperation.entryNameTS(newAsName, ControlData.timeStep); - if (!DataTimeSeries.dvAliasTS.containsKey(entryNameTS)){ - DssDataSetFixLength dds=new DssDataSetFixLength(); - double[] data=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; - dds.setData(data); - dds.setTimeStep(ControlData.partE); - dds.setStartTime(ControlData.memStartDate); - dds.setUnits(alias.units); - dds.setKind(alias.kind); - DataTimeSeries.dvAliasTS.put(entryNameTS,dds); - } - DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); - double[] dataList=ddsfl.getData(); - //Date memStartDate = new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int indext=TimeOperation.getNumberOfTimestep(ControlData.memStartDate, currDate, ddsfl.getTimeStep())-1; - //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=id.getData().doubleValue(); - dataList[indext]=id.getData().doubleValue(); - - //if (ControlData.outputCycleToDss){ - HashMap dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(ControlData.currCycleIndex); - if (!dvAliasTSCycle.containsKey(entryNameTS)){ - DssDataSetFixLength dds1=new DssDataSetFixLength(); - double[] data1=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; - dds1.setData(data1); - dds1.setTimeStep(ControlData.partE); - dds1.setStartTime(ControlData.memStartDate); - dds1.setUnits(alias.units); - dds1.setKind(alias.kind); - dvAliasTSCycle.put(entryNameTS,dds1); - } - double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); - //dataList1[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=id.getData().doubleValue(); - dataList1[indext]=id.getData().doubleValue(); - //} - - String asEntryNameTS=DssOperation.entryNameTS(asName, ControlData.timeStep); - double[] asDataList=DataTimeSeries.dvAliasTS.get(asEntryNameTS).getData(); - //int index=ControlData.currTimeStep.get(ControlData.currCycleIndex)+ParallelVars.timeArrayIndex; - int index=indext+prvs.timeArrayIndex; - if (index cycleValue = new HashMap(); - cycleValue.put(model, id); - varTimeArrayCycleValueMap.put(newAsName, cycleValue); - } - } - if (varCycleIndexList.contains(asName)){ - if (varCycleIndexValueMap.containsKey(newAsName)){ - varCycleIndexValueMap.get(newAsName).put(model, id); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, id); - varCycleIndexValueMap.put(newAsName, cycleValue); - } - } - String entryNameTS=DssOperation.entryNameTS(newAsName, ControlData.timeStep); - DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); - double[] dataList=ddsfl.getData(); - //Date memStartDate = new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int indext=TimeOperation.getNumberOfTimestep(ControlData.memStartDate, currDate, ddsfl.getTimeStep())-1; - //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=-901.0; - dataList[indext]=-901.0; - - //if (ControlData.outputCycleToDss){ - HashMap dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(ControlData.currCycleIndex); - double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); - //dataList1[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=-901.0; - dataList1[indext]=-901.0; - //} - } - evaluator.reset(); - } - } - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_as=ControlData.t_as+(int) (t2-t1); - } - - public void clearFutureSvMap(){ - svFutMap = new HashMap(); - } - - public void clearFutureAsMap(){ - asFutMap = new HashMap(); - } -} - +package wrimsv2.commondata.wresldata; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ForkJoinPool; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.components.ControlData; +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.DataTimeSeries; +import wrimsv2.evaluator.DssDataSetFixLength; +import wrimsv2.evaluator.DssOperation; +import wrimsv2.evaluator.EvalConstraint; +import wrimsv2.evaluator.TimeOperation; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.parallel.ParallelVars; +import wrimsv2.parallel.ProcessConstraint; +import wrimsv2.parallel.ProcessDvar; +import wrimsv2.parallel.ProcessTimeseries; +import wrimsv2.parallel.ProcessWeight; +import wrimsv2.parallel.ProcessWeightSurplusSlack; + +import org.antlr.runtime.RecognitionException; + +import wrimsv2.components.Error; + + +public class ModelDataSet implements Serializable { + + private static final long serialVersionUID = 1L; + // / weight table // > + public ArrayList wtList = new ArrayList(); + public ArrayList wtTimeArrayList = new ArrayList(); + public ArrayList wtSlackSurplusList = new ArrayList(); + public CopyOnWriteArrayList usedWtSlackSurplusList = new CopyOnWriteArrayList(); + public CopyOnWriteArrayList usedWtSlackSurplusDvList = new CopyOnWriteArrayList(); + +// public ArrayList wtList_global = new ArrayList(); +// public ArrayList wtList_local = new ArrayList(); + public Map wtMap = new HashMap(); + public Map wtSlackSurplusMap = new HashMap(); + + // / external function structure + public ArrayList exList = new ArrayList(); + public ArrayList exList_global = new ArrayList(); + public ArrayList exList_local = new ArrayList(); + public Map exMap = new HashMap(); + + +// // / sv, ts, and dv list +// public ArrayList svTsDvList = new ArrayList(); +// +// // / sv and ts list +// public ArrayList svTsList = new ArrayList(); + + // / svar timeseries data structure + public ArrayList tsList = new ArrayList(); + public ArrayList tsList_global = new ArrayList(); + public ArrayList tsList_local = new ArrayList(); + public Map tsMap = new HashMap(); + + // / svar data structure + public Set svSet_unknown = new HashSet(); + public ArrayList svList = new ArrayList(); + public ArrayList svList_global = new ArrayList(); + public ArrayList svList_local = new ArrayList(); + public Map svMap = new HashMap(); + public Map svFutMap = new HashMap(); + + // / dvar data structure + public ArrayList dvList = new ArrayList(); + public ArrayList dvList_deviationSlackSurplus = new ArrayList(); + public Map deviationSlackSurplus_toleranceMap = new HashMap(); + public ArrayList dvTimeArrayList = new ArrayList(); + public ArrayList timeArrayDvList = new ArrayList(); + public ArrayList dvSlackSurplusList = new ArrayList(); + public ArrayList dvList_global = new ArrayList(); + public ArrayList dvList_local = new ArrayList(); + public Map dvMap = new HashMap(); + public Map dvSlackSurplusMap = new HashMap(); + + // / alias data structure + public Set asSet_unknown = new HashSet(); + public ArrayList asList = new ArrayList(); + public ArrayList asList_global = new ArrayList(); + public ArrayList asList_local = new ArrayList(); + public Map asMap = new HashMap(); + public Map asFutMap = new HashMap(); + + // / goal data structure + public ArrayList gList = new ArrayList(); + public ArrayList gTimeArrayList = new ArrayList(); + public ArrayList gList_global = new ArrayList(); + public ArrayList gList_local = new ArrayList(); + public Map gMap = new HashMap(); + + public ArrayList incFileList=new ArrayList(); + public ArrayList incFileList_global=new ArrayList(); + public ArrayList incFileList_local=new ArrayList(); + + public Set varUsedByLaterCycle = new HashSet(); + + public Set dvarUsedByLaterCycle = new HashSet(); + public Set dvarTimeArrayUsedByLaterCycle = new HashSet(); + public Set svarUsedByLaterCycle = new HashSet(); + public Set aliasUsedByLaterCycle = new HashSet(); + + public void processModel(){ + resetSlackSurplusWeight(); // this clears slack and surplus vars + long t1 = Calendar.getInstance().getTimeInMillis(); + processTimeseries(); + if (ControlData.showRunTimeMessage) System.out.println("Process Timeseries Done."); + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_ts=ControlData.t_ts+(int) (t2-t1); + processSvar(); + if (ControlData.showRunTimeMessage) System.out.println("Process Svar Done."); + long t3 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_svar=ControlData.t_svar+(int) (t3-t2); + processDvar(); + if (ControlData.showRunTimeMessage) System.out.println("Process Dvar Done."); + long t4 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_dvar=ControlData.t_dvar+(int) (t4-t3); + processGoal(); + if (ControlData.showRunTimeMessage) System.out.println("Process Goal Done."); + long t5 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_goal=ControlData.t_goal+(int) (t5-t4); + processWeight(); + if (ControlData.showRunTimeMessage) System.out.println("Process Weight Done."); + long t6 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_wt=ControlData.t_wt+(int) (t6-t5); + processWeightSlackSurplus(); + if (ControlData.showRunTimeMessage) System.out.println("Process Weight Slack Surplus Done."); + long t7 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_wtss=ControlData.t_wtss+(int) (t7-t6); + } + + public void resetSlackSurplusWeight(){ + usedWtSlackSurplusList = new CopyOnWriteArrayList(); + } + + public void processWeight(){ + ModelDataSet mds=ControlData.currModelDataSet; + ArrayList wtList = mds.wtList; + Map wtMap =mds.wtMap; + SolverData.clearWeightMap(); + ConcurrentHashMap solverWtMap=SolverData.getWeightMap(); + ControlData.currEvalTypeIndex=7; + wtTimeArrayList = new ArrayList(); + ProcessWeight pw = new ProcessWeight(wtList, wtMap, solverWtMap, wtTimeArrayList, 0, wtList.size()-1); + ForkJoinPool pool = new ForkJoinPool(); + pool.invoke(pw); + } + + public void processWeightSlackSurplus(){ + ModelDataSet mds=ControlData.currModelDataSet; + CopyOnWriteArrayList usedWtSlackSurplusList = mds.usedWtSlackSurplusList; + Map wtSlackSurplusMap =mds.wtSlackSurplusMap; + SolverData.clearWeightSlackSurplusMap(); + ConcurrentHashMap solverWeightSlackSurplusMap=SolverData.getWeightSlackSurplusMap(); + ControlData.currEvalTypeIndex=7; + ProcessWeightSurplusSlack pwss = new ProcessWeightSurplusSlack(usedWtSlackSurplusDvList, wtSlackSurplusMap, solverWeightSlackSurplusMap, 0, usedWtSlackSurplusDvList.size()-1); + ForkJoinPool pool = new ForkJoinPool(); + pool.invoke(pwss); + } + + public void processSvar(){ + StudyDataSet sds = ControlData.currStudyDataSet; + ModelDataSet mds=ControlData.currModelDataSet; + ArrayList svList = mds.svList; + Map svMap =mds.svMap; + ControlData.currEvalTypeIndex=0; + Map> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); + Map> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); + Set svarUsedByLaterCycle = mds.svarUsedByLaterCycle; + ArrayList varCycleIndexList = sds.getVarCycleIndexList(); + Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); + String model=ControlData.currCycleName; + for (String svName: svList){ + ControlData.currEvalName=svName; + if (ControlData.showRunTimeMessage) System.out.println("Processing svar "+svName); + Svar svar=svMap.get(svName); + ArrayList caseConditions=svar.caseConditionParsers; + ParallelVars prvs = new ParallelVars(); + prvs.timeArrayIndex=0; + boolean condition=false; + int i=-1; + while(!condition && i<=caseConditions.size()-2){ + i=i+1; + ValueEvaluatorParser caseCondition=caseConditions.get(i); + caseCondition.setParallelVars(prvs); + try{ + caseCondition.evaluator(); + condition=caseCondition.evalCondition; + }catch (Exception e){ + Error.addEvaluationError("Case condition evaluation has error."); + condition=false; + } + caseCondition.reset(); + } + if (condition){ + ArrayList caseExpressions=svar.caseExpressionParsers; + ValueEvaluatorParser caseExpression=caseExpressions.get(i); + caseExpression.setParallelVars(prvs); + try { + caseExpression.evaluator(); + IntDouble evalValue=caseExpression.evalValue.copyOf(); + svar.setData(evalValue); + if (svarUsedByLaterCycle.contains(svName)){ + varCycleValueMap.get(svName).put(model, evalValue); + } + if (varCycleIndexList.contains(svName)){ + if (varCycleIndexValueMap.containsKey(svName)){ + varCycleIndexValueMap.get(svName).put(model, evalValue); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, evalValue); + varCycleIndexValueMap.put(svName, cycleValue); + } + } + } catch (RecognitionException e) { + Error.addEvaluationError("Case expression evaluation has error."); + IntDouble evalValue=new IntDouble(1.0, false); + svar.setData(evalValue); + if (svarUsedByLaterCycle.contains(svName)){ + varCycleValueMap.get(svName).put(model, evalValue); + } + if (varCycleIndexList.contains(svName)){ + if (varCycleIndexValueMap.containsKey(svName)){ + varCycleIndexValueMap.get(svName).put(model, evalValue); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, evalValue); + varCycleIndexValueMap.put(svName, cycleValue); + } + } + } + caseExpression.reset(); + }else{ + Error.addEvaluationError("None of the case conditions is satisfied."); + svar.setData(new IntDouble(1.0, false)); + } + + int timeArraySize=new TimeArray().getTimeArraySize(svar.timeArraySizeParser); + for (prvs.timeArrayIndex=1; prvs.timeArrayIndex<=timeArraySize; prvs.timeArrayIndex++){ + condition=false; + i=-1; + while(!condition && i<=caseConditions.size()-2){ + i=i+1; + ValueEvaluatorParser caseCondition=caseConditions.get(i); + caseCondition.setParallelVars(prvs); + try{ + caseCondition.evaluator(); + condition=caseCondition.evalCondition; + }catch (Exception e){ + Error.addEvaluationError("Case condition evaluation has error."); + condition=false; + } + caseCondition.reset(); + } + if (condition){ + ArrayList caseExpressions=svar.caseExpressionParsers; + ValueEvaluatorParser caseExpression=caseExpressions.get(i); + caseExpression.setParallelVars(prvs); + try { + caseExpression.evaluator(); + IntDouble evalValue=caseExpression.evalValue.copyOf(); + Svar newSvar=new Svar(); + String newSvName=svName+"__fut__"+prvs.timeArrayIndex; + newSvar.setData(evalValue); + svFutMap.put(newSvName, newSvar); + if (svarUsedByLaterCycle.contains(svName)){ + if (varTimeArrayCycleValueMap.containsKey(newSvName)){ + varTimeArrayCycleValueMap.get(newSvName).put(model, evalValue); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, evalValue); + varTimeArrayCycleValueMap.put(newSvName, cycleValue); + } + } + if (varCycleIndexList.contains(svName)){ + if (varCycleIndexValueMap.containsKey(newSvName)){ + varCycleIndexValueMap.get(newSvName).put(model, evalValue); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, evalValue); + varCycleIndexValueMap.put(newSvName, cycleValue); + } + } + } catch (RecognitionException e) { + Error.addEvaluationError("Case expression evaluation has error."); + IntDouble evalValue=new IntDouble(1.0, false); + Svar newSvar=new Svar(); + String newSvName=svName+"__fut__"+prvs.timeArrayIndex; + newSvar.setData(evalValue); + svFutMap.put(newSvName, newSvar); + if (svarUsedByLaterCycle.contains(svName)){ + if (varTimeArrayCycleValueMap.containsKey(newSvName)){ + varTimeArrayCycleValueMap.get(newSvName).put(model, evalValue); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, evalValue); + varTimeArrayCycleValueMap.put(newSvName, cycleValue); + } + } + if (varCycleIndexList.contains(svName)){ + if (varCycleIndexValueMap.containsKey(newSvName)){ + varCycleIndexValueMap.get(newSvName).put(model, evalValue); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, evalValue); + varCycleIndexValueMap.put(newSvName, cycleValue); + } + } + } + caseExpression.reset(); + }else{ + Error.addEvaluationError("None of the case conditions is satisfied."); + IntDouble evalValue=new IntDouble(1.0, false); + Svar newSvar=new Svar(); + String newSvName=svName+"__fut__"+prvs.timeArrayIndex; + newSvar.setData(evalValue); + svFutMap.put(newSvName, newSvar); + } + } + } + } + + public void processTimeseries(){ + ModelDataSet mds=ControlData.currModelDataSet; + ArrayList tsList = mds.tsList; + Map tsMap =mds.tsMap; + ControlData.currEvalTypeIndex=5; + ProcessTimeseries pt = new ProcessTimeseries(tsList, tsMap, 0, tsList.size()-1); + ForkJoinPool pool = new ForkJoinPool(); + pool.invoke(pt); + } + + public void processDvar(){ + ModelDataSet mds=ControlData.currModelDataSet; + ArrayList dvList = mds.dvList; + Map dvMap =mds.dvMap; + SolverData.clearDvarMap(); + ConcurrentHashMap solverDvarMap=SolverData.getDvarMap(); + ControlData.currDvMap=dvMap; + ControlData.currEvalTypeIndex=1; + dvTimeArrayList = new ArrayList(); + timeArrayDvList = new ArrayList(); + dvarTimeArrayUsedByLaterCycle = new HashSet(); + StudyDataSet sds = ControlData.currStudyDataSet; + ArrayList varCycleIndexList = sds.getVarCycleIndexList(); + ArrayList dvarTimeArrayCycleIndexList = sds.getDvarTimeArrayCycleIndexList(); + ProcessDvar pd = new ProcessDvar(dvList, dvMap, solverDvarMap, timeArrayDvList, dvTimeArrayList, dvarUsedByLaterCycle, dvarTimeArrayUsedByLaterCycle, varCycleIndexList, dvarTimeArrayCycleIndexList, 0, dvList.size()-1); + ForkJoinPool pool = new ForkJoinPool(); + pool.invoke(pd); + } + + public void processGoal(){ + ModelDataSet mds=ControlData.currModelDataSet; + ArrayList gList = mds.gList; + Map gMap =mds.gMap; + ControlData.currEvalTypeIndex=3; + SolverData.clearConstraintDataMap(); + ConcurrentHashMap solverGMap=SolverData.getConstraintDataMap(); + gTimeArrayList = new ArrayList(); + ProcessConstraint pc = new ProcessConstraint(gList, gMap, solverGMap, gTimeArrayList, usedWtSlackSurplusList, usedWtSlackSurplusDvList, 0, gList.size()-1); + ForkJoinPool pool = new ForkJoinPool(); + pool.invoke(pc); + } + + public void processAlias(){ + long t1 = Calendar.getInstance().getTimeInMillis(); + StudyDataSet sds = ControlData.currStudyDataSet; + ModelDataSet mds=ControlData.currModelDataSet; + ArrayList asList = mds.asList; + Map asMap =mds.asMap; + ControlData.currEvalTypeIndex=2; + Map> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); + Map> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); + Set aliasUsedByLaterCycle = mds.aliasUsedByLaterCycle; + ArrayList varCycleIndexList = sds.getVarCycleIndexList(); + Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); + String model=ControlData.currCycleName; + for (String asName: asList){ + ControlData.currEvalName=asName; + if (ControlData.showRunTimeMessage) System.out.println("Processing alias "+asName); + Alias alias=asMap.get(asName); + + ValueEvaluatorParser evaluator = alias.expressionParser; + ParallelVars prvs = new ParallelVars(); + evaluator.setParallelVars(prvs); + prvs.timeArrayIndex=0; + try { + evaluator.evaluator(); + IntDouble id=evaluator.evalValue; + alias.data=id.copyOf(); + if (aliasUsedByLaterCycle.contains(asName)){ + varCycleValueMap.get(asName).put(model, alias.data); + } + if (varCycleIndexList.contains(asName)){ + if (varCycleIndexValueMap.containsKey(asName)){ + varCycleIndexValueMap.get(asName).put(model, alias.data); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, alias.data); + varCycleIndexValueMap.put(asName, cycleValue); + } + } + String entryNameTS=DssOperation.entryNameTS(asName, ControlData.timeStep); + if (!DataTimeSeries.dvAliasTS.containsKey(entryNameTS)){ + DssDataSetFixLength dds=new DssDataSetFixLength(); + double[] data=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; + dds.setData(data); + dds.setTimeStep(ControlData.partE); + dds.setStartTime(ControlData.memStartDate); + dds.setUnits(alias.units); + dds.setKind(alias.kind); + DataTimeSeries.dvAliasTS.put(entryNameTS,dds); + } + DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); + double[] dataList=ddsfl.getData(); + //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=id.getData().doubleValue(); + //Date memStartDate = new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int index=TimeOperation.getNumberOfTimestep(ControlData.memStartDate, currDate, ddsfl.getTimeStep())-1; + dataList[index]=id.getData().doubleValue(); + + //if (ControlData.outputCycleToDss){ + HashMap dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(ControlData.currCycleIndex); + if (!dvAliasTSCycle.containsKey(entryNameTS)){ + DssDataSetFixLength dds1=new DssDataSetFixLength(); + double[] data1=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; + dds1.setData(data1); + dds1.setTimeStep(ControlData.partE); + dds1.setStartTime(ControlData.memStartDate); + dds1.setUnits(alias.units); + dds1.setKind(alias.kind); + dvAliasTSCycle.put(entryNameTS,dds1); + } + double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); + //dataList1[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=id.getData().doubleValue(); + dataList1[index]=id.getData().doubleValue(); + //} + } catch (RecognitionException e) { + Error.addEvaluationError("Alias evaluation has error."); + IntDouble id=new IntDouble(-901.0,false); + alias.data=id; + if (aliasUsedByLaterCycle.contains(asName)){ + varCycleValueMap.get(asName).put(model, id); + } + if (varCycleIndexList.contains(asName)){ + if (varCycleIndexValueMap.containsKey(asName)){ + varCycleIndexValueMap.get(asName).put(model, alias.data); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, alias.data); + varCycleIndexValueMap.put(asName, cycleValue); + } + } + String entryNameTS=DssOperation.entryNameTS(asName, ControlData.timeStep); + DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); + double[] dataList=ddsfl.getData(); + //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=-901.0; + //Date memStartDate = new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int index=TimeOperation.getNumberOfTimestep(ControlData.memStartDate, currDate, ddsfl.getTimeStep())-1; + dataList[index]=-901.0; + + //if (ControlData.outputCycleToDss){ + HashMap dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(ControlData.currCycleIndex); + double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); + //dataList1[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=-901.0; + dataList1[index]=-901.0; + //} + } + evaluator.reset(); + + if (!alias.timeArraySize.equals("0")){ + String newAsName=asName+"__fut__0"; + String entryNameTS=DssOperation.entryNameTS(newAsName, ControlData.timeStep); + if (!DataTimeSeries.dvAliasTS.containsKey(entryNameTS)){ + DssDataSetFixLength dds=new DssDataSetFixLength(); + double[] data=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; + dds.setData(data); + dds.setTimeStep(ControlData.partE); + dds.setStartTime(ControlData.memStartDate); + dds.setUnits(alias.units); + dds.setKind(alias.kind); + DataTimeSeries.dvAliasTS.put(entryNameTS,dds); + } + DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); + double[] dataList=ddsfl.getData(); + //Date memStartDate = new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int index=TimeOperation.getNumberOfTimestep(ControlData.memStartDate, currDate, ddsfl.getTimeStep())-1; + //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=alias.data.getData().doubleValue(); + dataList[index]=alias.data.getData().doubleValue(); + + //if (ControlData.outputCycleToDss){ + HashMap dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(ControlData.currCycleIndex); + if (!dvAliasTSCycle.containsKey(entryNameTS)){ + DssDataSetFixLength dds1=new DssDataSetFixLength(); + double[] data1=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; + dds1.setData(data1); + dds1.setTimeStep(ControlData.partE); + dds1.setStartTime(ControlData.memStartDate); + dds1.setUnits(alias.units); + dds1.setKind(alias.kind); + dvAliasTSCycle.put(entryNameTS,dds1); + } + double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); + //dataList1[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=alias.data.getData().doubleValue(); + dataList1[index]=alias.data.getData().doubleValue(); + //} + } + + int timeArraySize=new TimeArray().getTimeArraySize(alias.timeArraySizeParser); + for (prvs.timeArrayIndex=1; prvs.timeArrayIndex<=timeArraySize; prvs.timeArrayIndex++){ + String newAsName=asName+"__fut__"+prvs.timeArrayIndex; + try { + evaluator.evaluator(); + IntDouble id=evaluator.evalValue; + Alias newAlias=new Alias(); + newAlias.data=id.copyOf(); + asFutMap.put(newAsName, newAlias); + if (aliasUsedByLaterCycle.contains(asName)){ + if (varTimeArrayCycleValueMap.containsKey(newAsName)){ + varTimeArrayCycleValueMap.get(newAsName).put(model, newAlias.data); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, newAlias.data); + varTimeArrayCycleValueMap.put(newAsName, cycleValue); + } + } + if (varCycleIndexList.contains(asName)){ + if (varCycleIndexValueMap.containsKey(newAsName)){ + varCycleIndexValueMap.get(newAsName).put(model, newAlias.data); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, newAlias.data); + varCycleIndexValueMap.put(newAsName, cycleValue); + } + } + String entryNameTS=DssOperation.entryNameTS(newAsName, ControlData.timeStep); + if (!DataTimeSeries.dvAliasTS.containsKey(entryNameTS)){ + DssDataSetFixLength dds=new DssDataSetFixLength(); + double[] data=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; + dds.setData(data); + dds.setTimeStep(ControlData.partE); + dds.setStartTime(ControlData.memStartDate); + dds.setUnits(alias.units); + dds.setKind(alias.kind); + DataTimeSeries.dvAliasTS.put(entryNameTS,dds); + } + DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); + double[] dataList=ddsfl.getData(); + //Date memStartDate = new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int indext=TimeOperation.getNumberOfTimestep(ControlData.memStartDate, currDate, ddsfl.getTimeStep())-1; + //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=id.getData().doubleValue(); + dataList[indext]=id.getData().doubleValue(); + + //if (ControlData.outputCycleToDss){ + HashMap dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(ControlData.currCycleIndex); + if (!dvAliasTSCycle.containsKey(entryNameTS)){ + DssDataSetFixLength dds1=new DssDataSetFixLength(); + double[] data1=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; + dds1.setData(data1); + dds1.setTimeStep(ControlData.partE); + dds1.setStartTime(ControlData.memStartDate); + dds1.setUnits(alias.units); + dds1.setKind(alias.kind); + dvAliasTSCycle.put(entryNameTS,dds1); + } + double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); + //dataList1[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=id.getData().doubleValue(); + dataList1[indext]=id.getData().doubleValue(); + //} + + String asEntryNameTS=DssOperation.entryNameTS(asName, ControlData.timeStep); + double[] asDataList=DataTimeSeries.dvAliasTS.get(asEntryNameTS).getData(); + //int index=ControlData.currTimeStep.get(ControlData.currCycleIndex)+ParallelVars.timeArrayIndex; + int index=indext+prvs.timeArrayIndex; + if (index cycleValue = new HashMap(); + cycleValue.put(model, id); + varTimeArrayCycleValueMap.put(newAsName, cycleValue); + } + } + if (varCycleIndexList.contains(asName)){ + if (varCycleIndexValueMap.containsKey(newAsName)){ + varCycleIndexValueMap.get(newAsName).put(model, id); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, id); + varCycleIndexValueMap.put(newAsName, cycleValue); + } + } + String entryNameTS=DssOperation.entryNameTS(newAsName, ControlData.timeStep); + DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); + double[] dataList=ddsfl.getData(); + //Date memStartDate = new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int indext=TimeOperation.getNumberOfTimestep(ControlData.memStartDate, currDate, ddsfl.getTimeStep())-1; + //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=-901.0; + dataList[indext]=-901.0; + + //if (ControlData.outputCycleToDss){ + HashMap dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(ControlData.currCycleIndex); + double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); + //dataList1[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=-901.0; + dataList1[indext]=-901.0; + //} + } + evaluator.reset(); + } + } + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_as=ControlData.t_as+(int) (t2-t1); + } + + public void clearFutureSvMap(){ + svFutMap = new HashMap(); + } + + public void clearFutureAsMap(){ + asFutMap = new HashMap(); + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Param.java b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Param.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Param.java rename to wrims-core/src/main/java/wrimsv2/commondata/wresldata/Param.java index 406d97d90..fb0da3e10 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Param.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Param.java @@ -1,88 +1,88 @@ -package wrimsv2.commondata.wresldata; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -// global parameters -public class Param { - - // solver selection - public static final Integer SOLVER_XA = 10; - public static final Integer SOLVER_LPSOLVE = 20; - //public static final Integer SOLVER_CBC = 30; - public static final Integer SOLVER_GUROBI = 40; - public static final Integer SOLVER_CLP0 = 50; - public static final Integer SOLVER_CLP1 = 60; - public static final Integer SOLVER_CLP = 70; - public static final Integer SOLVER_CBC0 = 80; // exe by file - public static final Integer SOLVER_CBC1 = 90; // jni by file - public static final Integer SOLVER_CBC = 100; // jni - public static final Integer cbcMinIntNumber = 2; // minimum integer number for warm start - - public static boolean debug= false; - public static final String dv_std_lowerBound= "0"; - public static final String zero= "0"; - public static final String dv_std_upperBound= "upper_unbounded"; - public static final String lower_unbounded= "lower_unbounded"; - public static final String upper_unbounded= "upper_unbounded"; - public static final double lower_unbounded_double= -1e23; - public static final double upper_unbounded_double= 1e23; - public static final String dv_std_integer_lowerBound= "0"; - public static final String dv_std_integer_upperBound= "1"; - public static final String undefined= "undefined"; - public static final String defaultCaseName = "default"; - public static final String always = "always"; - public static final String constrain = "constrain"; - public static final String skip = "#"; - public static final String no = "n"; - public static final String yes = "y"; - public static final String arg_seperator = ","; - public static final String new_seperator = ";"; - public static final String csv_seperator = ","; - public static final String windows_pathseperator = "\\"; - public static final String linux_pathseperator = "/"; - public static final String wreslChekerName = "Wresl Checker "; - public static final String conditional = "conditional"; - public static final String model_label = "__model__"; - - public static final String legacywresl = "_legacywresl"; - - public static final Integer incFileType = 1; - public static final Integer tsType = 2; - public static final Integer svType = 3; - public static final Integer dvType = 4; - public static final Integer asType = 5; - public static final Integer exType = 6; - public static final Integer gl1Type = 7; - public static final Integer gl2Type = 8; - public static final Integer incModelType = 9; - public static final Integer ifIncItemGroupType = 10; - - public static final Integer dependant_reserved = 1; - public static final Integer dependant_special = 2; - public static final Integer dependant_varFunc = 3; - public static final Integer dependant_preCycleVar = 4; - - public static int printLevel = 1; - - - public static final String global="global"; - public static final String local="local"; - - public static final double deviationSlackSurplusTolerance = 1E-5; - public static final double inf_assumed = 10e30; - public static final double inf = Double.POSITIVE_INFINITY; - - public static Set reservedSet = new HashSet(Arrays.asList - ("month", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", - "prevjan", "prevfeb", "prevmar", "prevapr", "prevmay", "prevjun", - "prevjul", "prevaug", "prevsep", "prevoct", "prevnov", "prevdec", - "wateryear", "cfs_taf", "taf_cfs", "cfs_cfm", "af_cfs", "cfs_af", "daysin", "daysinmonth", - "i", "null", "pow", "exp", "log", "log10", "abs", "real","mod", - "day" - )); - - -} - +package wrimsv2.commondata.wresldata; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +// global parameters +public class Param { + + // solver selection + public static final Integer SOLVER_XA = 10; + public static final Integer SOLVER_LPSOLVE = 20; + //public static final Integer SOLVER_CBC = 30; + public static final Integer SOLVER_GUROBI = 40; + public static final Integer SOLVER_CLP0 = 50; + public static final Integer SOLVER_CLP1 = 60; + public static final Integer SOLVER_CLP = 70; + public static final Integer SOLVER_CBC0 = 80; // exe by file + public static final Integer SOLVER_CBC1 = 90; // jni by file + public static final Integer SOLVER_CBC = 100; // jni + public static final Integer cbcMinIntNumber = 2; // minimum integer number for warm start + + public static boolean debug= false; + public static final String dv_std_lowerBound= "0"; + public static final String zero= "0"; + public static final String dv_std_upperBound= "upper_unbounded"; + public static final String lower_unbounded= "lower_unbounded"; + public static final String upper_unbounded= "upper_unbounded"; + public static final double lower_unbounded_double= -1e23; + public static final double upper_unbounded_double= 1e23; + public static final String dv_std_integer_lowerBound= "0"; + public static final String dv_std_integer_upperBound= "1"; + public static final String undefined= "undefined"; + public static final String defaultCaseName = "default"; + public static final String always = "always"; + public static final String constrain = "constrain"; + public static final String skip = "#"; + public static final String no = "n"; + public static final String yes = "y"; + public static final String arg_seperator = ","; + public static final String new_seperator = ";"; + public static final String csv_seperator = ","; + public static final String windows_pathseperator = "\\"; + public static final String linux_pathseperator = "/"; + public static final String wreslChekerName = "Wresl Checker "; + public static final String conditional = "conditional"; + public static final String model_label = "__model__"; + + public static final String legacywresl = "_legacywresl"; + + public static final Integer incFileType = 1; + public static final Integer tsType = 2; + public static final Integer svType = 3; + public static final Integer dvType = 4; + public static final Integer asType = 5; + public static final Integer exType = 6; + public static final Integer gl1Type = 7; + public static final Integer gl2Type = 8; + public static final Integer incModelType = 9; + public static final Integer ifIncItemGroupType = 10; + + public static final Integer dependant_reserved = 1; + public static final Integer dependant_special = 2; + public static final Integer dependant_varFunc = 3; + public static final Integer dependant_preCycleVar = 4; + + public static int printLevel = 1; + + + public static final String global="global"; + public static final String local="local"; + + public static final double deviationSlackSurplusTolerance = 1E-5; + public static final double inf_assumed = 10e30; + public static final double inf = Double.POSITIVE_INFINITY; + + public static Set reservedSet = new HashSet(Arrays.asList + ("month", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", + "prevjan", "prevfeb", "prevmar", "prevapr", "prevmay", "prevjun", + "prevjul", "prevaug", "prevsep", "prevoct", "prevnov", "prevdec", + "wateryear", "cfs_taf", "taf_cfs", "cfs_cfm", "af_cfs", "cfs_af", "daysin", "daysinmonth", + "i", "null", "pow", "exp", "log", "log10", "abs", "real","mod", + "day" + )); + + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/StudyDataSet.java b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/StudyDataSet.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/StudyDataSet.java rename to wrims-core/src/main/java/wrimsv2/commondata/wresldata/StudyDataSet.java index 9c48a1919..74160f8dd 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/StudyDataSet.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/StudyDataSet.java @@ -1,172 +1,172 @@ -package wrimsv2.commondata.wresldata; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.ValueEvaluatorParser; - - -public class StudyDataSet implements Serializable { - - private static final long serialVersionUID = 1L; - - private String absMainFilePath=""; - - private ArrayList parameterList = new ArrayList(); - private LinkedHashMap parameterMap = new LinkedHashMap(); - public LinkedHashMap controlDataParameterMap = new LinkedHashMap(); - - private ArrayList modelList = new ArrayList(); - private ArrayList modelConditionList = new ArrayList(); - private ArrayList modelTimeStepList = new ArrayList(); - private ArrayList modelConditionParsers=new ArrayList(); - - /// < timeseries name, timeseries object > - private Map timeseriesMap = new HashMap(); - private Map> timeseriesTimeStepMap = new HashMap>(); - - /// < modelName, modelDataSet > - private Map modelDataSetMap = new HashMap(); - - /// this map contains value of vars needed for WRESL syntax: varName[cycleName] - /// < VarName, < CycleName, Value >> - private Map> varCycleValueMap = new HashMap>(); - private Map> varTimeArrayCycleValueMap = new HashMap>(); - private Map> varCycleIndexValueMap = new HashMap>(); - private ArrayList varCycleIndexList = new ArrayList(); - private ArrayList dvarTimeArrayCycleIndexList = new ArrayList(); - - public LinkedHashSet allIntDv=new LinkedHashSet(); - public Map> cycIntDvMap=new HashMap>(); - - public ArrayList getParameterList() { - return new ArrayList(parameterList); - } - - public void setParameterList(ArrayList parameterList) { - this.parameterList = parameterList; - } - - public LinkedHashMap getParameterMap() { - return new LinkedHashMap(parameterMap); - } - - public void setParameterMap(LinkedHashMap parameterMap) { - this.parameterMap = parameterMap; - } - - public Map getTimeseriesMap() { - return new HashMap(timeseriesMap); - } - - public void setTimeseriesMap(Map timeseriesMap) { - this.timeseriesMap = timeseriesMap; - } - - public Map> getTimeseriesTimeStepMap() { - return new HashMap>(timeseriesTimeStepMap); - } - - public void setTimeseriesTimeStepMap(Map> timeseriesTimeStepMap) { - this.timeseriesTimeStepMap = timeseriesTimeStepMap; - } - - public String getAbsMainFilePath() { - return new String(absMainFilePath); - } - - public void setAbsMainFilePath(String absMainFilePath) { - this.absMainFilePath = absMainFilePath; - } - - public ArrayList getModelList() { - return new ArrayList(modelList); - } - - public void setModelList(ArrayList modelList) { - this.modelList = modelList; - } - - public ArrayList getModelConditionList() { - return new ArrayList(modelConditionList); - } - - public ArrayList getModelTimeStepList() { - return modelTimeStepList; - } - - public void setModelConditionList(ArrayList modelConditionList) { - this.modelConditionList = modelConditionList; - } - - public void setModelTimeStepList(ArrayList modelTimeStepList) { - this.modelTimeStepList = modelTimeStepList; - } - - public ArrayList getModelConditionParsers() { - return modelConditionParsers; - } - - public void setModelConditionParsers(ArrayList modelConditionParsers) { - this.modelConditionParsers=modelConditionParsers; - } - - public Map getModelDataSetMap() { - return new HashMap(modelDataSetMap); - } - - public void setModelDataSetMap(Map modelDataSetMap) { - this.modelDataSetMap = modelDataSetMap; - } - - public Map> getVarCycleValueMap() { - return this.varCycleValueMap; - } - - public void setVarCycleValueMap(Map> varCycleValueMap) { - this.varCycleValueMap = varCycleValueMap; - } - - public Map> getVarTimeArrayCycleValueMap() { - return this.varTimeArrayCycleValueMap; - } - - public Map> getVarCycleIndexValueMap() { - return this.varCycleIndexValueMap; - } - - public void setVarCycleIndexValueMap(Map> varCycleIndexValueMap) { - this.varCycleIndexValueMap = varCycleIndexValueMap; - } - - public void clearVarTimeArrayCycleValueMap(){ - varTimeArrayCycleValueMap=new HashMap>(); - } - - public void clearVarCycleIndexByTimeStep(){ - varCycleIndexValueMap = new HashMap>(); - dvarTimeArrayCycleIndexList = new ArrayList (); - } - - public ArrayList getVarCycleIndexList(){ - return varCycleIndexList; - } - - public void setVarCycleIndexList(ArrayList varCycleIndexList){ - this.varCycleIndexList=new ArrayList(); - for (int i=0; i getDvarTimeArrayCycleIndexList(){ - return dvarTimeArrayCycleIndexList; - } -} +package wrimsv2.commondata.wresldata; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.ValueEvaluatorParser; + + +public class StudyDataSet implements Serializable { + + private static final long serialVersionUID = 1L; + + private String absMainFilePath=""; + + private ArrayList parameterList = new ArrayList(); + private LinkedHashMap parameterMap = new LinkedHashMap(); + public LinkedHashMap controlDataParameterMap = new LinkedHashMap(); + + private ArrayList modelList = new ArrayList(); + private ArrayList modelConditionList = new ArrayList(); + private ArrayList modelTimeStepList = new ArrayList(); + private ArrayList modelConditionParsers=new ArrayList(); + + /// < timeseries name, timeseries object > + private Map timeseriesMap = new HashMap(); + private Map> timeseriesTimeStepMap = new HashMap>(); + + /// < modelName, modelDataSet > + private Map modelDataSetMap = new HashMap(); + + /// this map contains value of vars needed for WRESL syntax: varName[cycleName] + /// < VarName, < CycleName, Value >> + private Map> varCycleValueMap = new HashMap>(); + private Map> varTimeArrayCycleValueMap = new HashMap>(); + private Map> varCycleIndexValueMap = new HashMap>(); + private ArrayList varCycleIndexList = new ArrayList(); + private ArrayList dvarTimeArrayCycleIndexList = new ArrayList(); + + public LinkedHashSet allIntDv=new LinkedHashSet(); + public Map> cycIntDvMap=new HashMap>(); + + public ArrayList getParameterList() { + return new ArrayList(parameterList); + } + + public void setParameterList(ArrayList parameterList) { + this.parameterList = parameterList; + } + + public LinkedHashMap getParameterMap() { + return new LinkedHashMap(parameterMap); + } + + public void setParameterMap(LinkedHashMap parameterMap) { + this.parameterMap = parameterMap; + } + + public Map getTimeseriesMap() { + return new HashMap(timeseriesMap); + } + + public void setTimeseriesMap(Map timeseriesMap) { + this.timeseriesMap = timeseriesMap; + } + + public Map> getTimeseriesTimeStepMap() { + return new HashMap>(timeseriesTimeStepMap); + } + + public void setTimeseriesTimeStepMap(Map> timeseriesTimeStepMap) { + this.timeseriesTimeStepMap = timeseriesTimeStepMap; + } + + public String getAbsMainFilePath() { + return new String(absMainFilePath); + } + + public void setAbsMainFilePath(String absMainFilePath) { + this.absMainFilePath = absMainFilePath; + } + + public ArrayList getModelList() { + return new ArrayList(modelList); + } + + public void setModelList(ArrayList modelList) { + this.modelList = modelList; + } + + public ArrayList getModelConditionList() { + return new ArrayList(modelConditionList); + } + + public ArrayList getModelTimeStepList() { + return modelTimeStepList; + } + + public void setModelConditionList(ArrayList modelConditionList) { + this.modelConditionList = modelConditionList; + } + + public void setModelTimeStepList(ArrayList modelTimeStepList) { + this.modelTimeStepList = modelTimeStepList; + } + + public ArrayList getModelConditionParsers() { + return modelConditionParsers; + } + + public void setModelConditionParsers(ArrayList modelConditionParsers) { + this.modelConditionParsers=modelConditionParsers; + } + + public Map getModelDataSetMap() { + return new HashMap(modelDataSetMap); + } + + public void setModelDataSetMap(Map modelDataSetMap) { + this.modelDataSetMap = modelDataSetMap; + } + + public Map> getVarCycleValueMap() { + return this.varCycleValueMap; + } + + public void setVarCycleValueMap(Map> varCycleValueMap) { + this.varCycleValueMap = varCycleValueMap; + } + + public Map> getVarTimeArrayCycleValueMap() { + return this.varTimeArrayCycleValueMap; + } + + public Map> getVarCycleIndexValueMap() { + return this.varCycleIndexValueMap; + } + + public void setVarCycleIndexValueMap(Map> varCycleIndexValueMap) { + this.varCycleIndexValueMap = varCycleIndexValueMap; + } + + public void clearVarTimeArrayCycleValueMap(){ + varTimeArrayCycleValueMap=new HashMap>(); + } + + public void clearVarCycleIndexByTimeStep(){ + varCycleIndexValueMap = new HashMap>(); + dvarTimeArrayCycleIndexList = new ArrayList (); + } + + public ArrayList getVarCycleIndexList(){ + return varCycleIndexList; + } + + public void setVarCycleIndexList(ArrayList varCycleIndexList){ + this.varCycleIndexList=new ArrayList(); + for (int i=0; i getDvarTimeArrayCycleIndexList(){ + return dvarTimeArrayCycleIndexList; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Svar.java b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Svar.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Svar.java rename to wrims-core/src/main/java/wrimsv2/commondata/wresldata/Svar.java index 4f6fc48a4..00f5214af 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Svar.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Svar.java @@ -1,106 +1,106 @@ -package wrimsv2.commondata.wresldata; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.evaluator.ValueEvaluatorTreeWalker; - - -public class Svar implements Serializable { - - private static final long serialVersionUID = 1L; - - // These properties are the same for all Svar time array - public String fromWresl; - public int line=1; - public String scope; - public String dssBPart; - public String format; - public String kind; - public String units; - public String convertToUnits; - public Set dependants; - public Set neededVarInCycleSet; - public boolean needVarFromEarlierCycle; - - - private IntDouble data; - - - // default is zero - public String timeArraySize; - public ValueEvaluatorParser timeArraySizeParser; - - // These are for: - // (1) normal Svar if timeArraySize=0 - // e.g., define someSvar { value 1 } - // - // (2) Svar time array if future expressions are the same - // e.g., define(3) someSvar { value $m } - public ArrayList caseName; - public ArrayList caseCondition; - public ArrayList caseConditionParsers; - public ArrayList caseConditionWalkers; - public ArrayList caseExpression; - public ArrayList caseExpressionParsers; - public ArrayList caseExpressionWalkers; - - - // These maps are for time array of Svar if future definitions have different expressions - // example 1: define(3) someSvar { - // (0) { value 99 } - // (1) { value a+b } - // (2) { value 7 } - // (3) { value 2*k } } - // example 2: define(3) someSvar { - // (0:2) { value 99 } - // (3) { value 2*k } } - public Map> timeMap_caseName; - public Map> timeMap_caseCondition; - public Map> timeMap_caseExpression; - - - - public Svar(){ - - scope=Param.undefined; - dssBPart=Param.undefined; - format=Param.undefined; - kind=Param.undefined; - units=Param.undefined; - convertToUnits =Param.undefined; - caseName = new ArrayList(); - caseCondition = new ArrayList(); - caseConditionParsers = new ArrayList(); - caseConditionWalkers = new ArrayList(); - caseExpression = new ArrayList(); - caseExpressionParsers = new ArrayList(); - caseExpressionWalkers = new ArrayList(); - fromWresl = Param.undefined; - dependants = new HashSet(); - data = null; - neededVarInCycleSet = new HashSet(); - needVarFromEarlierCycle = false; - - timeArraySize = "0"; // default has no future time array - - timeMap_caseName = new HashMap>(); - timeMap_caseCondition = new HashMap>(); - timeMap_caseExpression = new HashMap>(); - } - - public void setData(IntDouble data){ - this.data=data; - } - - public IntDouble getData(){ - return data; - } -} - +package wrimsv2.commondata.wresldata; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.evaluator.ValueEvaluatorTreeWalker; + + +public class Svar implements Serializable { + + private static final long serialVersionUID = 1L; + + // These properties are the same for all Svar time array + public String fromWresl; + public int line=1; + public String scope; + public String dssBPart; + public String format; + public String kind; + public String units; + public String convertToUnits; + public Set dependants; + public Set neededVarInCycleSet; + public boolean needVarFromEarlierCycle; + + + private IntDouble data; + + + // default is zero + public String timeArraySize; + public ValueEvaluatorParser timeArraySizeParser; + + // These are for: + // (1) normal Svar if timeArraySize=0 + // e.g., define someSvar { value 1 } + // + // (2) Svar time array if future expressions are the same + // e.g., define(3) someSvar { value $m } + public ArrayList caseName; + public ArrayList caseCondition; + public ArrayList caseConditionParsers; + public ArrayList caseConditionWalkers; + public ArrayList caseExpression; + public ArrayList caseExpressionParsers; + public ArrayList caseExpressionWalkers; + + + // These maps are for time array of Svar if future definitions have different expressions + // example 1: define(3) someSvar { + // (0) { value 99 } + // (1) { value a+b } + // (2) { value 7 } + // (3) { value 2*k } } + // example 2: define(3) someSvar { + // (0:2) { value 99 } + // (3) { value 2*k } } + public Map> timeMap_caseName; + public Map> timeMap_caseCondition; + public Map> timeMap_caseExpression; + + + + public Svar(){ + + scope=Param.undefined; + dssBPart=Param.undefined; + format=Param.undefined; + kind=Param.undefined; + units=Param.undefined; + convertToUnits =Param.undefined; + caseName = new ArrayList(); + caseCondition = new ArrayList(); + caseConditionParsers = new ArrayList(); + caseConditionWalkers = new ArrayList(); + caseExpression = new ArrayList(); + caseExpressionParsers = new ArrayList(); + caseExpressionWalkers = new ArrayList(); + fromWresl = Param.undefined; + dependants = new HashSet(); + data = null; + neededVarInCycleSet = new HashSet(); + needVarFromEarlierCycle = false; + + timeArraySize = "0"; // default has no future time array + + timeMap_caseName = new HashMap>(); + timeMap_caseCondition = new HashMap>(); + timeMap_caseExpression = new HashMap>(); + } + + public void setData(IntDouble data){ + this.data=data; + } + + public IntDouble getData(){ + return data; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/TimeArray.java b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/TimeArray.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/TimeArray.java rename to wrims-core/src/main/java/wrimsv2/commondata/wresldata/TimeArray.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Timeseries.java b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Timeseries.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Timeseries.java rename to wrims-core/src/main/java/wrimsv2/commondata/wresldata/Timeseries.java index a91aa37dc..6610c68d8 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/Timeseries.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/Timeseries.java @@ -1,40 +1,40 @@ -package wrimsv2.commondata.wresldata; - -import java.io.Serializable; - -import wrimsv2.components.IntDouble; - - -public class Timeseries implements Serializable { - - private static final long serialVersionUID = 1L; - public String scope; - public String dssBPart; - public String format; - public String kind; - public String units; - public String convertToUnits; - public String fromWresl; - public int line=1; - private IntDouble data; - - - public Timeseries(){ - scope=Param.undefined; - dssBPart=Param.undefined; - format=Param.undefined; - kind=Param.undefined; - units=Param.undefined; - convertToUnits =Param.undefined; - fromWresl = Param.undefined; - } - - public void setData(IntDouble data){ - this.data=data; - } - - public IntDouble getData(){ - return data; - } -} - +package wrimsv2.commondata.wresldata; + +import java.io.Serializable; + +import wrimsv2.components.IntDouble; + + +public class Timeseries implements Serializable { + + private static final long serialVersionUID = 1L; + public String scope; + public String dssBPart; + public String format; + public String kind; + public String units; + public String convertToUnits; + public String fromWresl; + public int line=1; + private IntDouble data; + + + public Timeseries(){ + scope=Param.undefined; + dssBPart=Param.undefined; + format=Param.undefined; + kind=Param.undefined; + units=Param.undefined; + convertToUnits =Param.undefined; + fromWresl = Param.undefined; + } + + public void setData(IntDouble data){ + this.data=data; + } + + public IntDouble getData(){ + return data; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/WeightElement.java b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/WeightElement.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/WeightElement.java rename to wrims-core/src/main/java/wrimsv2/commondata/wresldata/WeightElement.java index 485231ec1..5d38eec57 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/commondata/wresldata/WeightElement.java +++ b/wrims-core/src/main/java/wrimsv2/commondata/wresldata/WeightElement.java @@ -1,43 +1,43 @@ -package wrimsv2.commondata.wresldata; - -import java.io.Serializable; -import wrimsv2.evaluator.ValueEvaluatorParser; - - -public class WeightElement implements Serializable { - - private static final long serialVersionUID = 1L; - public String weight; - public String condition; - public ValueEvaluatorParser weightParser; - public ValueEvaluatorParser conditionParser; - public String fromWresl; - public int line=1; - private double value; - - // default is zero - public String timeArraySize; - public ValueEvaluatorParser timeArraySizeParser; - - public double min=-1; - public double max=-1; - public String minTC=""; - public String maxTC=""; - - public WeightElement(){ - weight = Param.undefined; - condition = Param.always; - fromWresl = Param.undefined; - - timeArraySize = "0"; // default has no future time array - } - - public void setValue(double value){ - this.value=value; - } - - public double getValue(){ - return value; - } -} - +package wrimsv2.commondata.wresldata; + +import java.io.Serializable; +import wrimsv2.evaluator.ValueEvaluatorParser; + + +public class WeightElement implements Serializable { + + private static final long serialVersionUID = 1L; + public String weight; + public String condition; + public ValueEvaluatorParser weightParser; + public ValueEvaluatorParser conditionParser; + public String fromWresl; + public int line=1; + private double value; + + // default is zero + public String timeArraySize; + public ValueEvaluatorParser timeArraySizeParser; + + public double min=-1; + public double max=-1; + public String minTC=""; + public String maxTC=""; + + public WeightElement(){ + weight = Param.undefined; + condition = Param.always; + fromWresl = Param.undefined; + + timeArraySize = "0"; // default has no future time array + } + + public void setValue(double value){ + this.value=value; + } + + public double getValue(){ + return value; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/BuildProps.java b/wrims-core/src/main/java/wrimsv2/components/BuildProps.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/components/BuildProps.java rename to wrims-core/src/main/java/wrimsv2/components/BuildProps.java index 28cf9fa40..507ec717f 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/BuildProps.java +++ b/wrims-core/src/main/java/wrimsv2/components/BuildProps.java @@ -1,33 +1,33 @@ -package wrimsv2.components; - -import java.util.Date; -import java.util.Properties; - -public class BuildProps { - - private Properties buildProps = null; - - - public BuildProps(){ - - buildProps = new Properties(); - //buildProps.put("version", "2.0"); - try { - buildProps.load(getClass().getResourceAsStream( - "/wrimsv2/version.props")); - } catch (Exception e) { - buildProps.put("vn", "NOT BUILT EVER - DEV Env"); - buildProps.put("buildtime", "" + new Date()); - //buildProps.put("system", "OS: " + System.getProperty("os.name")); - // e.printStackTrace(); - } - - } - - public String getVN() { - - return buildProps.getProperty("version"); - - } - +package wrimsv2.components; + +import java.util.Date; +import java.util.Properties; + +public class BuildProps { + + private Properties buildProps = null; + + + public BuildProps(){ + + buildProps = new Properties(); + //buildProps.put("version", "2.0"); + try { + buildProps.load(getClass().getResourceAsStream( + "/wrimsv2/version.props")); + } catch (Exception e) { + buildProps.put("vn", "NOT BUILT EVER - DEV Env"); + buildProps.put("buildtime", "" + new Date()); + //buildProps.put("system", "OS: " + System.getProperty("os.name")); + // e.printStackTrace(); + } + + } + + public String getVN() { + + return buildProps.getProperty("version"); + + } + } \ No newline at end of file diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/ClearValue.java b/wrims-core/src/main/java/wrimsv2/components/ClearValue.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/components/ClearValue.java rename to wrims-core/src/main/java/wrimsv2/components/ClearValue.java index c99f92cf0..cfbeb3a6c 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/ClearValue.java +++ b/wrims-core/src/main/java/wrimsv2/components/ClearValue.java @@ -1,63 +1,63 @@ -package wrimsv2.components; - -import java.util.ArrayList; -import java.util.Map; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Svar; - -public class ClearValue { - - public static void clearCycleLoopValue(ArrayList modelList, Map modelDataSetMap){ - String model=modelList.get(ControlData.currCycleIndex); - ModelDataSet mds=modelDataSetMap.get(model); - ArrayList dvList = mds.dvList; - Map dvMap =mds.dvMap; - for (String dvName: dvList){ - Dvar dvar=dvMap.get(dvName); - dvar.setData(null); - } - ArrayList svList = mds.svList; - Map svMap =mds.svMap; - for (String svName: svList){ - Svar svar=svMap.get(svName); - svar.setData(null); - } - ArrayList asList = mds.asList; - Map asMap =mds.asMap; - for (String asName: asList){ - Alias alias=asMap.get(asName); - alias.setData(null); - } - } - - public static void clearValues(ArrayList modelList, Map modelDataSetMap){ - for (int i=0; i dvList = mds.dvList; - Map dvMap =mds.dvMap; - for (String dvName: dvList){ - Dvar dvar=dvMap.get(dvName); - dvar.setData(null); - } - ArrayList svList = mds.svList; - Map svMap =mds.svMap; - for (String svName: svList){ - Svar svar=svMap.get(svName); - svar.setData(null); - } - ArrayList asList = mds.asList; - Map asMap =mds.asMap; - for (String asName: asList){ - Alias alias=asMap.get(asName); - alias.setData(null); - } - - mds.clearFutureSvMap(); - mds.clearFutureAsMap(); - } - } -} +package wrimsv2.components; + +import java.util.ArrayList; +import java.util.Map; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.Svar; + +public class ClearValue { + + public static void clearCycleLoopValue(ArrayList modelList, Map modelDataSetMap){ + String model=modelList.get(ControlData.currCycleIndex); + ModelDataSet mds=modelDataSetMap.get(model); + ArrayList dvList = mds.dvList; + Map dvMap =mds.dvMap; + for (String dvName: dvList){ + Dvar dvar=dvMap.get(dvName); + dvar.setData(null); + } + ArrayList svList = mds.svList; + Map svMap =mds.svMap; + for (String svName: svList){ + Svar svar=svMap.get(svName); + svar.setData(null); + } + ArrayList asList = mds.asList; + Map asMap =mds.asMap; + for (String asName: asList){ + Alias alias=asMap.get(asName); + alias.setData(null); + } + } + + public static void clearValues(ArrayList modelList, Map modelDataSetMap){ + for (int i=0; i dvList = mds.dvList; + Map dvMap =mds.dvMap; + for (String dvName: dvList){ + Dvar dvar=dvMap.get(dvName); + dvar.setData(null); + } + ArrayList svList = mds.svList; + Map svMap =mds.svMap; + for (String svName: svList){ + Svar svar=svMap.get(svName); + svar.setData(null); + } + ArrayList asList = mds.asList; + Map asMap =mds.asMap; + for (String asName: asList){ + Alias alias=asMap.get(asName); + alias.setData(null); + } + + mds.clearFutureSvMap(); + mds.clearFutureAsMap(); + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/ControlData.java b/wrims-core/src/main/java/wrimsv2/components/ControlData.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/components/ControlData.java rename to wrims-core/src/main/java/wrimsv2/components/ControlData.java index 5b02386a3..a055aadc0 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/ControlData.java +++ b/wrims-core/src/main/java/wrimsv2/components/ControlData.java @@ -1,225 +1,225 @@ -package wrimsv2.components; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.External; -import wrimsv2.commondata.wresldata.Goal; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.commondata.wresldata.Timeseries; -import wrimsv2.evaluator.CondensedReferenceCacheAndRead.CondensedReferenceCache; -import wrimsv2.evaluator.TimeOperation; -import wrimsv2.evaluator.LoopIndex; -import wrimsv2.external.ExternalFunction; -import wrimsv2.solver.ortools.OrToolsSolver; -import hec.heclib.dss.HecDss; - -import java.sql.Connection; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Stack; - -import lpsolve.LpSolve; - -import com.sunsetsoft.xa.Optimizer; - -public class ControlData { - public static ArrayList currTimeStep; - public static StudyDataSet currStudyDataSet=new StudyDataSet(); - public static ModelDataSet currModelDataSet=new ModelDataSet(); - public static LinkedHashMap parameterMap=new LinkedHashMap(); - public static Map currSvMap=new HashMap() ; - public static Map currSvFutMap=new HashMap() ; - public static Map currTsMap=new HashMap(); - public static Map currDvMap=new HashMap(); - public static Map currDvSlackSurplusMap=new HashMap(); - public static Map currAliasMap=new HashMap(); - public static Map currGoalMap=new HashMap(); - public static Map currExMap = new HashMap (); - public static Map allTsMap=new HashMap(); - public static Map allExternalFunction = new HashMap (); - public static Map allExternalFunctionMap = new HashMap(); - public static ArrayList allDll= new ArrayList() ; - public static String currCycleName; - public static int currCycleIndex; - public static int currEvalTypeIndex; //0=sv; 1=dv; 2=alias; 3=goal; 4=external; 5=timeseries define; 6=timeseries reading; 7=weight; 8=initial_vars; 9=conditional_include - public static String currEvalName; - public static int currDay=1; - public static int currMonth; - public static int currYear; - public static String defaultTimeStep="1MON"; - public static String timeStep ="1MON"; - public static String partE="1MON"; - public static int startYear; - public static int startMonth; - public static int startDay; - public static int endYear ; - public static int endMonth; - public static int endDay; - public static int cycleStartDay; - public static int cycleStartMonth; - public static int cycleStartYear; - public static int cycleEndDay; - public static int cycleEndMonth; - public static int cycleEndYear; - public static double cycleTimeStepPriority=0; - public static ArrayList totalTimeStep; - public static Date monthlyStartTime; - public static Date dailyStartTime; - public static String simulationTimeFrame; - public static String partA; - public static String svDvPartF; - public static String initPartF; - //public static Group groupInit; - //public static Group groupSvar; - //public static Group groupSvar2; - public static CondensedReferenceCache cacheInit; - public static CondensedReferenceCache cacheSvar; - public static CondensedReferenceCache cacheSvar2; - //public static DSSDataWriter writer; - public static HecDss dvDss; - public static String solverName="cbc'"; - public static Optimizer xasolver; - public static OrToolsSolver otsolver; - //public static int cbcSolverOptions = 2; - public static Double clp_cbc_objective; - public static String clp_cbc_note=""; - public static double lpsolve_objective; - public static double gurobi_objective; - public static boolean isPostProcessing=false; - public static boolean sendAliasToDvar=false; - public static boolean outputWreslCSV=false; - public static boolean showRunTimeMessage=false; - public static boolean showWreslLog=true; - public static boolean writeInitToDVOutput=true; - public static int solverType; - public static boolean isParseStudy=true; - public static boolean ignoreError=false; - public static boolean allowSvTsInit=false; - public static boolean allRestartFiles=false; - public static int numberRestartFiles=12; - public static int outputType=0; - public static boolean isOutputCycle=false; - public static boolean outputAllCycles=true; - public static String selectedCycleOutput="\'\'"; - public static String[] selectedCycles=new String[0]; - public static boolean initHDF5=false; - public static double solverTime_xa=0; - public static double solverTime_xa_this=0; - public static double solverTime_cbc=0; - public static double solverTime_cbc_this=0; - public static double solverCreationTime_cbc=0; - public static double solverCreationTime_xa=0; - public static double lpFileWritingTime=0; - public static double cdTime=0; - public static double adTime=0; - public static boolean useCplexLpString=false; - public static boolean saveCplexLpStringToFile=false; - public static boolean useCbcWarmStart=false; - public static boolean cbcCheckIntErr=true; - public static boolean cbcLogNativeLp=false; - public static boolean writeCbcSolvingTime=false; - public static boolean isNameSorting = false; - //public static Map> cycIntDvMap; - //public static LinkedHashSet allIntDv; - public static ArrayList cycWarmStart; - public static ArrayList cycWarmStop; - public static ArrayList cycWarmUse; - public static boolean cbc_debug_routeXA=false; //use xa solution - public static boolean cbc_debug_routeCbc=false; // use cbc solution - public static String[] watchList={}; - public static double watchList_tolerance = 1e99; - public static double zeroTolerance = 1e-11; // can read from config cbcToleranceZero - public static double relationTolerance; - public static Double xaIntegerT = null; - public static String xaSort = null; - public static boolean resimDate=false; - public static boolean resimGroundwater=false; - public static int resimYear; - public static int resimMonth; - public static int resimDay; - public static int cycleDataStartYear; - public static int cycleDataStartMonth; - public static int cycleDataStartDay; - - public static String USER; - public static String PASS; - public static String databaseURL; - public static String sqlGroup="calsim"; - public static int ovOption=0; - public static String ovFile=""; - public static boolean isSimOutput = true; - - public static boolean enableProgressLog = false; - - public static LocalDateTime ldt = LocalDateTime.now(); - public static String dateTimeAppend = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm", Locale.ENGLISH).format(ldt); - - public static boolean printGWFuncCalls=false; - - public static int yearOutputSection=-1; - public static int monMemSection=-1; - public static int outputYear; - public static int outputMonth; - public static int outputDay; - public static int memStartYear; - public static int memStartMonth; - public static int memStartDay; - public static int prevMemYear; - public static int prevMemMonth; - public static int prevMemDay; - public static int prevOutputYear; - public static int prevOutputMonth; - public static int prevOutputDay; - public static Date prevMemDate; - public static Date memStartDate; - public static Date prevOutputDate; - public static int nThreads=1; - public static boolean unchangeGWRestart=false; - public static boolean genSVCatalog=true; - public static boolean showTimeUsage=true; - public static int t_cbc=0; - public static int t_xa=0; - public static int t_ts=0; - public static int t_svar=0; - public static int t_dvar=0; - public static int t_goal=0; - public static int t_wt=0; - public static int t_wtss=0; - public static int t_as=0; - public static int t_readTs=0; - public static int t_writeDss=0; - public static int t_cam=0; - public static int t_parse=0; - public static int t_ann=0; - public static int n_ann=0; - public static int t_annx2=0; - public static int n_annx2=0; - public static int t_annec=0; - public static int n_annec=0; - public static int t_annlinegen=0; - public static int n_annlinegen=0; - public static int t_anngetndo_x2=0; - public static int n_anngetndo_x2=0; - public static int t_anngetndo_x2_curmonndosplit=0; - public static int n_anngetndo_x2_curmonndosplit=0; - public static int t_annec_matchdsm2=0; - public static int n_annec_matchdsm2=0; - - public static int pid=-1; - - public ControlData(){ - } - - public static String getPartE(){ - return timeStep; - } -} +package wrimsv2.components; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.External; +import wrimsv2.commondata.wresldata.Goal; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.commondata.wresldata.Timeseries; +import wrimsv2.evaluator.CondensedReferenceCacheAndRead.CondensedReferenceCache; +import wrimsv2.evaluator.TimeOperation; +import wrimsv2.evaluator.LoopIndex; +import wrimsv2.external.ExternalFunction; +import wrimsv2.solver.ortools.OrToolsSolver; +import hec.heclib.dss.HecDss; + +import java.sql.Connection; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Stack; + +import lpsolve.LpSolve; + +import com.sunsetsoft.xa.Optimizer; + +public class ControlData { + public static ArrayList currTimeStep; + public static StudyDataSet currStudyDataSet=new StudyDataSet(); + public static ModelDataSet currModelDataSet=new ModelDataSet(); + public static LinkedHashMap parameterMap=new LinkedHashMap(); + public static Map currSvMap=new HashMap() ; + public static Map currSvFutMap=new HashMap() ; + public static Map currTsMap=new HashMap(); + public static Map currDvMap=new HashMap(); + public static Map currDvSlackSurplusMap=new HashMap(); + public static Map currAliasMap=new HashMap(); + public static Map currGoalMap=new HashMap(); + public static Map currExMap = new HashMap (); + public static Map allTsMap=new HashMap(); + public static Map allExternalFunction = new HashMap (); + public static Map allExternalFunctionMap = new HashMap(); + public static ArrayList allDll= new ArrayList() ; + public static String currCycleName; + public static int currCycleIndex; + public static int currEvalTypeIndex; //0=sv; 1=dv; 2=alias; 3=goal; 4=external; 5=timeseries define; 6=timeseries reading; 7=weight; 8=initial_vars; 9=conditional_include + public static String currEvalName; + public static int currDay=1; + public static int currMonth; + public static int currYear; + public static String defaultTimeStep="1MON"; + public static String timeStep ="1MON"; + public static String partE="1MON"; + public static int startYear; + public static int startMonth; + public static int startDay; + public static int endYear ; + public static int endMonth; + public static int endDay; + public static int cycleStartDay; + public static int cycleStartMonth; + public static int cycleStartYear; + public static int cycleEndDay; + public static int cycleEndMonth; + public static int cycleEndYear; + public static double cycleTimeStepPriority=0; + public static ArrayList totalTimeStep; + public static Date monthlyStartTime; + public static Date dailyStartTime; + public static String simulationTimeFrame; + public static String partA; + public static String svDvPartF; + public static String initPartF; + //public static Group groupInit; + //public static Group groupSvar; + //public static Group groupSvar2; + public static CondensedReferenceCache cacheInit; + public static CondensedReferenceCache cacheSvar; + public static CondensedReferenceCache cacheSvar2; + //public static DSSDataWriter writer; + public static HecDss dvDss; + public static String solverName="cbc'"; + public static Optimizer xasolver; + public static OrToolsSolver otsolver; + //public static int cbcSolverOptions = 2; + public static Double clp_cbc_objective; + public static String clp_cbc_note=""; + public static double lpsolve_objective; + public static double gurobi_objective; + public static boolean isPostProcessing=false; + public static boolean sendAliasToDvar=false; + public static boolean outputWreslCSV=false; + public static boolean showRunTimeMessage=false; + public static boolean showWreslLog=true; + public static boolean writeInitToDVOutput=true; + public static int solverType; + public static boolean isParseStudy=true; + public static boolean ignoreError=false; + public static boolean allowSvTsInit=false; + public static boolean allRestartFiles=false; + public static int numberRestartFiles=12; + public static int outputType=0; + public static boolean isOutputCycle=false; + public static boolean outputAllCycles=true; + public static String selectedCycleOutput="\'\'"; + public static String[] selectedCycles=new String[0]; + public static boolean initHDF5=false; + public static double solverTime_xa=0; + public static double solverTime_xa_this=0; + public static double solverTime_cbc=0; + public static double solverTime_cbc_this=0; + public static double solverCreationTime_cbc=0; + public static double solverCreationTime_xa=0; + public static double lpFileWritingTime=0; + public static double cdTime=0; + public static double adTime=0; + public static boolean useCplexLpString=false; + public static boolean saveCplexLpStringToFile=false; + public static boolean useCbcWarmStart=false; + public static boolean cbcCheckIntErr=true; + public static boolean cbcLogNativeLp=false; + public static boolean writeCbcSolvingTime=false; + public static boolean isNameSorting = false; + //public static Map> cycIntDvMap; + //public static LinkedHashSet allIntDv; + public static ArrayList cycWarmStart; + public static ArrayList cycWarmStop; + public static ArrayList cycWarmUse; + public static boolean cbc_debug_routeXA=false; //use xa solution + public static boolean cbc_debug_routeCbc=false; // use cbc solution + public static String[] watchList={}; + public static double watchList_tolerance = 1e99; + public static double zeroTolerance = 1e-11; // can read from config cbcToleranceZero + public static double relationTolerance; + public static Double xaIntegerT = null; + public static String xaSort = null; + public static boolean resimDate=false; + public static boolean resimGroundwater=false; + public static int resimYear; + public static int resimMonth; + public static int resimDay; + public static int cycleDataStartYear; + public static int cycleDataStartMonth; + public static int cycleDataStartDay; + + public static String USER; + public static String PASS; + public static String databaseURL; + public static String sqlGroup="calsim"; + public static int ovOption=0; + public static String ovFile=""; + public static boolean isSimOutput = true; + + public static boolean enableProgressLog = false; + + public static LocalDateTime ldt = LocalDateTime.now(); + public static String dateTimeAppend = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm", Locale.ENGLISH).format(ldt); + + public static boolean printGWFuncCalls=false; + + public static int yearOutputSection=-1; + public static int monMemSection=-1; + public static int outputYear; + public static int outputMonth; + public static int outputDay; + public static int memStartYear; + public static int memStartMonth; + public static int memStartDay; + public static int prevMemYear; + public static int prevMemMonth; + public static int prevMemDay; + public static int prevOutputYear; + public static int prevOutputMonth; + public static int prevOutputDay; + public static Date prevMemDate; + public static Date memStartDate; + public static Date prevOutputDate; + public static int nThreads=1; + public static boolean unchangeGWRestart=false; + public static boolean genSVCatalog=true; + public static boolean showTimeUsage=true; + public static int t_cbc=0; + public static int t_xa=0; + public static int t_ts=0; + public static int t_svar=0; + public static int t_dvar=0; + public static int t_goal=0; + public static int t_wt=0; + public static int t_wtss=0; + public static int t_as=0; + public static int t_readTs=0; + public static int t_writeDss=0; + public static int t_cam=0; + public static int t_parse=0; + public static int t_ann=0; + public static int n_ann=0; + public static int t_annx2=0; + public static int n_annx2=0; + public static int t_annec=0; + public static int n_annec=0; + public static int t_annlinegen=0; + public static int n_annlinegen=0; + public static int t_anngetndo_x2=0; + public static int n_anngetndo_x2=0; + public static int t_anngetndo_x2_curmonndosplit=0; + public static int n_anngetndo_x2_curmonndosplit=0; + public static int t_annec_matchdsm2=0; + public static int n_annec_matchdsm2=0; + + public static int pid=-1; + + public ControlData(){ + } + + public static String getPartE(){ + return timeStep; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/Controller.java b/wrims-core/src/main/java/wrimsv2/components/Controller.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/components/Controller.java rename to wrims-core/src/main/java/wrimsv2/components/Controller.java index 14992f143..7cad7257b 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/Controller.java +++ b/wrims-core/src/main/java/wrimsv2/components/Controller.java @@ -1,599 +1,599 @@ -package wrimsv2.components; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Map; - -import org.antlr.runtime.RecognitionException; - -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.evaluator.AssignPastCycleVariable; -import wrimsv2.evaluator.DssOperation; -import wrimsv2.evaluator.PreEvaluator; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.ilp.ILP; -import wrimsv2.solver.LPSolveSolver; -import wrimsv2.solver.XASolver; -import wrimsv2.solver.SetXALog; -import wrimsv2.solver.InitialXASolver; -import wrimsv2.solver.Gurobi.GurobiSolver; -import wrimsv2.wreslparser.elements.StudyUtils; -import wrimsv2.wreslplus.elements.procedures.ErrorCheck; - -public class Controller { - - public Controller() { - long startTimeInMillis = Calendar.getInstance().getTimeInMillis(); - setControlData(); - //generateStudyFile(); - try { - StudyDataSet sds = parse(); - if (StudyUtils.total_errors==0){ - if (!StudyUtils.loadParserData && !FilePaths.fullMainPath.endsWith(".par")){ - StudyUtils.writeObj(sds, FilePaths.mainDirectory+File.separator+StudyUtils.configFileName+".par"); - } - new PreEvaluator(sds); - runModel(sds); - } - } catch (RecognitionException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - long endTimeInMillis = Calendar.getInstance().getTimeInMillis(); - int runPeriod=(int) (endTimeInMillis-startTimeInMillis); - System.out.println("=================Run Time is "+runPeriod/60000+"min"+Math.round((runPeriod/60000.0-runPeriod/60000)*60)+"sec===="); - } - - public Controller(String[] args) { - long startTimeInMillis = Calendar.getInstance().getTimeInMillis(); - setControlData(args); - //generateStudyFile(); - try { - StudyDataSet sds = parse(); - if (StudyUtils.total_errors==0){ - new PreEvaluator(sds); - runModel(sds); - } - } catch (RecognitionException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - long endTimeInMillis = Calendar.getInstance().getTimeInMillis(); - int runPeriod=(int) (endTimeInMillis-startTimeInMillis); - System.out.println("=================Run Time is "+runPeriod/60000+"min"+Math.round((runPeriod/60000.0-runPeriod/60000)*60)+"sec===="); - } - - public void setControlData(){ - FilePaths.groundwaterDir=""; - FilePaths.setMainFilePaths("d:\\2L_MW_7_O_120512\\run\\main.wresl"); - FilePaths.setSvarFilePaths("d:\\2L_MW_7_O_120512\\dss\\DailyPA_SV.dss"); - FilePaths.setInitFilePaths("d:\\2L_MW_7_O_120512\\dss\\DailyPA_init.dss"); - FilePaths.setDvarFilePaths("d:\\2L_MW_7_O_120512\\dss\\testDV.DSS"); - ControlData cd=new ControlData(); - cd.svDvPartF="KBPM"; - cd.initPartF="KBPM"; - cd.partA = "CALSIM"; - cd.defaultTimeStep="1DAY"; - cd.startYear=1980; - cd.startMonth=10; - cd.startDay=1; - cd.endYear=2011; - cd.endMonth=9; - cd.endDay=30; - cd.solverName="XA"; - FilePaths.csvFolderName="csv"; - cd.currYear=cd.startYear; - cd.currMonth=cd.startMonth; - cd.currDay=cd.startDay; - } - - public void setControlData(String[] args){ - FilePaths.groundwaterDir=args[0]; - FilePaths.setMainFilePaths(args[1]); - FilePaths.setSvarFilePaths(args[2]); - FilePaths.setInitFilePaths(args[3]); - FilePaths.setDvarFilePaths(args[4]); - ControlData cd=new ControlData(); - cd.svDvPartF=args[5]; - cd.initPartF=args[6]; - cd.partA = args[7]; - cd.defaultTimeStep = args[8]; - cd.startYear=Integer.parseInt(args[9]); - cd.startMonth=Integer.parseInt(args[10]); - cd.startDay=Integer.parseInt(args[11]); - cd.endYear=Integer.parseInt(args[12]); - cd.endMonth=Integer.parseInt(args[13]); - cd.endDay=Integer.parseInt(args[14]); - cd.solverName=args[15]; - FilePaths.csvFolderName = args[16]; - cd.currYear=cd.startYear; - cd.currMonth=cd.startMonth; - cd.currDay=cd.startDay; - } - - public void generateStudyFile(){ - String outPath=System.getenv("Java_Bin")+"study.sty"; - FileWriter outstream; - try { - outstream = new FileWriter(outPath); - BufferedWriter out = new BufferedWriter(outstream); - out.write("Study File: Generated by WRIMS. Do Not Edit!\n"); - out.write("Study Name\n"); - out.write("Author\n"); - out.write("Time\n"); - out.write("Note\n"); - out.write("Version\n"); - out.write(FilePaths.groundwaterDir+"\n"); - out.write("StudyFileFullPath\n"); - out.write(FilePaths.fullMainPath+"\n"); - out.write(FilePaths.fullSvarFilePath+"\n"); - out.write(FilePaths.fullDvarDssPath+"\n"); - out.write(FilePaths.fullInitFilePath+"\n"); - out.write(ControlData.defaultTimeStep+"\n"); - out.write(VariableTimeStep.getTotalTimeStep(ControlData.defaultTimeStep)+"\n"); - out.write(ControlData.startDay+"\n"); - out.write(ControlData.startMonth+"\n"); - out.write(ControlData.startYear+"\n"); - out.write("SLP\n"); - out.write("CycleNumber\n"); - out.write("FALSE\n"); - out.write("NONE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("CALSIM\n"); - out.write(ControlData.initPartF+"\n"); - out.write(ControlData.svDvPartF+"\n"); - out.write("FALSE\n"); - out.write("TRUE\n"); - out.write("FALSE\n"); - out.write("SINGLE\n"); - out.write("NODEBUG\n"); - out.close(); - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - - public StudyDataSet parse()throws RecognitionException, IOException{ - if(StudyUtils.loadParserData) { - return StudyUtils.loadObject(StudyUtils.parserDataPath); - }else{ - return StudyUtils.checkStudy(FilePaths.fullMainPath); - } - } - - public void runModel(StudyDataSet sds){ - System.out.println("==============Run Study Start============"); - new PreRunModel(sds); - if (ControlData.solverName.equalsIgnoreCase("Gurobi")){ - runModelGurobi(sds); - } else if (ILP.logging){ - runModelILP(sds); - } else if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG") ){ - runModelXA(sds); - } else { - Error.addConfigError("Solver name not recognized: "+ControlData.solverName); - Error.writeErrorLog(); - } - - if (Error.getTotalError()>0){ - System.out.println("=================Run ends with errors===="); - System.exit(1); - } else { - System.out.println("=================Run ends!================"); - } - } - - public void runModelXA(StudyDataSet sds){ - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - new InitialXASolver(); - if (Error.getTotalError()>0){ - System.out.println("Model run exits due to error."); - System.exit(1); - } - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - if (ControlData.solverName.equalsIgnoreCase("XALOG")) SetXALog.enableXALog(); - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - int i=0; - while (i=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.writeErrorLog(); - noError=false; - } - new XASolver(); - - // check monitored dvar list. they are slack and surplus generated automatically - // from the weight group deviation penalty - // give error if they are not zero or greater than a small tolerance. - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - System.out.println("Cycle "+(i+1)+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done."); - if (Error.error_evaluation.size()>=1) noError=false; - //if (ControlData.currTimeStep==0 && ControlData.currCycleIndex==2) new RCCComparison(); - //if (ControlData.currYear==1923 && ControlData.currMonth==9) new MultiStepAnalyzer(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - }else{ - new AssignPastCycleVariable(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - } - } - i=i+1; - } - VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); - VariableTimeStep.setCycleEndDate(sds); - } - ControlData.xasolver.close(); - if (ControlData.writeInitToDVOutput){ - DssOperation.writeInitDvarAliasToDSS(); - } - DssOperation.writeDVAliasToDSS(); - ControlData.dvDss.close(); - } - - public void runModelGurobi(StudyDataSet sds){ - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - - ILP.initializeIlp(); - GurobiSolver.initialize(); - - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - int i=0; - while (i=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.addSolvingError("evaluation error(s)"); - Error.writeErrorLog(); - noError=false; - } else { - ILP.setIlpFile(); - ILP.writeIlp(); - if (ILP.loggingVariableValue) { - ILP.setVarFile(); - ILP.writeSvarValue(); - } - GurobiSolver.setLp(ILP.cplexLpFilePath); - GurobiSolver.solve(); - } - - // check monitored dvar list. they are slack and surplus generated automatically - // from the weight group deviation penalty - // give error if they are not zero or greater than a small tolerance. - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - - ILP.writeObjValue_Gurobi(); - if (ILP.loggingVariableValue) ILP.writeDvarValue_Gurobi(); - - ILP.closeIlpFile(); - - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - System.out.println("Cycle "+(i+1)+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done."); - if (Error.error_evaluation.size()>=1) noError=false; - //if (ControlData.currTimeStep==0 && ControlData.currCycleIndex==1) new RCCComparison(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - }else{ - new AssignPastCycleVariable(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - } - } - i=i+1; - } - VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); - VariableTimeStep.setCycleEndDate(sds); - } - GurobiSolver.dispose(); - if (ControlData.writeInitToDVOutput){ - DssOperation.writeInitDvarAliasToDSS(); - } - DssOperation.writeDVAliasToDSS(); - ControlData.dvDss.close(); - } - - public void writeOutputDssEveryTenYears(){ - if (ControlData.currMonth==12 && ControlData.currYear%10==0){ - if (ControlData.timeStep.equals("1MON")){ - DssOperation.writeDVAliasToDSS(); - }else if(ControlData.timeStep.equals("1DAY") && ControlData.currDay==31){ - DssOperation.writeDVAliasToDSS(); - } - } - } - - public static void main(String[] args){ - new Controller(args); - } - - public void runModelILP(StudyDataSet sds){ - - ILP.initializeIlp(); - - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - if (ControlData.solverName.equalsIgnoreCase("lpsolve")) { - ControlData.solverType = Param.SOLVER_LPSOLVE; - // initiate lpsolve - } else if (ControlData.solverName.toLowerCase().contains("xa")) { - ControlData.solverType = Param.SOLVER_XA; //default - new InitialXASolver(); - } else { - Error.addConfigError("Solver name not recognized: "+ControlData.solverName); - Error.writeErrorLog(); - } - - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - if (ControlData.solverType == Param.SOLVER_XA && ControlData.solverName.toLowerCase().contains("xalog")) SetXALog.enableXALog(); - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - int i=0; - while (i=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.writeErrorLog(); - noError=false; - } - - // choose solver to solve. TODO: this is not efficient. need to be done outside ILP - if (ControlData.solverType == Param.SOLVER_LPSOLVE.intValue()) { - LPSolveSolver.setLP(ILP.lpSolveFilePath); - LPSolveSolver.solve(); - if (Error.error_solving.size()<1) { - if (ILP.logging) { - ILP.writeObjValue_LPSOLVE(); - if (ILP.loggingVariableValue) ILP.writeDvarValue_LPSOLVE(); - } - } - } else { - - new XASolver(); - - if (ILP.logging) { - ILP.writeObjValue_XA(); - if (ILP.loggingVariableValue) ILP.writeDvarValue_XA(); - } - } - - - - ILP.closeIlpFile(); - - // check monitored dvar list. they are slack and surplus generated automatically - // from the weight group deviation penalty - // give error if they are not zero or greater than a small tolerance. - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - System.out.println("Cycle "+(i+1)+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done."); - if (Error.error_evaluation.size()>=1) noError=false; - //if (ControlData.currTimeStep==0 && ControlData.currCycleIndex==2) new RCCComparison(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - }else{ - new AssignPastCycleVariable(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - } - } - i=i+1; - } - VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); - VariableTimeStep.setCycleEndDate(sds); - } - if (ControlData.solverType == Param.SOLVER_LPSOLVE) { - //ControlData.lpssolver.deleteLp(); - } else { - ControlData.xasolver.close(); - } - if (ControlData.writeInitToDVOutput){ - DssOperation.writeInitDvarAliasToDSS(); - } - DssOperation.writeDVAliasToDSS(); - ControlData.dvDss.close(); - } +package wrimsv2.components; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Map; + +import org.antlr.runtime.RecognitionException; + +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.evaluator.AssignPastCycleVariable; +import wrimsv2.evaluator.DssOperation; +import wrimsv2.evaluator.PreEvaluator; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.ilp.ILP; +import wrimsv2.solver.LPSolveSolver; +import wrimsv2.solver.XASolver; +import wrimsv2.solver.SetXALog; +import wrimsv2.solver.InitialXASolver; +import wrimsv2.solver.Gurobi.GurobiSolver; +import wrimsv2.wreslparser.elements.StudyUtils; +import wrimsv2.wreslplus.elements.procedures.ErrorCheck; + +public class Controller { + + public Controller() { + long startTimeInMillis = Calendar.getInstance().getTimeInMillis(); + setControlData(); + //generateStudyFile(); + try { + StudyDataSet sds = parse(); + if (StudyUtils.total_errors==0){ + if (!StudyUtils.loadParserData && !FilePaths.fullMainPath.endsWith(".par")){ + StudyUtils.writeObj(sds, FilePaths.mainDirectory+File.separator+StudyUtils.configFileName+".par"); + } + new PreEvaluator(sds); + runModel(sds); + } + } catch (RecognitionException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + long endTimeInMillis = Calendar.getInstance().getTimeInMillis(); + int runPeriod=(int) (endTimeInMillis-startTimeInMillis); + System.out.println("=================Run Time is "+runPeriod/60000+"min"+Math.round((runPeriod/60000.0-runPeriod/60000)*60)+"sec===="); + } + + public Controller(String[] args) { + long startTimeInMillis = Calendar.getInstance().getTimeInMillis(); + setControlData(args); + //generateStudyFile(); + try { + StudyDataSet sds = parse(); + if (StudyUtils.total_errors==0){ + new PreEvaluator(sds); + runModel(sds); + } + } catch (RecognitionException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + long endTimeInMillis = Calendar.getInstance().getTimeInMillis(); + int runPeriod=(int) (endTimeInMillis-startTimeInMillis); + System.out.println("=================Run Time is "+runPeriod/60000+"min"+Math.round((runPeriod/60000.0-runPeriod/60000)*60)+"sec===="); + } + + public void setControlData(){ + FilePaths.groundwaterDir=""; + FilePaths.setMainFilePaths("d:\\2L_MW_7_O_120512\\run\\main.wresl"); + FilePaths.setSvarFilePaths("d:\\2L_MW_7_O_120512\\dss\\DailyPA_SV.dss"); + FilePaths.setInitFilePaths("d:\\2L_MW_7_O_120512\\dss\\DailyPA_init.dss"); + FilePaths.setDvarFilePaths("d:\\2L_MW_7_O_120512\\dss\\testDV.DSS"); + ControlData cd=new ControlData(); + cd.svDvPartF="KBPM"; + cd.initPartF="KBPM"; + cd.partA = "CALSIM"; + cd.defaultTimeStep="1DAY"; + cd.startYear=1980; + cd.startMonth=10; + cd.startDay=1; + cd.endYear=2011; + cd.endMonth=9; + cd.endDay=30; + cd.solverName="XA"; + FilePaths.csvFolderName="csv"; + cd.currYear=cd.startYear; + cd.currMonth=cd.startMonth; + cd.currDay=cd.startDay; + } + + public void setControlData(String[] args){ + FilePaths.groundwaterDir=args[0]; + FilePaths.setMainFilePaths(args[1]); + FilePaths.setSvarFilePaths(args[2]); + FilePaths.setInitFilePaths(args[3]); + FilePaths.setDvarFilePaths(args[4]); + ControlData cd=new ControlData(); + cd.svDvPartF=args[5]; + cd.initPartF=args[6]; + cd.partA = args[7]; + cd.defaultTimeStep = args[8]; + cd.startYear=Integer.parseInt(args[9]); + cd.startMonth=Integer.parseInt(args[10]); + cd.startDay=Integer.parseInt(args[11]); + cd.endYear=Integer.parseInt(args[12]); + cd.endMonth=Integer.parseInt(args[13]); + cd.endDay=Integer.parseInt(args[14]); + cd.solverName=args[15]; + FilePaths.csvFolderName = args[16]; + cd.currYear=cd.startYear; + cd.currMonth=cd.startMonth; + cd.currDay=cd.startDay; + } + + public void generateStudyFile(){ + String outPath=System.getenv("Java_Bin")+"study.sty"; + FileWriter outstream; + try { + outstream = new FileWriter(outPath); + BufferedWriter out = new BufferedWriter(outstream); + out.write("Study File: Generated by WRIMS. Do Not Edit!\n"); + out.write("Study Name\n"); + out.write("Author\n"); + out.write("Time\n"); + out.write("Note\n"); + out.write("Version\n"); + out.write(FilePaths.groundwaterDir+"\n"); + out.write("StudyFileFullPath\n"); + out.write(FilePaths.fullMainPath+"\n"); + out.write(FilePaths.fullSvarFilePath+"\n"); + out.write(FilePaths.fullDvarDssPath+"\n"); + out.write(FilePaths.fullInitFilePath+"\n"); + out.write(ControlData.defaultTimeStep+"\n"); + out.write(VariableTimeStep.getTotalTimeStep(ControlData.defaultTimeStep)+"\n"); + out.write(ControlData.startDay+"\n"); + out.write(ControlData.startMonth+"\n"); + out.write(ControlData.startYear+"\n"); + out.write("SLP\n"); + out.write("CycleNumber\n"); + out.write("FALSE\n"); + out.write("NONE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("CALSIM\n"); + out.write(ControlData.initPartF+"\n"); + out.write(ControlData.svDvPartF+"\n"); + out.write("FALSE\n"); + out.write("TRUE\n"); + out.write("FALSE\n"); + out.write("SINGLE\n"); + out.write("NODEBUG\n"); + out.close(); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + public StudyDataSet parse()throws RecognitionException, IOException{ + if(StudyUtils.loadParserData) { + return StudyUtils.loadObject(StudyUtils.parserDataPath); + }else{ + return StudyUtils.checkStudy(FilePaths.fullMainPath); + } + } + + public void runModel(StudyDataSet sds){ + System.out.println("==============Run Study Start============"); + new PreRunModel(sds); + if (ControlData.solverName.equalsIgnoreCase("Gurobi")){ + runModelGurobi(sds); + } else if (ILP.logging){ + runModelILP(sds); + } else if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG") ){ + runModelXA(sds); + } else { + Error.addConfigError("Solver name not recognized: "+ControlData.solverName); + Error.writeErrorLog(); + } + + if (Error.getTotalError()>0){ + System.out.println("=================Run ends with errors===="); + System.exit(1); + } else { + System.out.println("=================Run ends!================"); + } + } + + public void runModelXA(StudyDataSet sds){ + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + new InitialXASolver(); + if (Error.getTotalError()>0){ + System.out.println("Model run exits due to error."); + System.exit(1); + } + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + if (ControlData.solverName.equalsIgnoreCase("XALOG")) SetXALog.enableXALog(); + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + int i=0; + while (i=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.writeErrorLog(); + noError=false; + } + new XASolver(); + + // check monitored dvar list. they are slack and surplus generated automatically + // from the weight group deviation penalty + // give error if they are not zero or greater than a small tolerance. + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + System.out.println("Cycle "+(i+1)+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done."); + if (Error.error_evaluation.size()>=1) noError=false; + //if (ControlData.currTimeStep==0 && ControlData.currCycleIndex==2) new RCCComparison(); + //if (ControlData.currYear==1923 && ControlData.currMonth==9) new MultiStepAnalyzer(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + }else{ + new AssignPastCycleVariable(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + } + } + i=i+1; + } + VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); + VariableTimeStep.setCycleEndDate(sds); + } + ControlData.xasolver.close(); + if (ControlData.writeInitToDVOutput){ + DssOperation.writeInitDvarAliasToDSS(); + } + DssOperation.writeDVAliasToDSS(); + ControlData.dvDss.close(); + } + + public void runModelGurobi(StudyDataSet sds){ + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + + ILP.initializeIlp(); + GurobiSolver.initialize(); + + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + int i=0; + while (i=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.addSolvingError("evaluation error(s)"); + Error.writeErrorLog(); + noError=false; + } else { + ILP.setIlpFile(); + ILP.writeIlp(); + if (ILP.loggingVariableValue) { + ILP.setVarFile(); + ILP.writeSvarValue(); + } + GurobiSolver.setLp(ILP.cplexLpFilePath); + GurobiSolver.solve(); + } + + // check monitored dvar list. they are slack and surplus generated automatically + // from the weight group deviation penalty + // give error if they are not zero or greater than a small tolerance. + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + + ILP.writeObjValue_Gurobi(); + if (ILP.loggingVariableValue) ILP.writeDvarValue_Gurobi(); + + ILP.closeIlpFile(); + + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + System.out.println("Cycle "+(i+1)+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done."); + if (Error.error_evaluation.size()>=1) noError=false; + //if (ControlData.currTimeStep==0 && ControlData.currCycleIndex==1) new RCCComparison(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + }else{ + new AssignPastCycleVariable(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + } + } + i=i+1; + } + VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); + VariableTimeStep.setCycleEndDate(sds); + } + GurobiSolver.dispose(); + if (ControlData.writeInitToDVOutput){ + DssOperation.writeInitDvarAliasToDSS(); + } + DssOperation.writeDVAliasToDSS(); + ControlData.dvDss.close(); + } + + public void writeOutputDssEveryTenYears(){ + if (ControlData.currMonth==12 && ControlData.currYear%10==0){ + if (ControlData.timeStep.equals("1MON")){ + DssOperation.writeDVAliasToDSS(); + }else if(ControlData.timeStep.equals("1DAY") && ControlData.currDay==31){ + DssOperation.writeDVAliasToDSS(); + } + } + } + + public static void main(String[] args){ + new Controller(args); + } + + public void runModelILP(StudyDataSet sds){ + + ILP.initializeIlp(); + + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + if (ControlData.solverName.equalsIgnoreCase("lpsolve")) { + ControlData.solverType = Param.SOLVER_LPSOLVE; + // initiate lpsolve + } else if (ControlData.solverName.toLowerCase().contains("xa")) { + ControlData.solverType = Param.SOLVER_XA; //default + new InitialXASolver(); + } else { + Error.addConfigError("Solver name not recognized: "+ControlData.solverName); + Error.writeErrorLog(); + } + + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + if (ControlData.solverType == Param.SOLVER_XA && ControlData.solverName.toLowerCase().contains("xalog")) SetXALog.enableXALog(); + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + int i=0; + while (i=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.writeErrorLog(); + noError=false; + } + + // choose solver to solve. TODO: this is not efficient. need to be done outside ILP + if (ControlData.solverType == Param.SOLVER_LPSOLVE.intValue()) { + LPSolveSolver.setLP(ILP.lpSolveFilePath); + LPSolveSolver.solve(); + if (Error.error_solving.size()<1) { + if (ILP.logging) { + ILP.writeObjValue_LPSOLVE(); + if (ILP.loggingVariableValue) ILP.writeDvarValue_LPSOLVE(); + } + } + } else { + + new XASolver(); + + if (ILP.logging) { + ILP.writeObjValue_XA(); + if (ILP.loggingVariableValue) ILP.writeDvarValue_XA(); + } + } + + + + ILP.closeIlpFile(); + + // check monitored dvar list. they are slack and surplus generated automatically + // from the weight group deviation penalty + // give error if they are not zero or greater than a small tolerance. + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + System.out.println("Cycle "+(i+1)+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done."); + if (Error.error_evaluation.size()>=1) noError=false; + //if (ControlData.currTimeStep==0 && ControlData.currCycleIndex==2) new RCCComparison(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + }else{ + new AssignPastCycleVariable(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + } + } + i=i+1; + } + VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); + VariableTimeStep.setCycleEndDate(sds); + } + if (ControlData.solverType == Param.SOLVER_LPSOLVE) { + //ControlData.lpssolver.deleteLp(); + } else { + ControlData.xasolver.close(); + } + if (ControlData.writeInitToDVOutput){ + DssOperation.writeInitDvarAliasToDSS(); + } + DssOperation.writeDVAliasToDSS(); + ControlData.dvDss.close(); + } } \ No newline at end of file diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/ControllerBatch.java b/wrims-core/src/main/java/wrimsv2/components/ControllerBatch.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/components/ControllerBatch.java rename to wrims-core/src/main/java/wrimsv2/components/ControllerBatch.java index c32a05637..91989ba74 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/ControllerBatch.java +++ b/wrims-core/src/main/java/wrimsv2/components/ControllerBatch.java @@ -1,1776 +1,1776 @@ -package wrimsv2.components; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Map; - -import org.antlr.runtime.RecognitionException; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.config.ConfigUtils; -import wrimsv2.evaluator.AssignPastCycleVariable; -import wrimsv2.evaluator.CsvOperation; -import wrimsv2.evaluator.DssOperation; -import wrimsv2.evaluator.PreEvaluator; -import wrimsv2.evaluator.TimeOperation; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.evaluator.WeightEval; -import wrimsv2.hdf5.HDF5Writer; -import wrimsv2.ilp.ILP; -import wrimsv2.launch.LaunchConfiguration; -import wrimsv2.solver.Cbc0Solver; -import wrimsv2.solver.CbcSolver; -import wrimsv2.solver.Clp0Solver; -import wrimsv2.solver.ClpSolver; -import wrimsv2.solver.InitialClpSolver; -import wrimsv2.solver.LPSolveSolver; -import wrimsv2.solver.XASolver; -import wrimsv2.solver.SetXALog; -import wrimsv2.solver.InitialXASolver; -import wrimsv2.solver.Gurobi.GurobiSolver; -import wrimsv2.solver.mpmodel.MPModel; -import wrimsv2.solver.ortools.OrToolsSolver; -import wrimsv2.sql.DataBaseProfile; -import wrimsv2.sql.MySQLCWriter; -import wrimsv2.sql.MySQLRWriter; -import wrimsv2.sql.SQLServerRWriter; -import wrimsv2.tools.General; -import wrimsv2.tools.Warmstart; -import wrimsv2.wreslparser.elements.StudyUtils; -import wrimsv2.wreslparser.elements.Tools; -import wrimsv2.wreslplus.elements.procedures.ErrorCheck; - -public class ControllerBatch { - - public boolean enableProgressLog = false; - public boolean enableConfigProgress = false; - private MySQLCWriter mySQLCWriter; - private MySQLRWriter mySQLRWriter; - private SQLServerRWriter sqlServerRWriter; - - public ControllerBatch() {} // do nothing - - public ControllerBatch(String[] args) { - long startTimeInMillis = Calendar.getInstance().getTimeInMillis(); - try { - new DataBaseProfile(args); - processArgs(args); - if (ILP.loggingUsageMemeory) General.getPID(); - connectToDataBase(); - if (enableConfigProgress) { - try { - FileWriter progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); - PrintWriter pw = new PrintWriter(progressFile); - pw.println("Parsing and preprocessing the model ..."); - pw.close(); - progressFile.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - StudyDataSet sds = parse(); - long afterParsing = Calendar.getInstance().getTimeInMillis(); - ControlData.t_parse=(int) (afterParsing-startTimeInMillis); - System.out.println("Parsing Time is "+ControlData.t_parse/60000+"min"+Math.round((ControlData.t_parse/60000.0-ControlData.t_parse/60000)*60)+"sec"); - - if (StudyUtils.total_errors+Error.getTotalError()==0 && !StudyUtils.compileOnly){ - if (!StudyUtils.loadParserData && !FilePaths.fullMainPath.endsWith(".par")){ - StudyUtils.writeObj(sds, FilePaths.mainDirectory+File.separator+StudyUtils.configFileName+".par"); - } - new PreEvaluator(sds); - new PreRunModel(sds); - //generateStudyFile(); - long check = Calendar.getInstance().getTimeInMillis(); - - ILP.getIlpDir(); - ILP.setVarDir(); - ILP.createNoteFile(); - ILP.setMaximumFractionDigits(); - - runModel(sds); - if (ControlData.showTimeUsage) new TimeUsage(); - long endTimeInMillis = Calendar.getInstance().getTimeInMillis(); - int runPeriod=(int) (endTimeInMillis-startTimeInMillis); - System.out.println("=================Run Time is "+runPeriod/60000+"min"+Math.round((runPeriod/60000.0-runPeriod/60000)*60)+"sec===="); - ILP.writeNoteLn("Total time", "(sec): "+ Math.round(runPeriod/1000.0)); - ILP.writeNoteLn("Total time", "(min): "+ Math.round(runPeriod/1000.0/60)); - } else { - System.out.println("=================Run ends with errors================="); - System.exit(1); - } - - } catch (RecognitionException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - System.exit(0); - } - - public void processArgs(String[] args){ - - if(args[0].startsWith("-")) { - if (args[0].toLowerCase().startsWith("-launch")){ - procLaunch(args); - }else{ - ConfigUtils.loadArgs(args); - } - if (args[0].toLowerCase().endsWith(".launch.config")){ - enableConfigProgress=true; - } - if (ControlData.enableProgressLog){ - enableProgressLog=true; - } - } else { - setControlData(args); - } - - } - - public void setControlData(String[] args){ - FilePaths.groundwaterDir=args[0]; - FilePaths.setMainFilePaths(args[1]); - FilePaths.setSvarFilePaths(args[2]); - FilePaths.setInitFilePaths(args[3]); - FilePaths.setDvarFilePaths(args[4]); - ControlData.svDvPartF=args[5]; - ControlData.initPartF=args[6]; - ControlData.partA = args[7]; - ControlData.defaultTimeStep = args[8]; - ControlData.startYear=Integer.parseInt(args[9]); - ControlData.startMonth=Integer.parseInt(args[10]); - ControlData.startDay=Integer.parseInt(args[11]); - ControlData.endYear=Integer.parseInt(args[12]); - ControlData.endMonth=Integer.parseInt(args[13]); - ControlData.endDay=Integer.parseInt(args[14]); - ControlData.solverName=args[15]; - FilePaths.csvFolderName = args[16]; - ControlData.currYear=ControlData.startYear; - ControlData.currMonth=ControlData.startMonth; - ControlData.currDay=ControlData.startDay; - } - - public void generateStudyFile(){ - String outPath=System.getenv("temp_wrims2")+"\\study.sty"; - FileWriter outstream; - try { - outstream = new FileWriter(outPath); - BufferedWriter out = new BufferedWriter(outstream); - out.write("Study File: Generated by WRIMS. Do Not Edit!\n"); - out.write("Study Name\n"); - out.write("Author\n"); - out.write("Time\n"); - out.write("Note\n"); - out.write("Version\n"); - out.write(FilePaths.groundwaterDir+"\n"); - out.write("StudyFileFullPath\n"); - out.write(FilePaths.fullMainPath+"\n"); - out.write(FilePaths.fullSvarFilePath+"\n"); - out.write(FilePaths.fullDvarDssPath+"\n"); - out.write(FilePaths.fullInitFilePath+"\n"); - out.write(ControlData.defaultTimeStep+"\n"); - out.write(VariableTimeStep.getTotalTimeStep(ControlData.defaultTimeStep)+"\n"); - out.write(ControlData.startDay+"\n"); - out.write(ControlData.startMonth+"\n"); - out.write(ControlData.startYear+"\n"); - out.write("SLP\n"); - out.write("CycleNumber\n"); - out.write("FALSE\n"); - out.write("NONE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write(" \n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("CALSIM\n"); - out.write(ControlData.initPartF+"\n"); - out.write(ControlData.svDvPartF+"\n"); - out.write("FALSE\n"); - out.write("TRUE\n"); - out.write("FALSE\n"); - out.write("SINGLE\n"); - out.write("NODEBUG\n"); - out.close(); - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - - public StudyDataSet parse()throws RecognitionException, IOException{ - - if (Error.getTotalError()>0){ - - System.out.println("============================================"); - System.out.println("Total errors in the config file: "+Error.getTotalError()); - System.out.println("============================================"); - - return null; - - } else if(StudyUtils.loadParserData) { - - StudyDataSet sds = StudyUtils.loadObject(StudyUtils.parserDataPath); - LoadParameter.process(sds); - if (ControlData.useCbcWarmStart || ControlData.cbcCheckIntErr || ControlData.cbc_debug_routeCbc || ControlData.cbc_debug_routeXA){ - if (ControlData.solverName.equalsIgnoreCase("Cbc") || ControlData.solverName.equalsIgnoreCase("Cbc1")){ - - Warmstart.collectIntegerDV_3(sds); - - } - } - return sds; - - } else if(StudyUtils.compileOnly) { - - return StudyUtils.compileStudy(FilePaths.fullMainPath); - - } else { - - return StudyUtils.checkStudy(FilePaths.fullMainPath); - - } - } - - - public void runModel(StudyDataSet sds){ - System.out.println("==============Run Study Start============"); - - if (ControlData.solverName.equalsIgnoreCase("Gurobi")){ - runModelGurobi(sds); - } else if (ControlData.solverName.equalsIgnoreCase("Glpk")){ - runModelOrTools(sds, "GLPK_MIXED_INTEGER_PROGRAMMING"); - } else if (ControlData.solverName.equalsIgnoreCase("Clp")){ - runModelClp(sds); - } else if (ControlData.solverName.equalsIgnoreCase("Cbc")&&(ControlData.cbc_debug_routeXA||ControlData.cbc_debug_routeCbc)){ - runModelCbc(sds); - } else if (ILP.logging){ - runModelILP(sds); - } else if (ControlData.solverName.equalsIgnoreCase("Cbc")){ - runModelCbc(sds); - } else if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG") ){ - runModelXA(sds); - } else { - Error.addConfigError("Solver name not recognized: "+ControlData.solverName); - Error.writeErrorLog(); - } - - WeightEval.outputWtTableAR(); - - if (Error.getTotalError()>0){ - System.out.println("=================Run ends with errors===="); - System.exit(1); - } else { - System.out.println("=================Run ends!================"); - } - } - public void runModelXA(StudyDataSet sds){ - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - new InitialXASolver(); - if (Error.getTotalError()>0){ - System.out.println("Model run exits due to error."); - System.exit(1); - } - - TimeOperation.initOutputDate(ControlData.yearOutputSection); - TimeOperation.initMemDate(ControlData.monMemSection); - - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - int sectionI=0; - time_marching: - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - if (ControlData.solverName.equalsIgnoreCase("XALOG")) SetXALog.enableXALog(); - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - int i=0; - while (i=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.writeErrorLog(); - noError=false;break time_marching; - } - new XASolver(); - - // check monitored dvar list. they are slack and surplus generated automatically - // from the weight group deviation penalty - // give error if they are not zero or greater than a small tolerance. - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.writeOneCycleSv(mds, cycleI); - } - } - if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); - if (Error.error_evaluation.size()>=1) noError=false; - try{ - if (enableConfigProgress) { - FileWriter progressFile = new FileWriter(StudyUtils.configFilePath+".prgss"); - PrintWriter pw = new PrintWriter(progressFile); - pw.println("Run to "+ControlData.currYear +"/"+ ControlData.currMonth +"/"+ ControlData.currDay); - pw.close(); - progressFile.close(); - }else if(enableProgressLog){ - FileWriter progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt"); - PrintWriter pw = new PrintWriter(progressFile); - int cy = 0; - if (ControlData.currYear > cy) { - cy = ControlData.currYear; - pw.println(ControlData.startYear + " " + ControlData.endYear + " " + ControlData.currYear +" "+ ControlData.currMonth); - pw.close(); - progressFile.close(); - } - } - }catch(IOException e){ - e.printStackTrace(); - } - - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - }else{ - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.skipOneCycle(mds, cycleI); - } - } - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); - new AssignPastCycleVariable(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - } - } - i=i+1; - } - Date date1= new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - Date date2= new Date(ControlData.outputYear-1900, ControlData.outputMonth-1, ControlData.outputDay); - if (ControlData.yearOutputSection>0 && date1.after(date2)){ - if (ControlData.writeInitToDVOutput && sectionI==0){ - DssOperation.writeInitDvarAliasToDSS(); - } - sectionI++; - DssOperation.writeDVAliasToDSS(); - TimeOperation.setMemDate(ControlData.monMemSection); - DssOperation.shiftData(); - TimeOperation.setOutputDate(ControlData.yearOutputSection); - } - VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); - VariableTimeStep.setCycleEndDate(sds); - } - ControlData.xasolver.close(); - - if (ControlData.yearOutputSection<0 && ControlData.writeInitToDVOutput) DssOperation.writeInitDvarAliasToDSS(); - DssOperation.writeDVAliasToDSS(); - ControlData.dvDss.close(); - if (ControlData.outputType==1){ - HDF5Writer.createDvarAliasLookup(); - HDF5Writer.writeTimestepData(); - HDF5Writer.writeCyclesDvAlias(); - HDF5Writer.closeDataStructure(); - }else if (ControlData.outputType==2){ - mySQLCWriter.process(); - }else if (ControlData.outputType==3){ - mySQLRWriter.process(); - }else if (ControlData.outputType==4){ - sqlServerRWriter.process(); - }else if (ControlData.outputType==5){ - CsvOperation co = new CsvOperation(); - co.ouputCSV(FilePaths.fullCsvPath, 0); - } - - // write complete or fail - if (enableProgressLog || enableConfigProgress) { - try { - FileWriter progressFile; - if (enableConfigProgress){ - progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); - }else{ - progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt", true); - } - PrintWriter pw = new PrintWriter(progressFile); - if (Error.getTotalError() > 0) { - pw.println("Run failed."); - } else { - pw.println("Run completed."); - } - pw.close(); - progressFile.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public void writeOutputDssEveryTenYears(){ - if (ControlData.currMonth==12 && ControlData.currYear%10==0){ - if (ControlData.timeStep.equals("1MON")){ - DssOperation.writeDVAliasToDSS(); - }else if(ControlData.timeStep.equals("1DAY") && ControlData.currDay==31){ - DssOperation.writeDVAliasToDSS(); - } - } - } - - public static void main(String[] args){ - new ControllerBatch(args); - } - - public void runModelILP(StudyDataSet sds){ - - ILP.initializeIlp(); - - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - if (ControlData.solverName.equalsIgnoreCase("clp0")) { - ControlData.solverType = Param.SOLVER_CLP0; - // initiate clp0 - Clp0Solver.init(); - } else if (ControlData.solverName.equalsIgnoreCase("clp1")) { - ControlData.solverType = Param.SOLVER_CLP1; - // initiate clp - ClpSolver.init(true); - } else if (ControlData.solverName.equalsIgnoreCase("clp")) { - ControlData.solverType = Param.SOLVER_CLP; - // initiate clp - ClpSolver.init(false); - } else if (ControlData.solverName.equalsIgnoreCase("cbc0")) { - ControlData.solverType = Param.SOLVER_CBC0; - // initiate cbc0 - Cbc0Solver.init(); - } else if (ControlData.solverName.equalsIgnoreCase("cbc1")) { - ControlData.solverType = Param.SOLVER_CBC1; - // initiate cbc file passing jni - CbcSolver.init(true, sds); - } else if (ControlData.solverName.equalsIgnoreCase("cbc")) { - ControlData.solverType = Param.SOLVER_CBC; - // initiate cbc file passing jni - CbcSolver.init(false, sds); - } else if (ControlData.solverName.equalsIgnoreCase("lpsolve")) { - ControlData.solverType = Param.SOLVER_LPSOLVE; - // initiate lpsolve - } else if (ControlData.solverName.toLowerCase().contains("xa")) { - ControlData.solverType = Param.SOLVER_XA; //default - new InitialXASolver(); - } else { - Error.addConfigError("Solver name not recognized: "+ControlData.solverName); - Error.writeErrorLog(); - } - - TimeOperation.initOutputDate(ControlData.yearOutputSection); - TimeOperation.initMemDate(ControlData.monMemSection); - - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - int sectionI=0; - time_marching: - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - if (ControlData.solverType == Param.SOLVER_XA && ControlData.solverName.toLowerCase().contains("xalog")) SetXALog.enableXALog(); - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - int i=0; - while (i=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.writeErrorLog(); - noError=false;break time_marching; - } - - // choose solver to solve. TODO: this is not efficient. need to be done outside ILP - if (ControlData.solverType == Param.SOLVER_LPSOLVE.intValue()) { - LPSolveSolver.setLP(ILP.lpSolveFilePath); - LPSolveSolver.solve(); - if (Error.error_solving.size()<1) { - if (ILP.logging) { - ILP.writeObjValue_LPSOLVE(); - if (ILP.loggingVariableValue) ILP.writeDvarValue_LPSOLVE(); - } - } - // for cbc0 - } else if (ControlData.solverType == Param.SOLVER_CBC0.intValue()){ - - ILP.closeCplexLpFile(); // prevent double-locked by both wrims and ilp - - // send lp file path to cbc - Cbc0Solver.setLP(ILP.cplexLpFilePath); - - // call cbc solve - Cbc0Solver.solve(); - - - - // check solving errors and put them in Error.error_solving - if (Error.error_solving.size()<1) { - if (ILP.logging) { - - ILP.reOpenCplexLpFile(true); - // write objValue in lp file - ILP.writeObjValue_Clp0_Cbc0(); - if (ILP.loggingVariableValue) { - // TODO: write solution - ILP.writeDvarValue_Clp0_Cbc0(Cbc0Solver.varDoubleMap); - } - } - } - // for clp - } else if (ControlData.solverType == Param.SOLVER_CLP0.intValue()){ - - ILP.closeCplexLpFile(); // prevent double-locked by both wrims and ilp - - // send lp file path to clp - Clp0Solver.setLP(ILP.cplexLpFilePath); - - // call clp solve - Clp0Solver.solve(); - - - - // check solving errors and put them in Error.error_solving - if (Error.error_solving.size()<1) { - if (ILP.logging) { - - ILP.reOpenCplexLpFile(true); - // write objValue in lp file - ILP.writeObjValue_Clp0_Cbc0(); - if (ILP.loggingVariableValue) { - // TODO: write solution - ILP.writeDvarValue_Clp0_Cbc0(Clp0Solver.varDoubleMap); - } - } - } - } else if (ControlData.solverType == Param.SOLVER_CBC1.intValue()||ControlData.solverType == Param.SOLVER_CBC.intValue()){ - - if(!ControlData.useCplexLpString) ILP.closeCplexLpFile(); // prevent double-locked by both wrims and ilp - - - CbcSolver.newProblem(); - - // check solving errors and put them in Error.error_solving - if (Error.error_solving.size()<1) { - if (ILP.logging) { - - if(!ControlData.useCplexLpString) ILP.reOpenCplexLpFile(true); - // write objValue in lp file - ILP.writeObjValue_Clp0_Cbc0(); - if(ControlData.saveCplexLpStringToFile) ILP.saveCplexLpStringToFile(); - if (ILP.loggingVariableValue) { - // TODO: write solution - ILP.writeDvarValue_Clp0_Cbc0(CbcSolver.varDoubleMap); - } - } - } - - } else if (ControlData.solverType == Param.SOLVER_CLP1.intValue()){ - - ILP.closeCplexLpFile(); // prevent double-locked by both wrims and ilp - - // send lp file path to clp - ClpSolver.newProblem(ILP.cplexLpFilePath, true); - - // check solving errors and put them in Error.error_solving - if (Error.error_solving.size()<1) { - if (ILP.logging) { - - ILP.reOpenCplexLpFile(true); - // write objValue in lp file - ILP.writeObjValue_Clp0_Cbc0(); - if (ILP.loggingVariableValue) { - // TODO: write solution - ILP.writeDvarValue_Clp0_Cbc0(ClpSolver.varDoubleMap); - } - } - } - - } else { - - new XASolver(); - - if (ILP.logging) { - ILP.writeObjValue_XA(); - if (ILP.loggingVariableValue) ILP.writeDvarValue_XA(); - } - } - - - - ILP.closeIlpFile(); - - // check monitored dvar list. they are slack and surplus generated automatically - // from the weight group deviation penalty - // give error if they are not zero or greater than a small tolerance. - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.writeOneCycleSv(mds, cycleI); - } - } - if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); - if (Error.error_evaluation.size()>=1) noError=false; - try{ - if (enableConfigProgress) { - FileWriter progressFile = new FileWriter(StudyUtils.configFilePath+".prgss"); - PrintWriter pw = new PrintWriter(progressFile); - pw.println("Run to "+ControlData.currYear +"/"+ ControlData.currMonth +"/"+ ControlData.currDay); - pw.close(); - progressFile.close(); - }else if(enableProgressLog){ - FileWriter progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt"); - PrintWriter pw = new PrintWriter(progressFile); - int cy = 0; - if (ControlData.currYear > cy) { - cy = ControlData.currYear; - pw.println(ControlData.startYear + " " + ControlData.endYear + " " + ControlData.currYear +" "+ ControlData.currMonth); - pw.close(); - progressFile.close(); - } - } - }catch(IOException e){ - e.printStackTrace(); - } - - if (CbcSolver.intLog && ControlData.solverType == Param.SOLVER_CBC.intValue()) { - CbcSolver.logIntCheck(sds); - } - - if (ControlData.solverType == Param.SOLVER_CBC1.intValue()||ControlData.solverType == Param.SOLVER_CBC.intValue()) { CbcSolver.resetModel();} - - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - }else{ - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.skipOneCycle(mds, cycleI); - } - } - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); - new AssignPastCycleVariable(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - } - } - i=i+1; - } - Date date1= new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - Date date2= new Date(ControlData.outputYear-1900, ControlData.outputMonth-1, ControlData.outputDay); - if (ControlData.yearOutputSection>0 && date1.after(date2)){ - if (ControlData.writeInitToDVOutput && sectionI==0){ - DssOperation.writeInitDvarAliasToDSS(); - } - sectionI++; - DssOperation.writeDVAliasToDSS(); - TimeOperation.setMemDate(ControlData.monMemSection); - DssOperation.shiftData(); - TimeOperation.setOutputDate(ControlData.yearOutputSection); - } - VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); - VariableTimeStep.setCycleEndDate(sds); - } - if (ControlData.solverType == Param.SOLVER_LPSOLVE) { - //ControlData.lpssolver.deleteLp(); - } else if (ControlData.solverType == Param.SOLVER_CLP0) { - // close clp exe - } else if (ControlData.solverType == Param.SOLVER_CBC0) { - // close cbc exe - } else if (ControlData.solverType == Param.SOLVER_CBC || ControlData.solverType == Param.SOLVER_CBC1) { - CbcSolver.close(); - } else if (ControlData.solverType == Param.SOLVER_CLP1 || ControlData.solverType == Param.SOLVER_CLP) { - ClpSolver.close(); - } else { - ControlData.xasolver.close(); - } - - if (ControlData.yearOutputSection<0 && ControlData.writeInitToDVOutput) DssOperation.writeInitDvarAliasToDSS(); - DssOperation.writeDVAliasToDSS(); - ControlData.dvDss.close(); - if (ControlData.outputType==1){ - HDF5Writer.createDvarAliasLookup(); - HDF5Writer.writeTimestepData(); - HDF5Writer.writeCyclesDvAlias(); - HDF5Writer.closeDataStructure(); - }else if (ControlData.outputType==2){ - mySQLCWriter.process(); - }else if (ControlData.outputType==3){ - mySQLRWriter.process(); - }else if (ControlData.outputType==4){ - sqlServerRWriter.process(); - }else if (ControlData.outputType==5){ - CsvOperation co = new CsvOperation(); - co.ouputCSV(FilePaths.fullCsvPath, 0); - } - - // write complete or fail - if (enableProgressLog || enableConfigProgress) { - try { - FileWriter progressFile; - if (enableConfigProgress){ - progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); - }else{ - progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt", true); - } - PrintWriter pw = new PrintWriter(progressFile); - if (Error.getTotalError() > 0) { - pw.println("Run failed."); - } else { - pw.println("Run completed."); - } - pw.close(); - progressFile.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public void runModelGurobi(StudyDataSet sds){ - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - - ILP.initializeIlp(); - GurobiSolver.initialize(); - - TimeOperation.initOutputDate(ControlData.yearOutputSection); - TimeOperation.initMemDate(ControlData.monMemSection); - int sectionI=0; - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - int i=0; - while (i=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.addSolvingError("evaluation error(s)"); - Error.writeErrorLog(); - noError=false; - } else { - ILP.setIlpFile(); - ILP.writeIlp(); - if (ILP.loggingVariableValue) { - ILP.setVarFile(); - ILP.writeSvarValue(); - } - GurobiSolver.setLp(ILP.cplexLpFilePath); - GurobiSolver.solve(); - } - - // check monitored dvar list. they are slack and surplus generated automatically - // from the weight group deviation penalty - // give error if they are not zero or greater than a small tolerance. - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - - ILP.writeObjValue_Gurobi(); - if (ILP.loggingVariableValue) ILP.writeDvarValue_Gurobi(); - - ILP.closeIlpFile(); - - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.writeOneCycleSv(mds, cycleI); - } - } - if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); - if (Error.error_evaluation.size()>=1) noError=false; - try{ - if (enableConfigProgress) { - FileWriter progressFile = new FileWriter(StudyUtils.configFilePath+".prgss"); - PrintWriter pw = new PrintWriter(progressFile); - pw.println("Run to "+ControlData.currYear +"/"+ ControlData.currMonth +"/"+ ControlData.currDay); - pw.close(); - progressFile.close(); - }else if(enableProgressLog){ - FileWriter progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt"); - PrintWriter pw = new PrintWriter(progressFile); - int cy = 0; - if (ControlData.currYear > cy) { - cy = ControlData.currYear; - pw.println(ControlData.startYear + " " + ControlData.endYear + " " + ControlData.currYear +" "+ ControlData.currMonth); - pw.close(); - progressFile.close(); - } - } - }catch(IOException e){ - e.printStackTrace(); - } - - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - }else{ - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.skipOneCycle(mds, cycleI); - } - } - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); - new AssignPastCycleVariable(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - } - } - i=i+1; - } - Date date1= new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - Date date2= new Date(ControlData.outputYear-1900, ControlData.outputMonth-1, ControlData.outputDay); - if (ControlData.yearOutputSection>0 && date1.after(date2)){ - if (ControlData.writeInitToDVOutput && sectionI==0){ - DssOperation.writeInitDvarAliasToDSS(); - } - sectionI++; - DssOperation.writeDVAliasToDSS(); - TimeOperation.setMemDate(ControlData.monMemSection); - DssOperation.shiftData(); - TimeOperation.setOutputDate(ControlData.yearOutputSection); - } - VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); - VariableTimeStep.setCycleEndDate(sds); - } - GurobiSolver.dispose(); - - if (ControlData.yearOutputSection<0 && ControlData.writeInitToDVOutput) DssOperation.writeInitDvarAliasToDSS(); - DssOperation.writeDVAliasToDSS(); - ControlData.dvDss.close(); - if (ControlData.outputType==1){ - HDF5Writer.createDvarAliasLookup(); - HDF5Writer.writeTimestepData(); - HDF5Writer.writeCyclesDvAlias(); - HDF5Writer.closeDataStructure(); - }else if (ControlData.outputType==2){ - mySQLCWriter.process(); - }else if (ControlData.outputType==3){ - mySQLRWriter.process(); - }else if (ControlData.outputType==4){ - sqlServerRWriter.process(); - }else if (ControlData.outputType==5){ - CsvOperation co = new CsvOperation(); - co.ouputCSV(FilePaths.fullCsvPath, 0); - } - - // write complete or fail - if (enableProgressLog || enableConfigProgress) { - try { - FileWriter progressFile; - if (enableConfigProgress){ - progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); - }else{ - progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt", true); - } - PrintWriter pw = new PrintWriter(progressFile); - if (Error.getTotalError() > 0) { - pw.println("Run failed."); - } else { - pw.println("Run completed."); - } - pw.close(); - progressFile.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public void runModelGurobiTest(StudyDataSet sds){ - - - File ilpRootDir = new File(FilePaths.mainDirectory, "=ILP="); - File ilpDir = new File(ilpRootDir, StudyUtils.configFileName); - File cplexLpDir = new File(ilpDir,"cplexlp_input"); - PrintWriter objValueFile = null; - try { - objValueFile = Tools.openFile(ilpDir.getAbsolutePath(), "ObjValues.log"); - } - catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - GurobiSolver.initialize(); - - //while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - for (int year = ControlData.startYear; year <= ControlData.endYear; year++) { - - for (int month = 1; month <= 12; month++) { - - for (int cycle = 1; cycle <= sds.getModelList().size(); cycle++) { - - String twoDigitMonth = String.format("%02d", month); - String twoDigitCycle = String.format("%02d", cycle); - String lpFileName = year + "_" + twoDigitMonth + "_c" + twoDigitCycle + ".lp"; - - String msg = year + "_" + twoDigitMonth + "_c" + twoDigitCycle; - - File lpFile = new File(cplexLpDir, lpFileName); - - if (lpFile.exists()){ - - GurobiSolver.setLp(lpFile.getAbsolutePath()); - GurobiSolver.solve(); - - double objValue = ControlData.gurobi_objective; - String objValueStr = Double.toString(objValue); - - ILP.writeObjValueLog(msg, objValueStr, objValueFile); - - } - - } - } - } - - GurobiSolver.dispose(); - - } - - public void runModelOrTools(StudyDataSet sds, String mpSolverType){ - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - - if (ILP.logging) ILP.initializeIlp(); - OrToolsSolver.initialize(); - ControlData.otsolver = new OrToolsSolver(mpSolverType); - - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - int i=0; - while (i=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.addSolvingError("evaluation error(s)"); - Error.writeErrorLog(); - noError=false; - } else { - - MPModel m = ControlData.otsolver.createModel(); - - if (Error.error_solving.size()>=1){ - Error.writeErrorLog(); - noError=false; - break; - } - - - if (ILP.logging) { - ILP.setIlpFile(); - if (ILP.loggingMPModel) ILP.writeMPModelFile(m); - ILP.writeIlp(); - if (ILP.loggingVariableValue) { - ILP.setVarFile(); - ILP.writeSvarValue(); - } - } - - ControlData.otsolver.run(); - } - - // check monitored dvar list. they are slack and surplus generated automatically - // from the weight group deviation penalty - // give error if they are not zero or greater than a small tolerance. - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - - if (ILP.logging) { - ILP.writeObjValue_OrTools(); - if (ILP.loggingVariableValue) ILP.writeDvarValue_OrTools(); - - ILP.closeIlpFile(); - } - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.writeOneCycleSv(mds, cycleI); - } - } - if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); - if (Error.error_evaluation.size()>=1) noError=false; - - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - }else{ - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.skipOneCycle(mds, cycleI); - } - } - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); - new AssignPastCycleVariable(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - } - } - i=i+1; - } - VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); - VariableTimeStep.setCycleEndDate(sds); - } - ControlData.otsolver.delete(); - - if (ControlData.writeInitToDVOutput){ - DssOperation.writeInitDvarAliasToDSS(); - } - DssOperation.writeDVAliasToDSS(); - ControlData.dvDss.close(); - if (ControlData.outputType==1){ - HDF5Writer.createDvarAliasLookup(); - HDF5Writer.writeTimestepData(); - HDF5Writer.writeCyclesDvAlias(); - HDF5Writer.closeDataStructure(); - }else if (ControlData.outputType==2){ - mySQLCWriter.process(); - }else if (ControlData.outputType==3){ - mySQLRWriter.process(); - }else if (ControlData.outputType==4){ - sqlServerRWriter.process(); - }else if (ControlData.outputType==5){ - CsvOperation co = new CsvOperation(); - co.ouputCSV(FilePaths.fullCsvPath, 0); - } - } - - public void runModelClp(StudyDataSet sds){ - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - ClpSolver.init(false); - - if (Error.getTotalError()>0){ - System.out.println("Model run exits due to error."); - System.exit(1); - } - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - int i=0; - while (i=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.writeErrorLog(); - noError=false; - } - String lpProblemlName = ControlData.currYear+"_"+ControlData.currMonth+"_c"+(ControlData.currCycleIndex+1); - - ClpSolver.newProblem(lpProblemlName, false); - - // check monitored dvar list. they are slack and surplus generated automatically - // from the weight group deviation penalty - // give error if they are not zero or greater than a small tolerance. - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.writeOneCycleSv(mds, cycleI); - } - } - if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); - if (Error.error_evaluation.size()>=1) noError=false; - try{ - if (enableConfigProgress) { - FileWriter progressFile = new FileWriter(StudyUtils.configFilePath+".prgss"); - PrintWriter pw = new PrintWriter(progressFile); - pw.println("Run to "+ControlData.currYear +"/"+ ControlData.currMonth +"/"+ ControlData.currDay); - pw.close(); - progressFile.close(); - }else if(enableProgressLog){ - FileWriter progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt"); - PrintWriter pw = new PrintWriter(progressFile); - int cy = 0; - if (ControlData.currYear > cy) { - cy = ControlData.currYear; - pw.println(ControlData.startYear + " " + ControlData.endYear + " " + ControlData.currYear +" "+ ControlData.currMonth); - pw.close(); - progressFile.close(); - } - } - }catch(IOException e){ - e.printStackTrace(); - } - - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - }else{ - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.skipOneCycle(mds, cycleI); - } - } - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); - new AssignPastCycleVariable(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - } - } - i=i+1; - } - VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); - VariableTimeStep.setCycleEndDate(sds); - - } - ClpSolver.close(); - - if (ControlData.writeInitToDVOutput){ - DssOperation.writeInitDvarAliasToDSS(); - } - DssOperation.writeDVAliasToDSS(); - ControlData.dvDss.close(); - if (ControlData.outputType==1){ - HDF5Writer.createDvarAliasLookup(); - HDF5Writer.writeTimestepData(); - HDF5Writer.writeCyclesDvAlias(); - HDF5Writer.closeDataStructure(); - }else if (ControlData.outputType==2){ - mySQLCWriter.process(); - }else if (ControlData.outputType==3){ - mySQLRWriter.process(); - }else if (ControlData.outputType==4){ - sqlServerRWriter.process(); - }else if (ControlData.outputType==5){ - CsvOperation co = new CsvOperation(); - co.ouputCSV(FilePaths.fullCsvPath, 0); - } - - // write complete or fail - if (enableProgressLog || enableConfigProgress) { - try { - FileWriter progressFile; - if (enableConfigProgress){ - progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); - }else{ - progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt", true); - } - PrintWriter pw = new PrintWriter(progressFile); - if (Error.getTotalError() > 0) { - pw.println("Run failed."); - } else { - pw.println("Run completed."); - } - pw.close(); - progressFile.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public void runModelCbc(StudyDataSet sds){ - - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - CbcSolver.init(false, sds); if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) {new InitialXASolver();} - if (Error.getTotalError()>0){ - System.out.println("Model run exits due to error."); - System.exit(1); - } - - TimeOperation.initOutputDate(ControlData.yearOutputSection); - TimeOperation.initMemDate(ControlData.monMemSection); - - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - int sectionI=0; - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - int i=0; - while (i=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.writeErrorLog(); - noError=false;break time_marching; - } - - HashSet originalDvarKeys=null; - - if (ControlData.cbc_debug_routeCbc || ControlData.cbc_debug_routeXA) { - originalDvarKeys = new LinkedHashSet(SolverData.getDvarMap().keySet()); -// ILP.getIlpDir(); -// ILP.setVarDir(); - ILP.setSvarFile(); -// ILP.setMaximumFractionDigits(); - // write svar - ILP.writeSvarValue(); - } - - if (ControlData.cbc_debug_routeCbc) { - new XASolver(); - SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); - if (Error.error_solving.size() > 0) { - String msg = "XA solving error."; - ILP.writeNoteLn("", msg); - System.out.println("" + msg); - Error.writeErrorLog(); - Error.error_solving.clear(); - } - - } - - CbcSolver.newProblem(); - - if (ControlData.cbc_debug_routeXA) { - SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); - new XASolver(); - } - - // check monitored dvar list. they are slack and surplus generated automatically - // from the weight group deviation penalty - // give error if they are not zero or greater than a small tolerance. - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.writeOneCycleSv(mds, cycleI); - } - } - if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); - if (Error.error_evaluation.size()>=1) noError=false; - try{ - if (enableConfigProgress) { - FileWriter progressFile = new FileWriter(StudyUtils.configFilePath+".prgss"); - PrintWriter pw = new PrintWriter(progressFile); - pw.println("Run to "+ControlData.currYear +"/"+ ControlData.currMonth +"/"+ ControlData.currDay); - pw.close(); - progressFile.close(); - }else if(enableProgressLog){ - FileWriter progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt"); - PrintWriter pw = new PrintWriter(progressFile); - int cy = 0; - if (ControlData.currYear > cy) { - cy = ControlData.currYear; - pw.println(ControlData.startYear + " " + ControlData.endYear + " " + ControlData.currYear +" "+ ControlData.currMonth); - pw.close(); - progressFile.close(); - } - } - }catch(IOException e){ - e.printStackTrace(); - } - - //if (CbcSolver.intLog && (!ControlData.cbc_debug_routeXA && !ControlData.cbc_debug_routeCbc)) { - if (CbcSolver.intLog) { - CbcSolver.logIntCheck(sds); - } - - if (ControlData.cbc_debug_routeXA ||ControlData.cbc_debug_routeCbc ) { - CbcSolver.logCbcDebug(sds); - } else if (ControlData.watchList!=null) { - CbcSolver.logCbcWatchList(sds); - } - - CbcSolver.resetModel(); - - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - }else{ - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.skipOneCycle(mds, cycleI); - } - } - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); - new AssignPastCycleVariable(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - } - } - i=i+1; - } - Date date1= new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - Date date2= new Date(ControlData.outputYear-1900, ControlData.outputMonth-1, ControlData.outputDay); - if (ControlData.yearOutputSection>0 && date1.after(date2)){ - if (ControlData.writeInitToDVOutput && sectionI==0){ - DssOperation.writeInitDvarAliasToDSS(); - } - sectionI++; - DssOperation.writeDVAliasToDSS(); - TimeOperation.setMemDate(ControlData.monMemSection); - DssOperation.shiftData(); - TimeOperation.setOutputDate(ControlData.yearOutputSection); - } - VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); - VariableTimeStep.setCycleEndDate(sds); - } - CbcSolver.close(); if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) {ControlData.xasolver.close();} - - if (ControlData.yearOutputSection<0 && ControlData.writeInitToDVOutput) DssOperation.writeInitDvarAliasToDSS(); - DssOperation.writeDVAliasToDSS(); - ControlData.dvDss.close(); - if (ControlData.outputType==1){ - HDF5Writer.createDvarAliasLookup(); - HDF5Writer.writeTimestepData(); - HDF5Writer.writeCyclesDvAlias(); - HDF5Writer.closeDataStructure(); - }else if (ControlData.outputType==2){ - mySQLCWriter.process(); - }else if (ControlData.outputType==3){ - mySQLRWriter.process(); - }else if (ControlData.outputType==4){ - sqlServerRWriter.process(); - }else if (ControlData.outputType==5){ - CsvOperation co = new CsvOperation(); - co.ouputCSV(FilePaths.fullCsvPath, 0); - } - - // write complete or fail - if (enableProgressLog || enableConfigProgress) { - try { - FileWriter progressFile; - if (enableConfigProgress){ - progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); - }else{ - progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt", true); - } - PrintWriter pw = new PrintWriter(progressFile); - if (Error.getTotalError() > 0) { - pw.println("Run failed."); - } else { - pw.println("Run completed."); - } - pw.close(); - progressFile.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public void connectToDataBase(){ - if (ControlData.outputType==2){ - mySQLCWriter=new MySQLCWriter(); - }else if (ControlData.outputType==3){ - mySQLRWriter=new MySQLRWriter(); - }else if (ControlData.outputType==4){ - sqlServerRWriter=new SQLServerRWriter(); - } - } - - public void procLaunch(String[] args){ - String launchFilePath = args[0].substring(args[0].indexOf("=") + 1, args[0].length()); - new LaunchConfiguration(launchFilePath); - } +package wrimsv2.components; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; + +import org.antlr.runtime.RecognitionException; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.config.ConfigUtils; +import wrimsv2.evaluator.AssignPastCycleVariable; +import wrimsv2.evaluator.CsvOperation; +import wrimsv2.evaluator.DssOperation; +import wrimsv2.evaluator.PreEvaluator; +import wrimsv2.evaluator.TimeOperation; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.evaluator.WeightEval; +import wrimsv2.hdf5.HDF5Writer; +import wrimsv2.ilp.ILP; +import wrimsv2.launch.LaunchConfiguration; +import wrimsv2.solver.Cbc0Solver; +import wrimsv2.solver.CbcSolver; +import wrimsv2.solver.Clp0Solver; +import wrimsv2.solver.ClpSolver; +import wrimsv2.solver.InitialClpSolver; +import wrimsv2.solver.LPSolveSolver; +import wrimsv2.solver.XASolver; +import wrimsv2.solver.SetXALog; +import wrimsv2.solver.InitialXASolver; +import wrimsv2.solver.Gurobi.GurobiSolver; +import wrimsv2.solver.mpmodel.MPModel; +import wrimsv2.solver.ortools.OrToolsSolver; +import wrimsv2.sql.DataBaseProfile; +import wrimsv2.sql.MySQLCWriter; +import wrimsv2.sql.MySQLRWriter; +import wrimsv2.sql.SQLServerRWriter; +import wrimsv2.tools.General; +import wrimsv2.tools.Warmstart; +import wrimsv2.wreslparser.elements.StudyUtils; +import wrimsv2.wreslparser.elements.Tools; +import wrimsv2.wreslplus.elements.procedures.ErrorCheck; + +public class ControllerBatch { + + public boolean enableProgressLog = false; + public boolean enableConfigProgress = false; + private MySQLCWriter mySQLCWriter; + private MySQLRWriter mySQLRWriter; + private SQLServerRWriter sqlServerRWriter; + + public ControllerBatch() {} // do nothing + + public ControllerBatch(String[] args) { + long startTimeInMillis = Calendar.getInstance().getTimeInMillis(); + try { + new DataBaseProfile(args); + processArgs(args); + if (ILP.loggingUsageMemeory) General.getPID(); + connectToDataBase(); + if (enableConfigProgress) { + try { + FileWriter progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); + PrintWriter pw = new PrintWriter(progressFile); + pw.println("Parsing and preprocessing the model ..."); + pw.close(); + progressFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + StudyDataSet sds = parse(); + long afterParsing = Calendar.getInstance().getTimeInMillis(); + ControlData.t_parse=(int) (afterParsing-startTimeInMillis); + System.out.println("Parsing Time is "+ControlData.t_parse/60000+"min"+Math.round((ControlData.t_parse/60000.0-ControlData.t_parse/60000)*60)+"sec"); + + if (StudyUtils.total_errors+Error.getTotalError()==0 && !StudyUtils.compileOnly){ + if (!StudyUtils.loadParserData && !FilePaths.fullMainPath.endsWith(".par")){ + StudyUtils.writeObj(sds, FilePaths.mainDirectory+File.separator+StudyUtils.configFileName+".par"); + } + new PreEvaluator(sds); + new PreRunModel(sds); + //generateStudyFile(); + long check = Calendar.getInstance().getTimeInMillis(); + + ILP.getIlpDir(); + ILP.setVarDir(); + ILP.createNoteFile(); + ILP.setMaximumFractionDigits(); + + runModel(sds); + if (ControlData.showTimeUsage) new TimeUsage(); + long endTimeInMillis = Calendar.getInstance().getTimeInMillis(); + int runPeriod=(int) (endTimeInMillis-startTimeInMillis); + System.out.println("=================Run Time is "+runPeriod/60000+"min"+Math.round((runPeriod/60000.0-runPeriod/60000)*60)+"sec===="); + ILP.writeNoteLn("Total time", "(sec): "+ Math.round(runPeriod/1000.0)); + ILP.writeNoteLn("Total time", "(min): "+ Math.round(runPeriod/1000.0/60)); + } else { + System.out.println("=================Run ends with errors================="); + System.exit(1); + } + + } catch (RecognitionException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + System.exit(0); + } + + public void processArgs(String[] args){ + + if(args[0].startsWith("-")) { + if (args[0].toLowerCase().startsWith("-launch")){ + procLaunch(args); + }else{ + ConfigUtils.loadArgs(args); + } + if (args[0].toLowerCase().endsWith(".launch.config")){ + enableConfigProgress=true; + } + if (ControlData.enableProgressLog){ + enableProgressLog=true; + } + } else { + setControlData(args); + } + + } + + public void setControlData(String[] args){ + FilePaths.groundwaterDir=args[0]; + FilePaths.setMainFilePaths(args[1]); + FilePaths.setSvarFilePaths(args[2]); + FilePaths.setInitFilePaths(args[3]); + FilePaths.setDvarFilePaths(args[4]); + ControlData.svDvPartF=args[5]; + ControlData.initPartF=args[6]; + ControlData.partA = args[7]; + ControlData.defaultTimeStep = args[8]; + ControlData.startYear=Integer.parseInt(args[9]); + ControlData.startMonth=Integer.parseInt(args[10]); + ControlData.startDay=Integer.parseInt(args[11]); + ControlData.endYear=Integer.parseInt(args[12]); + ControlData.endMonth=Integer.parseInt(args[13]); + ControlData.endDay=Integer.parseInt(args[14]); + ControlData.solverName=args[15]; + FilePaths.csvFolderName = args[16]; + ControlData.currYear=ControlData.startYear; + ControlData.currMonth=ControlData.startMonth; + ControlData.currDay=ControlData.startDay; + } + + public void generateStudyFile(){ + String outPath=System.getenv("temp_wrims2")+"\\study.sty"; + FileWriter outstream; + try { + outstream = new FileWriter(outPath); + BufferedWriter out = new BufferedWriter(outstream); + out.write("Study File: Generated by WRIMS. Do Not Edit!\n"); + out.write("Study Name\n"); + out.write("Author\n"); + out.write("Time\n"); + out.write("Note\n"); + out.write("Version\n"); + out.write(FilePaths.groundwaterDir+"\n"); + out.write("StudyFileFullPath\n"); + out.write(FilePaths.fullMainPath+"\n"); + out.write(FilePaths.fullSvarFilePath+"\n"); + out.write(FilePaths.fullDvarDssPath+"\n"); + out.write(FilePaths.fullInitFilePath+"\n"); + out.write(ControlData.defaultTimeStep+"\n"); + out.write(VariableTimeStep.getTotalTimeStep(ControlData.defaultTimeStep)+"\n"); + out.write(ControlData.startDay+"\n"); + out.write(ControlData.startMonth+"\n"); + out.write(ControlData.startYear+"\n"); + out.write("SLP\n"); + out.write("CycleNumber\n"); + out.write("FALSE\n"); + out.write("NONE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write(" \n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("CALSIM\n"); + out.write(ControlData.initPartF+"\n"); + out.write(ControlData.svDvPartF+"\n"); + out.write("FALSE\n"); + out.write("TRUE\n"); + out.write("FALSE\n"); + out.write("SINGLE\n"); + out.write("NODEBUG\n"); + out.close(); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + public StudyDataSet parse()throws RecognitionException, IOException{ + + if (Error.getTotalError()>0){ + + System.out.println("============================================"); + System.out.println("Total errors in the config file: "+Error.getTotalError()); + System.out.println("============================================"); + + return null; + + } else if(StudyUtils.loadParserData) { + + StudyDataSet sds = StudyUtils.loadObject(StudyUtils.parserDataPath); + LoadParameter.process(sds); + if (ControlData.useCbcWarmStart || ControlData.cbcCheckIntErr || ControlData.cbc_debug_routeCbc || ControlData.cbc_debug_routeXA){ + if (ControlData.solverName.equalsIgnoreCase("Cbc") || ControlData.solverName.equalsIgnoreCase("Cbc1")){ + + Warmstart.collectIntegerDV_3(sds); + + } + } + return sds; + + } else if(StudyUtils.compileOnly) { + + return StudyUtils.compileStudy(FilePaths.fullMainPath); + + } else { + + return StudyUtils.checkStudy(FilePaths.fullMainPath); + + } + } + + + public void runModel(StudyDataSet sds){ + System.out.println("==============Run Study Start============"); + + if (ControlData.solverName.equalsIgnoreCase("Gurobi")){ + runModelGurobi(sds); + } else if (ControlData.solverName.equalsIgnoreCase("Glpk")){ + runModelOrTools(sds, "GLPK_MIXED_INTEGER_PROGRAMMING"); + } else if (ControlData.solverName.equalsIgnoreCase("Clp")){ + runModelClp(sds); + } else if (ControlData.solverName.equalsIgnoreCase("Cbc")&&(ControlData.cbc_debug_routeXA||ControlData.cbc_debug_routeCbc)){ + runModelCbc(sds); + } else if (ILP.logging){ + runModelILP(sds); + } else if (ControlData.solverName.equalsIgnoreCase("Cbc")){ + runModelCbc(sds); + } else if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG") ){ + runModelXA(sds); + } else { + Error.addConfigError("Solver name not recognized: "+ControlData.solverName); + Error.writeErrorLog(); + } + + WeightEval.outputWtTableAR(); + + if (Error.getTotalError()>0){ + System.out.println("=================Run ends with errors===="); + System.exit(1); + } else { + System.out.println("=================Run ends!================"); + } + } + public void runModelXA(StudyDataSet sds){ + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + new InitialXASolver(); + if (Error.getTotalError()>0){ + System.out.println("Model run exits due to error."); + System.exit(1); + } + + TimeOperation.initOutputDate(ControlData.yearOutputSection); + TimeOperation.initMemDate(ControlData.monMemSection); + + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + int sectionI=0; + time_marching: + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + if (ControlData.solverName.equalsIgnoreCase("XALOG")) SetXALog.enableXALog(); + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + int i=0; + while (i=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.writeErrorLog(); + noError=false;break time_marching; + } + new XASolver(); + + // check monitored dvar list. they are slack and surplus generated automatically + // from the weight group deviation penalty + // give error if they are not zero or greater than a small tolerance. + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.writeOneCycleSv(mds, cycleI); + } + } + if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); + if (Error.error_evaluation.size()>=1) noError=false; + try{ + if (enableConfigProgress) { + FileWriter progressFile = new FileWriter(StudyUtils.configFilePath+".prgss"); + PrintWriter pw = new PrintWriter(progressFile); + pw.println("Run to "+ControlData.currYear +"/"+ ControlData.currMonth +"/"+ ControlData.currDay); + pw.close(); + progressFile.close(); + }else if(enableProgressLog){ + FileWriter progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt"); + PrintWriter pw = new PrintWriter(progressFile); + int cy = 0; + if (ControlData.currYear > cy) { + cy = ControlData.currYear; + pw.println(ControlData.startYear + " " + ControlData.endYear + " " + ControlData.currYear +" "+ ControlData.currMonth); + pw.close(); + progressFile.close(); + } + } + }catch(IOException e){ + e.printStackTrace(); + } + + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + }else{ + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.skipOneCycle(mds, cycleI); + } + } + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); + new AssignPastCycleVariable(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + } + } + i=i+1; + } + Date date1= new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + Date date2= new Date(ControlData.outputYear-1900, ControlData.outputMonth-1, ControlData.outputDay); + if (ControlData.yearOutputSection>0 && date1.after(date2)){ + if (ControlData.writeInitToDVOutput && sectionI==0){ + DssOperation.writeInitDvarAliasToDSS(); + } + sectionI++; + DssOperation.writeDVAliasToDSS(); + TimeOperation.setMemDate(ControlData.monMemSection); + DssOperation.shiftData(); + TimeOperation.setOutputDate(ControlData.yearOutputSection); + } + VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); + VariableTimeStep.setCycleEndDate(sds); + } + ControlData.xasolver.close(); + + if (ControlData.yearOutputSection<0 && ControlData.writeInitToDVOutput) DssOperation.writeInitDvarAliasToDSS(); + DssOperation.writeDVAliasToDSS(); + ControlData.dvDss.close(); + if (ControlData.outputType==1){ + HDF5Writer.createDvarAliasLookup(); + HDF5Writer.writeTimestepData(); + HDF5Writer.writeCyclesDvAlias(); + HDF5Writer.closeDataStructure(); + }else if (ControlData.outputType==2){ + mySQLCWriter.process(); + }else if (ControlData.outputType==3){ + mySQLRWriter.process(); + }else if (ControlData.outputType==4){ + sqlServerRWriter.process(); + }else if (ControlData.outputType==5){ + CsvOperation co = new CsvOperation(); + co.ouputCSV(FilePaths.fullCsvPath, 0); + } + + // write complete or fail + if (enableProgressLog || enableConfigProgress) { + try { + FileWriter progressFile; + if (enableConfigProgress){ + progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); + }else{ + progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt", true); + } + PrintWriter pw = new PrintWriter(progressFile); + if (Error.getTotalError() > 0) { + pw.println("Run failed."); + } else { + pw.println("Run completed."); + } + pw.close(); + progressFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void writeOutputDssEveryTenYears(){ + if (ControlData.currMonth==12 && ControlData.currYear%10==0){ + if (ControlData.timeStep.equals("1MON")){ + DssOperation.writeDVAliasToDSS(); + }else if(ControlData.timeStep.equals("1DAY") && ControlData.currDay==31){ + DssOperation.writeDVAliasToDSS(); + } + } + } + + public static void main(String[] args){ + new ControllerBatch(args); + } + + public void runModelILP(StudyDataSet sds){ + + ILP.initializeIlp(); + + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + if (ControlData.solverName.equalsIgnoreCase("clp0")) { + ControlData.solverType = Param.SOLVER_CLP0; + // initiate clp0 + Clp0Solver.init(); + } else if (ControlData.solverName.equalsIgnoreCase("clp1")) { + ControlData.solverType = Param.SOLVER_CLP1; + // initiate clp + ClpSolver.init(true); + } else if (ControlData.solverName.equalsIgnoreCase("clp")) { + ControlData.solverType = Param.SOLVER_CLP; + // initiate clp + ClpSolver.init(false); + } else if (ControlData.solverName.equalsIgnoreCase("cbc0")) { + ControlData.solverType = Param.SOLVER_CBC0; + // initiate cbc0 + Cbc0Solver.init(); + } else if (ControlData.solverName.equalsIgnoreCase("cbc1")) { + ControlData.solverType = Param.SOLVER_CBC1; + // initiate cbc file passing jni + CbcSolver.init(true, sds); + } else if (ControlData.solverName.equalsIgnoreCase("cbc")) { + ControlData.solverType = Param.SOLVER_CBC; + // initiate cbc file passing jni + CbcSolver.init(false, sds); + } else if (ControlData.solverName.equalsIgnoreCase("lpsolve")) { + ControlData.solverType = Param.SOLVER_LPSOLVE; + // initiate lpsolve + } else if (ControlData.solverName.toLowerCase().contains("xa")) { + ControlData.solverType = Param.SOLVER_XA; //default + new InitialXASolver(); + } else { + Error.addConfigError("Solver name not recognized: "+ControlData.solverName); + Error.writeErrorLog(); + } + + TimeOperation.initOutputDate(ControlData.yearOutputSection); + TimeOperation.initMemDate(ControlData.monMemSection); + + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + int sectionI=0; + time_marching: + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + if (ControlData.solverType == Param.SOLVER_XA && ControlData.solverName.toLowerCase().contains("xalog")) SetXALog.enableXALog(); + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + int i=0; + while (i=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.writeErrorLog(); + noError=false;break time_marching; + } + + // choose solver to solve. TODO: this is not efficient. need to be done outside ILP + if (ControlData.solverType == Param.SOLVER_LPSOLVE.intValue()) { + LPSolveSolver.setLP(ILP.lpSolveFilePath); + LPSolveSolver.solve(); + if (Error.error_solving.size()<1) { + if (ILP.logging) { + ILP.writeObjValue_LPSOLVE(); + if (ILP.loggingVariableValue) ILP.writeDvarValue_LPSOLVE(); + } + } + // for cbc0 + } else if (ControlData.solverType == Param.SOLVER_CBC0.intValue()){ + + ILP.closeCplexLpFile(); // prevent double-locked by both wrims and ilp + + // send lp file path to cbc + Cbc0Solver.setLP(ILP.cplexLpFilePath); + + // call cbc solve + Cbc0Solver.solve(); + + + + // check solving errors and put them in Error.error_solving + if (Error.error_solving.size()<1) { + if (ILP.logging) { + + ILP.reOpenCplexLpFile(true); + // write objValue in lp file + ILP.writeObjValue_Clp0_Cbc0(); + if (ILP.loggingVariableValue) { + // TODO: write solution + ILP.writeDvarValue_Clp0_Cbc0(Cbc0Solver.varDoubleMap); + } + } + } + // for clp + } else if (ControlData.solverType == Param.SOLVER_CLP0.intValue()){ + + ILP.closeCplexLpFile(); // prevent double-locked by both wrims and ilp + + // send lp file path to clp + Clp0Solver.setLP(ILP.cplexLpFilePath); + + // call clp solve + Clp0Solver.solve(); + + + + // check solving errors and put them in Error.error_solving + if (Error.error_solving.size()<1) { + if (ILP.logging) { + + ILP.reOpenCplexLpFile(true); + // write objValue in lp file + ILP.writeObjValue_Clp0_Cbc0(); + if (ILP.loggingVariableValue) { + // TODO: write solution + ILP.writeDvarValue_Clp0_Cbc0(Clp0Solver.varDoubleMap); + } + } + } + } else if (ControlData.solverType == Param.SOLVER_CBC1.intValue()||ControlData.solverType == Param.SOLVER_CBC.intValue()){ + + if(!ControlData.useCplexLpString) ILP.closeCplexLpFile(); // prevent double-locked by both wrims and ilp + + + CbcSolver.newProblem(); + + // check solving errors and put them in Error.error_solving + if (Error.error_solving.size()<1) { + if (ILP.logging) { + + if(!ControlData.useCplexLpString) ILP.reOpenCplexLpFile(true); + // write objValue in lp file + ILP.writeObjValue_Clp0_Cbc0(); + if(ControlData.saveCplexLpStringToFile) ILP.saveCplexLpStringToFile(); + if (ILP.loggingVariableValue) { + // TODO: write solution + ILP.writeDvarValue_Clp0_Cbc0(CbcSolver.varDoubleMap); + } + } + } + + } else if (ControlData.solverType == Param.SOLVER_CLP1.intValue()){ + + ILP.closeCplexLpFile(); // prevent double-locked by both wrims and ilp + + // send lp file path to clp + ClpSolver.newProblem(ILP.cplexLpFilePath, true); + + // check solving errors and put them in Error.error_solving + if (Error.error_solving.size()<1) { + if (ILP.logging) { + + ILP.reOpenCplexLpFile(true); + // write objValue in lp file + ILP.writeObjValue_Clp0_Cbc0(); + if (ILP.loggingVariableValue) { + // TODO: write solution + ILP.writeDvarValue_Clp0_Cbc0(ClpSolver.varDoubleMap); + } + } + } + + } else { + + new XASolver(); + + if (ILP.logging) { + ILP.writeObjValue_XA(); + if (ILP.loggingVariableValue) ILP.writeDvarValue_XA(); + } + } + + + + ILP.closeIlpFile(); + + // check monitored dvar list. they are slack and surplus generated automatically + // from the weight group deviation penalty + // give error if they are not zero or greater than a small tolerance. + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.writeOneCycleSv(mds, cycleI); + } + } + if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); + if (Error.error_evaluation.size()>=1) noError=false; + try{ + if (enableConfigProgress) { + FileWriter progressFile = new FileWriter(StudyUtils.configFilePath+".prgss"); + PrintWriter pw = new PrintWriter(progressFile); + pw.println("Run to "+ControlData.currYear +"/"+ ControlData.currMonth +"/"+ ControlData.currDay); + pw.close(); + progressFile.close(); + }else if(enableProgressLog){ + FileWriter progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt"); + PrintWriter pw = new PrintWriter(progressFile); + int cy = 0; + if (ControlData.currYear > cy) { + cy = ControlData.currYear; + pw.println(ControlData.startYear + " " + ControlData.endYear + " " + ControlData.currYear +" "+ ControlData.currMonth); + pw.close(); + progressFile.close(); + } + } + }catch(IOException e){ + e.printStackTrace(); + } + + if (CbcSolver.intLog && ControlData.solverType == Param.SOLVER_CBC.intValue()) { + CbcSolver.logIntCheck(sds); + } + + if (ControlData.solverType == Param.SOLVER_CBC1.intValue()||ControlData.solverType == Param.SOLVER_CBC.intValue()) { CbcSolver.resetModel();} + + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + }else{ + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.skipOneCycle(mds, cycleI); + } + } + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); + new AssignPastCycleVariable(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + } + } + i=i+1; + } + Date date1= new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + Date date2= new Date(ControlData.outputYear-1900, ControlData.outputMonth-1, ControlData.outputDay); + if (ControlData.yearOutputSection>0 && date1.after(date2)){ + if (ControlData.writeInitToDVOutput && sectionI==0){ + DssOperation.writeInitDvarAliasToDSS(); + } + sectionI++; + DssOperation.writeDVAliasToDSS(); + TimeOperation.setMemDate(ControlData.monMemSection); + DssOperation.shiftData(); + TimeOperation.setOutputDate(ControlData.yearOutputSection); + } + VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); + VariableTimeStep.setCycleEndDate(sds); + } + if (ControlData.solverType == Param.SOLVER_LPSOLVE) { + //ControlData.lpssolver.deleteLp(); + } else if (ControlData.solverType == Param.SOLVER_CLP0) { + // close clp exe + } else if (ControlData.solverType == Param.SOLVER_CBC0) { + // close cbc exe + } else if (ControlData.solverType == Param.SOLVER_CBC || ControlData.solverType == Param.SOLVER_CBC1) { + CbcSolver.close(); + } else if (ControlData.solverType == Param.SOLVER_CLP1 || ControlData.solverType == Param.SOLVER_CLP) { + ClpSolver.close(); + } else { + ControlData.xasolver.close(); + } + + if (ControlData.yearOutputSection<0 && ControlData.writeInitToDVOutput) DssOperation.writeInitDvarAliasToDSS(); + DssOperation.writeDVAliasToDSS(); + ControlData.dvDss.close(); + if (ControlData.outputType==1){ + HDF5Writer.createDvarAliasLookup(); + HDF5Writer.writeTimestepData(); + HDF5Writer.writeCyclesDvAlias(); + HDF5Writer.closeDataStructure(); + }else if (ControlData.outputType==2){ + mySQLCWriter.process(); + }else if (ControlData.outputType==3){ + mySQLRWriter.process(); + }else if (ControlData.outputType==4){ + sqlServerRWriter.process(); + }else if (ControlData.outputType==5){ + CsvOperation co = new CsvOperation(); + co.ouputCSV(FilePaths.fullCsvPath, 0); + } + + // write complete or fail + if (enableProgressLog || enableConfigProgress) { + try { + FileWriter progressFile; + if (enableConfigProgress){ + progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); + }else{ + progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt", true); + } + PrintWriter pw = new PrintWriter(progressFile); + if (Error.getTotalError() > 0) { + pw.println("Run failed."); + } else { + pw.println("Run completed."); + } + pw.close(); + progressFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void runModelGurobi(StudyDataSet sds){ + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + + ILP.initializeIlp(); + GurobiSolver.initialize(); + + TimeOperation.initOutputDate(ControlData.yearOutputSection); + TimeOperation.initMemDate(ControlData.monMemSection); + int sectionI=0; + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + int i=0; + while (i=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.addSolvingError("evaluation error(s)"); + Error.writeErrorLog(); + noError=false; + } else { + ILP.setIlpFile(); + ILP.writeIlp(); + if (ILP.loggingVariableValue) { + ILP.setVarFile(); + ILP.writeSvarValue(); + } + GurobiSolver.setLp(ILP.cplexLpFilePath); + GurobiSolver.solve(); + } + + // check monitored dvar list. they are slack and surplus generated automatically + // from the weight group deviation penalty + // give error if they are not zero or greater than a small tolerance. + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + + ILP.writeObjValue_Gurobi(); + if (ILP.loggingVariableValue) ILP.writeDvarValue_Gurobi(); + + ILP.closeIlpFile(); + + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.writeOneCycleSv(mds, cycleI); + } + } + if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); + if (Error.error_evaluation.size()>=1) noError=false; + try{ + if (enableConfigProgress) { + FileWriter progressFile = new FileWriter(StudyUtils.configFilePath+".prgss"); + PrintWriter pw = new PrintWriter(progressFile); + pw.println("Run to "+ControlData.currYear +"/"+ ControlData.currMonth +"/"+ ControlData.currDay); + pw.close(); + progressFile.close(); + }else if(enableProgressLog){ + FileWriter progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt"); + PrintWriter pw = new PrintWriter(progressFile); + int cy = 0; + if (ControlData.currYear > cy) { + cy = ControlData.currYear; + pw.println(ControlData.startYear + " " + ControlData.endYear + " " + ControlData.currYear +" "+ ControlData.currMonth); + pw.close(); + progressFile.close(); + } + } + }catch(IOException e){ + e.printStackTrace(); + } + + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + }else{ + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.skipOneCycle(mds, cycleI); + } + } + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); + new AssignPastCycleVariable(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + } + } + i=i+1; + } + Date date1= new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + Date date2= new Date(ControlData.outputYear-1900, ControlData.outputMonth-1, ControlData.outputDay); + if (ControlData.yearOutputSection>0 && date1.after(date2)){ + if (ControlData.writeInitToDVOutput && sectionI==0){ + DssOperation.writeInitDvarAliasToDSS(); + } + sectionI++; + DssOperation.writeDVAliasToDSS(); + TimeOperation.setMemDate(ControlData.monMemSection); + DssOperation.shiftData(); + TimeOperation.setOutputDate(ControlData.yearOutputSection); + } + VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); + VariableTimeStep.setCycleEndDate(sds); + } + GurobiSolver.dispose(); + + if (ControlData.yearOutputSection<0 && ControlData.writeInitToDVOutput) DssOperation.writeInitDvarAliasToDSS(); + DssOperation.writeDVAliasToDSS(); + ControlData.dvDss.close(); + if (ControlData.outputType==1){ + HDF5Writer.createDvarAliasLookup(); + HDF5Writer.writeTimestepData(); + HDF5Writer.writeCyclesDvAlias(); + HDF5Writer.closeDataStructure(); + }else if (ControlData.outputType==2){ + mySQLCWriter.process(); + }else if (ControlData.outputType==3){ + mySQLRWriter.process(); + }else if (ControlData.outputType==4){ + sqlServerRWriter.process(); + }else if (ControlData.outputType==5){ + CsvOperation co = new CsvOperation(); + co.ouputCSV(FilePaths.fullCsvPath, 0); + } + + // write complete or fail + if (enableProgressLog || enableConfigProgress) { + try { + FileWriter progressFile; + if (enableConfigProgress){ + progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); + }else{ + progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt", true); + } + PrintWriter pw = new PrintWriter(progressFile); + if (Error.getTotalError() > 0) { + pw.println("Run failed."); + } else { + pw.println("Run completed."); + } + pw.close(); + progressFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void runModelGurobiTest(StudyDataSet sds){ + + + File ilpRootDir = new File(FilePaths.mainDirectory, "=ILP="); + File ilpDir = new File(ilpRootDir, StudyUtils.configFileName); + File cplexLpDir = new File(ilpDir,"cplexlp_input"); + PrintWriter objValueFile = null; + try { + objValueFile = Tools.openFile(ilpDir.getAbsolutePath(), "ObjValues.log"); + } + catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + GurobiSolver.initialize(); + + //while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + for (int year = ControlData.startYear; year <= ControlData.endYear; year++) { + + for (int month = 1; month <= 12; month++) { + + for (int cycle = 1; cycle <= sds.getModelList().size(); cycle++) { + + String twoDigitMonth = String.format("%02d", month); + String twoDigitCycle = String.format("%02d", cycle); + String lpFileName = year + "_" + twoDigitMonth + "_c" + twoDigitCycle + ".lp"; + + String msg = year + "_" + twoDigitMonth + "_c" + twoDigitCycle; + + File lpFile = new File(cplexLpDir, lpFileName); + + if (lpFile.exists()){ + + GurobiSolver.setLp(lpFile.getAbsolutePath()); + GurobiSolver.solve(); + + double objValue = ControlData.gurobi_objective; + String objValueStr = Double.toString(objValue); + + ILP.writeObjValueLog(msg, objValueStr, objValueFile); + + } + + } + } + } + + GurobiSolver.dispose(); + + } + + public void runModelOrTools(StudyDataSet sds, String mpSolverType){ + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + + if (ILP.logging) ILP.initializeIlp(); + OrToolsSolver.initialize(); + ControlData.otsolver = new OrToolsSolver(mpSolverType); + + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + int i=0; + while (i=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.addSolvingError("evaluation error(s)"); + Error.writeErrorLog(); + noError=false; + } else { + + MPModel m = ControlData.otsolver.createModel(); + + if (Error.error_solving.size()>=1){ + Error.writeErrorLog(); + noError=false; + break; + } + + + if (ILP.logging) { + ILP.setIlpFile(); + if (ILP.loggingMPModel) ILP.writeMPModelFile(m); + ILP.writeIlp(); + if (ILP.loggingVariableValue) { + ILP.setVarFile(); + ILP.writeSvarValue(); + } + } + + ControlData.otsolver.run(); + } + + // check monitored dvar list. they are slack and surplus generated automatically + // from the weight group deviation penalty + // give error if they are not zero or greater than a small tolerance. + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + + if (ILP.logging) { + ILP.writeObjValue_OrTools(); + if (ILP.loggingVariableValue) ILP.writeDvarValue_OrTools(); + + ILP.closeIlpFile(); + } + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.writeOneCycleSv(mds, cycleI); + } + } + if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); + if (Error.error_evaluation.size()>=1) noError=false; + + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + }else{ + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.skipOneCycle(mds, cycleI); + } + } + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); + new AssignPastCycleVariable(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + } + } + i=i+1; + } + VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); + VariableTimeStep.setCycleEndDate(sds); + } + ControlData.otsolver.delete(); + + if (ControlData.writeInitToDVOutput){ + DssOperation.writeInitDvarAliasToDSS(); + } + DssOperation.writeDVAliasToDSS(); + ControlData.dvDss.close(); + if (ControlData.outputType==1){ + HDF5Writer.createDvarAliasLookup(); + HDF5Writer.writeTimestepData(); + HDF5Writer.writeCyclesDvAlias(); + HDF5Writer.closeDataStructure(); + }else if (ControlData.outputType==2){ + mySQLCWriter.process(); + }else if (ControlData.outputType==3){ + mySQLRWriter.process(); + }else if (ControlData.outputType==4){ + sqlServerRWriter.process(); + }else if (ControlData.outputType==5){ + CsvOperation co = new CsvOperation(); + co.ouputCSV(FilePaths.fullCsvPath, 0); + } + } + + public void runModelClp(StudyDataSet sds){ + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + ClpSolver.init(false); + + if (Error.getTotalError()>0){ + System.out.println("Model run exits due to error."); + System.exit(1); + } + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + int i=0; + while (i=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.writeErrorLog(); + noError=false; + } + String lpProblemlName = ControlData.currYear+"_"+ControlData.currMonth+"_c"+(ControlData.currCycleIndex+1); + + ClpSolver.newProblem(lpProblemlName, false); + + // check monitored dvar list. they are slack and surplus generated automatically + // from the weight group deviation penalty + // give error if they are not zero or greater than a small tolerance. + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.writeOneCycleSv(mds, cycleI); + } + } + if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); + if (Error.error_evaluation.size()>=1) noError=false; + try{ + if (enableConfigProgress) { + FileWriter progressFile = new FileWriter(StudyUtils.configFilePath+".prgss"); + PrintWriter pw = new PrintWriter(progressFile); + pw.println("Run to "+ControlData.currYear +"/"+ ControlData.currMonth +"/"+ ControlData.currDay); + pw.close(); + progressFile.close(); + }else if(enableProgressLog){ + FileWriter progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt"); + PrintWriter pw = new PrintWriter(progressFile); + int cy = 0; + if (ControlData.currYear > cy) { + cy = ControlData.currYear; + pw.println(ControlData.startYear + " " + ControlData.endYear + " " + ControlData.currYear +" "+ ControlData.currMonth); + pw.close(); + progressFile.close(); + } + } + }catch(IOException e){ + e.printStackTrace(); + } + + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + }else{ + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.skipOneCycle(mds, cycleI); + } + } + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); + new AssignPastCycleVariable(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + } + } + i=i+1; + } + VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); + VariableTimeStep.setCycleEndDate(sds); + + } + ClpSolver.close(); + + if (ControlData.writeInitToDVOutput){ + DssOperation.writeInitDvarAliasToDSS(); + } + DssOperation.writeDVAliasToDSS(); + ControlData.dvDss.close(); + if (ControlData.outputType==1){ + HDF5Writer.createDvarAliasLookup(); + HDF5Writer.writeTimestepData(); + HDF5Writer.writeCyclesDvAlias(); + HDF5Writer.closeDataStructure(); + }else if (ControlData.outputType==2){ + mySQLCWriter.process(); + }else if (ControlData.outputType==3){ + mySQLRWriter.process(); + }else if (ControlData.outputType==4){ + sqlServerRWriter.process(); + }else if (ControlData.outputType==5){ + CsvOperation co = new CsvOperation(); + co.ouputCSV(FilePaths.fullCsvPath, 0); + } + + // write complete or fail + if (enableProgressLog || enableConfigProgress) { + try { + FileWriter progressFile; + if (enableConfigProgress){ + progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); + }else{ + progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt", true); + } + PrintWriter pw = new PrintWriter(progressFile); + if (Error.getTotalError() > 0) { + pw.println("Run failed."); + } else { + pw.println("Run completed."); + } + pw.close(); + progressFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void runModelCbc(StudyDataSet sds){ + + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + CbcSolver.init(false, sds); if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) {new InitialXASolver();} + if (Error.getTotalError()>0){ + System.out.println("Model run exits due to error."); + System.exit(1); + } + + TimeOperation.initOutputDate(ControlData.yearOutputSection); + TimeOperation.initMemDate(ControlData.monMemSection); + + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + int sectionI=0; + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + int i=0; + while (i=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.writeErrorLog(); + noError=false;break time_marching; + } + + HashSet originalDvarKeys=null; + + if (ControlData.cbc_debug_routeCbc || ControlData.cbc_debug_routeXA) { + originalDvarKeys = new LinkedHashSet(SolverData.getDvarMap().keySet()); +// ILP.getIlpDir(); +// ILP.setVarDir(); + ILP.setSvarFile(); +// ILP.setMaximumFractionDigits(); + // write svar + ILP.writeSvarValue(); + } + + if (ControlData.cbc_debug_routeCbc) { + new XASolver(); + SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); + if (Error.error_solving.size() > 0) { + String msg = "XA solving error."; + ILP.writeNoteLn("", msg); + System.out.println("" + msg); + Error.writeErrorLog(); + Error.error_solving.clear(); + } + + } + + CbcSolver.newProblem(); + + if (ControlData.cbc_debug_routeXA) { + SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); + new XASolver(); + } + + // check monitored dvar list. they are slack and surplus generated automatically + // from the weight group deviation penalty + // give error if they are not zero or greater than a small tolerance. + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.writeOneCycleSv(mds, cycleI); + } + } + if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); + if (Error.error_evaluation.size()>=1) noError=false; + try{ + if (enableConfigProgress) { + FileWriter progressFile = new FileWriter(StudyUtils.configFilePath+".prgss"); + PrintWriter pw = new PrintWriter(progressFile); + pw.println("Run to "+ControlData.currYear +"/"+ ControlData.currMonth +"/"+ ControlData.currDay); + pw.close(); + progressFile.close(); + }else if(enableProgressLog){ + FileWriter progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt"); + PrintWriter pw = new PrintWriter(progressFile); + int cy = 0; + if (ControlData.currYear > cy) { + cy = ControlData.currYear; + pw.println(ControlData.startYear + " " + ControlData.endYear + " " + ControlData.currYear +" "+ ControlData.currMonth); + pw.close(); + progressFile.close(); + } + } + }catch(IOException e){ + e.printStackTrace(); + } + + //if (CbcSolver.intLog && (!ControlData.cbc_debug_routeXA && !ControlData.cbc_debug_routeCbc)) { + if (CbcSolver.intLog) { + CbcSolver.logIntCheck(sds); + } + + if (ControlData.cbc_debug_routeXA ||ControlData.cbc_debug_routeCbc ) { + CbcSolver.logCbcDebug(sds); + } else if (ControlData.watchList!=null) { + CbcSolver.logCbcWatchList(sds); + } + + CbcSolver.resetModel(); + + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + }else{ + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.skipOneCycle(mds, cycleI); + } + } + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Skipped. ("+model+")"); + new AssignPastCycleVariable(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + } + } + i=i+1; + } + Date date1= new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + Date date2= new Date(ControlData.outputYear-1900, ControlData.outputMonth-1, ControlData.outputDay); + if (ControlData.yearOutputSection>0 && date1.after(date2)){ + if (ControlData.writeInitToDVOutput && sectionI==0){ + DssOperation.writeInitDvarAliasToDSS(); + } + sectionI++; + DssOperation.writeDVAliasToDSS(); + TimeOperation.setMemDate(ControlData.monMemSection); + DssOperation.shiftData(); + TimeOperation.setOutputDate(ControlData.yearOutputSection); + } + VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); + VariableTimeStep.setCycleEndDate(sds); + } + CbcSolver.close(); if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) {ControlData.xasolver.close();} + + if (ControlData.yearOutputSection<0 && ControlData.writeInitToDVOutput) DssOperation.writeInitDvarAliasToDSS(); + DssOperation.writeDVAliasToDSS(); + ControlData.dvDss.close(); + if (ControlData.outputType==1){ + HDF5Writer.createDvarAliasLookup(); + HDF5Writer.writeTimestepData(); + HDF5Writer.writeCyclesDvAlias(); + HDF5Writer.closeDataStructure(); + }else if (ControlData.outputType==2){ + mySQLCWriter.process(); + }else if (ControlData.outputType==3){ + mySQLRWriter.process(); + }else if (ControlData.outputType==4){ + sqlServerRWriter.process(); + }else if (ControlData.outputType==5){ + CsvOperation co = new CsvOperation(); + co.ouputCSV(FilePaths.fullCsvPath, 0); + } + + // write complete or fail + if (enableProgressLog || enableConfigProgress) { + try { + FileWriter progressFile; + if (enableConfigProgress){ + progressFile= new FileWriter(StudyUtils.configFilePath+".prgss"); + }else{ + progressFile= new FileWriter(FilePaths.mainDirectory + "progress.txt", true); + } + PrintWriter pw = new PrintWriter(progressFile); + if (Error.getTotalError() > 0) { + pw.println("Run failed."); + } else { + pw.println("Run completed."); + } + pw.close(); + progressFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void connectToDataBase(){ + if (ControlData.outputType==2){ + mySQLCWriter=new MySQLCWriter(); + }else if (ControlData.outputType==3){ + mySQLRWriter=new MySQLRWriter(); + }else if (ControlData.outputType==4){ + sqlServerRWriter=new SQLServerRWriter(); + } + } + + public void procLaunch(String[] args){ + String launchFilePath = args[0].substring(args[0].indexOf("=") + 1, args[0].length()); + new LaunchConfiguration(launchFilePath); + } } \ No newline at end of file diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/ControllerDebug.java b/wrims-core/src/main/java/wrimsv2/components/ControllerDebug.java similarity index 93% rename from wrims_v2/wrims_v2/src/wrimsv2/components/ControllerDebug.java rename to wrims-core/src/main/java/wrimsv2/components/ControllerDebug.java index 69524ec76..492d5defb 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/ControllerDebug.java +++ b/wrims-core/src/main/java/wrimsv2/components/ControllerDebug.java @@ -1,742 +1,712 @@ -package wrimsv2.components; - -import gurobi.GRBException; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Date; -import java.util.Set; - -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; - -import com.sunsetsoft.xa.Optimizer; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.External; -import wrimsv2.commondata.wresldata.Goal; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.commondata.wresldata.Timeseries; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.config.ConfigUtils; -import wrimsv2.debug.ReProcessExternal; -import wrimsv2.evaluator.AssignPastCycleVariable; -import wrimsv2.evaluator.CsvOperation; -import wrimsv2.evaluator.DataTimeSeries; -import wrimsv2.evaluator.DssDataSet; -import wrimsv2.evaluator.DssDataSetFixLength; -import wrimsv2.evaluator.DssOperation; -import wrimsv2.evaluator.EvalConstraint; -import wrimsv2.evaluator.EvalExpression; -import wrimsv2.evaluator.Evaluation; -import wrimsv2.evaluator.EvaluatorLexer; -import wrimsv2.evaluator.EvaluatorParser; -import wrimsv2.evaluator.PreEvaluator; -import wrimsv2.evaluator.TimeOperation; -import wrimsv2.evaluator.ValueEvaluation; -import wrimsv2.evaluator.ValueEvaluatorLexer; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.evaluator.WeightEval; -import wrimsv2.external.LoadAllDll; -import wrimsv2.hdf5.HDF5Writer; -import wrimsv2.ilp.ILP; -import wrimsv2.launch.LaunchConfiguration; -import wrimsv2.parallel.ParallelVars; -import wrimsv2.solver.CbcSolver; -import wrimsv2.solver.CloseCurrentSolver; -import wrimsv2.solver.LPSolveSolver; -import wrimsv2.solver.XASolver; -import wrimsv2.solver.SetXALog; -import wrimsv2.solver.InitialXASolver; -import wrimsv2.solver.Gurobi.GurobiSolver; -import wrimsv2.sql.DataBaseProfile; -import wrimsv2.sql.MySQLCWriter; -import wrimsv2.sql.MySQLRWriter; -import wrimsv2.sql.SQLServerRWriter; -import wrimsv2.tools.General; -import wrimsv2.tools.RCCComparison; -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslparser.elements.StudyConfig; -import wrimsv2.wreslparser.elements.StudyParser; -import wrimsv2.wreslparser.elements.StudyUtils; -import wrimsv2.wreslparser.elements.TempData; -import wrimsv2.wreslparser.elements.WriteCSV; -import wrimsv2.wreslplus.elements.procedures.ErrorCheck; -import lpsolve.*; - -public class ControllerDebug extends Thread { - private DebugInterface di; - public int debugYear; - public int debugMonth; - public int debugDay; - public int debugCycle; - public int totalCycles=0; - public String conditionalBreakpoint; - public ValueEvaluatorParser conditionalBreakpointParser; - public String[] args; - public int modelIndex; - public static ArrayList initialTimeStep; - - private MySQLCWriter mySQLCWriter; - private MySQLRWriter mySQLRWriter; - private SQLServerRWriter sqlServerRWriter; - - public ControllerDebug(String[] args, DebugInterface di) { - this.di=di; - this.args=args; - } - - @Override - public void run() { - new DataBaseProfile(args); - if (args[0].toLowerCase().startsWith("-launch")){ - procLaunch(args); - }else{ - ConfigUtils.loadArgs(args); - } - if (ILP.loggingUsageMemeory) General.getPID(); - connectToDataBase(); - //generateStudyFile(); - try { - long t1 = Calendar.getInstance().getTimeInMillis(); - StudyDataSet sds = parse(); - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_parse=ControlData.t_parse+(int) (t2-t1); - if (StudyParser.total_errors==0){ - if (!StudyUtils.loadParserData && !FilePaths.fullMainPath.endsWith(".par")){ - StudyUtils.writeObj(sds, FilePaths.mainDirectory+File.separator+StudyUtils.configFileName+".par"); - } - totalCycles=sds.getModelList().size(); - di.sendEvent("totalcycle#"+totalCycles); - new PreEvaluator(sds); - runModel(sds); - } - } catch (RecognitionException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - di.isDebugging=false; - try { - di.sendEvent("terminate"); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void setControlData(String[] args){ - FilePaths.groundwaterDir=args[0]; - FilePaths.setMainFilePaths(args[1]); - FilePaths.setSvarFilePaths(args[2]); - FilePaths.setInitFilePaths(args[3]); - FilePaths.setDvarFilePaths(args[4]); - ControlData cd=new ControlData(); - cd.svDvPartF=args[5]; - cd.initPartF=args[6]; - cd.partA = args[7]; - cd.defaultTimeStep = args[8]; - cd.startYear=Integer.parseInt(args[9]); - cd.startMonth=Integer.parseInt(args[10]); - cd.startDay=Integer.parseInt(args[11]); - cd.endYear=Integer.parseInt(args[12]); - cd.endMonth=Integer.parseInt(args[13]); - cd.endDay=Integer.parseInt(args[14]); - cd.solverName=args[15]; - FilePaths.csvFolderName = args[16]; - cd.currYear=cd.startYear; - cd.currMonth=cd.startMonth; - cd.currDay=cd.startDay; - } - - public void generateStudyFile(){ - String outPath=System.getenv("temp_wrims2")+"\\study.sty"; - FileWriter outstream; - try { - outstream = new FileWriter(outPath); - BufferedWriter out = new BufferedWriter(outstream); - out.write("Study File: Generated by WRIMS. Do Not Edit!\n"); - out.write("Study Name\n"); - out.write("Author\n"); - out.write("Time\n"); - out.write("Note\n"); - out.write("Version\n"); - out.write(FilePaths.groundwaterDir+"\n"); - out.write("StudyFileFullPath\n"); - out.write(FilePaths.fullMainPath+"\n"); - out.write(FilePaths.fullSvarFilePath+"\n"); - out.write(FilePaths.fullDvarDssPath+"\n"); - out.write(FilePaths.fullInitFilePath+"\n"); - out.write(ControlData.defaultTimeStep+"\n"); - out.write(VariableTimeStep.getTotalTimeStep(ControlData.defaultTimeStep)+"\n"); - out.write(ControlData.startDay+"\n"); - out.write(ControlData.startMonth+"\n"); - out.write(ControlData.startYear+"\n"); - out.write("SLP\n"); - out.write("CycleNumber\n"); - out.write("FALSE\n"); - out.write("NONE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write(" \n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("CALSIM\n"); - out.write(ControlData.initPartF+"\n"); - out.write(ControlData.svDvPartF+"\n"); - out.write("FALSE\n"); - out.write("TRUE\n"); - out.write("FALSE\n"); - out.write("SINGLE\n"); - out.write("NODEBUG\n"); - out.close(); - - } catch (IOException e) { - e.printStackTrace(); - } - } - - public StudyDataSet parse()throws RecognitionException, IOException{ - if(StudyUtils.loadParserData) { - StudyDataSet sds = StudyUtils.loadObject(StudyUtils.parserDataPath); - LoadParameter.process(sds); - return sds; - }else{ - return StudyUtils.checkStudy(FilePaths.fullMainPath); - } - } - - public void runModel(StudyDataSet sds){ - System.out.println("=============Prepare Run Study==========="); - new PreRunModel(sds); - System.out.println("==============Run Study Start============"); - if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG") || ControlData.solverName.equalsIgnoreCase("CBC") || ControlData.solverName.equalsIgnoreCase("Gurobi")){ - runModelSolvers(sds); - }else{ - Error.addConfigError("Solver name not recognized: "+ControlData.solverName); - Error.writeErrorLog(); - if (ControlData.outputType!=1) ControlData.dvDss.close(); - return; - } - if (ControlData.showTimeUsage) new TimeUsage(); - System.out.println("=================Run ends!================"); - } - - public void runModelSolvers(StudyDataSet sds){ - - ILP.getIlpDir(); - ILP.setVarDir(); - ILP.createNoteFile(); - ILP.setMaximumFractionDigits(); - ILP.initializeIlp(); - - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG")) { - new InitialXASolver(); - if (Error.getTotalError()>0){ - System.out.println("Model run suspends due to error."); - di.handleRequest("suspend"); - } - }else if (ControlData.solverName.equalsIgnoreCase("CBC")){ - CbcSolver.init(false, sds); - if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) {new InitialXASolver();} - }else if (ControlData.solverName.equalsIgnoreCase("Gurobi")){ - GurobiSolver.initialize(); - } - - TimeOperation.initOutputDate(ControlData.yearOutputSection); - TimeOperation.initMemDate(ControlData.monMemSection); - - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - int sectionI=0; - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - if (ControlData.solverName.equalsIgnoreCase("XALOG")) SetXALog.enableXALog(); - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - modelIndex=0; - prepareInitialTimeStep(); - while (modelIndex=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.writeErrorLog(); - noError=false; - } - - if (ControlData.solverName.equalsIgnoreCase("XA")) { - new XASolver(); - }else if (ControlData.solverName.equalsIgnoreCase("XALOG")){ - if (isSelectedCycleOutput){ - ILP.setIlpFile(); - ILP.writeIlp(); - ILP.setVarFile(); - ILP.writeSvarValue(); - } - new XASolver(); - ILP.writeObjValue_XA(); - ILP.writeDvarValue_XA(); - }else if (ControlData.solverName.equalsIgnoreCase("CBC")){ - HashSet originalDvarKeys=null; - if (ControlData.cbc_debug_routeCbc || ControlData.cbc_debug_routeXA) { - originalDvarKeys = new LinkedHashSet(SolverData.getDvarMap().keySet()); -// ILP.getIlpDir(); -// ILP.setVarDir(); - ILP.setSvarFile(); -// ILP.setMaximumFractionDigits(); - // write svar - ILP.writeSvarValue(); - }else if (ILP.logging) { - ILP.setIlpFile(); - ILP.writeIlp(); - if (ILP.loggingVariableValue){ - ILP.setVarFile(); - ILP.writeSvarValue(); - } - } - - if (ControlData.cbc_debug_routeCbc) { - new XASolver(); - SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); - if (Error.error_solving.size() > 0) { - String msg = "XA solving error."; - ILP.writeNoteLn("", msg); - System.out.println("" + msg); - Error.writeErrorLog(); - Error.error_solving.clear(); - } - - } - - CbcSolver.newProblem(); - - if (ControlData.cbc_debug_routeXA) { - SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); - new XASolver(); - } - - if (ControlData.cbc_debug_routeXA ||ControlData.cbc_debug_routeCbc ) { - CbcSolver.logCbcDebug(sds); - }else if (ControlData.watchList.length>0) { - CbcSolver.logCbcWatchList(sds); - }else if (Error.error_solving.size()<1) { - if (ILP.logging) { - ILP.writeObjValue_Clp0_Cbc0(); - if (ILP.loggingVariableValue) ILP.writeDvarValue_Clp0_Cbc0(CbcSolver.varDoubleMap); - } - } - }else if (ControlData.solverName.equalsIgnoreCase("LPSolve")) { - ILP.setIlpFile(); - ILP.writeIlp(); - if (ILP.loggingVariableValue) { - ILP.setVarFile(); - ILP.writeSvarValue(); - } - LPSolveSolver.setLP(ILP.lpSolveFilePath); - LPSolveSolver.solve(); - if (Error.error_solving.size()<1) { - if (ILP.logging) { - ILP.writeObjValue_LPSOLVE(); - if (ILP.loggingVariableValue) ILP.writeDvarValue_LPSOLVE(); - } - } - }else if (ControlData.solverName.equalsIgnoreCase("Gurobi")){ - ILP.setIlpFile(); - ILP.writeIlp(); - if (ILP.loggingVariableValue) { - ILP.setVarFile(); - ILP.writeSvarValue(); - } - GurobiSolver.setLp(ILP.cplexLpFilePath); - GurobiSolver.solve(); - if (Error.error_solving.size()<1) { - if (ILP.logging) { - ILP.writeObjValue_LPSOLVE(); - if (ILP.loggingVariableValue) ILP.writeDvarValue_Gurobi(); - } - } - } - ILP.closeIlpFile(); - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.writeOneCycleSv(mds, cycleI); - } - } - if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); - if (CbcSolver.intLog && ControlData.solverName.equalsIgnoreCase("CBC")) { - CbcSolver.logIntCheck(sds); - } - if (ControlData.solverName.equalsIgnoreCase("CBC")){CbcSolver.resetModel();} - pauseForDebug(modelIndex); - if (Error.error_evaluation.size()>=1) noError=false; - if (Error.getTotalError()==0) noError=true; - //if (ControlData.currTimeStep==0 && ControlData.currCycleIndex==2) new RCCComparison(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - }else{ - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.skipOneCycle(mds, cycleI); - } - } - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" skipped. ("+model+")"); - new AssignPastCycleVariable(); - deferPause(modelIndex); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - } - } - modelIndex=modelIndex+1; - } - Date date1= new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - Date date2= new Date(ControlData.outputYear-1900, ControlData.outputMonth-1, ControlData.outputDay); - if (ControlData.yearOutputSection>0 && date1.after(date2)){ - if (ControlData.writeInitToDVOutput && sectionI==0){ - DssOperation.writeInitDvarAliasToDSS(); - } - sectionI++; - DssOperation.writeDVAliasToDSS(); - TimeOperation.setMemDate(ControlData.monMemSection); - DssOperation.shiftData(); - TimeOperation.setOutputDate(ControlData.yearOutputSection); - } - updateVarMonitor(); - if (ControlData.resimDate){ - ControlData.resimDate=false; - noError=true; - sds=ControlData.currStudyDataSet; - modelList=sds.getModelList(); - modelDataSetMap=sds.getModelDataSetMap(); - modelConditionParsers=sds.getModelConditionParsers(); - new ReProcessExternal(sds); - resetStartDate(sds); - } - VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); - VariableTimeStep.setCycleEndDate(sds); - } - new CloseCurrentSolver(ControlData.solverName); - - if (ControlData.yearOutputSection<0 && ControlData.writeInitToDVOutput) DssOperation.writeInitDvarAliasToDSS(); - DssOperation.writeDVAliasToDSS(); - ControlData.dvDss.close(); - if (ControlData.outputType==1){ - HDF5Writer.createDvarAliasLookup(); - HDF5Writer.writeTimestepData(); - HDF5Writer.writeCyclesDvAlias(); - HDF5Writer.closeDataStructure(); - }else if (ControlData.outputType==2){ - mySQLCWriter.process(); - }else if (ControlData.outputType==3){ - mySQLRWriter.process(); - }else if (ControlData.outputType==4){ - sqlServerRWriter.process(); - }else if (ControlData.outputType==5){ - CsvOperation co = new CsvOperation(); - co.ouputCSV(FilePaths.fullCsvPath, 0); - } - - WeightEval.outputWtTableAR(); - } - - public void prepareInitialTimeStep(){ - initialTimeStep=new ArrayList(); - for (Integer timeStep: ControlData.currTimeStep){ - initialTimeStep.add(timeStep.intValue()); - } - } - - public void resetStartDate(StudyDataSet sds){ - int diffTimeStep; - VariableTimeStep.procCycleTimeStep(sds); - for(int i=0; i0){ - try { - int cycle=ControlData.currCycleIndex+1; - di.sendEvent("suspended!"+ControlData.currYear+"#"+ControlData.currMonth+"#"+ControlData.currDay+"#"+cycle); - System.out.println("Error! Paused"); - } catch (IOException e) { - e.printStackTrace(); - } - this.suspend(); - }else{ - checkConditionalBreakpoint(); - } - } - - public void deferPause(int i){ - if (ControlData.timeStep.equals("1MON")){ - if (ControlData.currYear==debugYear && ControlData.currMonth==debugMonth && i==debugCycle-1){ - debugCycle=debugCycle+1; - if (debugCycle>totalCycles){ - debugCycle=1; - debugTimeAddOneMonth(); - } - } - }else{ - if (ControlData.currYear==debugYear && ControlData.currMonth==debugMonth && ControlData.currDay==debugDay && i==debugCycle-1){ - debugCycle=debugCycle+1; - if (debugCycle>totalCycles){ - debugCycle=1; - debugTimeAddOneDay(); - } - } - } - } - - - public void debugTimeAddOneMonth(){ - debugMonth=debugMonth+1; - if (debugMonth>12){ - debugMonth=debugMonth-12; - debugYear=debugYear+1; - } - debugDay=TimeOperation.numberOfDays(debugMonth, debugYear); - } - - public void debugTimeAddOneDay(){ - Date debugDate = new Date (debugYear-1900, debugMonth-1, debugDay); - Calendar c = Calendar.getInstance(); - c.setTime(debugDate); - c.add(Calendar.DATE, 1); - debugDate = c.getTime(); - debugMonth=debugDate.getMonth()+1; - debugYear=debugDate.getYear()+1900; - debugDay=debugDate.getDate(); - } - - private void checkConditionalBreakpoint() { - boolean condition=false; - ControlData.currEvalTypeIndex=1000; - if (conditionalBreakpointParser!=null){ - try{ - conditionalBreakpointParser.evaluator(); - condition=conditionalBreakpointParser.evalCondition; - }catch (Exception e){ - condition=false; - } - - conditionalBreakpointParser.reset(); - Error.error_evaluation.clear(); - } - - if (condition){ - try { - di.sendEvent("suspended!"+debugYear+"#"+debugMonth+"#"+debugDay+"#"+debugCycle); - System.out.println("conditional breakpoint of " + conditionalBreakpoint + " reached"); - System.out.println("paused"); - } catch (IOException e) { - e.printStackTrace(); - } - this.suspend(); - } - } - - public void updateVarMonitor(){ - String dataString="updateVarMonitor!"; - for (int k=0; k dvAliasTSMap = DataTimeSeries.dvAliasTS; - - if (dvAliasTSMap.containsKey(entryName)){ - DssDataSetFixLength ddsf = dvAliasTSMap.get(entryName); - double[] dataArray = ddsf.getData(); - ParallelVars prvs = TimeOperation.findTime(-1); - int currIndex; - if (monitorVarTimeStep.equals("1MON")){ - currIndex=ValueEvaluation.timeSeriesIndex(ddsf, prvs)-1; - }else{ - currIndex=ValueEvaluation.timeSeriesIndex(ddsf, prvs)-2; - } - for (int i=0; i<=currIndex; i++){ - double value=dataArray[i]; - if (!(value==-901.0 || value==-902.0)){ - int timestepListed=i-currIndex; - prvs = TimeOperation.findTime(timestepListed); - dataString=dataString+timestepListed+":"+prvs.dataMonth+"-"+prvs.dataDay+"-"+prvs.dataYear+":"+di.df.format(value)+"#"; - } - } - }else{ - HashMap svTSMap = DataTimeSeries.svTS; - if (svTSMap.containsKey(entryName)){ - DssDataSet dds = svTSMap.get(entryName); - ArrayList dataArrayList = dds.getData(); - ParallelVars prvs = TimeOperation.findTime(-1); - int currIndex=ValueEvaluation.timeSeriesIndex(dds, prvs); - for (int i=0; i<=currIndex; i++){ - double value=dataArrayList.get(i); - if (!(value==-901.0 || value==-902.0)){ - int timestepListed=i-currIndex; - prvs = TimeOperation.findTime(timestepListed); - dataString=dataString+timestepListed+":"+prvs.dataMonth+"-"+prvs.dataDay+"-"+prvs.dataYear+":"+di.df.format(value)+"#"; - } - } - } - } - dataString=dataString+"!"; - } - if (dataString.endsWith("!")) dataString=dataString.substring(0, dataString.length()-1); - if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); - try { - di.sendEvent(dataString); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void writeOutputDssEveryTenYears(){ - if (ControlData.currMonth==12 && ControlData.currYear%10==0){ - if (ControlData.timeStep.equals("1MON")){ - DssOperation.writeDVAliasToDSS(); - }else if(ControlData.timeStep.equals("1DAY") && ControlData.currDay==31){ - DssOperation.writeDVAliasToDSS(); - } - } - } - - public void connectToDataBase(){ - if (ControlData.outputType==2){ - mySQLCWriter=new MySQLCWriter(); - }else if (ControlData.outputType==3){ - mySQLRWriter=new MySQLRWriter(); - }else if (ControlData.outputType==4){ - sqlServerRWriter=new SQLServerRWriter(); - } - } - - public void procLaunch(String[] args){ - String launchFilePath = args[0].substring(args[0].indexOf("=") + 1, args[0].length()); - new LaunchConfiguration(launchFilePath); - } +package wrimsv2.components; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Date; + +import org.antlr.runtime.RecognitionException; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.config.ConfigUtils; +import wrimsv2.debug.ReProcessExternal; +import wrimsv2.evaluator.AssignPastCycleVariable; +import wrimsv2.evaluator.CsvOperation; +import wrimsv2.evaluator.DataTimeSeries; +import wrimsv2.evaluator.DssDataSet; +import wrimsv2.evaluator.DssDataSetFixLength; +import wrimsv2.evaluator.DssOperation; +import wrimsv2.evaluator.PreEvaluator; +import wrimsv2.evaluator.TimeOperation; +import wrimsv2.evaluator.ValueEvaluation; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.evaluator.WeightEval; +import wrimsv2.hdf5.HDF5Writer; +import wrimsv2.ilp.ILP; +import wrimsv2.launch.LaunchConfiguration; +import wrimsv2.parallel.ParallelVars; +import wrimsv2.solver.CbcSolver; +import wrimsv2.solver.CloseCurrentSolver; +import wrimsv2.solver.LPSolveSolver; +import wrimsv2.solver.XASolver; +import wrimsv2.solver.SetXALog; +import wrimsv2.solver.InitialXASolver; +import wrimsv2.solver.Gurobi.GurobiSolver; +import wrimsv2.sql.DataBaseProfile; +import wrimsv2.sql.MySQLCWriter; +import wrimsv2.sql.MySQLRWriter; +import wrimsv2.sql.SQLServerRWriter; +import wrimsv2.tools.General; +import wrimsv2.wreslparser.elements.StudyParser; +import wrimsv2.wreslparser.elements.StudyUtils; +import wrimsv2.wreslplus.elements.procedures.ErrorCheck; + +public class ControllerDebug extends Thread { + private DebugInterface di; + public int debugYear; + public int debugMonth; + public int debugDay; + public int debugCycle; + public int totalCycles=0; + public String conditionalBreakpoint; + public ValueEvaluatorParser conditionalBreakpointParser; + public String[] args; + public int modelIndex; + public static ArrayList initialTimeStep; + + private MySQLCWriter mySQLCWriter; + private MySQLRWriter mySQLRWriter; + private SQLServerRWriter sqlServerRWriter; + + public ControllerDebug(String[] args, DebugInterface di) { + this.di=di; + this.args=args; + } + + @Override + public void run() { + new DataBaseProfile(args); + if (args[0].toLowerCase().startsWith("-launch")){ + procLaunch(args); + }else{ + ConfigUtils.loadArgs(args); + } + if (ILP.loggingUsageMemeory) General.getPID(); + connectToDataBase(); + //generateStudyFile(); + try { + long t1 = Calendar.getInstance().getTimeInMillis(); + StudyDataSet sds = parse(); + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_parse=ControlData.t_parse+(int) (t2-t1); + if (StudyParser.total_errors==0){ + if (!StudyUtils.loadParserData && !FilePaths.fullMainPath.endsWith(".par")){ + StudyUtils.writeObj(sds, FilePaths.mainDirectory+File.separator+StudyUtils.configFileName+".par"); + } + totalCycles=sds.getModelList().size(); + di.sendEvent("totalcycle#"+totalCycles); + new PreEvaluator(sds); + runModel(sds); + } + } catch (RecognitionException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + di.isDebugging=false; + try { + di.sendEvent("terminate"); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void setControlData(String[] args){ + FilePaths.groundwaterDir=args[0]; + FilePaths.setMainFilePaths(args[1]); + FilePaths.setSvarFilePaths(args[2]); + FilePaths.setInitFilePaths(args[3]); + FilePaths.setDvarFilePaths(args[4]); + ControlData cd=new ControlData(); + cd.svDvPartF=args[5]; + cd.initPartF=args[6]; + cd.partA = args[7]; + cd.defaultTimeStep = args[8]; + cd.startYear=Integer.parseInt(args[9]); + cd.startMonth=Integer.parseInt(args[10]); + cd.startDay=Integer.parseInt(args[11]); + cd.endYear=Integer.parseInt(args[12]); + cd.endMonth=Integer.parseInt(args[13]); + cd.endDay=Integer.parseInt(args[14]); + cd.solverName=args[15]; + FilePaths.csvFolderName = args[16]; + cd.currYear=cd.startYear; + cd.currMonth=cd.startMonth; + cd.currDay=cd.startDay; + } + + public void generateStudyFile(){ + String outPath=System.getenv("temp_wrims2")+"\\study.sty"; + FileWriter outstream; + try { + outstream = new FileWriter(outPath); + BufferedWriter out = new BufferedWriter(outstream); + out.write("Study File: Generated by WRIMS. Do Not Edit!\n"); + out.write("Study Name\n"); + out.write("Author\n"); + out.write("Time\n"); + out.write("Note\n"); + out.write("Version\n"); + out.write(FilePaths.groundwaterDir+"\n"); + out.write("StudyFileFullPath\n"); + out.write(FilePaths.fullMainPath+"\n"); + out.write(FilePaths.fullSvarFilePath+"\n"); + out.write(FilePaths.fullDvarDssPath+"\n"); + out.write(FilePaths.fullInitFilePath+"\n"); + out.write(ControlData.defaultTimeStep+"\n"); + out.write(VariableTimeStep.getTotalTimeStep(ControlData.defaultTimeStep)+"\n"); + out.write(ControlData.startDay+"\n"); + out.write(ControlData.startMonth+"\n"); + out.write(ControlData.startYear+"\n"); + out.write("SLP\n"); + out.write("CycleNumber\n"); + out.write("FALSE\n"); + out.write("NONE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write(" \n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("CALSIM\n"); + out.write(ControlData.initPartF+"\n"); + out.write(ControlData.svDvPartF+"\n"); + out.write("FALSE\n"); + out.write("TRUE\n"); + out.write("FALSE\n"); + out.write("SINGLE\n"); + out.write("NODEBUG\n"); + out.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + public StudyDataSet parse()throws RecognitionException, IOException{ + if(StudyUtils.loadParserData) { + StudyDataSet sds = StudyUtils.loadObject(StudyUtils.parserDataPath); + LoadParameter.process(sds); + return sds; + }else{ + return StudyUtils.checkStudy(FilePaths.fullMainPath); + } + } + + public void runModel(StudyDataSet sds){ + System.out.println("=============Prepare Run Study==========="); + new PreRunModel(sds); + System.out.println("==============Run Study Start============"); + if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG") || ControlData.solverName.equalsIgnoreCase("CBC") || ControlData.solverName.equalsIgnoreCase("Gurobi")){ + runModelSolvers(sds); + }else{ + Error.addConfigError("Solver name not recognized: "+ControlData.solverName); + Error.writeErrorLog(); + if (ControlData.outputType!=1) ControlData.dvDss.close(); + return; + } + if (ControlData.showTimeUsage) new TimeUsage(); + System.out.println("=================Run ends!================"); + } + + public void runModelSolvers(StudyDataSet sds){ + + ILP.getIlpDir(); + ILP.setVarDir(); + ILP.createNoteFile(); + ILP.setMaximumFractionDigits(); + ILP.initializeIlp(); + + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG")) { + new InitialXASolver(); + if (Error.getTotalError()>0){ + System.out.println("Model run suspends due to error."); + di.handleRequest("suspend"); + } + }else if (ControlData.solverName.equalsIgnoreCase("CBC")){ + CbcSolver.init(false, sds); + if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) {new InitialXASolver();} + }else if (ControlData.solverName.equalsIgnoreCase("Gurobi")){ + GurobiSolver.initialize(); + } + + TimeOperation.initOutputDate(ControlData.yearOutputSection); + TimeOperation.initMemDate(ControlData.monMemSection); + + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + int sectionI=0; + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + if (ControlData.solverName.equalsIgnoreCase("XALOG")) SetXALog.enableXALog(); + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + modelIndex=0; + prepareInitialTimeStep(); + while (modelIndex=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.writeErrorLog(); + noError=false; + } + + if (ControlData.solverName.equalsIgnoreCase("XA")) { + new XASolver(); + }else if (ControlData.solverName.equalsIgnoreCase("XALOG")){ + if (isSelectedCycleOutput){ + ILP.setIlpFile(); + ILP.writeIlp(); + ILP.setVarFile(); + ILP.writeSvarValue(); + } + new XASolver(); + ILP.writeObjValue_XA(); + ILP.writeDvarValue_XA(); + }else if (ControlData.solverName.equalsIgnoreCase("CBC")){ + HashSet originalDvarKeys=null; + if (ControlData.cbc_debug_routeCbc || ControlData.cbc_debug_routeXA) { + originalDvarKeys = new LinkedHashSet(SolverData.getDvarMap().keySet()); +// ILP.getIlpDir(); +// ILP.setVarDir(); + ILP.setSvarFile(); +// ILP.setMaximumFractionDigits(); + // write svar + ILP.writeSvarValue(); + }else if (ILP.logging) { + ILP.setIlpFile(); + ILP.writeIlp(); + if (ILP.loggingVariableValue){ + ILP.setVarFile(); + ILP.writeSvarValue(); + } + } + + if (ControlData.cbc_debug_routeCbc) { + new XASolver(); + SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); + if (Error.error_solving.size() > 0) { + String msg = "XA solving error."; + ILP.writeNoteLn("", msg); + System.out.println("" + msg); + Error.writeErrorLog(); + Error.error_solving.clear(); + } + + } + + CbcSolver.newProblem(); + + if (ControlData.cbc_debug_routeXA) { + SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); + new XASolver(); + } + + if (ControlData.cbc_debug_routeXA ||ControlData.cbc_debug_routeCbc ) { + CbcSolver.logCbcDebug(sds); + }else if (ControlData.watchList.length>0) { + CbcSolver.logCbcWatchList(sds); + }else if (Error.error_solving.size()<1) { + if (ILP.logging) { + ILP.writeObjValue_Clp0_Cbc0(); + if (ILP.loggingVariableValue) ILP.writeDvarValue_Clp0_Cbc0(CbcSolver.varDoubleMap); + } + } + }else if (ControlData.solverName.equalsIgnoreCase("LPSolve")) { + ILP.setIlpFile(); + ILP.writeIlp(); + if (ILP.loggingVariableValue) { + ILP.setVarFile(); + ILP.writeSvarValue(); + } + LPSolveSolver.setLP(ILP.lpSolveFilePath); + LPSolveSolver.solve(); + if (Error.error_solving.size()<1) { + if (ILP.logging) { + ILP.writeObjValue_LPSOLVE(); + if (ILP.loggingVariableValue) ILP.writeDvarValue_LPSOLVE(); + } + } + }else if (ControlData.solverName.equalsIgnoreCase("Gurobi")){ + ILP.setIlpFile(); + ILP.writeIlp(); + if (ILP.loggingVariableValue) { + ILP.setVarFile(); + ILP.writeSvarValue(); + } + GurobiSolver.setLp(ILP.cplexLpFilePath); + GurobiSolver.solve(); + if (Error.error_solving.size()<1) { + if (ILP.logging) { + ILP.writeObjValue_LPSOLVE(); + if (ILP.loggingVariableValue) ILP.writeDvarValue_Gurobi(); + } + } + } + ILP.closeIlpFile(); + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.writeOneCycleSv(mds, cycleI); + } + } + if (ILP.loggingUsageMemeory) ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + //ILP.logUsageMemory(ControlData.currYear, ControlData.currMonth, ControlData.currDay, ControlData.currCycleIndex); + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); + if (CbcSolver.intLog && ControlData.solverName.equalsIgnoreCase("CBC")) { + CbcSolver.logIntCheck(sds); + } + if (ControlData.solverName.equalsIgnoreCase("CBC")){CbcSolver.resetModel();} + pauseForDebug(modelIndex); + if (Error.error_evaluation.size()>=1) noError=false; + if (Error.getTotalError()==0) noError=true; + //if (ControlData.currTimeStep==0 && ControlData.currCycleIndex==2) new RCCComparison(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + }else{ + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.skipOneCycle(mds, cycleI); + } + } + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" skipped. ("+model+")"); + new AssignPastCycleVariable(); + deferPause(modelIndex); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + } + } + modelIndex=modelIndex+1; + } + Date date1= new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + Date date2= new Date(ControlData.outputYear-1900, ControlData.outputMonth-1, ControlData.outputDay); + if (ControlData.yearOutputSection>0 && date1.after(date2)){ + if (ControlData.writeInitToDVOutput && sectionI==0){ + DssOperation.writeInitDvarAliasToDSS(); + } + sectionI++; + DssOperation.writeDVAliasToDSS(); + TimeOperation.setMemDate(ControlData.monMemSection); + DssOperation.shiftData(); + TimeOperation.setOutputDate(ControlData.yearOutputSection); + } + updateVarMonitor(); + if (ControlData.resimDate){ + ControlData.resimDate=false; + noError=true; + sds=ControlData.currStudyDataSet; + modelList=sds.getModelList(); + modelDataSetMap=sds.getModelDataSetMap(); + modelConditionParsers=sds.getModelConditionParsers(); + new ReProcessExternal(sds); + resetStartDate(sds); + } + VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); + VariableTimeStep.setCycleEndDate(sds); + } + new CloseCurrentSolver(ControlData.solverName); + + if (ControlData.yearOutputSection<0 && ControlData.writeInitToDVOutput) DssOperation.writeInitDvarAliasToDSS(); + DssOperation.writeDVAliasToDSS(); + ControlData.dvDss.close(); + if (ControlData.outputType==1){ + HDF5Writer.createDvarAliasLookup(); + HDF5Writer.writeTimestepData(); + HDF5Writer.writeCyclesDvAlias(); + HDF5Writer.closeDataStructure(); + }else if (ControlData.outputType==2){ + mySQLCWriter.process(); + }else if (ControlData.outputType==3){ + mySQLRWriter.process(); + }else if (ControlData.outputType==4){ + sqlServerRWriter.process(); + }else if (ControlData.outputType==5){ + CsvOperation co = new CsvOperation(); + co.ouputCSV(FilePaths.fullCsvPath, 0); + } + + WeightEval.outputWtTableAR(); + } + + public void prepareInitialTimeStep(){ + initialTimeStep=new ArrayList(); + for (Integer timeStep: ControlData.currTimeStep){ + initialTimeStep.add(timeStep.intValue()); + } + } + + public void resetStartDate(StudyDataSet sds){ + int diffTimeStep; + VariableTimeStep.procCycleTimeStep(sds); + for(int i=0; i0){ + try { + int cycle=ControlData.currCycleIndex+1; + di.sendEvent("suspended!"+ControlData.currYear+"#"+ControlData.currMonth+"#"+ControlData.currDay+"#"+cycle); + System.out.println("Error! Paused"); + } catch (IOException e) { + e.printStackTrace(); + } + this.suspend(); + }else{ + checkConditionalBreakpoint(); + } + } + + public void deferPause(int i){ + if (ControlData.timeStep.equals("1MON")){ + if (ControlData.currYear==debugYear && ControlData.currMonth==debugMonth && i==debugCycle-1){ + debugCycle=debugCycle+1; + if (debugCycle>totalCycles){ + debugCycle=1; + debugTimeAddOneMonth(); + } + } + }else{ + if (ControlData.currYear==debugYear && ControlData.currMonth==debugMonth && ControlData.currDay==debugDay && i==debugCycle-1){ + debugCycle=debugCycle+1; + if (debugCycle>totalCycles){ + debugCycle=1; + debugTimeAddOneDay(); + } + } + } + } + + + public void debugTimeAddOneMonth(){ + debugMonth=debugMonth+1; + if (debugMonth>12){ + debugMonth=debugMonth-12; + debugYear=debugYear+1; + } + debugDay=TimeOperation.numberOfDays(debugMonth, debugYear); + } + + public void debugTimeAddOneDay(){ + Date debugDate = new Date (debugYear-1900, debugMonth-1, debugDay); + Calendar c = Calendar.getInstance(); + c.setTime(debugDate); + c.add(Calendar.DATE, 1); + debugDate = c.getTime(); + debugMonth=debugDate.getMonth()+1; + debugYear=debugDate.getYear()+1900; + debugDay=debugDate.getDate(); + } + + private void checkConditionalBreakpoint() { + boolean condition=false; + ControlData.currEvalTypeIndex=1000; + if (conditionalBreakpointParser!=null){ + try{ + conditionalBreakpointParser.evaluator(); + condition=conditionalBreakpointParser.evalCondition; + }catch (Exception e){ + condition=false; + } + + conditionalBreakpointParser.reset(); + Error.error_evaluation.clear(); + } + + if (condition){ + try { + di.sendEvent("suspended!"+debugYear+"#"+debugMonth+"#"+debugDay+"#"+debugCycle); + System.out.println("conditional breakpoint of " + conditionalBreakpoint + " reached"); + System.out.println("paused"); + } catch (IOException e) { + e.printStackTrace(); + } + this.suspend(); + } + } + + public void updateVarMonitor(){ + String dataString="updateVarMonitor!"; + for (int k=0; k dvAliasTSMap = DataTimeSeries.dvAliasTS; + + if (dvAliasTSMap.containsKey(entryName)){ + DssDataSetFixLength ddsf = dvAliasTSMap.get(entryName); + double[] dataArray = ddsf.getData(); + ParallelVars prvs = TimeOperation.findTime(-1); + int currIndex; + if (monitorVarTimeStep.equals("1MON")){ + currIndex=ValueEvaluation.timeSeriesIndex(ddsf, prvs)-1; + }else{ + currIndex=ValueEvaluation.timeSeriesIndex(ddsf, prvs)-2; + } + for (int i=0; i<=currIndex; i++){ + double value=dataArray[i]; + if (!(value==-901.0 || value==-902.0)){ + int timestepListed=i-currIndex; + prvs = TimeOperation.findTime(timestepListed); + dataString=dataString+timestepListed+":"+prvs.dataMonth+"-"+prvs.dataDay+"-"+prvs.dataYear+":"+di.df.format(value)+"#"; + } + } + }else{ + HashMap svTSMap = DataTimeSeries.svTS; + if (svTSMap.containsKey(entryName)){ + DssDataSet dds = svTSMap.get(entryName); + ArrayList dataArrayList = dds.getData(); + ParallelVars prvs = TimeOperation.findTime(-1); + int currIndex=ValueEvaluation.timeSeriesIndex(dds, prvs); + for (int i=0; i<=currIndex; i++){ + double value=dataArrayList.get(i); + if (!(value==-901.0 || value==-902.0)){ + int timestepListed=i-currIndex; + prvs = TimeOperation.findTime(timestepListed); + dataString=dataString+timestepListed+":"+prvs.dataMonth+"-"+prvs.dataDay+"-"+prvs.dataYear+":"+di.df.format(value)+"#"; + } + } + } + } + dataString=dataString+"!"; + } + if (dataString.endsWith("!")) dataString=dataString.substring(0, dataString.length()-1); + if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); + try { + di.sendEvent(dataString); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void writeOutputDssEveryTenYears(){ + if (ControlData.currMonth==12 && ControlData.currYear%10==0){ + if (ControlData.timeStep.equals("1MON")){ + DssOperation.writeDVAliasToDSS(); + }else if(ControlData.timeStep.equals("1DAY") && ControlData.currDay==31){ + DssOperation.writeDVAliasToDSS(); + } + } + } + + public void connectToDataBase(){ + if (ControlData.outputType==2){ + mySQLCWriter=new MySQLCWriter(); + }else if (ControlData.outputType==3){ + mySQLRWriter=new MySQLRWriter(); + }else if (ControlData.outputType==4){ + sqlServerRWriter=new SQLServerRWriter(); + } + } + + public void procLaunch(String[] args){ + String launchFilePath = args[0].substring(args[0].indexOf("=") + 1, args[0].length()); + new LaunchConfiguration(launchFilePath); + } } \ No newline at end of file diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/ControllerSG.java b/wrims-core/src/main/java/wrimsv2/components/ControllerSG.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/components/ControllerSG.java rename to wrims-core/src/main/java/wrimsv2/components/ControllerSG.java index cd22a584d..3deee8e1f 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/ControllerSG.java +++ b/wrims-core/src/main/java/wrimsv2/components/ControllerSG.java @@ -1,623 +1,623 @@ -package wrimsv2.components; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Map; - -import org.antlr.runtime.RecognitionException; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.evaluator.AssignPastCycleVariable; -import wrimsv2.evaluator.DssOperation; -import wrimsv2.evaluator.PreEvaluator; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.hdf5.HDF5Writer; -import wrimsv2.ilp.ILP; -import wrimsv2.solver.CbcSolver; -import wrimsv2.solver.XASolver; -import wrimsv2.solver.SetXALog; -import wrimsv2.solver.InitialXASolver; -import wrimsv2.tools.General; -import wrimsv2.wreslparser.elements.StudyUtils; -import wrimsv2.wreslplus.elements.procedures.ErrorCheck; - -public class ControllerSG { - - public ControllerSG() { - long startTimeInMillis = Calendar.getInstance().getTimeInMillis(); - setControlData(); - //generateStudyFile(); - try { - StudyDataSet sds = parse(); - if (StudyUtils.total_errors==0){ - if (!StudyUtils.loadParserData && !FilePaths.fullMainPath.endsWith(".par")){ - StudyUtils.writeObj(sds, FilePaths.mainDirectory+File.separator+StudyUtils.configFileName+".par"); - } - new PreEvaluator(sds); - runModel(sds); - } - } catch (RecognitionException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - long endTimeInMillis = Calendar.getInstance().getTimeInMillis(); - int runPeriod=(int) (endTimeInMillis-startTimeInMillis); - System.out.println("=================Run Time is "+runPeriod/60000+"min"+Math.round((runPeriod/60000.0-runPeriod/60000)*60)+"sec===="); - } - - public ControllerSG(String[] args) { - long startTimeInMillis = Calendar.getInstance().getTimeInMillis(); - setControlData(args); - //generateStudyFile(); - try { - StudyDataSet sds = parse(); - if (StudyUtils.total_errors==0){ - if (!StudyUtils.loadParserData && !FilePaths.fullMainPath.endsWith(".par")){ - StudyUtils.writeObj(sds, FilePaths.mainDirectory+File.separator+StudyUtils.configFileName+".par"); - } - new PreEvaluator(sds); - runModel(sds); - } - } catch (RecognitionException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - long endTimeInMillis = Calendar.getInstance().getTimeInMillis(); - int runPeriod=(int) (endTimeInMillis-startTimeInMillis); - System.out.println("=================Run Time is "+runPeriod/60000+"min"+Math.round((runPeriod/60000.0-runPeriod/60000)*60)+"sec===="); - System.exit(0); - } - - public void setControlData(){ - FilePaths.groundwaterDir="D:\\cvwrsm\\trunk\\calsim30\\calsim30_bo\\common\\CVGroundwater\\Data\\"; - FilePaths.setMainFilePaths("D:\\cvwrsm\\trunk\\calsim30\\calsim30_bo\\CONV\\Run\\mainCONV_30.wresl"); - FilePaths.setSvarFilePaths("D:\\cvwrsm\\trunk\\calsim30\\calsim30_bo\\common\\DSS\\CalSim30_06_SV.dss"); - FilePaths.setInitFilePaths("D:\\cvwrsm\\trunk\\calsim30\\calsim30_bo\\common\\DSS\\CalSim30_06Init.dss"); - FilePaths.setDvarFilePaths("D:\\cvwrsm\\trunk\\calsim30\\calsim30_bo\\CONV\\DSS\\TestWRIMSV2DV.dss"); - ControlData cd=new ControlData(); - cd.svDvPartF="CALSIM30_06"; - cd.initPartF="CALSIM30_06"; - cd.partA = "CALSIM"; - cd.defaultTimeStep="1MON"; - cd.startYear=1921; - cd.startMonth=10; - cd.startDay=31; - cd.endYear=2003; - cd.endMonth=9; - cd.endDay=30; - cd.solverName="XA"; - FilePaths.csvFolderName="csv"; - cd.currYear=cd.startYear; - cd.currMonth=cd.startMonth; - cd.currDay=cd.startDay; - } - - public void setControlData(String[] args){ - FilePaths.groundwaterDir=args[0]; - FilePaths.setMainFilePaths(args[1]); - FilePaths.setSvarFilePaths(args[2]); - FilePaths.setInitFilePaths(args[3]); - FilePaths.setDvarFilePaths(args[4]); - ControlData cd=new ControlData(); - cd.svDvPartF=args[5]; - cd.initPartF=args[6]; - cd.partA = args[7]; - cd.defaultTimeStep = args[8]; - cd.startYear=Integer.parseInt(args[9]); - cd.startMonth=Integer.parseInt(args[10]); - cd.startDay=Integer.parseInt(args[11]); - cd.endYear=Integer.parseInt(args[12]); - cd.endMonth=Integer.parseInt(args[13]); - cd.endDay=Integer.parseInt(args[14]); - cd.solverName=args[15]; - FilePaths.csvFolderName = args[16]; - cd.currYear=cd.startYear; - cd.currMonth=cd.startMonth; - cd.currDay=cd.startDay; - if (args.length>17){ - StudyUtils.useWreslPlus = false; - if (args[17].equalsIgnoreCase("wreslplus")){ - StudyUtils.useWreslPlus = true; - } - } - } - - public void generateStudyFile(){ - String outPath="study.sty"; - FileWriter outstream; - try { - outstream = new FileWriter(outPath); - BufferedWriter out = new BufferedWriter(outstream); - out.write("Study File: Generated by WRIMS. Do Not Edit!\n"); - out.write("Study Name\n"); - out.write("Author\n"); - out.write("Time\n"); - out.write("Note\n"); - out.write("Version\n"); - out.write(FilePaths.groundwaterDir+"\n"); - out.write("StudyFileFullPath\n"); - out.write(FilePaths.fullMainPath+"\n"); - out.write(FilePaths.fullSvarFilePath+"\n"); - out.write(FilePaths.fullDvarDssPath+"\n"); - out.write(FilePaths.fullInitFilePath+"\n"); - out.write(ControlData.defaultTimeStep+"\n"); - out.write(VariableTimeStep.getTotalTimeStep(ControlData.defaultTimeStep)+"\n"); - out.write(ControlData.startDay+"\n"); - out.write(ControlData.startMonth+"\n"); - out.write(ControlData.startYear+"\n"); - out.write("SLP\n"); - out.write("CycleNumber\n"); - out.write("FALSE\n"); - out.write("NONE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("FALSE\n"); - out.write("CALSIM\n"); - out.write(ControlData.initPartF+"\n"); - out.write(ControlData.svDvPartF+"\n"); - out.write("FALSE\n"); - out.write("TRUE\n"); - out.write("FALSE\n"); - out.write("SINGLE\n"); - out.write("NODEBUG\n"); - out.close(); - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public StudyDataSet parse()throws RecognitionException, IOException{ - if(StudyUtils.loadParserData) { - return StudyUtils.loadObject(StudyUtils.parserDataPath); - }else{ - return StudyUtils.checkStudy(FilePaths.fullMainPath); - } - } - - public void runModel(StudyDataSet sds){ - System.out.println("=============Prepare Run Study==========="); - new PreRunModel(sds); - System.out.println("==============Run Study Start============"); - if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG") ){ - runModelXA(sds); - } else if (ControlData.solverName.equalsIgnoreCase("Cbc")){ - runModelCbc(sds); - } - System.out.println("=================Run ends!================"); - } - - public void runModelXA(StudyDataSet sds){ - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - new InitialXASolver(); - if (Error.getTotalError()>0){ - System.out.println("Model run exits due to error."); - System.exit(1); - } - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - if (ControlData.solverName.equalsIgnoreCase("XALOG")) SetXALog.enableXALog(); - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - int i=0; - while (i=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.writeErrorLog(); - noError=false; - } - new XASolver(); - - // check monitored dvar list. they are slack and surplus generated automatically - // from the weight group deviation penalty - // give error if they are not zero or greater than a small tolerance. - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.writeOneCycleSv(mds, cycleI); - } - } - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); - if (Error.error_evaluation.size()>=1) noError=false; - //if (ControlData.currTimeStep==0 && ControlData.currCycleIndex==2) new RCCComparison(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - }else{ - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.skipOneCycle(mds, cycleI); - } - } - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" skipped. ("+model+")"); - new AssignPastCycleVariable(); - ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); - if (ControlData.timeStep.equals("1MON")){ - VariableTimeStep.currTimeAddOneMonth(); - }else{ - VariableTimeStep.currTimeAddOneDay(); - } - } - } - i=i+1; - } - VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); - VariableTimeStep.setCycleEndDate(sds); - } - ControlData.xasolver.close(); - if (ControlData.outputType==1){ - HDF5Writer.createDvarAliasLookup(); - HDF5Writer.writeTimestepData(); - HDF5Writer.writeCyclesDvAlias(); - HDF5Writer.closeDataStructure(); - }else{ - if (ControlData.writeInitToDVOutput){ - DssOperation.writeInitDvarAliasToDSS(); - } - DssOperation.writeDVAliasToDSS(); - ControlData.dvDss.close(); - } - } - - public void runModelCbc(StudyDataSet sds){ - - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - - CbcSolver.init(false, sds); if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) {new InitialXASolver();} - if (Error.getTotalError()>0){ - System.out.println("Model run exits due to error."); - System.exit(1); - } - ArrayList modelConditionParsers=sds.getModelConditionParsers(); - boolean noError=true; - VariableTimeStep.initialCurrTimeStep(modelList); - VariableTimeStep.initialCycleStartDate(); - VariableTimeStep.setCycleEndDate(sds); - while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ - - ClearValue.clearValues(modelList, modelDataSetMap); - sds.clearVarTimeArrayCycleValueMap(); - sds.clearVarCycleIndexByTimeStep(); - int i=0; - while (i=1){ - Error.writeEvaluationErrorFile("Error_evaluation.txt"); - Error.writeErrorLog(); - noError=false; - } - - HashSet originalDvarKeys=null; - - if (ControlData.cbc_debug_routeCbc || ControlData.cbc_debug_routeXA) { - originalDvarKeys = new LinkedHashSet(SolverData.getDvarMap().keySet()); - } - - if (ControlData.cbc_debug_routeCbc) { - new XASolver(); - SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); - if (Error.error_solving.size() > 0) { - String msg = "XA solving error."; - ILP.writeNoteLn("", msg); - System.out.println("" + msg); - Error.writeErrorLog(); - Error.error_solving.clear(); - } - - } - - CbcSolver.newProblem(); - - if (ControlData.cbc_debug_routeXA) { - SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); - new XASolver(); - } - - // check monitored dvar list. they are slack and surplus generated automatically - // from the weight group deviation penalty - // give error if they are not zero or greater than a small tolerance. - noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); - - if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); - if (Error.error_solving.size()<1){ - ControlData.isPostProcessing=true; - mds.processAlias(); - if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); - }else{ - Error.writeSolvingErrorFile("Error_solving.txt"); - Error.writeErrorLog(); - noError=false; - } - int cycleI=i+1; - String strCycleI=cycleI+""; - boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); - if (ControlData.outputType==1){ - if (ControlData.isOutputCycle && isSelectedCycleOutput){ - HDF5Writer.writeOneCycleSv(mds, cycleI); - } - } - System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); - if (Error.error_evaluation.size()>=1) noError=false; - - - if (CbcSolver.intLog && (!ControlData.cbc_debug_routeXA && !ControlData.cbc_debug_routeCbc)) { - - String cbc_int = ""; - if (sds.cycIntDvMap != null && sds.cycIntDvMap.containsKey(ControlData.currCycleIndex)) { - ArrayList intDVs = new ArrayList(sds.cycIntDvMap.get(ControlData.currCycleIndex)); - for (String v : sds.allIntDv) { - if (intDVs.contains(v)){ - //xa_int += " "+ Math.round(ControlData.xasolver.getColumnActivity(v)); - if (Error.getTotalError()==0) { - cbc_int += " "+ Math.round(CbcSolver.varDoubleMap.get(v)); - } else { - cbc_int += " ?"; - } - } else { - //xa_int += " "; - cbc_int += " "; - } - } - } - // write solve time - cbc_int += " "+String.format("%8.2f",ControlData.solverTime_cbc_this); - - // write solve name - cbc_int += " "+CbcSolver.solveName; - - ILP.writeNoteLn(ILP.getYearMonthCycle(), ""+ cbc_int, ILP._noteFile_cbc_int_log); - - } - - - if (ControlData.cbc_debug_routeXA ||ControlData.cbc_debug_routeCbc ) { - - // write watch var values - boolean recordLP = false; - double wa_cbc = 0; - double wa_xa = 0; - if (ControlData.watchList != null) { - String wa_cbc_str = ""; - String wa_xa_str = ""; - for (String s : ControlData.watchList) { - if (ControlData.currModelDataSet.dvList.contains(s)){ - - //System.out.println(s); - wa_cbc = CbcSolver.varDoubleMap.get(s); - wa_xa = ControlData.xasolver.getColumnActivity(s); - wa_cbc_str += String.format("%14.3f", wa_cbc) + " "; - wa_xa_str += String.format("%14.3f", wa_xa) + " "; - - if (Math.abs(wa_xa-wa_cbc)>ControlData.watchList_tolerance) recordLP=true; - } - } - ILP.writeNoteLn(ILP.getYearMonthCycle(), wa_cbc_str, ILP._watchFile_cbc); - ILP.writeNoteLn(ILP.getYearMonthCycle(), wa_xa_str, ILP._watchFile_xa); - - } - - // write int value, time, and obj diff - ILP.writeNoteLn(ILP.getYearMonthCycle(), ""+ControlData.xasolver.getObjective(), ILP._noteFile_xa_obj); - ILP.writeNoteLn(ILP.getYearMonthCycle(), ""+ControlData.clp_cbc_objective, ILP._noteFile_cbc_obj); - - String xa_int = ""; - String cbc_int = ""; - if (sds.cycIntDvMap != null) { - ArrayList intDVs = new ArrayList(sds.cycIntDvMap.get(ControlData.currCycleIndex)); - for (String v : sds.allIntDv) { - if (intDVs.contains(v)){ - xa_int += " "+ Math.round(ControlData.xasolver.getColumnActivity(v)); - if (Error.getTotalError()==0) { - cbc_int += " "+ Math.round(CbcSolver.varDoubleMap.get(v)); - } else { - cbc_int += " ?"; - } - } else { - xa_int += " "; - cbc_int += " "; - } - } - } - - // write solve name - cbc_int += " "+CbcSolver.solveName; - xa_int += " "+CbcSolver.solveName; - - if (Error.getTotalError() == 0) { - if (recordLP) { - CbcSolver.reloadAndWriteLp("_watch_diff", true, false); - } - - double diff = ControlData.clp_cbc_objective - ControlData.xasolver.getObjective(); - if (Math.abs(diff) > CbcSolver.record_if_obj_diff) { - CbcSolver.reloadAndWriteLp("_obj"+Math.round(diff), true, false); - } - if (Math.abs(diff) > CbcSolver.log_if_obj_diff) { - xa_int += " obj: " + String.format("%16.3f", diff); - cbc_int += " obj: " + String.format("%16.3f", diff); - if (diff>CbcSolver.maxObjDiff){ - CbcSolver.maxObjDiff = diff; - CbcSolver.maxObjDiff_id = ILP.getYearMonthCycle(); - } else if(diff17){ + StudyUtils.useWreslPlus = false; + if (args[17].equalsIgnoreCase("wreslplus")){ + StudyUtils.useWreslPlus = true; + } + } + } + + public void generateStudyFile(){ + String outPath="study.sty"; + FileWriter outstream; + try { + outstream = new FileWriter(outPath); + BufferedWriter out = new BufferedWriter(outstream); + out.write("Study File: Generated by WRIMS. Do Not Edit!\n"); + out.write("Study Name\n"); + out.write("Author\n"); + out.write("Time\n"); + out.write("Note\n"); + out.write("Version\n"); + out.write(FilePaths.groundwaterDir+"\n"); + out.write("StudyFileFullPath\n"); + out.write(FilePaths.fullMainPath+"\n"); + out.write(FilePaths.fullSvarFilePath+"\n"); + out.write(FilePaths.fullDvarDssPath+"\n"); + out.write(FilePaths.fullInitFilePath+"\n"); + out.write(ControlData.defaultTimeStep+"\n"); + out.write(VariableTimeStep.getTotalTimeStep(ControlData.defaultTimeStep)+"\n"); + out.write(ControlData.startDay+"\n"); + out.write(ControlData.startMonth+"\n"); + out.write(ControlData.startYear+"\n"); + out.write("SLP\n"); + out.write("CycleNumber\n"); + out.write("FALSE\n"); + out.write("NONE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("FALSE\n"); + out.write("CALSIM\n"); + out.write(ControlData.initPartF+"\n"); + out.write(ControlData.svDvPartF+"\n"); + out.write("FALSE\n"); + out.write("TRUE\n"); + out.write("FALSE\n"); + out.write("SINGLE\n"); + out.write("NODEBUG\n"); + out.close(); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public StudyDataSet parse()throws RecognitionException, IOException{ + if(StudyUtils.loadParserData) { + return StudyUtils.loadObject(StudyUtils.parserDataPath); + }else{ + return StudyUtils.checkStudy(FilePaths.fullMainPath); + } + } + + public void runModel(StudyDataSet sds){ + System.out.println("=============Prepare Run Study==========="); + new PreRunModel(sds); + System.out.println("==============Run Study Start============"); + if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG") ){ + runModelXA(sds); + } else if (ControlData.solverName.equalsIgnoreCase("Cbc")){ + runModelCbc(sds); + } + System.out.println("=================Run ends!================"); + } + + public void runModelXA(StudyDataSet sds){ + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + new InitialXASolver(); + if (Error.getTotalError()>0){ + System.out.println("Model run exits due to error."); + System.exit(1); + } + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + if (ControlData.solverName.equalsIgnoreCase("XALOG")) SetXALog.enableXALog(); + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + int i=0; + while (i=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.writeErrorLog(); + noError=false; + } + new XASolver(); + + // check monitored dvar list. they are slack and surplus generated automatically + // from the weight group deviation penalty + // give error if they are not zero or greater than a small tolerance. + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.writeOneCycleSv(mds, cycleI); + } + } + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); + if (Error.error_evaluation.size()>=1) noError=false; + //if (ControlData.currTimeStep==0 && ControlData.currCycleIndex==2) new RCCComparison(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + }else{ + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.skipOneCycle(mds, cycleI); + } + } + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" skipped. ("+model+")"); + new AssignPastCycleVariable(); + ControlData.currTimeStep.set(ControlData.currCycleIndex, ControlData.currTimeStep.get(ControlData.currCycleIndex)+1); + if (ControlData.timeStep.equals("1MON")){ + VariableTimeStep.currTimeAddOneMonth(); + }else{ + VariableTimeStep.currTimeAddOneDay(); + } + } + } + i=i+1; + } + VariableTimeStep.setCycleStartDate(ControlData.cycleEndDay, ControlData.cycleEndMonth, ControlData.cycleEndYear); + VariableTimeStep.setCycleEndDate(sds); + } + ControlData.xasolver.close(); + if (ControlData.outputType==1){ + HDF5Writer.createDvarAliasLookup(); + HDF5Writer.writeTimestepData(); + HDF5Writer.writeCyclesDvAlias(); + HDF5Writer.closeDataStructure(); + }else{ + if (ControlData.writeInitToDVOutput){ + DssOperation.writeInitDvarAliasToDSS(); + } + DssOperation.writeDVAliasToDSS(); + ControlData.dvDss.close(); + } + } + + public void runModelCbc(StudyDataSet sds){ + + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + + CbcSolver.init(false, sds); if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) {new InitialXASolver();} + if (Error.getTotalError()>0){ + System.out.println("Model run exits due to error."); + System.exit(1); + } + ArrayList modelConditionParsers=sds.getModelConditionParsers(); + boolean noError=true; + VariableTimeStep.initialCurrTimeStep(modelList); + VariableTimeStep.initialCycleStartDate(); + VariableTimeStep.setCycleEndDate(sds); + while (VariableTimeStep.checkEndDate(ControlData.cycleStartDay, ControlData.cycleStartMonth, ControlData.cycleStartYear, ControlData.endDay, ControlData.endMonth, ControlData.endYear)<=0 && noError){ + + ClearValue.clearValues(modelList, modelDataSetMap); + sds.clearVarTimeArrayCycleValueMap(); + sds.clearVarCycleIndexByTimeStep(); + int i=0; + while (i=1){ + Error.writeEvaluationErrorFile("Error_evaluation.txt"); + Error.writeErrorLog(); + noError=false; + } + + HashSet originalDvarKeys=null; + + if (ControlData.cbc_debug_routeCbc || ControlData.cbc_debug_routeXA) { + originalDvarKeys = new LinkedHashSet(SolverData.getDvarMap().keySet()); + } + + if (ControlData.cbc_debug_routeCbc) { + new XASolver(); + SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); + if (Error.error_solving.size() > 0) { + String msg = "XA solving error."; + ILP.writeNoteLn("", msg); + System.out.println("" + msg); + Error.writeErrorLog(); + Error.error_solving.clear(); + } + + } + + CbcSolver.newProblem(); + + if (ControlData.cbc_debug_routeXA) { + SolverData.getDvarMap().keySet().retainAll(originalDvarKeys); + new XASolver(); + } + + // check monitored dvar list. they are slack and surplus generated automatically + // from the weight group deviation penalty + // give error if they are not zero or greater than a small tolerance. + noError = !ErrorCheck.checkDeviationSlackSurplus(mds.deviationSlackSurplus_toleranceMap, mds.dvMap); + + if (ControlData.showRunTimeMessage) System.out.println("Solving Done."); + if (Error.error_solving.size()<1){ + ControlData.isPostProcessing=true; + mds.processAlias(); + if (ControlData.showRunTimeMessage) System.out.println("Assign Alias Done."); + }else{ + Error.writeSolvingErrorFile("Error_solving.txt"); + Error.writeErrorLog(); + noError=false; + } + int cycleI=i+1; + String strCycleI=cycleI+""; + boolean isSelectedCycleOutput=General.isSelectedCycleOutput(strCycleI); + if (ControlData.outputType==1){ + if (ControlData.isOutputCycle && isSelectedCycleOutput){ + HDF5Writer.writeOneCycleSv(mds, cycleI); + } + } + System.out.println("Cycle "+cycleI+" in "+ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+" Done. ("+model+")"); + if (Error.error_evaluation.size()>=1) noError=false; + + + if (CbcSolver.intLog && (!ControlData.cbc_debug_routeXA && !ControlData.cbc_debug_routeCbc)) { + + String cbc_int = ""; + if (sds.cycIntDvMap != null && sds.cycIntDvMap.containsKey(ControlData.currCycleIndex)) { + ArrayList intDVs = new ArrayList(sds.cycIntDvMap.get(ControlData.currCycleIndex)); + for (String v : sds.allIntDv) { + if (intDVs.contains(v)){ + //xa_int += " "+ Math.round(ControlData.xasolver.getColumnActivity(v)); + if (Error.getTotalError()==0) { + cbc_int += " "+ Math.round(CbcSolver.varDoubleMap.get(v)); + } else { + cbc_int += " ?"; + } + } else { + //xa_int += " "; + cbc_int += " "; + } + } + } + // write solve time + cbc_int += " "+String.format("%8.2f",ControlData.solverTime_cbc_this); + + // write solve name + cbc_int += " "+CbcSolver.solveName; + + ILP.writeNoteLn(ILP.getYearMonthCycle(), ""+ cbc_int, ILP._noteFile_cbc_int_log); + + } + + + if (ControlData.cbc_debug_routeXA ||ControlData.cbc_debug_routeCbc ) { + + // write watch var values + boolean recordLP = false; + double wa_cbc = 0; + double wa_xa = 0; + if (ControlData.watchList != null) { + String wa_cbc_str = ""; + String wa_xa_str = ""; + for (String s : ControlData.watchList) { + if (ControlData.currModelDataSet.dvList.contains(s)){ + + //System.out.println(s); + wa_cbc = CbcSolver.varDoubleMap.get(s); + wa_xa = ControlData.xasolver.getColumnActivity(s); + wa_cbc_str += String.format("%14.3f", wa_cbc) + " "; + wa_xa_str += String.format("%14.3f", wa_xa) + " "; + + if (Math.abs(wa_xa-wa_cbc)>ControlData.watchList_tolerance) recordLP=true; + } + } + ILP.writeNoteLn(ILP.getYearMonthCycle(), wa_cbc_str, ILP._watchFile_cbc); + ILP.writeNoteLn(ILP.getYearMonthCycle(), wa_xa_str, ILP._watchFile_xa); + + } + + // write int value, time, and obj diff + ILP.writeNoteLn(ILP.getYearMonthCycle(), ""+ControlData.xasolver.getObjective(), ILP._noteFile_xa_obj); + ILP.writeNoteLn(ILP.getYearMonthCycle(), ""+ControlData.clp_cbc_objective, ILP._noteFile_cbc_obj); + + String xa_int = ""; + String cbc_int = ""; + if (sds.cycIntDvMap != null) { + ArrayList intDVs = new ArrayList(sds.cycIntDvMap.get(ControlData.currCycleIndex)); + for (String v : sds.allIntDv) { + if (intDVs.contains(v)){ + xa_int += " "+ Math.round(ControlData.xasolver.getColumnActivity(v)); + if (Error.getTotalError()==0) { + cbc_int += " "+ Math.round(CbcSolver.varDoubleMap.get(v)); + } else { + cbc_int += " ?"; + } + } else { + xa_int += " "; + cbc_int += " "; + } + } + } + + // write solve name + cbc_int += " "+CbcSolver.solveName; + xa_int += " "+CbcSolver.solveName; + + if (Error.getTotalError() == 0) { + if (recordLP) { + CbcSolver.reloadAndWriteLp("_watch_diff", true, false); + } + + double diff = ControlData.clp_cbc_objective - ControlData.xasolver.getObjective(); + if (Math.abs(diff) > CbcSolver.record_if_obj_diff) { + CbcSolver.reloadAndWriteLp("_obj"+Math.round(diff), true, false); + } + if (Math.abs(diff) > CbcSolver.log_if_obj_diff) { + xa_int += " obj: " + String.format("%16.3f", diff); + cbc_int += " obj: " + String.format("%16.3f", diff); + if (diff>CbcSolver.maxObjDiff){ + CbcSolver.maxObjDiff = diff; + CbcSolver.maxObjDiff_id = ILP.getYearMonthCycle(); + } else if(diff breakIndex=new ArrayList(); - public ArrayList breakFile=new ArrayList(); - public boolean isDebugging=true; - private ControllerDebug controllerDebug; - private FileWriter statusFile; - public PrintWriter fileOut; - private boolean isStart=false; - private String[] debugSvar; - private String[] debugDvar; - private String[] debugAlias; - private String[] allDebugVariables; - private ArrayList filterGoalNames=new ArrayList(); - private Map filterGoals=new HashMap(); - public DecimalFormat df = new DecimalFormat("#.####"); - public static String[] monitorVarNames=new String[0]; - public static String monitorVarTimeStep=""; - private String dataDir="data"; - private int terminateCode=0; - - public DebugInterface(int requestPort, int eventPort, String args[]){ - try{ - statusFile = new FileWriter("DebugStatus.txt"); - }catch (IOException e){ - e.printStackTrace(); - } - fileOut = new PrintWriter(statusFile); - try { - requestSocket = new ServerSocket(requestPort); - eventSocket = new ServerSocket(eventPort); - requestConnection=requestSocket.accept(); - eventConnection=eventSocket.accept(); - requestOut=new PrintWriter(requestConnection.getOutputStream()); - requestOut.flush(); - requestIn=new BufferedReader(new InputStreamReader(requestConnection.getInputStream())); - eventOut=new PrintWriter(eventConnection.getOutputStream()); - eventOut.flush(); - eventIn=new BufferedReader(new InputStreamReader(eventConnection.getInputStream())); - String message=""; - controllerDebug=new ControllerDebug(args, this); - do { - try{ - message=requestIn.readLine(); - handleRequest (message); - }catch (Exception e){ - e.printStackTrace(); - } - }while (isDebugging); - } catch (IOException e){ - System.out.println(e.getMessage()); - } - - finally{ - try{ - fileOut.close(); - requestIn.close(); - requestOut.close(); - requestSocket.close(); - eventSocket.close(); - System.exit(terminateCode); - } - catch(IOException ioException){ - ioException.printStackTrace(); - } - } - - } - - public void handleRequest(String request) { - String dataString=""; - String goalString=""; - if (request.equals("start")) { - controllerDebug.start(); - isStart=true; - try { - sendRequest("started"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } else if (request.equals("resume")) { - controllerDebug.resume(); - try { - sendRequest("resumed"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.equals("data")){ - try { - dataString=getDataString(); - sendRequest(dataString); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("data:")){ - ControlData.isParseStudy=false; - int index=request.indexOf(":"); - try { - if (request.equals("data:")){ - sendRequest(""); - }else{ - String fileName=request.substring(index+1); - if (StudyUtils.useWreslPlus){ - dataString=getVariableInOneFileWP(fileName); - }else{ - dataString=getVariableInOneFile(fileName); - } - sendRequest(dataString); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - ControlData.isParseStudy=true; - }else if (request.startsWith("tsdetail:")){ - int index=request.indexOf(":"); - try { - if (request.equals("tsdetail:")){ - sendRequest(""); - }else{ - String variableNames=request.substring(index+1); - dataString=getTimeseriesDetail(variableNames); - sendRequest(dataString); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("futdetail:")){ - int index=request.indexOf(":"); - try { - if (request.equals("futdetail:")){ - sendRequest(""); - }else{ - String variableName=request.substring(index+1); - dataString=getFutureValueDetail(variableName); - sendRequest(dataString); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("cycledetail:")){ - int index=request.indexOf(":"); - try { - if (request.equals("cycledetail:")){ - sendRequest(""); - }else{ - String variableName=request.substring(index+1); - dataString=getCycleValueDetail(variableName); - sendRequest(dataString); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("watch:")){ - int index=request.indexOf(":"); - try{ - if (request.equals("watch:")){ - sendRequest(""); - }else{ - String vGNameString=request.substring(index+1); - dataString=getWatch(vGNameString); - sendRequest(dataString); - } - }catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.equals("alldata")){ - try{ - dataString=getAllVariableFiles(); - sendRequest(dataString); - }catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("goal:")){ - ControlData.isParseStudy=false; - int index=request.indexOf(":"); - try { - if (request.equals("goal:")){ - sendRequest(""); - }else{ - String fileName=request.substring(index+1); - if (StudyUtils.useWreslPlus){ - goalString=getGoalInOneFileWP(fileName); - }else{ - goalString=getGoalInOneFile(fileName); - } - sendRequest(goalString); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - ControlData.isParseStudy=true; - }else if (request.equals("allgoals")){ - try{ - goalString=getAllGoalFile(); - sendRequest(goalString); - }catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.equals("allcontrolgoals")){ - try{ - String goalName=getAllControlGoalName(); - sendRequest(goalName); - }catch (IOException e){ - e.printStackTrace(); - } - - }else if (request.startsWith("filtergoal:")){ - int index=request.indexOf(":"); - try { - if (request.equals("filtergoal:")){ - sendRequest(""); - }else{ - String fileName=request.substring(index+1); - goalString=getFilterGoal(fileName); - sendRequest(goalString); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("time")){ - String [] requestParts=request.split(":"); - String[] yearMonthDayCycle=requestParts[1].split("/"); - controllerDebug.debugYear=Integer.parseInt(yearMonthDayCycle[0]); - controllerDebug.debugMonth=Integer.parseInt(yearMonthDayCycle[1]); - controllerDebug.debugDay=Integer.parseInt(yearMonthDayCycle[2]); - controllerDebug.debugCycle=Integer.parseInt(yearMonthDayCycle[3]); - try { - sendRequest("time defined"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("variables:")){ - String [] requestParts=request.split(":"); - allDebugVariables=requestParts[1].split("#"); - try { - sendRequest("variables defined"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.equals("terminate")) { - controllerDebug.stop(); - if (isDebugging){ - if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG")) { - ControlData.xasolver.close(); - }else if (ControlData.solverName.equalsIgnoreCase("Cbc")){ - CbcSolver.close(); - } - DssOperation.saveInitialData(ControlData.dvDss, FilePaths.fullDvarDssPath); - DssOperation.saveDvarData(ControlData.dvDss, FilePaths.fullDvarDssPath); - ControlData.dvDss.close(); - terminateCode=1; - } - System.out.println("Terminated"); - try { - sendRequest("terminated"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - isDebugging=false; - }else if (request.equals("suspend")) { - controllerDebug.suspend(); - System.out.println("suspended"); - try { - sendRequest("suspended"); - sendEvent("suspended"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.equals("pause")) { - controllerDebug.debugYear=ControlData.currYear; - controllerDebug.debugMonth=ControlData.currMonth; - controllerDebug.debugDay=ControlData.currDay; - controllerDebug.debugCycle=ControlData.currCycleIndex+1; - try { - sendRequest("paused"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("modify_timeseries:")){ - String[] requestParts=request.split(":"); - boolean isModified=modifyTimeSeries(requestParts); - try { - if (isModified){ - sendRequest("modified"); - }else{ - sendRequest("not_modified"); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("modify_cycle:")){ - String[] requestParts=request.split(":"); - boolean isModified=modifyCycle(requestParts); - try { - if (isModified){ - sendRequest("modified"); - }else{ - sendRequest("not_modified"); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("resim_cycle:")){ - String[] requestParts=request.split(":"); - Error.clear(); - if (requestParts[1].equals("loadsv")){ - new ReLoadSVDss(ControlData.currStudyDataSet); - } - if (requestParts[3].equals("loadtable")){ - TableSeries.tableSeries=new HashMap (); - } - controllerDebug.modelIndex=Integer.parseInt(requestParts[2])-2; - controllerDebug.resume(); - try { - sendRequest("resumed"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("resim_date:")){ - String[] requestParts=request.split(":"); - Error.clear(); - ControlData.resimDate=true; - ControlData.resimGroundwater=true; - if (requestParts[1].equals("recompile")){ - StudyDataSet sds; - try { - sds = controllerDebug.parse(); - if (StudyParser.total_errors==0){ - ControlData.currStudyDataSet=sds; - controllerDebug.totalCycles = sds.getModelList().size(); - sendEvent("totalcycle#"+controllerDebug.totalCycles); - new PreEvaluator(sds); - }else{ - System.out.println("The change of your code has errors."); - sendEvent("terminate"); - } - } catch (RecognitionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (requestParts[2].equals("loadsv")){ - new ReLoadSVDss(ControlData.currStudyDataSet); - } - if (requestParts[6].equals("loadtable")){ - TableSeries.tableSeries=new HashMap (); - } - controllerDebug.modelIndex=ControlData.currStudyDataSet.getModelList().size()-1; - ControlData.resimYear=Integer.parseInt(requestParts[3]); - ControlData.resimMonth=Integer.parseInt(requestParts[4]); - ControlData.resimDay=Integer.parseInt(requestParts[5]); - ControlData.currYear=ControlData.cycleEndYear; - ControlData.currMonth=ControlData.cycleEndMonth; - ControlData.currDay=ControlData.cycleEndDay; - if (ControlData.isOutputCycle){ - Date resimDate=new Date(ControlData.resimYear-1900, ControlData.resimMonth-1, ControlData.resimDay); - Date cycleDataDate = new Date(ControlData.cycleDataStartYear-1900, ControlData.cycleDataStartMonth-1, ControlData.cycleDataStartDay); - if (resimDate.before(cycleDataDate)){ - ControlData.cycleDataStartYear=ControlData.resimYear; - ControlData.cycleDataStartMonth=ControlData.resimMonth; - ControlData.cycleDataStartDay=ControlData.resimDay; - } - } - - controllerDebug.resume(); - try { - sendRequest("resumed"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("solveroption:")){ - String[] requestParts=request.split(":"); - setSolverOptions(requestParts); - try { - sendRequest("solveroptionset"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if(request.equals("OutputCycleDataToDssOn")){ - if (!ControlData.isOutputCycle) initOutputCycleDataToDss(); - try { - sendRequest("OutputCycleDataToDssOn"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - System.out.println("Output cycle data to Dss file is turned on"); - }else if(request.equals("OutputCycleDataToDssOff")){ - ControlData.isOutputCycle=false; - try { - sendRequest("OutputCycleDataToDssOff"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - System.out.println("Output cycle data to Dss file is turned off"); - }else if(request.equals("OutputAllCyclesOn")){ - ControlData.outputAllCycles=true; - try { - sendRequest("OutputAllCyclesOn"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - System.out.println("All cycles are selected"); - }else if(request.equals("OutputAllCyclesOff")){ - ControlData.outputAllCycles=false; - try { - sendRequest("OutputAllCyclesOff"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if(request.startsWith("SelectedCycleOutput:")){ - int index=request.indexOf(":"); - ControlData.selectedCycleOutput=request.substring(index+1); - try { - sendRequest("Selected output cycles are set"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if (!ControlData.outputAllCycles) System.out.println("Cycles "+ControlData.selectedCycleOutput.replace("\'", "")+" are selected"); - setSelectedOutputCycles(); - }else if(request.startsWith("ShowRunTimeMessage:")){ - int index=request.indexOf(":"); - String showRunTimeMessage=request.substring(index+1); - if (showRunTimeMessage.equalsIgnoreCase("True")){ - ControlData.showRunTimeMessage=true; - try { - sendRequest("Run time messages shown"); - System.out.println("Run time messages shown"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else{ - ControlData.showRunTimeMessage=false; - try { - sendRequest("Run time messages disabled"); - System.out.println("Run time messages disabled"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }else if(request.startsWith("PrintGWFuncCalls:")){ - int index=request.indexOf(":"); - String printGWFuncCalls=request.substring(index+1); - if (printGWFuncCalls.equalsIgnoreCase("True")){ - ControlData.printGWFuncCalls=true; - try { - sendRequest("Print groundwater function calls on"); - System.out.println("Print groundwater function calls on"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else{ - ControlData.printGWFuncCalls=false; - try { - sendRequest("Print groundwater function calls off"); - System.out.println("Print groundwater function calls off"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }else if(request.startsWith("TrackMemoryUsage:")){ - int index=request.indexOf(":"); - String ilpLogUsageMemory=request.substring(index+1); - if (ilpLogUsageMemory.equalsIgnoreCase("True")){ - ILP.loggingUsageMemeory=true; - try { - sendRequest("Track memory usage on"); - System.out.println("Track memory usage on"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else{ - ILP.loggingUsageMemeory=false; - try { - sendRequest("Track memory usage off"); - System.out.println("Track memory usage off"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }else if (request.startsWith("savesvdss:")){ - int index=request.indexOf(":"); - String fileName=request.substring(index+1); - boolean saveSucceed=saveSvDss(fileName); - try { - if (saveSucceed) { - sendRequest("svardsssaved"); - }else{ - sendRequest("dsssavefailed"); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("savedvdss:")){ - int index=request.indexOf(":"); - String fileName=request.substring(index+1); - boolean saveSucceed=saveDvDss(fileName); - try { - if (saveSucceed) { - sendRequest("dvardsssaved"); - }else{ - sendRequest("dsssavefailed"); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if(request.startsWith("saveinitdss:")){ - int index=request.indexOf(":"); - String fileName=request.substring(index+1); - boolean saveSucceed=saveInitDss(fileName); - try { - if (saveSucceed) { - sendRequest("initdsssaved"); - }else{ - sendRequest("dsssavefailed"); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("conditional_breakpoint:")){ - setConditionalBreakpoint(request); - try { - sendRequest("conditioal breakpoint set"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - }else if (request.startsWith("cbcTolerancePrimal:")){ - String[] requestParts=request.split(":"); - CbcSolver.solve_2_primalT = Double.parseDouble(requestParts[1]); - try { - sendRequest(request+" set"); - System.out.println(request+" set"); - } catch (IOException e) { - e.printStackTrace(); - } - }else if (request.startsWith("cbcTolerancePrimalRelax:")){ - String[] requestParts=request.split(":"); - CbcSolver.solve_2_primalT_relax = Double.parseDouble(requestParts[1]); - ControlData.relationTolerance = Math.max(CbcSolver.solve_2_primalT_relax*10, 1e-6); - try { - sendRequest(request+" set"); - System.out.println(request+" set"); - } catch (IOException e) { - e.printStackTrace(); - } - }else if (request.startsWith("cbcToleranceWarmPrimal:")){ - String[] requestParts=request.split(":"); - CbcSolver.solve_whs_primalT = Double.parseDouble(requestParts[1]); - try { - sendRequest(request+" set"); - System.out.println(request+" set"); - } catch (IOException e) { - e.printStackTrace(); - } - }else if (request.startsWith("cbcToleranceInteger:")){ - String[] requestParts=request.split(":"); - CbcSolver.integerT = Double.parseDouble(requestParts[1]); - try { - sendRequest(request+" set"); - System.out.println(request+" set"); - } catch (IOException e) { - e.printStackTrace(); - } - }else if (request.startsWith("cbcToleranceIntegerCheck:")){ - String[] requestParts=request.split(":"); - CbcSolver.integerT_check = Double.parseDouble(requestParts[1]); - try { - sendRequest(request+" set"); - System.out.println(request+" set"); - } catch (IOException e) { - e.printStackTrace(); - } - }else if (request.startsWith("cbcToleranceZero:")){ - String[] requestParts=request.split(":"); - ControlData.zeroTolerance = Double.parseDouble(requestParts[1]); - try { - sendRequest(request+" set"); - System.out.println(request+" set"); - } catch (IOException e) { - e.printStackTrace(); - } - }else if (request.startsWith("cbcHintRelaxPenalty:")){ - String[] requestParts=request.split(":"); - CbcSolver.cbcHintRelaxPenalty = Double.parseDouble(requestParts[1]); - try { - sendRequest(request+" set"); - System.out.println(request+" set"); - } catch (IOException e) { - e.printStackTrace(); - } - }else if (request.startsWith("cbcHintTimeMax:")){ - String[] requestParts=request.split(":"); - CbcSolver.cbcHintTimeMax = Integer.parseInt(requestParts[1]); - try { - sendRequest(request+" set"); - System.out.println(request+" set"); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public void sendRequest(String request) throws IOException { - synchronized (requestConnection){ - try{ - requestOut.println(request); - requestOut.flush(); - }catch(Exception e){ - e.printStackTrace(); - } - } - } - - public void sendEvent(String event) throws IOException { - synchronized (eventConnection){ - try{ - eventOut.println(event); - eventOut.flush(); - }catch(Exception e){ - e.printStackTrace(); - } - } - } - - public String getVariableInOneFile(String fileFullPath){ - String dataString=""; - String modelName=ControlData.currStudyDataSet.getModelList().get(ControlData.currCycleIndex); - ModelDataSet mds=ControlData.currStudyDataSet.getModelDataSetMap().get(modelName); - Map tsMap = mds.tsMap; - Map dvMap = SolverData.getDvarMap(); - Map svMap = mds.svMap; - Map svFutMap = mds.svFutMap; - Map asMap = mds.asMap; - Map partsMap=new HashMap(); - try { - WreslTreeWalker walker = FileParser.parseOneFileForDebug(fileFullPath); - if (walker==null) return dataString; - SimulationDataSet fileDataSet = walker.thisFileDataSet; - ArrayList dvList = fileDataSet.dvList; - ArrayList svList = fileDataSet.svList; - ArrayList asList = fileDataSet.asList; - ArrayList tsList = fileDataSet.tsList; - ArrayList wtList = fileDataSet.wtList; - asList.removeAll(dvList); - ArrayList sortedList=new ArrayList(); - sortedList.addAll(dvList); - sortedList.addAll(svList); - sortedList.addAll(tsList); - sortedList.addAll(asList); - sortedList.addAll(wtList); - - ArrayList gList = fileDataSet.gList; - for (String gName:gList){ - Set dependants = fileDataSet.gMap.get(gName).expressionDependants; - Iterator iterator = dependants.iterator(); - while (iterator.hasNext()){ - String varName=iterator.next(); - if (!sortedList.contains(varName)){ - sortedList.add(varName); - } - } - } - for (String svName:svList){ - Set dependants = fileDataSet.svMap.get(svName).dependants; - Iterator iterator = dependants.iterator(); - while (iterator.hasNext()){ - String varName=iterator.next(); - if (!sortedList.contains(varName)){ - sortedList.add(varName); - } - } - } - for (String asName:asList){ - if (fileDataSet.asMap.containsKey(asName)){ - Set dependants = fileDataSet.asMap.get(asName).dependants; - Iterator iterator = dependants.iterator(); - while (iterator.hasNext()){ - String varName=iterator.next(); - if (!sortedList.contains(varName)){ - sortedList.add(varName); - } - } - } - } - - IntDouble intDouble; - Collections.sort(sortedList, String.CASE_INSENSITIVE_ORDER); - for (String variable: sortedList){ - if (svMap.containsKey(variable)){ - Svar sv = svMap.get(variable); - intDouble=sv.getData(); - if (intDouble != null) { - dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; - partsMap.put(variable, sv.kind+":"+ControlData.timeStep); - } - }else if (dvMap.containsKey(variable)){ - Dvar dv = dvMap.get(variable); - intDouble=dv.getData(); - if (intDouble != null) { - dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; - partsMap.put(variable, dv.kind+":"+ControlData.timeStep); - } - }else if (tsMap.containsKey(variable)){ - Timeseries ts = tsMap.get(variable); - intDouble=ts.getData(); - if (intDouble != null) { - dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; - partsMap.put(variable, ts.kind+":"+ControlData.timeStep); - } - }else if (asMap.containsKey(variable)){ - Alias as = asMap.get(variable); - intDouble=as.getData(); - if (intDouble != null) { - dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; - partsMap.put(variable, as.kind+":"+ControlData.timeStep); - } - } - } - if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); - dataString=dataString+"!"; - for (String variable: partsMap.keySet()){ - dataString=dataString+variable+":"+partsMap.get(variable)+"#"; - } - if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); - } catch (RecognitionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return dataString; - } - - public String getVariableInOneFileWP(String fileFullPath){ - String dataString=""; - StudyDataSet sds = ControlData.currStudyDataSet; - String modelName=sds.getModelList().get(ControlData.currCycleIndex); - ModelDataSet mds=sds.getModelDataSetMap().get(modelName); - Map parameterMap = sds.getParameterMap(); - Map tsMap = mds.tsMap; - Map dvMap = SolverData.getDvarMap(); - Map svMap = mds.svMap; - Map svFutMap = mds.svFutMap; - Map asMap = mds.asMap; - Map partsMap=new HashMap(); - ArrayList parameterList = new ArrayList(); - ArrayList dvList = new ArrayList(); - ArrayList svList = new ArrayList(); - ArrayList asList = new ArrayList(); - ArrayList tsList = new ArrayList(); - ArrayList wtList = new ArrayList(); - ArrayList gList = new ArrayList(); - ArrayList sortedList = new ArrayList(); - ModelTemp modelTemp; - fileFullPath=fileFullPath.replace("/", "\\"); - if (fileFullPath.equalsIgnoreCase(FilePaths.fullMainPath)){ - StudyTemp studyTemp = ParserUtils.parseWreslMain(fileFullPath); - if (studyTemp==null) return dataString; - parameterList = studyTemp.parameterList; - sortedList.addAll(parameterList); - Map modelMap = studyTemp.modelMap; - ArrayList modelList = studyTemp.modelList; - for (String model: modelList){ - modelTemp=modelMap.get(model); - dvList = modelTemp.dvList; - svList = modelTemp.svList; - asList = modelTemp.asList; - tsList = modelTemp.tsList; - gList = modelTemp.glList; - ProcWeight.collectWeightVar(modelTemp); - wtList = modelTemp.wvList_post; - asList.removeAll(dvList); - sortedList.addAll(dvList); - sortedList.addAll(svList); - sortedList.addAll(tsList); - sortedList.addAll(asList); - sortedList.addAll(wtList); - for (String gName:gList){ - if (modelTemp.glMap.containsKey(gName)){ - Set dependants = modelTemp.glMap.get(gName).dependants; - Iterator iterator = dependants.iterator(); - while (iterator.hasNext()){ - String varName=iterator.next(); - if (!sortedList.contains(varName)){ - sortedList.add(varName); - } - } - } - } - for (String svName:svList){ - if (modelTemp.svMap.containsKey(svName)){ - Set dependants = modelTemp.svMap.get(svName).dependants; - Iterator iterator = dependants.iterator(); - while (iterator.hasNext()){ - String varName=iterator.next(); - if (!sortedList.contains(varName)){ - sortedList.add(varName); - } - } - } - } - for (String asName:asList){ - if (modelTemp.asMap.containsKey(asName)){ - Set dependants = modelTemp.asMap.get(asName).dependants; - Iterator iterator = dependants.iterator(); - while (iterator.hasNext()){ - String varName=iterator.next(); - if (!sortedList.contains(varName)){ - sortedList.add(varName); - } - } - } - } - ArrayList varIfInc = getVariableIfInc(modelTemp); - sortedList.remove(varIfInc); - sortedList.addAll(varIfInc); - } - }else{ - modelTemp = ParserUtils.parseWreslFile(fileFullPath); - if (modelTemp==null) return dataString; - dvList = modelTemp.dvList; - svList = modelTemp.svList; - asList = modelTemp.asList; - tsList = modelTemp.tsList; - gList = modelTemp.glList; - ProcWeight.collectWeightVar(modelTemp); - wtList = modelTemp.wvList_post; - sortedList = new ArrayList(); - asList.removeAll(dvList); - sortedList.addAll(dvList); - sortedList.addAll(svList); - sortedList.addAll(tsList); - sortedList.addAll(asList); - sortedList.addAll(wtList); - for (String gName:gList){ - if (modelTemp.glMap.containsKey(gName)){ - Set dependants = modelTemp.glMap.get(gName).dependants; - Iterator iterator = dependants.iterator(); - while (iterator.hasNext()){ - String varName=iterator.next(); - if (!sortedList.contains(varName)){ - sortedList.add(varName); - } - } - } - } - for (String svName:svList){ - if (modelTemp.svMap.containsKey(svName)){ - Set dependants = modelTemp.svMap.get(svName).dependants; - Iterator iterator = dependants.iterator(); - while (iterator.hasNext()){ - String varName=iterator.next(); - if (!sortedList.contains(varName)){ - sortedList.add(varName); - } - } - } - } - for (String asName:asList){ - if (modelTemp.asMap.containsKey(asName)){ - Set dependants = modelTemp.asMap.get(asName).dependants; - Iterator iterator = dependants.iterator(); - while (iterator.hasNext()){ - String varName=iterator.next(); - if (!sortedList.contains(varName)){ - sortedList.add(varName); - } - } - } - } - ArrayList varIfInc = getVariableIfInc(modelTemp); - sortedList.remove(varIfInc); - sortedList.addAll(varIfInc); - } - IntDouble intDouble; - Collections.sort(sortedList, String.CASE_INSENSITIVE_ORDER); - for (String variable: sortedList){ - variable=variable.toLowerCase(); - if (svMap.containsKey(variable)){ - Svar sv = svMap.get(variable); - intDouble=sv.getData(); - if (intDouble != null) { - dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; - partsMap.put(variable, sv.kind+":"+ControlData.timeStep); - } - }else if (dvMap.containsKey(variable)){ - Dvar dv = dvMap.get(variable); - intDouble=dv.getData(); - if (intDouble != null) { - dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; - partsMap.put(variable, dv.kind+":"+ControlData.timeStep); - } - }else if (tsMap.containsKey(variable)){ - Timeseries ts = tsMap.get(variable); - intDouble=ts.getData(); - if (intDouble != null) { - dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; - partsMap.put(variable, ts.kind+":"+ControlData.timeStep); - } - }else if (asMap.containsKey(variable)){ - Alias as = asMap.get(variable); - intDouble=as.getData(); - if (intDouble != null) { - dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; - partsMap.put(variable, as.kind+":"+ControlData.timeStep); - } - }else if (parameterMap.containsKey(variable)){ - Svar sv = parameterMap.get(variable); - intDouble=sv.getData(); - if (intDouble != null){ - dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; - partsMap.put(variable, sv.kind+":"+ControlData.timeStep); - } - } - } - if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); - dataString=dataString+"!"; - for (String variable: partsMap.keySet()){ - dataString=dataString+variable+":"+partsMap.get(variable)+"#"; - } - if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); - - return dataString; - } - - public ArrayList getVariableIfInc(ModelTemp modelTemp){ - ArrayList varList= new ArrayList(); - ArrayList ifIncItemGroupIDList = modelTemp.ifIncItemGroupIDList; - Map ifIncItemGroupMap = modelTemp.ifIncItemGroupMap; - for (int i=0; i conditionValueList = ProcIfIncItemGroup.evaluateConditions(Tools.allToLowerCase(ifIncItemGroup.conditionList)); - int j=0; - int cn=conditionValueList.size(); - while (j> inc_svar_map_list = ifIncItemGroup.inc_svar_map_list; - HashMap inc_svar_map = inc_svar_map_list.get(j); - Set svarNames = inc_svar_map.keySet(); - varList.addAll(svarNames); - Iterator iterator = svarNames.iterator(); - while (iterator.hasNext()){ - String svarName = iterator.next(); - SvarTemp svar = inc_svar_map.get(svarName); - Set dependants = svar.dependants; - varList.removeAll(dependants); - varList.addAll(dependants); - } - - ArrayList> inc_dvar_map_list = ifIncItemGroup.inc_dvar_map_list; - HashMap inc_dvar_map = inc_dvar_map_list.get(j); - Set dvarNames = inc_dvar_map.keySet(); - varList.addAll(dvarNames); - iterator = dvarNames.iterator(); - while (iterator.hasNext()){ - String dvarName = iterator.next(); - DvarTemp dvar = inc_dvar_map.get(dvarName); - Set dependants = dvar.dependants; - varList.removeAll(dependants); - varList.addAll(dependants); - } - - ArrayList> inc_alias_map_list = ifIncItemGroup.inc_alias_map_list; - HashMap inc_alias_map = inc_alias_map_list.get(j); - Set aliasNames = inc_alias_map.keySet(); - varList.addAll(aliasNames); - iterator = aliasNames.iterator(); - while (iterator.hasNext()){ - String aliasName = iterator.next(); - AliasTemp alias = inc_alias_map.get(aliasName); - Set dependants = alias.dependants; - varList.removeAll(dependants); - varList.addAll(dependants); - } - - ArrayList> inc_goalSimple_map_list = ifIncItemGroup.inc_goalSimple_map_list; - HashMap inc_goalSimple_map = inc_goalSimple_map_list.get(j); - Set goalSimpleNames = inc_goalSimple_map.keySet(); - iterator = goalSimpleNames.iterator(); - while (iterator.hasNext()){ - String goalSimpleName = iterator.next(); - GoalTemp goalSimple = inc_goalSimple_map.get(goalSimpleName); - Set dependants = goalSimple.dependants; - varList.removeAll(dependants); - varList.addAll(dependants); - } - - ArrayList> inc_goalComplex_map_list = ifIncItemGroup.inc_goalComplex_map_list; - HashMap inc_goalComplex_map = inc_goalComplex_map_list.get(j); - Set goalComplexNames = inc_goalComplex_map.keySet(); - iterator = goalComplexNames.iterator(); - while (iterator.hasNext()){ - String goalComplexName = iterator.next(); - GoalTemp goalComplex = inc_goalComplex_map.get(goalComplexName); - Set dependants = goalComplex.dependants; - varList.removeAll(dependants); - varList.addAll(dependants); - } - - varList.addAll(ifIncItemGroup.inc_timeseries_map_list.get(j).keySet()); - } - } - return varList; - } - - public String getGoalInOneFile(String fileFullPath){ - String goalString=""; - Map gMap = SolverData.getConstraintDataMap(); - Map dvMap = SolverData.getDvarMap(); - ArrayList controlGoals=new ArrayList(); - - try { - WreslTreeWalker walker = FileParser.parseOneFileForDebug(fileFullPath); - if (walker==null) return goalString; - SimulationDataSet fileDataSet = walker.thisFileDataSet; - ArrayList sortedGoalList = fileDataSet.gList; - - Collections.sort(sortedGoalList, String.CASE_INSENSITIVE_ORDER); - for (int i=0; i multiplier = ee.getMultiplier(); - Set mKeySet = multiplier.keySet(); - Iterator mi = mKeySet.iterator(); - boolean hasData = true; - while (mi.hasNext()){ - String variable=mi.next(); - Number value=multiplier.get(variable).getData(); - double value1=value.doubleValue(); - if (goalString.endsWith(":")){ - if (value1==1.0){ - goalString=goalString+variable; - }else if (value1==-1.0){ - goalString=goalString+"-"+variable; - }else{ - goalString=goalString+df.format(value)+variable; - } - }else{ - if (value1==1.0){ - goalString=goalString+"+"+variable; - }else if (value1 == -1.0){ - goalString=goalString+"-"+variable; - }else if(value1>=0){ - goalString=goalString+"+"+df.format(value)+variable; - }else{ - goalString=goalString+df.format(value)+variable; - } - } - if (!(variable.startsWith("surplus__") || variable.startsWith("slack__"))){ - IntDouble id = dvMap.get(variable).getData(); - if (id==null){ - hasData=false; - }else{ - double variableValue=id.getData().doubleValue(); - lhs=lhs+value1*variableValue; - } - } - } - Number value=ee.getValue().getData(); - double value1=value.doubleValue(); - if (value1>0){ - goalString=goalString+"+"+df.format(value)+ec.getSign()+"0#"; - }else if(value1<0){ - goalString=goalString+df.format(value)+ec.getSign()+"0#"; - }else{ - goalString=goalString+ec.getSign()+"0#"; - } - lhs=lhs+value1; - if (Math.abs(lhs)<=0.00001 && hasData){ - controlGoals.add(goalName); - } - } - } - } - if (goalString.endsWith("#")) goalString=goalString.substring(0, goalString.length()-1); - } catch (RecognitionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - goalString=goalString+"!"; - for (String controlGoal:controlGoals){ - goalString=goalString+controlGoal+":"; - } - if (goalString.endsWith(":")) goalString=goalString.substring(0, goalString.length()-1); - return goalString; - } - - public String getGoalInOneFileWP(String fileFullPath){ - String goalString=""; - Map gMap = SolverData.getConstraintDataMap(); - Map dvMap = SolverData.getDvarMap(); - ArrayList controlGoals=new ArrayList(); - ArrayList sortedGoalList=new ArrayList(); - - fileFullPath=fileFullPath.replace("/", "\\"); - if (fileFullPath.equalsIgnoreCase(FilePaths.fullMainPath)){ - StudyTemp studyTemp = ParserUtils.parseWreslMain(fileFullPath); - if (studyTemp==null) return goalString; - Map modelMap = studyTemp.modelMap; - ArrayList modelList = studyTemp.modelList; - for (String model: modelList){ - ModelTemp modelTemp = modelMap.get(model); - sortedGoalList.addAll(modelTemp.glList); - ArrayList ifIncItemGroupIDList = modelTemp.ifIncItemGroupIDList; - Map ifIncItemGroupMap = modelTemp.ifIncItemGroupMap; - for (int i=0; i conditionValueList = ProcIfIncItemGroup.evaluateConditions(Tools.allToLowerCase(ifIncItemGroup.conditionList)); - int j=0; - int cn=conditionValueList.size(); - while (j simpleGoals = ifIncItemGroup.inc_goalSimple_map_list.get(j); - HashMap complexGoals = ifIncItemGroup.inc_goalComplex_map_list.get(j); - sortedGoalList.addAll(simpleGoals.keySet()); - sortedGoalList.addAll(complexGoals.keySet()); - } - } - } - }else{ - ModelTemp modelTemp = ParserUtils.parseWreslFile(fileFullPath); - if (modelTemp==null) return goalString; - sortedGoalList = modelTemp.glList; - ArrayList ifIncItemGroupIDList = modelTemp.ifIncItemGroupIDList; - Map ifIncItemGroupMap = modelTemp.ifIncItemGroupMap; - for (int i=0; i conditionValueList = ProcIfIncItemGroup.evaluateConditions(Tools.allToLowerCase(ifIncItemGroup.conditionList)); - int j=0; - int cn=conditionValueList.size(); - while (j simpleGoals = ifIncItemGroup.inc_goalSimple_map_list.get(j); - HashMap complexGoals = ifIncItemGroup.inc_goalComplex_map_list.get(j); - sortedGoalList.addAll(simpleGoals.keySet()); - sortedGoalList.addAll(complexGoals.keySet()); - } - } - } - - Collections.sort(sortedGoalList, String.CASE_INSENSITIVE_ORDER); - for (int i=0; i multiplier = ee.getMultiplier(); - Set mKeySet = multiplier.keySet(); - Iterator mi = mKeySet.iterator(); - boolean hasData = true; - while (mi.hasNext()){ - String variable=mi.next(); - Number value=multiplier.get(variable).getData(); - double value1=value.doubleValue(); - if (goalString.endsWith(":")){ - if (value1==1.0){ - goalString=goalString+variable; - }else if (value1==-1.0){ - goalString=goalString+"-"+variable; - }else{ - goalString=goalString+df.format(value)+variable; - } - }else{ - if (value1==1.0){ - goalString=goalString+"+"+variable; - }else if (value1 == -1.0){ - goalString=goalString+"-"+variable; - }else if(value1>=0){ - goalString=goalString+"+"+df.format(value)+variable; - }else{ - goalString=goalString+df.format(value)+variable; - } - } - if (!(variable.startsWith("surplus__") || variable.startsWith("slack__"))){ - IntDouble id = dvMap.get(variable).getData(); - if (id==null){ - hasData=false; - }else{ - double variableValue=id.getData().doubleValue(); - lhs=lhs+value1*variableValue; - } - } - } - Number value=ee.getValue().getData(); - double value1=value.doubleValue(); - if (value1>0){ - goalString=goalString+"+"+df.format(value)+ec.getSign()+"0#"; - }else if(value1<0){ - goalString=goalString+df.format(value)+ec.getSign()+"0#"; - }else{ - goalString=goalString+ec.getSign()+"0#"; - } - lhs=lhs+value1; - if (Math.abs(lhs)<=0.00001 && hasData){ - controlGoals.add(goalName); - } - } - } - } - if (goalString.endsWith("#")) goalString=goalString.substring(0, goalString.length()-1); - goalString=goalString+"!"; - for (String controlGoal:controlGoals){ - goalString=goalString+controlGoal+":"; - } - if (goalString.endsWith(":")) goalString=goalString.substring(0, goalString.length()-1); - return goalString; - } - - public String getFilterGoal(String fileName){ - String filtergoal="filteredgoalretrieved"; - if (procFilterFile(fileName)){ - Map gMap = SolverData.getConstraintDataMap(); - Map dvMap = SolverData.getDvarMap(); - Set goalKeySet=filterGoals.keySet(); - - try{ - File dataFolder= new File(dataDir); - dataFolder.mkdirs(); - File filterGoalFile = new File(dataFolder, "filtergoals.dat"); - FileOutputStream filterGoalStream = new FileOutputStream(filterGoalFile); - OutputStreamWriter filterGoalWriter = new OutputStreamWriter(filterGoalStream); - BufferedWriter filterGoalBuffer = new BufferedWriter(filterGoalWriter); - - for (int i=0; i multiplier = ee.getMultiplier(); - Set mKeySet = multiplier.keySet(); - Iterator mi = mKeySet.iterator(); - boolean hasData = true; - while (mi.hasNext()){ - String variable=mi.next(); - Number value=multiplier.get(variable).getData(); - double value1=value.doubleValue(); - if (goalString.endsWith(":")){ - if (value1==1.0){ - goalString=goalString+variable; - }else if (value1==-1.0){ - goalString=goalString+"-"+variable; - }else{ - goalString=goalString+df.format(value)+variable; - } - }else{ - if (value1==1.0){ - goalString=goalString+"+"+variable; - }else if (value1 == -1.0){ - goalString=goalString+"-"+variable; - }else if(value1>=0){ - goalString=goalString+"+"+df.format(value)+variable; - }else{ - goalString=goalString+df.format(value)+variable; - } - } - if (!(variable.startsWith("surplus__") || variable.startsWith("slack__"))){ - IntDouble id = dvMap.get(variable).getData(); - if (id==null){ - hasData=false; - }else{ - double variableValue=id.getData().doubleValue(); - lhs=lhs+value1*variableValue; - } - } - } - Number value=ee.getValue().getData(); - double value1=value.doubleValue(); - if (value1>0){ - goalString=goalString+"+"+df.format(value)+ec.getSign()+"0"; - }else if(value1<0){ - goalString=goalString+df.format(value)+ec.getSign()+"0"; - }else{ - goalString=goalString+ec.getSign()+"0"; - } - lhs=lhs+value1; - FilterGoal fg = filterGoals.get(goalName); - double tolerance=Double.parseDouble(fg.getTolerance()); - if (Math.abs(lhs)<=tolerance && hasData){ - goalString=goalString+";"+"y"+System.getProperty("line.separator"); - }else{ - goalString=goalString+";"+"n"+System.getProperty("line.separator"); - } - filterGoalBuffer.write(goalString); - } - } - } - filterGoalBuffer.close(); - }catch (IOException e){ - return "failed"; - } - }else{ - return "failed"; - } - return filtergoal; - } - - public boolean procFilterFile(String filterName){ - boolean doFilter=true; - filterGoals=new HashMap(); - filterGoalNames=new ArrayList(); - File filterFile=new File(filterName); - if (filterFile.exists()){ - doFilter=true; - try { - FileReader fr = new FileReader(filterFile); - BufferedReader br = new BufferedReader(fr); - String line = br.readLine(); - if (line != null){ - while ((line = br.readLine()) != null) { - line=line.trim().toLowerCase(); - String[] filterParts=line.split(","); - int length=filterParts.length; - FilterGoal fg=new FilterGoal(); - if (length==3){ - fg.setAlias(filterParts[1]); - fg.setTolerance(filterParts[2]); - }else if (length==2){ - fg.setAlias(filterParts[1]); - } - filterGoals.put(filterParts[0], fg); - filterGoalNames.add(filterParts[0]); - } - } - fr.close(); - } catch (Exception e) { - e.printStackTrace(); - doFilter=false; - } - }else{ - doFilter=false; - } - return doFilter; - } - - public String getAllVariableString(){ - String dataString=""; - ArrayList allDataNames=new ArrayList(); - ArrayList allTsNames=new ArrayList(); - ArrayList allDvNames=new ArrayList(); - ArrayList allSvNames=new ArrayList(); - ArrayList allAsNames=new ArrayList(); - ArrayList allParameterNames=new ArrayList(); - Map allData=new HashMap(); - StudyDataSet sds = ControlData.currStudyDataSet; - String modelName=sds.getModelList().get(ControlData.currCycleIndex); - ModelDataSet mds=sds.getModelDataSetMap().get(modelName); - Map tsMap = mds.tsMap; - Map dvMap = SolverData.getDvarMap(); - Map svMap = mds.svMap; - Map svFutMap = mds.svFutMap; - Map asMap = mds.asMap; - Map parameterMap = sds.getParameterMap(); - Map partsMap=new HashMap(); - - IntDouble intDouble; - - Set tsKeySet = tsMap.keySet(); - Iterator tsIterator = tsKeySet.iterator(); - while (tsIterator.hasNext()){ - String tsName=tsIterator.next(); - if (!allDataNames.contains(tsName)){ - Timeseries ts = tsMap.get(tsName); - intDouble=ts.getData(); - if (intDouble != null){ - allDataNames.add(tsName); - allTsNames.add(tsName); - allData.put(tsName, intDouble.getData()); - partsMap.put(tsName, ts.kind+":"+ControlData.timeStep); - } - } - } - - Set dvKeySet = dvMap.keySet(); - Iterator dvIterator = dvKeySet.iterator(); - while (dvIterator.hasNext()){ - String dvName=dvIterator.next(); - if (!allDataNames.contains(dvName)){ - Dvar dv = dvMap.get(dvName); - intDouble=dv.getData(); - if (intDouble !=null){ - allDataNames.add(dvName); - allDvNames.add(dvName); - allData.put(dvName, intDouble.getData()); - partsMap.put(dvName, dv.kind+":"+ControlData.timeStep); - } - } - } - - Set svKeySet = svMap.keySet(); - Iterator svIterator = svKeySet.iterator(); - while (svIterator.hasNext()){ - String svName=svIterator.next(); - if (!allDataNames.contains(svName)){ - Svar sv = svMap.get(svName); - intDouble=sv.getData(); - if (intDouble!=null){ - allDataNames.add(svName); - allSvNames.add(svName); - allData.put(svName, intDouble.getData()); - partsMap.put(svName, sv.kind+":"+ControlData.timeStep); - } - } - } - - Set svFutKeySet = svFutMap.keySet(); - Iterator svFutIterator = svFutKeySet.iterator(); - while (svFutIterator.hasNext()){ - String svFutName=svFutIterator.next(); - if (!allDataNames.contains(svFutName)){ - Svar svFut = svFutMap.get(svFutName); - intDouble=svFut.getData(); - if (intDouble!=null){ - allDataNames.add(svFutName); - allSvNames.add(svFutName); - allData.put(svFutName, intDouble.getData()); - partsMap.put(svFutName, svFut.kind+":"+ControlData.timeStep); - } - } - } - - Set asKeySet = asMap.keySet(); - Iterator asIterator = asKeySet.iterator(); - while (asIterator.hasNext()){ - String asName=asIterator.next(); - if (!allDataNames.contains(asName)){ - Alias as = asMap.get(asName); - intDouble=as.getData(); - if (intDouble!=null){ - allDataNames.add(asName); - allData.put(asName, intDouble.getData()); - partsMap.put(asName, as.kind+":"+ControlData.timeStep); - } - } - if (!allAsNames.contains(asName)){ - allAsNames.add(asName); - } - } - - Set parameterKeySet = parameterMap.keySet(); - Iterator parameterIterator = parameterKeySet.iterator(); - while (parameterIterator.hasNext()){ - String parameterName=parameterIterator.next(); - if (!allDataNames.contains(parameterName)){ - Svar parameter = parameterMap.get(parameterName); - intDouble=parameter.getData(); - if (intDouble!=null){ - allDataNames.add(parameterName); - allParameterNames.add(parameterName); - allData.put(parameterName, intDouble.getData()); - partsMap.put(parameterName, parameter.kind+":"+ControlData.timeStep); - } - } - } - - Collections.sort(allDataNames, String.CASE_INSENSITIVE_ORDER); - for (String variable: allDataNames){ - dataString=dataString+variable+":"+df.format(allData.get(variable))+"#"; - } - - dataString=dataString+"&"; - for (String variable: partsMap.keySet()){ - dataString=dataString+variable+":"+partsMap.get(variable)+"#"; - } - - dataString=dataString+"&"; - - Map weightMap = SolverData.getWeightMap(); - for (int i=0; i<=1; i++){ - ArrayList weightCollection; - if (i==0){ - weightCollection = ControlData.currModelDataSet.wtList; - }else{ - weightCollection = ControlData.currModelDataSet.wtTimeArrayList; - } - Iterator weightIterator = weightCollection.iterator(); - - while(weightIterator.hasNext()){ - String weightName=(String)weightIterator.next(); - dataString=dataString+weightName+":"+df.format(weightMap.get(weightName).getValue())+"#"; - } - } - Map weightSlackSurplusMap = SolverData.getWeightSlackSurplusMap(); - CopyOnWriteArrayList usedWeightSlackSurplusCollection = ControlData.currModelDataSet.usedWtSlackSurplusList; - Iterator usedWeightSlackSurplusIterator = usedWeightSlackSurplusCollection.iterator(); - - while(usedWeightSlackSurplusIterator.hasNext()){ - String usedWeightSlackSurplusName=(String)usedWeightSlackSurplusIterator.next(); - dataString=dataString+usedWeightSlackSurplusName+":"+df.format(weightSlackSurplusMap.get(usedWeightSlackSurplusName).getValue())+"#"; - } - - if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); - return dataString; - } - - public String getAllVariableFiles(){ - String allDataString="alldataretrieved"; - ArrayList allDataNames=new ArrayList(); - ArrayList allTsNames=new ArrayList(); - ArrayList allDvNames=new ArrayList(); - ArrayList allSvNames=new ArrayList(); - ArrayList allAsNames=new ArrayList(); - ArrayList allParameterNames=new ArrayList(); - Map allData=new HashMap(); - StudyDataSet sds = ControlData.currStudyDataSet; - String modelName=sds.getModelList().get(ControlData.currCycleIndex); - ModelDataSet mds=sds.getModelDataSetMap().get(modelName); - Map tsMap = mds.tsMap; - Map dvMap = SolverData.getDvarMap(); - Map svMap = mds.svMap; - Map svFutMap = mds.svFutMap; - Map asMap = mds.asMap; - Map parameterMap = sds.getParameterMap(); - Map partsMap=new HashMap(); - - IntDouble intDouble; - - Set tsKeySet = tsMap.keySet(); - Iterator tsIterator = tsKeySet.iterator(); - while (tsIterator.hasNext()){ - String tsName=tsIterator.next(); - if (!allDataNames.contains(tsName)){ - Timeseries ts = tsMap.get(tsName); - intDouble=ts.getData(); - if (intDouble != null){ - allDataNames.add(tsName); - allTsNames.add(tsName); - allData.put(tsName, intDouble.getData()); - partsMap.put(tsName, ts.kind+":"+ControlData.timeStep); - } - } - } - - Set dvKeySet = dvMap.keySet(); - Iterator dvIterator = dvKeySet.iterator(); - while (dvIterator.hasNext()){ - String dvName=dvIterator.next(); - if (!allDataNames.contains(dvName)){ - Dvar dv = dvMap.get(dvName); - intDouble=dv.getData(); - if (intDouble !=null){ - allDataNames.add(dvName); - allDvNames.add(dvName); - allData.put(dvName, intDouble.getData()); - partsMap.put(dvName, dv.kind+":"+ControlData.timeStep); - } - } - } - - Set svKeySet = svMap.keySet(); - Iterator svIterator = svKeySet.iterator(); - while (svIterator.hasNext()){ - String svName=svIterator.next(); - if (!allDataNames.contains(svName)){ - Svar sv = svMap.get(svName); - intDouble=sv.getData(); - if (intDouble!=null){ - allDataNames.add(svName); - allSvNames.add(svName); - allData.put(svName, intDouble.getData()); - partsMap.put(svName, sv.kind+":"+ControlData.timeStep); - } - } - } - - Set svFutKeySet = svFutMap.keySet(); - Iterator svFutIterator = svFutKeySet.iterator(); - while (svFutIterator.hasNext()){ - String svFutName=svFutIterator.next(); - if (!allDataNames.contains(svFutName)){ - Svar svFut = svFutMap.get(svFutName); - intDouble=svFut.getData(); - if (intDouble!=null){ - allDataNames.add(svFutName); - allSvNames.add(svFutName); - allData.put(svFutName, intDouble.getData()); - partsMap.put(svFutName, svFut.kind+":"+ControlData.timeStep); - } - } - } - - Set asKeySet = asMap.keySet(); - Iterator asIterator = asKeySet.iterator(); - while (asIterator.hasNext()){ - String asName=asIterator.next(); - if (!allDataNames.contains(asName)){ - Alias as = asMap.get(asName); - intDouble=as.getData(); - if (intDouble!=null){ - allDataNames.add(asName); - allData.put(asName, intDouble.getData()); - partsMap.put(asName, as.kind+":"+ControlData.timeStep); - } - } - if (!allAsNames.contains(asName)){ - allAsNames.add(asName); - } - } - - Set parameterKeySet = parameterMap.keySet(); - Iterator parameterIterator = parameterKeySet.iterator(); - while (parameterIterator.hasNext()){ - String parameterName=parameterIterator.next(); - if (!allDataNames.contains(parameterName)){ - Svar parameter = parameterMap.get(parameterName); - intDouble=parameter.getData(); - if (intDouble!=null){ - allDataNames.add(parameterName); - allParameterNames.add(parameterName); - allData.put(parameterName, intDouble.getData()); - partsMap.put(parameterName, parameter.kind+":"+ControlData.timeStep); - } - } - } - - try{ - File dataFolder= new File(dataDir); - dataFolder.mkdirs(); - File allDataFile = new File(dataFolder, "allvariables.dat"); - FileOutputStream allDataStream = new FileOutputStream(allDataFile); - OutputStreamWriter allDataWriter = new OutputStreamWriter(allDataStream); - BufferedWriter allDataBuffer = new BufferedWriter(allDataWriter); - - Collections.sort(allDataNames, String.CASE_INSENSITIVE_ORDER); - for (String variable: allDataNames){ - allDataBuffer.write(variable+":"+df.format(allData.get(variable))+System.getProperty("line.separator")); - } - allDataBuffer.close(); - - dataFolder.mkdirs(); - File allPartFile = new File(dataFolder, "allparts.dat"); - FileOutputStream allPartStream = new FileOutputStream(allPartFile); - OutputStreamWriter allPartWriter = new OutputStreamWriter(allPartStream); - BufferedWriter allPartBuffer = new BufferedWriter(allPartWriter); - - for (String variable: partsMap.keySet()){ - allPartBuffer.write(variable+":"+partsMap.get(variable)+System.getProperty("line.separator")); - } - allPartBuffer.close(); - - File allWeightFile = new File(dataFolder, "allweights.dat"); - FileOutputStream allWeightStream = new FileOutputStream(allWeightFile); - OutputStreamWriter allWeightWriter = new OutputStreamWriter(allWeightStream); - BufferedWriter allWeightBuffer = new BufferedWriter(allWeightWriter); - - Map weightMap = SolverData.getWeightMap(); - for (int i=0; i<=1; i++){ - ArrayList weightCollection; - if (i==0){ - weightCollection = ControlData.currModelDataSet.wtList; - }else{ - weightCollection = ControlData.currModelDataSet.wtTimeArrayList; - } - Iterator weightIterator = weightCollection.iterator(); - - while(weightIterator.hasNext()){ - String weightName=(String)weightIterator.next(); - allWeightBuffer.write(weightName+":"+df.format(weightMap.get(weightName).getValue())+System.getProperty("line.separator")); - } - } - Map weightSlackSurplusMap = SolverData.getWeightSlackSurplusMap(); - CopyOnWriteArrayList usedWeightSlackSurplusCollection = ControlData.currModelDataSet.usedWtSlackSurplusList; - Iterator usedWeightSlackSurplusIterator = usedWeightSlackSurplusCollection.iterator(); - - while(usedWeightSlackSurplusIterator.hasNext()){ - String usedWeightSlackSurplusName=(String)usedWeightSlackSurplusIterator.next(); - allWeightBuffer.write(usedWeightSlackSurplusName+":"+df.format(weightSlackSurplusMap.get(usedWeightSlackSurplusName).getValue())+System.getProperty("line.separator")); - } - allWeightBuffer.close(); - }catch (IOException e){ - allDataString="failed"; - } - return allDataString; - } - - public String getAllGoalString(){ - String goalString=""; - Map gMap = SolverData.getConstraintDataMap(); - Set goalKeySet=gMap.keySet(); - ArrayList gKeyArrayList=new ArrayList(); - Iterator ki=goalKeySet.iterator(); - while (ki.hasNext()){ - gKeyArrayList.add((String) ki.next()); - } - Collections.sort(gKeyArrayList, String.CASE_INSENSITIVE_ORDER); - for (int i=0; i multiplier = ee.getMultiplier(); - Set mKeySet = multiplier.keySet(); - Iterator mi = mKeySet.iterator(); - while (mi.hasNext()){ - String variable=mi.next(); - Number value=multiplier.get(variable).getData(); - double value1=value.doubleValue(); - if (goalString.endsWith(":")){ - if (value1==1.0){ - goalString=goalString+variable; - }else if (value1==-1.0){ - goalString=goalString+"-"+variable; - }else{ - goalString=goalString+df.format(value)+variable; - } - }else{ - if (value1==1.0){ - goalString=goalString+"+"+variable; - }else if (value1 == -1.0){ - goalString=goalString+"-"+variable; - }else if(value1>=0){ - goalString=goalString+"+"+df.format(value)+variable; - }else{ - goalString=goalString+df.format(value)+variable; - } - } - } - Number value=ee.getValue().getData(); - double value1=value.doubleValue(); - if (value1>0){ - goalString=goalString+"+"+df.format(value)+ec.getSign()+"0#"; - }else if(value1<0){ - goalString=goalString+df.format(value)+ec.getSign()+"0#"; - }else{ - goalString=goalString+ec.getSign()+"0#"; - } - } - } - if (goalString.endsWith("#")) goalString=goalString.substring(0, goalString.length()-1); - return goalString; - } - - public String getAllGoalFile(){ - String allgoal="allgoalretrieved"; - Map gMap = SolverData.getConstraintDataMap(); - Set goalKeySet=gMap.keySet(); - ArrayList gKeyArrayList=new ArrayList(); - Iterator ki=goalKeySet.iterator(); - while (ki.hasNext()){ - gKeyArrayList.add((String) ki.next()); - } - Collections.sort(gKeyArrayList, String.CASE_INSENSITIVE_ORDER); - - try{ - File dataFolder= new File(dataDir); - dataFolder.mkdirs(); - File allGoalFile = new File(dataFolder, "allgoals.dat"); - FileOutputStream allGoalStream = new FileOutputStream(allGoalFile); - OutputStreamWriter allGoalWriter = new OutputStreamWriter(allGoalStream); - BufferedWriter allGoalBuffer = new BufferedWriter(allGoalWriter); - - for (int i=0; i multiplier = ee.getMultiplier(); - Set mKeySet = multiplier.keySet(); - Iterator mi = mKeySet.iterator(); - while (mi.hasNext()){ - String variable=mi.next(); - Number value=multiplier.get(variable).getData(); - double value1=value.doubleValue(); - if (goalString.endsWith(":")){ - if (value1==1.0){ - goalString=goalString+variable; - }else if (value1==-1.0){ - goalString=goalString+"-"+variable; - }else{ - goalString=goalString+df.format(value)+variable; - } - }else{ - if (value1==1.0){ - goalString=goalString+"+"+variable; - }else if (value1 == -1.0){ - goalString=goalString+"-"+variable; - }else if(value1>=0){ - goalString=goalString+"+"+df.format(value)+variable; - }else{ - goalString=goalString+df.format(value)+variable; - } - } - } - Number value=ee.getValue().getData(); - double value1=value.doubleValue(); - if (value1>0){ - goalString=goalString+"+"+df.format(value)+ec.getSign()+"0"+System.getProperty("line.separator"); - }else if(value1<0){ - goalString=goalString+df.format(value)+ec.getSign()+"0"+System.getProperty("line.separator"); - }else{ - goalString=goalString+ec.getSign()+"0"+System.getProperty("line.separator"); - } - allGoalBuffer.write(goalString); - } - } - allGoalBuffer.close(); - }catch (IOException e){ - return "failed"; - } - return allgoal; - } - - public String getWatch(String vGNameString){ - String dataString=""; - StudyDataSet sds=ControlData.currStudyDataSet; - String modelName=sds.getModelList().get(ControlData.currCycleIndex); - ModelDataSet mds=sds.getModelDataSetMap().get(modelName); - Map parameterMap = sds.getParameterMap(); - Map tsMap = mds.tsMap; - Map dvMap = SolverData.getDvarMap(); - Map svMap = mds.svMap; - Map svFutMap = mds.svFutMap; - Map asMap = mds.asMap; - Map gMap = SolverData.getConstraintDataMap(); - Map partsMap=new HashMap(); - - String[] vGNames; - if (vGNameString.contains("#")){ - vGNames=vGNameString.split("#"); - }else{ - vGNames=new String[1]; - vGNames[0]=vGNameString; - } - ArrayList controlGoals=new ArrayList(); - IntDouble intDouble; - for (int i=0; i multiplier = ee.getMultiplier(); - Set mKeySet = multiplier.keySet(); - Iterator mi = mKeySet.iterator(); - boolean hasData = true; - while (mi.hasNext()){ - String variable=mi.next(); - Number value=multiplier.get(variable).getData(); - double value1=value.doubleValue(); - if (dataString.endsWith(":")){ - if (value1==1.0){ - dataString=dataString+variable; - }else if (value1==-1.0){ - dataString=dataString+"-"+variable; - }else{ - dataString=dataString+df.format(value)+variable; - } - }else{ - if (value1==1.0){ - dataString=dataString+"+"+variable; - }else if (value1 == -1.0){ - dataString=dataString+"-"+variable; - }else if(value1>=0){ - dataString=dataString+"+"+df.format(value)+variable; - }else{ - dataString=dataString+df.format(value)+variable; - } - } - if (!(variable.startsWith("surplus__") || variable.startsWith("slack__"))){ - IntDouble id = dvMap.get(variable).getData(); - if (id==null){ - hasData=false; - }else{ - double variableValue=id.getData().doubleValue(); - lhs=lhs+value1*variableValue; - } - } - } - Number value=ee.getValue().getData(); - double value1=value.doubleValue(); - if (value1>0){ - dataString=dataString+"+"+df.format(value)+ec.getSign()+"0#"; - }else if(value1<0){ - dataString=dataString+df.format(value)+ec.getSign()+"0#"; - }else{ - dataString=dataString+ec.getSign()+"0#"; - } - lhs=lhs+value1; - if (Math.abs(lhs)<=0.00001 && hasData){ - controlGoals.add(vGName); - } - } - }else{ - dataString=dataString+vGName+":"+"N/A#"; - } - } - if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); - - dataString=dataString+"!"; - for (String controlGoal:controlGoals){ - dataString=dataString+controlGoal+":"; - } - if (dataString.endsWith(":")) dataString=dataString.substring(0, dataString.length()-1); - - dataString=dataString+"&"; - for (String variable: partsMap.keySet()){ - dataString=dataString+variable+":"+partsMap.get(variable)+"#"; - } - if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); - - return dataString; - } - - public String getAllControlGoalName(){ - String goalNames=""; - Map gMap = SolverData.getConstraintDataMap(); - Map dvMap = SolverData.getDvarMap(); - Set goalKeySet=gMap.keySet(); - Iterator ki=goalKeySet.iterator(); - while (ki.hasNext()){ - double lhs=0.0; - String goalName=(String)ki.next(); - EvalConstraint ec=gMap.get(goalName); - if (ec!=null){ - EvalExpression ee=ec.getEvalExpression(); - Map multiplier = ee.getMultiplier(); - Set mKeySet = multiplier.keySet(); - Iterator mi = mKeySet.iterator(); - boolean hasData = true; - while (mi.hasNext()){ - String variable=mi.next(); - double value1=multiplier.get(variable).getData().doubleValue(); - if (!(variable.startsWith("surplus__") || variable.startsWith("slack__"))){ - IntDouble id = dvMap.get(variable).getData(); - if (id ==null){ - hasData=false; - }else{ - double variableValue=id.getData().doubleValue(); - lhs=lhs+variableValue*value1; - } - } - } - double value1=ee.getValue().getData().doubleValue(); - lhs=lhs+value1; - if (Math.abs(lhs)<=0.00001 && hasData) goalNames=goalNames+goalName+":"; - } - } - if (goalNames.endsWith(":")) goalNames=goalNames.substring(0, goalNames.length()-1); - return goalNames; - } - - public String getTimeseriesDetail(String variableNames){ - monitorVarNames=variableNames.split("#"); - monitorVarTimeStep=ControlData.timeStep; - controllerDebug.updateVarMonitor(); - - String dataString=""; - String variableName=monitorVarNames[0]; - String entryName=DssOperation.entryNameTS(variableName, ControlData.timeStep); - HashMap dvAliasTSMap = DataTimeSeries.dvAliasTS; - - if (dvAliasTSMap.containsKey(entryName)){ - DssDataSetFixLength ddsf = dvAliasTSMap.get(entryName); - double[] dataArray = ddsf.getData(); - ParallelVars prvs = TimeOperation.findTime(0); - int currIndex; - if (ControlData.timeStep.equals("1MON")){ - currIndex=ValueEvaluation.timeSeriesIndex(ddsf, prvs); - }else{ - currIndex=ValueEvaluation.timeSeriesIndex(ddsf, prvs)-1; - } - for (int i=0; i<=currIndex; i++){ - double value; - value=dataArray[i]; - if (!(value==-901.0 || value==-902.0)){ - int timestepListed=i-currIndex; - prvs = TimeOperation.findTime(timestepListed); - dataString=dataString+timestepListed+":"+prvs.dataMonth+"-"+prvs.dataDay+"-"+prvs.dataYear+":"+df.format(value)+"#"; - } - } - }else{ - HashMap svTSMap = DataTimeSeries.svTS; - if (svTSMap.containsKey(entryName)){ - DssDataSet dds = svTSMap.get(entryName); - ArrayList dataArrayList = dds.getData(); - ParallelVars prvs = TimeOperation.findTime(0); - int currIndex=ValueEvaluation.timeSeriesIndex(dds, prvs); - for (int i=0; i indexList=new ArrayList(); - Map futureArray= new HashMap(); - if (mds.svList.contains(variableName)){ - Map svFutMap = mds.svFutMap; - Set keySet=svFutMap.keySet(); - for (String key:keySet){ - if (key.startsWith(variableName+"__fut__")){ - String[] splittedKey=key.split("__fut__"); - if (splittedKey.length>1){ - int index = Integer.parseInt(splittedKey[1]); - IntDouble intDouble=svFutMap.get(key).getData(); - if (intDouble != null) { - indexList.add(index); - futureArray.put(index, intDouble.getData()); - } - } - } - } - }else if (mds.dvList.contains(variableName)){ - Map dvMap = SolverData.getDvarMap(); - Set keySet=dvMap.keySet(); - for (String key:keySet){ - if (key.startsWith(variableName+"__fut__")){ - String[] splittedKey=key.split("__fut__"); - if (splittedKey.length>1){ - int index = Integer.parseInt(splittedKey[1]); - IntDouble intDouble=dvMap.get(key).getData(); - if (intDouble != null){ - indexList.add(index); - futureArray.put(index, intDouble.getData()); - } - } - } - } - } - Collections.sort(indexList); - for (int i=0; i modelTimeStepList = sds.getModelTimeStepList(); - ArrayList ml = sds.getModelList(); - ArrayList> dvAliasTSCycles = DataTimeSeries.dvAliasTSCycles; - boolean variableFound=false; - for (int cycleIndex=1; cycleIndex<=ControlData.currCycleIndex+1; cycleIndex++){ - String entryNameTS=DssOperation.entryNameTS(variableName, modelTimeStepList.get(cycleIndex-1)); - HashMap dvAliasTSCycle = dvAliasTSCycles.get(cycleIndex-1); - if (dvAliasTSCycle.containsKey(entryNameTS)){ - variableFound=true; - DssDataSetFixLength dds = dvAliasTSCycle.get(entryNameTS); - int index=ControlData.currTimeStep.get(cycleIndex-1); - if (dds!=null){ - double[] data=dds.getData(); - String cycle=ml.get(cycleIndex-1); - if (cycleIndex==ControlData.currCycleIndex+1){ - dataString=dataString+cycleIndex+":"+cycle+":"+df.format(data[index])+"#";; - }else{ - if (index>=1){ - dataString=dataString+cycleIndex+":"+cycle+":"+df.format(data[index-1])+"#";; - } - } - } - } - } - if (!variableFound){ - Map> varCycleValue = sds.getVarCycleValueMap(); - Map> varCycleIndexValue = sds.getVarCycleIndexValueMap(); - if (varCycleValue.containsKey(variableName)){ - Map cycleValue = varCycleValue.get(variableName); - int cycleIndex=1; - for (String cycle: ml){ - if (cycleIndex<=ControlData.currCycleIndex+1){ - if (cycleValue.containsKey(cycle)){ - IntDouble id=cycleValue.get(cycle); - if (id!=null) dataString=dataString+cycleIndex+":"+cycle+":"+df.format(id.getData())+"#"; - }else if (varCycleIndexValue.containsKey(variableName)){ - Map cycleIndexValue = varCycleIndexValue.get(variableName); - if (cycleIndexValue.containsKey(cycle)){ - IntDouble id=cycleIndexValue.get(cycle); - if (id!=null) dataString=dataString+cycleIndex+":"+cycle+":"+df.format(id.getData())+"#"; - } - } - } - cycleIndex=cycleIndex+1; - } - }else{ - Map> varTimeArrayCycleValue = sds.getVarTimeArrayCycleValueMap(); - if (varTimeArrayCycleValue.containsKey(variableName)){ - Map cycleValue = varTimeArrayCycleValue.get(variableName); - int cycleIndex=1; - for (String cycle: ml){ - if (cycleIndex<=ControlData.currCycleIndex+1){ - if (cycleValue.containsKey(cycle)){ - IntDouble id=cycleValue.get(cycle); - if (id!=null) dataString=dataString+cycleIndex+":"+cycle+":"+df.format(id.getData())+"#"; - }else if (varCycleIndexValue.containsKey(variableName)){ - Map cycleIndexValue = varCycleIndexValue.get(variableName); - if (cycleIndexValue.containsKey(cycle)){ - IntDouble id=cycleIndexValue.get(cycle); - if (id!=null) dataString=dataString+cycleIndex+":"+cycle+":"+df.format(id.getData())+"#"; - } - } - } - cycleIndex=cycleIndex+1; - } - }else{ - if (varCycleIndexValue.containsKey(variableName)){ - Map cycleValue = varCycleIndexValue.get(variableName); - int cycleIndex=1; - for (String cycle: ml){ - if (cycleValue.containsKey(cycle) && cycleIndex<=ControlData.currCycleIndex+1){ - IntDouble id=cycleValue.get(cycle); - if (id!=null) dataString=dataString+cycleIndex+":"+cycle+":"+df.format(id.getData())+"#"; - } - cycleIndex=cycleIndex+1; - } - } - } - } - } - if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); - return dataString; - } - - public boolean modifyTimeSeries(String[] requestParts){ - boolean isModified=false; - String[] varStrings=requestParts[1].split("#"); - String varName=varStrings[0]; - int index=Integer.parseInt(varStrings[1]); - double value=Double.parseDouble(varStrings[2]); - String entryName=DssOperation.entryNameTS(varName, monitorVarTimeStep); - HashMap dvAliasTSMap = DataTimeSeries.dvAliasTS; - if (dvAliasTSMap.containsKey(entryName)){ - DssDataSetFixLength ddsf = dvAliasTSMap.get(entryName); - double[] dataArray = ddsf.getData(); - ParallelVars prvs = TimeOperation.findTime(index); - int tsIndex=ValueEvaluation.timeSeriesIndex(ddsf, prvs)-1; - dataArray[tsIndex]=value; - isModified=true; - }else{ - HashMap svTSMap = DataTimeSeries.svTS; - if (svTSMap.containsKey(entryName)){ - DssDataSet dds = svTSMap.get(entryName); - ArrayList dataArrayList = dds.getData(); - ParallelVars prvs = TimeOperation.findTime(index); - int tsIndex=ValueEvaluation.timeSeriesIndex(dds, prvs); - dataArrayList.set(tsIndex, value); - isModified=true; - } - } - return isModified; - } - - public boolean modifyCycle(String[] requestParts){ - boolean isModified=false; - String[] varStrings=requestParts[1].split("#"); - String varName=varStrings[0]; - String cycle=varStrings[1]; - double value=Double.parseDouble(varStrings[2]); - StudyDataSet sds = ControlData.currStudyDataSet; - Map> varCycleValue = sds.getVarCycleValueMap(); - if (varCycleValue.containsKey(varName)){ - Map cycleValue = varCycleValue.get(varName); - if (cycleValue.containsKey(cycle)){ - cycleValue.put(cycle, new IntDouble(value, false)); - isModified=true; - } - }else{ - Map> varTimeArrayCycleValue = sds.getVarTimeArrayCycleValueMap(); - if (varTimeArrayCycleValue.containsKey(varName)){ - Map cycleValue = varTimeArrayCycleValue.get(varName); - cycleValue.put(cycle, new IntDouble(value, false)); - isModified=true; - } - } - return isModified; - } - - public String getDataString(){ - String dataString=""; - for (int i=0; i>(totalCycleNumber); - //for (int i=0; i dvAliasTSCycle = new HashMap(); - // DataTimeSeries.dvAliasTSCycles.add(dvAliasTSCycle); - //} - } - - public void setSelectedOutputCycles(){ - String strSelectedCycleOutput = ControlData.selectedCycleOutput.replace("\'", ""); - ControlData.selectedCycles = strSelectedCycleOutput.split(","); - } - - public static void main(String[] args){ - int argsSize=args.length; - String[] modArgs=new String[argsSize-2]; - for (int i=0; i<=argsSize-3; i++){ - modArgs[i]=args[i+2]; - } - int requestPort=Integer.parseInt(args[0]); - int eventPort=Integer.parseInt(args[1]); - new DebugInterface(requestPort, eventPort, modArgs); - } -} +package wrimsv2.components; + +import hec.heclib.dss.HecDss; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.TokenStream; + +// import com.sun.java.util.collections.Arrays; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.commondata.wresldata.Timeseries; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.debug.ChangeSolver; +import wrimsv2.debug.FilterGoal; +import wrimsv2.debug.ReLoadSVDss; +import wrimsv2.evaluator.DataTimeSeries; +import wrimsv2.evaluator.DssDataSet; +import wrimsv2.evaluator.DssDataSetFixLength; +import wrimsv2.evaluator.DssOperation; +import wrimsv2.evaluator.EvalConstraint; +import wrimsv2.evaluator.EvalExpression; +import wrimsv2.evaluator.LookUpTable; +import wrimsv2.evaluator.PreEvaluator; +import wrimsv2.evaluator.TableSeries; +import wrimsv2.evaluator.TimeOperation; +import wrimsv2.evaluator.ValueEvaluation; +import wrimsv2.evaluator.ValueEvaluatorLexer; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.ilp.ILP; +import wrimsv2.parallel.ParallelVars; +import wrimsv2.solver.CbcSolver; +import wrimsv2.solver.CloseCurrentSolver; +import wrimsv2.solver.InitialXASolver; +import wrimsv2.solver.SetXALog; +import wrimsv2.solver.Gurobi.GurobiSolver; +import wrimsv2.tools.Warmstart; +import wrimsv2.wreslparser.elements.FileParser; +import wrimsv2.wreslparser.elements.SimulationDataSet; +import wrimsv2.wreslparser.elements.StudyParser; +import wrimsv2.wreslparser.elements.StudyUtils; +import wrimsv2.wreslparser.grammar.WreslTreeWalker; +import wrimsv2.wreslplus.elements.AliasTemp; +import wrimsv2.wreslplus.elements.DvarTemp; +import wrimsv2.wreslplus.elements.GoalTemp; +import wrimsv2.wreslplus.elements.IfIncItemGroup; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.ParserUtils; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.SvarTemp; +import wrimsv2.wreslplus.elements.Tools; +import wrimsv2.wreslplus.elements.procedures.ProcIfIncItemGroup; +import wrimsv2.wreslplus.elements.procedures.ProcWeight; + +public class DebugInterface { + private ServerSocket requestSocket; + private Socket requestConnection; + private ServerSocket eventSocket; + private Socket eventConnection; + private PrintWriter requestOut; + private BufferedReader requestIn; + private PrintWriter eventOut; + private BufferedReader eventIn; + public ArrayList breakIndex=new ArrayList(); + public ArrayList breakFile=new ArrayList(); + public boolean isDebugging=true; + private ControllerDebug controllerDebug; + private FileWriter statusFile; + public PrintWriter fileOut; + private boolean isStart=false; + private String[] debugSvar; + private String[] debugDvar; + private String[] debugAlias; + private String[] allDebugVariables; + private ArrayList filterGoalNames=new ArrayList(); + private Map filterGoals=new HashMap(); + public DecimalFormat df = new DecimalFormat("#.####"); + public static String[] monitorVarNames=new String[0]; + public static String monitorVarTimeStep=""; + private String dataDir="data"; + private int terminateCode=0; + + public DebugInterface(int requestPort, int eventPort, String args[]){ + try{ + statusFile = new FileWriter("DebugStatus.txt"); + }catch (IOException e){ + e.printStackTrace(); + } + fileOut = new PrintWriter(statusFile); + try { + requestSocket = new ServerSocket(requestPort); + eventSocket = new ServerSocket(eventPort); + requestConnection=requestSocket.accept(); + eventConnection=eventSocket.accept(); + requestOut=new PrintWriter(requestConnection.getOutputStream()); + requestOut.flush(); + requestIn=new BufferedReader(new InputStreamReader(requestConnection.getInputStream())); + eventOut=new PrintWriter(eventConnection.getOutputStream()); + eventOut.flush(); + eventIn=new BufferedReader(new InputStreamReader(eventConnection.getInputStream())); + String message=""; + controllerDebug=new ControllerDebug(args, this); + do { + try{ + message=requestIn.readLine(); + handleRequest (message); + }catch (Exception e){ + e.printStackTrace(); + } + }while (isDebugging); + } catch (IOException e){ + System.out.println(e.getMessage()); + } + + finally{ + try{ + fileOut.close(); + requestIn.close(); + requestOut.close(); + requestSocket.close(); + eventSocket.close(); + System.exit(terminateCode); + } + catch(IOException ioException){ + ioException.printStackTrace(); + } + } + + } + + public void handleRequest(String request) { + String dataString=""; + String goalString=""; + if (request.equals("start")) { + controllerDebug.start(); + isStart=true; + try { + sendRequest("started"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } else if (request.equals("resume")) { + controllerDebug.resume(); + try { + sendRequest("resumed"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.equals("data")){ + try { + dataString=getDataString(); + sendRequest(dataString); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("data:")){ + ControlData.isParseStudy=false; + int index=request.indexOf(":"); + try { + if (request.equals("data:")){ + sendRequest(""); + }else{ + String fileName=request.substring(index+1); + if (StudyUtils.useWreslPlus){ + dataString=getVariableInOneFileWP(fileName); + }else{ + dataString=getVariableInOneFile(fileName); + } + sendRequest(dataString); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + ControlData.isParseStudy=true; + }else if (request.startsWith("tsdetail:")){ + int index=request.indexOf(":"); + try { + if (request.equals("tsdetail:")){ + sendRequest(""); + }else{ + String variableNames=request.substring(index+1); + dataString=getTimeseriesDetail(variableNames); + sendRequest(dataString); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("futdetail:")){ + int index=request.indexOf(":"); + try { + if (request.equals("futdetail:")){ + sendRequest(""); + }else{ + String variableName=request.substring(index+1); + dataString=getFutureValueDetail(variableName); + sendRequest(dataString); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("cycledetail:")){ + int index=request.indexOf(":"); + try { + if (request.equals("cycledetail:")){ + sendRequest(""); + }else{ + String variableName=request.substring(index+1); + dataString=getCycleValueDetail(variableName); + sendRequest(dataString); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("watch:")){ + int index=request.indexOf(":"); + try{ + if (request.equals("watch:")){ + sendRequest(""); + }else{ + String vGNameString=request.substring(index+1); + dataString=getWatch(vGNameString); + sendRequest(dataString); + } + }catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.equals("alldata")){ + try{ + dataString=getAllVariableFiles(); + sendRequest(dataString); + }catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("goal:")){ + ControlData.isParseStudy=false; + int index=request.indexOf(":"); + try { + if (request.equals("goal:")){ + sendRequest(""); + }else{ + String fileName=request.substring(index+1); + if (StudyUtils.useWreslPlus){ + goalString=getGoalInOneFileWP(fileName); + }else{ + goalString=getGoalInOneFile(fileName); + } + sendRequest(goalString); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + ControlData.isParseStudy=true; + }else if (request.equals("allgoals")){ + try{ + goalString=getAllGoalFile(); + sendRequest(goalString); + }catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.equals("allcontrolgoals")){ + try{ + String goalName=getAllControlGoalName(); + sendRequest(goalName); + }catch (IOException e){ + e.printStackTrace(); + } + + }else if (request.startsWith("filtergoal:")){ + int index=request.indexOf(":"); + try { + if (request.equals("filtergoal:")){ + sendRequest(""); + }else{ + String fileName=request.substring(index+1); + goalString=getFilterGoal(fileName); + sendRequest(goalString); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("time")){ + String [] requestParts=request.split(":"); + String[] yearMonthDayCycle=requestParts[1].split("/"); + controllerDebug.debugYear=Integer.parseInt(yearMonthDayCycle[0]); + controllerDebug.debugMonth=Integer.parseInt(yearMonthDayCycle[1]); + controllerDebug.debugDay=Integer.parseInt(yearMonthDayCycle[2]); + controllerDebug.debugCycle=Integer.parseInt(yearMonthDayCycle[3]); + try { + sendRequest("time defined"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("variables:")){ + String [] requestParts=request.split(":"); + allDebugVariables=requestParts[1].split("#"); + try { + sendRequest("variables defined"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.equals("terminate")) { + controllerDebug.stop(); + if (isDebugging){ + if (ControlData.solverName.equalsIgnoreCase("XA") || ControlData.solverName.equalsIgnoreCase("XALOG")) { + ControlData.xasolver.close(); + }else if (ControlData.solverName.equalsIgnoreCase("Cbc")){ + CbcSolver.close(); + } + DssOperation.saveInitialData(ControlData.dvDss, FilePaths.fullDvarDssPath); + DssOperation.saveDvarData(ControlData.dvDss, FilePaths.fullDvarDssPath); + ControlData.dvDss.close(); + terminateCode=1; + } + System.out.println("Terminated"); + try { + sendRequest("terminated"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + isDebugging=false; + }else if (request.equals("suspend")) { + controllerDebug.suspend(); + System.out.println("suspended"); + try { + sendRequest("suspended"); + sendEvent("suspended"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.equals("pause")) { + controllerDebug.debugYear=ControlData.currYear; + controllerDebug.debugMonth=ControlData.currMonth; + controllerDebug.debugDay=ControlData.currDay; + controllerDebug.debugCycle=ControlData.currCycleIndex+1; + try { + sendRequest("paused"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("modify_timeseries:")){ + String[] requestParts=request.split(":"); + boolean isModified=modifyTimeSeries(requestParts); + try { + if (isModified){ + sendRequest("modified"); + }else{ + sendRequest("not_modified"); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("modify_cycle:")){ + String[] requestParts=request.split(":"); + boolean isModified=modifyCycle(requestParts); + try { + if (isModified){ + sendRequest("modified"); + }else{ + sendRequest("not_modified"); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("resim_cycle:")){ + String[] requestParts=request.split(":"); + Error.clear(); + if (requestParts[1].equals("loadsv")){ + new ReLoadSVDss(ControlData.currStudyDataSet); + } + if (requestParts[3].equals("loadtable")){ + TableSeries.tableSeries=new HashMap (); + } + controllerDebug.modelIndex=Integer.parseInt(requestParts[2])-2; + controllerDebug.resume(); + try { + sendRequest("resumed"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("resim_date:")){ + String[] requestParts=request.split(":"); + Error.clear(); + ControlData.resimDate=true; + ControlData.resimGroundwater=true; + if (requestParts[1].equals("recompile")){ + StudyDataSet sds; + try { + sds = controllerDebug.parse(); + if (StudyParser.total_errors==0){ + ControlData.currStudyDataSet=sds; + controllerDebug.totalCycles = sds.getModelList().size(); + sendEvent("totalcycle#"+controllerDebug.totalCycles); + new PreEvaluator(sds); + }else{ + System.out.println("The change of your code has errors."); + sendEvent("terminate"); + } + } catch (RecognitionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + if (requestParts[2].equals("loadsv")){ + new ReLoadSVDss(ControlData.currStudyDataSet); + } + if (requestParts[6].equals("loadtable")){ + TableSeries.tableSeries=new HashMap (); + } + controllerDebug.modelIndex=ControlData.currStudyDataSet.getModelList().size()-1; + ControlData.resimYear=Integer.parseInt(requestParts[3]); + ControlData.resimMonth=Integer.parseInt(requestParts[4]); + ControlData.resimDay=Integer.parseInt(requestParts[5]); + ControlData.currYear=ControlData.cycleEndYear; + ControlData.currMonth=ControlData.cycleEndMonth; + ControlData.currDay=ControlData.cycleEndDay; + if (ControlData.isOutputCycle){ + Date resimDate=new Date(ControlData.resimYear-1900, ControlData.resimMonth-1, ControlData.resimDay); + Date cycleDataDate = new Date(ControlData.cycleDataStartYear-1900, ControlData.cycleDataStartMonth-1, ControlData.cycleDataStartDay); + if (resimDate.before(cycleDataDate)){ + ControlData.cycleDataStartYear=ControlData.resimYear; + ControlData.cycleDataStartMonth=ControlData.resimMonth; + ControlData.cycleDataStartDay=ControlData.resimDay; + } + } + + controllerDebug.resume(); + try { + sendRequest("resumed"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("solveroption:")){ + String[] requestParts=request.split(":"); + setSolverOptions(requestParts); + try { + sendRequest("solveroptionset"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if(request.equals("OutputCycleDataToDssOn")){ + if (!ControlData.isOutputCycle) initOutputCycleDataToDss(); + try { + sendRequest("OutputCycleDataToDssOn"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.println("Output cycle data to Dss file is turned on"); + }else if(request.equals("OutputCycleDataToDssOff")){ + ControlData.isOutputCycle=false; + try { + sendRequest("OutputCycleDataToDssOff"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.println("Output cycle data to Dss file is turned off"); + }else if(request.equals("OutputAllCyclesOn")){ + ControlData.outputAllCycles=true; + try { + sendRequest("OutputAllCyclesOn"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.println("All cycles are selected"); + }else if(request.equals("OutputAllCyclesOff")){ + ControlData.outputAllCycles=false; + try { + sendRequest("OutputAllCyclesOff"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if(request.startsWith("SelectedCycleOutput:")){ + int index=request.indexOf(":"); + ControlData.selectedCycleOutput=request.substring(index+1); + try { + sendRequest("Selected output cycles are set"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + if (!ControlData.outputAllCycles) System.out.println("Cycles "+ControlData.selectedCycleOutput.replace("\'", "")+" are selected"); + setSelectedOutputCycles(); + }else if(request.startsWith("ShowRunTimeMessage:")){ + int index=request.indexOf(":"); + String showRunTimeMessage=request.substring(index+1); + if (showRunTimeMessage.equalsIgnoreCase("True")){ + ControlData.showRunTimeMessage=true; + try { + sendRequest("Run time messages shown"); + System.out.println("Run time messages shown"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else{ + ControlData.showRunTimeMessage=false; + try { + sendRequest("Run time messages disabled"); + System.out.println("Run time messages disabled"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + }else if(request.startsWith("PrintGWFuncCalls:")){ + int index=request.indexOf(":"); + String printGWFuncCalls=request.substring(index+1); + if (printGWFuncCalls.equalsIgnoreCase("True")){ + ControlData.printGWFuncCalls=true; + try { + sendRequest("Print groundwater function calls on"); + System.out.println("Print groundwater function calls on"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else{ + ControlData.printGWFuncCalls=false; + try { + sendRequest("Print groundwater function calls off"); + System.out.println("Print groundwater function calls off"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + }else if(request.startsWith("TrackMemoryUsage:")){ + int index=request.indexOf(":"); + String ilpLogUsageMemory=request.substring(index+1); + if (ilpLogUsageMemory.equalsIgnoreCase("True")){ + ILP.loggingUsageMemeory=true; + try { + sendRequest("Track memory usage on"); + System.out.println("Track memory usage on"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else{ + ILP.loggingUsageMemeory=false; + try { + sendRequest("Track memory usage off"); + System.out.println("Track memory usage off"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + }else if (request.startsWith("savesvdss:")){ + int index=request.indexOf(":"); + String fileName=request.substring(index+1); + boolean saveSucceed=saveSvDss(fileName); + try { + if (saveSucceed) { + sendRequest("svardsssaved"); + }else{ + sendRequest("dsssavefailed"); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("savedvdss:")){ + int index=request.indexOf(":"); + String fileName=request.substring(index+1); + boolean saveSucceed=saveDvDss(fileName); + try { + if (saveSucceed) { + sendRequest("dvardsssaved"); + }else{ + sendRequest("dsssavefailed"); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if(request.startsWith("saveinitdss:")){ + int index=request.indexOf(":"); + String fileName=request.substring(index+1); + boolean saveSucceed=saveInitDss(fileName); + try { + if (saveSucceed) { + sendRequest("initdsssaved"); + }else{ + sendRequest("dsssavefailed"); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("conditional_breakpoint:")){ + setConditionalBreakpoint(request); + try { + sendRequest("conditioal breakpoint set"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else if (request.startsWith("cbcTolerancePrimal:")){ + String[] requestParts=request.split(":"); + CbcSolver.solve_2_primalT = Double.parseDouble(requestParts[1]); + try { + sendRequest(request+" set"); + System.out.println(request+" set"); + } catch (IOException e) { + e.printStackTrace(); + } + }else if (request.startsWith("cbcTolerancePrimalRelax:")){ + String[] requestParts=request.split(":"); + CbcSolver.solve_2_primalT_relax = Double.parseDouble(requestParts[1]); + ControlData.relationTolerance = Math.max(CbcSolver.solve_2_primalT_relax*10, 1e-6); + try { + sendRequest(request+" set"); + System.out.println(request+" set"); + } catch (IOException e) { + e.printStackTrace(); + } + }else if (request.startsWith("cbcToleranceWarmPrimal:")){ + String[] requestParts=request.split(":"); + CbcSolver.solve_whs_primalT = Double.parseDouble(requestParts[1]); + try { + sendRequest(request+" set"); + System.out.println(request+" set"); + } catch (IOException e) { + e.printStackTrace(); + } + }else if (request.startsWith("cbcToleranceInteger:")){ + String[] requestParts=request.split(":"); + CbcSolver.integerT = Double.parseDouble(requestParts[1]); + try { + sendRequest(request+" set"); + System.out.println(request+" set"); + } catch (IOException e) { + e.printStackTrace(); + } + }else if (request.startsWith("cbcToleranceIntegerCheck:")){ + String[] requestParts=request.split(":"); + CbcSolver.integerT_check = Double.parseDouble(requestParts[1]); + try { + sendRequest(request+" set"); + System.out.println(request+" set"); + } catch (IOException e) { + e.printStackTrace(); + } + }else if (request.startsWith("cbcToleranceZero:")){ + String[] requestParts=request.split(":"); + ControlData.zeroTolerance = Double.parseDouble(requestParts[1]); + try { + sendRequest(request+" set"); + System.out.println(request+" set"); + } catch (IOException e) { + e.printStackTrace(); + } + }else if (request.startsWith("cbcHintRelaxPenalty:")){ + String[] requestParts=request.split(":"); + CbcSolver.cbcHintRelaxPenalty = Double.parseDouble(requestParts[1]); + try { + sendRequest(request+" set"); + System.out.println(request+" set"); + } catch (IOException e) { + e.printStackTrace(); + } + }else if (request.startsWith("cbcHintTimeMax:")){ + String[] requestParts=request.split(":"); + CbcSolver.cbcHintTimeMax = Integer.parseInt(requestParts[1]); + try { + sendRequest(request+" set"); + System.out.println(request+" set"); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void sendRequest(String request) throws IOException { + synchronized (requestConnection){ + try{ + requestOut.println(request); + requestOut.flush(); + }catch(Exception e){ + e.printStackTrace(); + } + } + } + + public void sendEvent(String event) throws IOException { + synchronized (eventConnection){ + try{ + eventOut.println(event); + eventOut.flush(); + }catch(Exception e){ + e.printStackTrace(); + } + } + } + + public String getVariableInOneFile(String fileFullPath){ + String dataString=""; + String modelName=ControlData.currStudyDataSet.getModelList().get(ControlData.currCycleIndex); + ModelDataSet mds=ControlData.currStudyDataSet.getModelDataSetMap().get(modelName); + Map tsMap = mds.tsMap; + Map dvMap = SolverData.getDvarMap(); + Map svMap = mds.svMap; + Map svFutMap = mds.svFutMap; + Map asMap = mds.asMap; + Map partsMap=new HashMap(); + try { + WreslTreeWalker walker = FileParser.parseOneFileForDebug(fileFullPath); + if (walker==null) return dataString; + SimulationDataSet fileDataSet = walker.thisFileDataSet; + ArrayList dvList = fileDataSet.dvList; + ArrayList svList = fileDataSet.svList; + ArrayList asList = fileDataSet.asList; + ArrayList tsList = fileDataSet.tsList; + ArrayList wtList = fileDataSet.wtList; + asList.removeAll(dvList); + ArrayList sortedList=new ArrayList(); + sortedList.addAll(dvList); + sortedList.addAll(svList); + sortedList.addAll(tsList); + sortedList.addAll(asList); + sortedList.addAll(wtList); + + ArrayList gList = fileDataSet.gList; + for (String gName:gList){ + Set dependants = fileDataSet.gMap.get(gName).expressionDependants; + Iterator iterator = dependants.iterator(); + while (iterator.hasNext()){ + String varName=iterator.next(); + if (!sortedList.contains(varName)){ + sortedList.add(varName); + } + } + } + for (String svName:svList){ + Set dependants = fileDataSet.svMap.get(svName).dependants; + Iterator iterator = dependants.iterator(); + while (iterator.hasNext()){ + String varName=iterator.next(); + if (!sortedList.contains(varName)){ + sortedList.add(varName); + } + } + } + for (String asName:asList){ + if (fileDataSet.asMap.containsKey(asName)){ + Set dependants = fileDataSet.asMap.get(asName).dependants; + Iterator iterator = dependants.iterator(); + while (iterator.hasNext()){ + String varName=iterator.next(); + if (!sortedList.contains(varName)){ + sortedList.add(varName); + } + } + } + } + + IntDouble intDouble; + Collections.sort(sortedList, String.CASE_INSENSITIVE_ORDER); + for (String variable: sortedList){ + if (svMap.containsKey(variable)){ + Svar sv = svMap.get(variable); + intDouble=sv.getData(); + if (intDouble != null) { + dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; + partsMap.put(variable, sv.kind+":"+ControlData.timeStep); + } + }else if (dvMap.containsKey(variable)){ + Dvar dv = dvMap.get(variable); + intDouble=dv.getData(); + if (intDouble != null) { + dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; + partsMap.put(variable, dv.kind+":"+ControlData.timeStep); + } + }else if (tsMap.containsKey(variable)){ + Timeseries ts = tsMap.get(variable); + intDouble=ts.getData(); + if (intDouble != null) { + dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; + partsMap.put(variable, ts.kind+":"+ControlData.timeStep); + } + }else if (asMap.containsKey(variable)){ + Alias as = asMap.get(variable); + intDouble=as.getData(); + if (intDouble != null) { + dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; + partsMap.put(variable, as.kind+":"+ControlData.timeStep); + } + } + } + if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); + dataString=dataString+"!"; + for (String variable: partsMap.keySet()){ + dataString=dataString+variable+":"+partsMap.get(variable)+"#"; + } + if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); + } catch (RecognitionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return dataString; + } + + public String getVariableInOneFileWP(String fileFullPath){ + String dataString=""; + StudyDataSet sds = ControlData.currStudyDataSet; + String modelName=sds.getModelList().get(ControlData.currCycleIndex); + ModelDataSet mds=sds.getModelDataSetMap().get(modelName); + Map parameterMap = sds.getParameterMap(); + Map tsMap = mds.tsMap; + Map dvMap = SolverData.getDvarMap(); + Map svMap = mds.svMap; + Map svFutMap = mds.svFutMap; + Map asMap = mds.asMap; + Map partsMap=new HashMap(); + ArrayList parameterList = new ArrayList(); + ArrayList dvList = new ArrayList(); + ArrayList svList = new ArrayList(); + ArrayList asList = new ArrayList(); + ArrayList tsList = new ArrayList(); + ArrayList wtList = new ArrayList(); + ArrayList gList = new ArrayList(); + ArrayList sortedList = new ArrayList(); + ModelTemp modelTemp; + fileFullPath=fileFullPath.replace("/", "\\"); + if (fileFullPath.equalsIgnoreCase(FilePaths.fullMainPath)){ + StudyTemp studyTemp = ParserUtils.parseWreslMain(fileFullPath); + if (studyTemp==null) return dataString; + parameterList = studyTemp.parameterList; + sortedList.addAll(parameterList); + Map modelMap = studyTemp.modelMap; + ArrayList modelList = studyTemp.modelList; + for (String model: modelList){ + modelTemp=modelMap.get(model); + dvList = modelTemp.dvList; + svList = modelTemp.svList; + asList = modelTemp.asList; + tsList = modelTemp.tsList; + gList = modelTemp.glList; + ProcWeight.collectWeightVar(modelTemp); + wtList = modelTemp.wvList_post; + asList.removeAll(dvList); + sortedList.addAll(dvList); + sortedList.addAll(svList); + sortedList.addAll(tsList); + sortedList.addAll(asList); + sortedList.addAll(wtList); + for (String gName:gList){ + if (modelTemp.glMap.containsKey(gName)){ + Set dependants = modelTemp.glMap.get(gName).dependants; + Iterator iterator = dependants.iterator(); + while (iterator.hasNext()){ + String varName=iterator.next(); + if (!sortedList.contains(varName)){ + sortedList.add(varName); + } + } + } + } + for (String svName:svList){ + if (modelTemp.svMap.containsKey(svName)){ + Set dependants = modelTemp.svMap.get(svName).dependants; + Iterator iterator = dependants.iterator(); + while (iterator.hasNext()){ + String varName=iterator.next(); + if (!sortedList.contains(varName)){ + sortedList.add(varName); + } + } + } + } + for (String asName:asList){ + if (modelTemp.asMap.containsKey(asName)){ + Set dependants = modelTemp.asMap.get(asName).dependants; + Iterator iterator = dependants.iterator(); + while (iterator.hasNext()){ + String varName=iterator.next(); + if (!sortedList.contains(varName)){ + sortedList.add(varName); + } + } + } + } + ArrayList varIfInc = getVariableIfInc(modelTemp); + sortedList.remove(varIfInc); + sortedList.addAll(varIfInc); + } + }else{ + modelTemp = ParserUtils.parseWreslFile(fileFullPath); + if (modelTemp==null) return dataString; + dvList = modelTemp.dvList; + svList = modelTemp.svList; + asList = modelTemp.asList; + tsList = modelTemp.tsList; + gList = modelTemp.glList; + ProcWeight.collectWeightVar(modelTemp); + wtList = modelTemp.wvList_post; + sortedList = new ArrayList(); + asList.removeAll(dvList); + sortedList.addAll(dvList); + sortedList.addAll(svList); + sortedList.addAll(tsList); + sortedList.addAll(asList); + sortedList.addAll(wtList); + for (String gName:gList){ + if (modelTemp.glMap.containsKey(gName)){ + Set dependants = modelTemp.glMap.get(gName).dependants; + Iterator iterator = dependants.iterator(); + while (iterator.hasNext()){ + String varName=iterator.next(); + if (!sortedList.contains(varName)){ + sortedList.add(varName); + } + } + } + } + for (String svName:svList){ + if (modelTemp.svMap.containsKey(svName)){ + Set dependants = modelTemp.svMap.get(svName).dependants; + Iterator iterator = dependants.iterator(); + while (iterator.hasNext()){ + String varName=iterator.next(); + if (!sortedList.contains(varName)){ + sortedList.add(varName); + } + } + } + } + for (String asName:asList){ + if (modelTemp.asMap.containsKey(asName)){ + Set dependants = modelTemp.asMap.get(asName).dependants; + Iterator iterator = dependants.iterator(); + while (iterator.hasNext()){ + String varName=iterator.next(); + if (!sortedList.contains(varName)){ + sortedList.add(varName); + } + } + } + } + ArrayList varIfInc = getVariableIfInc(modelTemp); + sortedList.remove(varIfInc); + sortedList.addAll(varIfInc); + } + IntDouble intDouble; + Collections.sort(sortedList, String.CASE_INSENSITIVE_ORDER); + for (String variable: sortedList){ + variable=variable.toLowerCase(); + if (svMap.containsKey(variable)){ + Svar sv = svMap.get(variable); + intDouble=sv.getData(); + if (intDouble != null) { + dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; + partsMap.put(variable, sv.kind+":"+ControlData.timeStep); + } + }else if (dvMap.containsKey(variable)){ + Dvar dv = dvMap.get(variable); + intDouble=dv.getData(); + if (intDouble != null) { + dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; + partsMap.put(variable, dv.kind+":"+ControlData.timeStep); + } + }else if (tsMap.containsKey(variable)){ + Timeseries ts = tsMap.get(variable); + intDouble=ts.getData(); + if (intDouble != null) { + dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; + partsMap.put(variable, ts.kind+":"+ControlData.timeStep); + } + }else if (asMap.containsKey(variable)){ + Alias as = asMap.get(variable); + intDouble=as.getData(); + if (intDouble != null) { + dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; + partsMap.put(variable, as.kind+":"+ControlData.timeStep); + } + }else if (parameterMap.containsKey(variable)){ + Svar sv = parameterMap.get(variable); + intDouble=sv.getData(); + if (intDouble != null){ + dataString=dataString+variable+":"+df.format(intDouble.getData())+"#"; + partsMap.put(variable, sv.kind+":"+ControlData.timeStep); + } + } + } + if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); + dataString=dataString+"!"; + for (String variable: partsMap.keySet()){ + dataString=dataString+variable+":"+partsMap.get(variable)+"#"; + } + if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); + + return dataString; + } + + public ArrayList getVariableIfInc(ModelTemp modelTemp){ + ArrayList varList= new ArrayList(); + ArrayList ifIncItemGroupIDList = modelTemp.ifIncItemGroupIDList; + Map ifIncItemGroupMap = modelTemp.ifIncItemGroupMap; + for (int i=0; i conditionValueList = ProcIfIncItemGroup.evaluateConditions(Tools.allToLowerCase(ifIncItemGroup.conditionList)); + int j=0; + int cn=conditionValueList.size(); + while (j> inc_svar_map_list = ifIncItemGroup.inc_svar_map_list; + HashMap inc_svar_map = inc_svar_map_list.get(j); + Set svarNames = inc_svar_map.keySet(); + varList.addAll(svarNames); + Iterator iterator = svarNames.iterator(); + while (iterator.hasNext()){ + String svarName = iterator.next(); + SvarTemp svar = inc_svar_map.get(svarName); + Set dependants = svar.dependants; + varList.removeAll(dependants); + varList.addAll(dependants); + } + + ArrayList> inc_dvar_map_list = ifIncItemGroup.inc_dvar_map_list; + HashMap inc_dvar_map = inc_dvar_map_list.get(j); + Set dvarNames = inc_dvar_map.keySet(); + varList.addAll(dvarNames); + iterator = dvarNames.iterator(); + while (iterator.hasNext()){ + String dvarName = iterator.next(); + DvarTemp dvar = inc_dvar_map.get(dvarName); + Set dependants = dvar.dependants; + varList.removeAll(dependants); + varList.addAll(dependants); + } + + ArrayList> inc_alias_map_list = ifIncItemGroup.inc_alias_map_list; + HashMap inc_alias_map = inc_alias_map_list.get(j); + Set aliasNames = inc_alias_map.keySet(); + varList.addAll(aliasNames); + iterator = aliasNames.iterator(); + while (iterator.hasNext()){ + String aliasName = iterator.next(); + AliasTemp alias = inc_alias_map.get(aliasName); + Set dependants = alias.dependants; + varList.removeAll(dependants); + varList.addAll(dependants); + } + + ArrayList> inc_goalSimple_map_list = ifIncItemGroup.inc_goalSimple_map_list; + HashMap inc_goalSimple_map = inc_goalSimple_map_list.get(j); + Set goalSimpleNames = inc_goalSimple_map.keySet(); + iterator = goalSimpleNames.iterator(); + while (iterator.hasNext()){ + String goalSimpleName = iterator.next(); + GoalTemp goalSimple = inc_goalSimple_map.get(goalSimpleName); + Set dependants = goalSimple.dependants; + varList.removeAll(dependants); + varList.addAll(dependants); + } + + ArrayList> inc_goalComplex_map_list = ifIncItemGroup.inc_goalComplex_map_list; + HashMap inc_goalComplex_map = inc_goalComplex_map_list.get(j); + Set goalComplexNames = inc_goalComplex_map.keySet(); + iterator = goalComplexNames.iterator(); + while (iterator.hasNext()){ + String goalComplexName = iterator.next(); + GoalTemp goalComplex = inc_goalComplex_map.get(goalComplexName); + Set dependants = goalComplex.dependants; + varList.removeAll(dependants); + varList.addAll(dependants); + } + + varList.addAll(ifIncItemGroup.inc_timeseries_map_list.get(j).keySet()); + } + } + return varList; + } + + public String getGoalInOneFile(String fileFullPath){ + String goalString=""; + Map gMap = SolverData.getConstraintDataMap(); + Map dvMap = SolverData.getDvarMap(); + ArrayList controlGoals=new ArrayList(); + + try { + WreslTreeWalker walker = FileParser.parseOneFileForDebug(fileFullPath); + if (walker==null) return goalString; + SimulationDataSet fileDataSet = walker.thisFileDataSet; + ArrayList sortedGoalList = fileDataSet.gList; + + Collections.sort(sortedGoalList, String.CASE_INSENSITIVE_ORDER); + for (int i=0; i multiplier = ee.getMultiplier(); + Set mKeySet = multiplier.keySet(); + Iterator mi = mKeySet.iterator(); + boolean hasData = true; + while (mi.hasNext()){ + String variable=mi.next(); + Number value=multiplier.get(variable).getData(); + double value1=value.doubleValue(); + if (goalString.endsWith(":")){ + if (value1==1.0){ + goalString=goalString+variable; + }else if (value1==-1.0){ + goalString=goalString+"-"+variable; + }else{ + goalString=goalString+df.format(value)+variable; + } + }else{ + if (value1==1.0){ + goalString=goalString+"+"+variable; + }else if (value1 == -1.0){ + goalString=goalString+"-"+variable; + }else if(value1>=0){ + goalString=goalString+"+"+df.format(value)+variable; + }else{ + goalString=goalString+df.format(value)+variable; + } + } + if (!(variable.startsWith("surplus__") || variable.startsWith("slack__"))){ + IntDouble id = dvMap.get(variable).getData(); + if (id==null){ + hasData=false; + }else{ + double variableValue=id.getData().doubleValue(); + lhs=lhs+value1*variableValue; + } + } + } + Number value=ee.getValue().getData(); + double value1=value.doubleValue(); + if (value1>0){ + goalString=goalString+"+"+df.format(value)+ec.getSign()+"0#"; + }else if(value1<0){ + goalString=goalString+df.format(value)+ec.getSign()+"0#"; + }else{ + goalString=goalString+ec.getSign()+"0#"; + } + lhs=lhs+value1; + if (Math.abs(lhs)<=0.00001 && hasData){ + controlGoals.add(goalName); + } + } + } + } + if (goalString.endsWith("#")) goalString=goalString.substring(0, goalString.length()-1); + } catch (RecognitionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + goalString=goalString+"!"; + for (String controlGoal:controlGoals){ + goalString=goalString+controlGoal+":"; + } + if (goalString.endsWith(":")) goalString=goalString.substring(0, goalString.length()-1); + return goalString; + } + + public String getGoalInOneFileWP(String fileFullPath){ + String goalString=""; + Map gMap = SolverData.getConstraintDataMap(); + Map dvMap = SolverData.getDvarMap(); + ArrayList controlGoals=new ArrayList(); + ArrayList sortedGoalList=new ArrayList(); + + fileFullPath=fileFullPath.replace("/", "\\"); + if (fileFullPath.equalsIgnoreCase(FilePaths.fullMainPath)){ + StudyTemp studyTemp = ParserUtils.parseWreslMain(fileFullPath); + if (studyTemp==null) return goalString; + Map modelMap = studyTemp.modelMap; + ArrayList modelList = studyTemp.modelList; + for (String model: modelList){ + ModelTemp modelTemp = modelMap.get(model); + sortedGoalList.addAll(modelTemp.glList); + ArrayList ifIncItemGroupIDList = modelTemp.ifIncItemGroupIDList; + Map ifIncItemGroupMap = modelTemp.ifIncItemGroupMap; + for (int i=0; i conditionValueList = ProcIfIncItemGroup.evaluateConditions(Tools.allToLowerCase(ifIncItemGroup.conditionList)); + int j=0; + int cn=conditionValueList.size(); + while (j simpleGoals = ifIncItemGroup.inc_goalSimple_map_list.get(j); + HashMap complexGoals = ifIncItemGroup.inc_goalComplex_map_list.get(j); + sortedGoalList.addAll(simpleGoals.keySet()); + sortedGoalList.addAll(complexGoals.keySet()); + } + } + } + }else{ + ModelTemp modelTemp = ParserUtils.parseWreslFile(fileFullPath); + if (modelTemp==null) return goalString; + sortedGoalList = modelTemp.glList; + ArrayList ifIncItemGroupIDList = modelTemp.ifIncItemGroupIDList; + Map ifIncItemGroupMap = modelTemp.ifIncItemGroupMap; + for (int i=0; i conditionValueList = ProcIfIncItemGroup.evaluateConditions(Tools.allToLowerCase(ifIncItemGroup.conditionList)); + int j=0; + int cn=conditionValueList.size(); + while (j simpleGoals = ifIncItemGroup.inc_goalSimple_map_list.get(j); + HashMap complexGoals = ifIncItemGroup.inc_goalComplex_map_list.get(j); + sortedGoalList.addAll(simpleGoals.keySet()); + sortedGoalList.addAll(complexGoals.keySet()); + } + } + } + + Collections.sort(sortedGoalList, String.CASE_INSENSITIVE_ORDER); + for (int i=0; i multiplier = ee.getMultiplier(); + Set mKeySet = multiplier.keySet(); + Iterator mi = mKeySet.iterator(); + boolean hasData = true; + while (mi.hasNext()){ + String variable=mi.next(); + Number value=multiplier.get(variable).getData(); + double value1=value.doubleValue(); + if (goalString.endsWith(":")){ + if (value1==1.0){ + goalString=goalString+variable; + }else if (value1==-1.0){ + goalString=goalString+"-"+variable; + }else{ + goalString=goalString+df.format(value)+variable; + } + }else{ + if (value1==1.0){ + goalString=goalString+"+"+variable; + }else if (value1 == -1.0){ + goalString=goalString+"-"+variable; + }else if(value1>=0){ + goalString=goalString+"+"+df.format(value)+variable; + }else{ + goalString=goalString+df.format(value)+variable; + } + } + if (!(variable.startsWith("surplus__") || variable.startsWith("slack__"))){ + IntDouble id = dvMap.get(variable).getData(); + if (id==null){ + hasData=false; + }else{ + double variableValue=id.getData().doubleValue(); + lhs=lhs+value1*variableValue; + } + } + } + Number value=ee.getValue().getData(); + double value1=value.doubleValue(); + if (value1>0){ + goalString=goalString+"+"+df.format(value)+ec.getSign()+"0#"; + }else if(value1<0){ + goalString=goalString+df.format(value)+ec.getSign()+"0#"; + }else{ + goalString=goalString+ec.getSign()+"0#"; + } + lhs=lhs+value1; + if (Math.abs(lhs)<=0.00001 && hasData){ + controlGoals.add(goalName); + } + } + } + } + if (goalString.endsWith("#")) goalString=goalString.substring(0, goalString.length()-1); + goalString=goalString+"!"; + for (String controlGoal:controlGoals){ + goalString=goalString+controlGoal+":"; + } + if (goalString.endsWith(":")) goalString=goalString.substring(0, goalString.length()-1); + return goalString; + } + + public String getFilterGoal(String fileName){ + String filtergoal="filteredgoalretrieved"; + if (procFilterFile(fileName)){ + Map gMap = SolverData.getConstraintDataMap(); + Map dvMap = SolverData.getDvarMap(); + Set goalKeySet=filterGoals.keySet(); + + try{ + File dataFolder= new File(dataDir); + dataFolder.mkdirs(); + File filterGoalFile = new File(dataFolder, "filtergoals.dat"); + FileOutputStream filterGoalStream = new FileOutputStream(filterGoalFile); + OutputStreamWriter filterGoalWriter = new OutputStreamWriter(filterGoalStream); + BufferedWriter filterGoalBuffer = new BufferedWriter(filterGoalWriter); + + for (int i=0; i multiplier = ee.getMultiplier(); + Set mKeySet = multiplier.keySet(); + Iterator mi = mKeySet.iterator(); + boolean hasData = true; + while (mi.hasNext()){ + String variable=mi.next(); + Number value=multiplier.get(variable).getData(); + double value1=value.doubleValue(); + if (goalString.endsWith(":")){ + if (value1==1.0){ + goalString=goalString+variable; + }else if (value1==-1.0){ + goalString=goalString+"-"+variable; + }else{ + goalString=goalString+df.format(value)+variable; + } + }else{ + if (value1==1.0){ + goalString=goalString+"+"+variable; + }else if (value1 == -1.0){ + goalString=goalString+"-"+variable; + }else if(value1>=0){ + goalString=goalString+"+"+df.format(value)+variable; + }else{ + goalString=goalString+df.format(value)+variable; + } + } + if (!(variable.startsWith("surplus__") || variable.startsWith("slack__"))){ + IntDouble id = dvMap.get(variable).getData(); + if (id==null){ + hasData=false; + }else{ + double variableValue=id.getData().doubleValue(); + lhs=lhs+value1*variableValue; + } + } + } + Number value=ee.getValue().getData(); + double value1=value.doubleValue(); + if (value1>0){ + goalString=goalString+"+"+df.format(value)+ec.getSign()+"0"; + }else if(value1<0){ + goalString=goalString+df.format(value)+ec.getSign()+"0"; + }else{ + goalString=goalString+ec.getSign()+"0"; + } + lhs=lhs+value1; + FilterGoal fg = filterGoals.get(goalName); + double tolerance=Double.parseDouble(fg.getTolerance()); + if (Math.abs(lhs)<=tolerance && hasData){ + goalString=goalString+";"+"y"+System.getProperty("line.separator"); + }else{ + goalString=goalString+";"+"n"+System.getProperty("line.separator"); + } + filterGoalBuffer.write(goalString); + } + } + } + filterGoalBuffer.close(); + }catch (IOException e){ + return "failed"; + } + }else{ + return "failed"; + } + return filtergoal; + } + + public boolean procFilterFile(String filterName){ + boolean doFilter=true; + filterGoals=new HashMap(); + filterGoalNames=new ArrayList(); + File filterFile=new File(filterName); + if (filterFile.exists()){ + doFilter=true; + try { + FileReader fr = new FileReader(filterFile); + BufferedReader br = new BufferedReader(fr); + String line = br.readLine(); + if (line != null){ + while ((line = br.readLine()) != null) { + line=line.trim().toLowerCase(); + String[] filterParts=line.split(","); + int length=filterParts.length; + FilterGoal fg=new FilterGoal(); + if (length==3){ + fg.setAlias(filterParts[1]); + fg.setTolerance(filterParts[2]); + }else if (length==2){ + fg.setAlias(filterParts[1]); + } + filterGoals.put(filterParts[0], fg); + filterGoalNames.add(filterParts[0]); + } + } + fr.close(); + } catch (Exception e) { + e.printStackTrace(); + doFilter=false; + } + }else{ + doFilter=false; + } + return doFilter; + } + + public String getAllVariableString(){ + String dataString=""; + ArrayList allDataNames=new ArrayList(); + ArrayList allTsNames=new ArrayList(); + ArrayList allDvNames=new ArrayList(); + ArrayList allSvNames=new ArrayList(); + ArrayList allAsNames=new ArrayList(); + ArrayList allParameterNames=new ArrayList(); + Map allData=new HashMap(); + StudyDataSet sds = ControlData.currStudyDataSet; + String modelName=sds.getModelList().get(ControlData.currCycleIndex); + ModelDataSet mds=sds.getModelDataSetMap().get(modelName); + Map tsMap = mds.tsMap; + Map dvMap = SolverData.getDvarMap(); + Map svMap = mds.svMap; + Map svFutMap = mds.svFutMap; + Map asMap = mds.asMap; + Map parameterMap = sds.getParameterMap(); + Map partsMap=new HashMap(); + + IntDouble intDouble; + + Set tsKeySet = tsMap.keySet(); + Iterator tsIterator = tsKeySet.iterator(); + while (tsIterator.hasNext()){ + String tsName=tsIterator.next(); + if (!allDataNames.contains(tsName)){ + Timeseries ts = tsMap.get(tsName); + intDouble=ts.getData(); + if (intDouble != null){ + allDataNames.add(tsName); + allTsNames.add(tsName); + allData.put(tsName, intDouble.getData()); + partsMap.put(tsName, ts.kind+":"+ControlData.timeStep); + } + } + } + + Set dvKeySet = dvMap.keySet(); + Iterator dvIterator = dvKeySet.iterator(); + while (dvIterator.hasNext()){ + String dvName=dvIterator.next(); + if (!allDataNames.contains(dvName)){ + Dvar dv = dvMap.get(dvName); + intDouble=dv.getData(); + if (intDouble !=null){ + allDataNames.add(dvName); + allDvNames.add(dvName); + allData.put(dvName, intDouble.getData()); + partsMap.put(dvName, dv.kind+":"+ControlData.timeStep); + } + } + } + + Set svKeySet = svMap.keySet(); + Iterator svIterator = svKeySet.iterator(); + while (svIterator.hasNext()){ + String svName=svIterator.next(); + if (!allDataNames.contains(svName)){ + Svar sv = svMap.get(svName); + intDouble=sv.getData(); + if (intDouble!=null){ + allDataNames.add(svName); + allSvNames.add(svName); + allData.put(svName, intDouble.getData()); + partsMap.put(svName, sv.kind+":"+ControlData.timeStep); + } + } + } + + Set svFutKeySet = svFutMap.keySet(); + Iterator svFutIterator = svFutKeySet.iterator(); + while (svFutIterator.hasNext()){ + String svFutName=svFutIterator.next(); + if (!allDataNames.contains(svFutName)){ + Svar svFut = svFutMap.get(svFutName); + intDouble=svFut.getData(); + if (intDouble!=null){ + allDataNames.add(svFutName); + allSvNames.add(svFutName); + allData.put(svFutName, intDouble.getData()); + partsMap.put(svFutName, svFut.kind+":"+ControlData.timeStep); + } + } + } + + Set asKeySet = asMap.keySet(); + Iterator asIterator = asKeySet.iterator(); + while (asIterator.hasNext()){ + String asName=asIterator.next(); + if (!allDataNames.contains(asName)){ + Alias as = asMap.get(asName); + intDouble=as.getData(); + if (intDouble!=null){ + allDataNames.add(asName); + allData.put(asName, intDouble.getData()); + partsMap.put(asName, as.kind+":"+ControlData.timeStep); + } + } + if (!allAsNames.contains(asName)){ + allAsNames.add(asName); + } + } + + Set parameterKeySet = parameterMap.keySet(); + Iterator parameterIterator = parameterKeySet.iterator(); + while (parameterIterator.hasNext()){ + String parameterName=parameterIterator.next(); + if (!allDataNames.contains(parameterName)){ + Svar parameter = parameterMap.get(parameterName); + intDouble=parameter.getData(); + if (intDouble!=null){ + allDataNames.add(parameterName); + allParameterNames.add(parameterName); + allData.put(parameterName, intDouble.getData()); + partsMap.put(parameterName, parameter.kind+":"+ControlData.timeStep); + } + } + } + + Collections.sort(allDataNames, String.CASE_INSENSITIVE_ORDER); + for (String variable: allDataNames){ + dataString=dataString+variable+":"+df.format(allData.get(variable))+"#"; + } + + dataString=dataString+"&"; + for (String variable: partsMap.keySet()){ + dataString=dataString+variable+":"+partsMap.get(variable)+"#"; + } + + dataString=dataString+"&"; + + Map weightMap = SolverData.getWeightMap(); + for (int i=0; i<=1; i++){ + ArrayList weightCollection; + if (i==0){ + weightCollection = ControlData.currModelDataSet.wtList; + }else{ + weightCollection = ControlData.currModelDataSet.wtTimeArrayList; + } + Iterator weightIterator = weightCollection.iterator(); + + while(weightIterator.hasNext()){ + String weightName=(String)weightIterator.next(); + dataString=dataString+weightName+":"+df.format(weightMap.get(weightName).getValue())+"#"; + } + } + Map weightSlackSurplusMap = SolverData.getWeightSlackSurplusMap(); + CopyOnWriteArrayList usedWeightSlackSurplusCollection = ControlData.currModelDataSet.usedWtSlackSurplusList; + Iterator usedWeightSlackSurplusIterator = usedWeightSlackSurplusCollection.iterator(); + + while(usedWeightSlackSurplusIterator.hasNext()){ + String usedWeightSlackSurplusName=(String)usedWeightSlackSurplusIterator.next(); + dataString=dataString+usedWeightSlackSurplusName+":"+df.format(weightSlackSurplusMap.get(usedWeightSlackSurplusName).getValue())+"#"; + } + + if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); + return dataString; + } + + public String getAllVariableFiles(){ + String allDataString="alldataretrieved"; + ArrayList allDataNames=new ArrayList(); + ArrayList allTsNames=new ArrayList(); + ArrayList allDvNames=new ArrayList(); + ArrayList allSvNames=new ArrayList(); + ArrayList allAsNames=new ArrayList(); + ArrayList allParameterNames=new ArrayList(); + Map allData=new HashMap(); + StudyDataSet sds = ControlData.currStudyDataSet; + String modelName=sds.getModelList().get(ControlData.currCycleIndex); + ModelDataSet mds=sds.getModelDataSetMap().get(modelName); + Map tsMap = mds.tsMap; + Map dvMap = SolverData.getDvarMap(); + Map svMap = mds.svMap; + Map svFutMap = mds.svFutMap; + Map asMap = mds.asMap; + Map parameterMap = sds.getParameterMap(); + Map partsMap=new HashMap(); + + IntDouble intDouble; + + Set tsKeySet = tsMap.keySet(); + Iterator tsIterator = tsKeySet.iterator(); + while (tsIterator.hasNext()){ + String tsName=tsIterator.next(); + if (!allDataNames.contains(tsName)){ + Timeseries ts = tsMap.get(tsName); + intDouble=ts.getData(); + if (intDouble != null){ + allDataNames.add(tsName); + allTsNames.add(tsName); + allData.put(tsName, intDouble.getData()); + partsMap.put(tsName, ts.kind+":"+ControlData.timeStep); + } + } + } + + Set dvKeySet = dvMap.keySet(); + Iterator dvIterator = dvKeySet.iterator(); + while (dvIterator.hasNext()){ + String dvName=dvIterator.next(); + if (!allDataNames.contains(dvName)){ + Dvar dv = dvMap.get(dvName); + intDouble=dv.getData(); + if (intDouble !=null){ + allDataNames.add(dvName); + allDvNames.add(dvName); + allData.put(dvName, intDouble.getData()); + partsMap.put(dvName, dv.kind+":"+ControlData.timeStep); + } + } + } + + Set svKeySet = svMap.keySet(); + Iterator svIterator = svKeySet.iterator(); + while (svIterator.hasNext()){ + String svName=svIterator.next(); + if (!allDataNames.contains(svName)){ + Svar sv = svMap.get(svName); + intDouble=sv.getData(); + if (intDouble!=null){ + allDataNames.add(svName); + allSvNames.add(svName); + allData.put(svName, intDouble.getData()); + partsMap.put(svName, sv.kind+":"+ControlData.timeStep); + } + } + } + + Set svFutKeySet = svFutMap.keySet(); + Iterator svFutIterator = svFutKeySet.iterator(); + while (svFutIterator.hasNext()){ + String svFutName=svFutIterator.next(); + if (!allDataNames.contains(svFutName)){ + Svar svFut = svFutMap.get(svFutName); + intDouble=svFut.getData(); + if (intDouble!=null){ + allDataNames.add(svFutName); + allSvNames.add(svFutName); + allData.put(svFutName, intDouble.getData()); + partsMap.put(svFutName, svFut.kind+":"+ControlData.timeStep); + } + } + } + + Set asKeySet = asMap.keySet(); + Iterator asIterator = asKeySet.iterator(); + while (asIterator.hasNext()){ + String asName=asIterator.next(); + if (!allDataNames.contains(asName)){ + Alias as = asMap.get(asName); + intDouble=as.getData(); + if (intDouble!=null){ + allDataNames.add(asName); + allData.put(asName, intDouble.getData()); + partsMap.put(asName, as.kind+":"+ControlData.timeStep); + } + } + if (!allAsNames.contains(asName)){ + allAsNames.add(asName); + } + } + + Set parameterKeySet = parameterMap.keySet(); + Iterator parameterIterator = parameterKeySet.iterator(); + while (parameterIterator.hasNext()){ + String parameterName=parameterIterator.next(); + if (!allDataNames.contains(parameterName)){ + Svar parameter = parameterMap.get(parameterName); + intDouble=parameter.getData(); + if (intDouble!=null){ + allDataNames.add(parameterName); + allParameterNames.add(parameterName); + allData.put(parameterName, intDouble.getData()); + partsMap.put(parameterName, parameter.kind+":"+ControlData.timeStep); + } + } + } + + try{ + File dataFolder= new File(dataDir); + dataFolder.mkdirs(); + File allDataFile = new File(dataFolder, "allvariables.dat"); + FileOutputStream allDataStream = new FileOutputStream(allDataFile); + OutputStreamWriter allDataWriter = new OutputStreamWriter(allDataStream); + BufferedWriter allDataBuffer = new BufferedWriter(allDataWriter); + + Collections.sort(allDataNames, String.CASE_INSENSITIVE_ORDER); + for (String variable: allDataNames){ + allDataBuffer.write(variable+":"+df.format(allData.get(variable))+System.getProperty("line.separator")); + } + allDataBuffer.close(); + + dataFolder.mkdirs(); + File allPartFile = new File(dataFolder, "allparts.dat"); + FileOutputStream allPartStream = new FileOutputStream(allPartFile); + OutputStreamWriter allPartWriter = new OutputStreamWriter(allPartStream); + BufferedWriter allPartBuffer = new BufferedWriter(allPartWriter); + + for (String variable: partsMap.keySet()){ + allPartBuffer.write(variable+":"+partsMap.get(variable)+System.getProperty("line.separator")); + } + allPartBuffer.close(); + + File allWeightFile = new File(dataFolder, "allweights.dat"); + FileOutputStream allWeightStream = new FileOutputStream(allWeightFile); + OutputStreamWriter allWeightWriter = new OutputStreamWriter(allWeightStream); + BufferedWriter allWeightBuffer = new BufferedWriter(allWeightWriter); + + Map weightMap = SolverData.getWeightMap(); + for (int i=0; i<=1; i++){ + ArrayList weightCollection; + if (i==0){ + weightCollection = ControlData.currModelDataSet.wtList; + }else{ + weightCollection = ControlData.currModelDataSet.wtTimeArrayList; + } + Iterator weightIterator = weightCollection.iterator(); + + while(weightIterator.hasNext()){ + String weightName=(String)weightIterator.next(); + allWeightBuffer.write(weightName+":"+df.format(weightMap.get(weightName).getValue())+System.getProperty("line.separator")); + } + } + Map weightSlackSurplusMap = SolverData.getWeightSlackSurplusMap(); + CopyOnWriteArrayList usedWeightSlackSurplusCollection = ControlData.currModelDataSet.usedWtSlackSurplusList; + Iterator usedWeightSlackSurplusIterator = usedWeightSlackSurplusCollection.iterator(); + + while(usedWeightSlackSurplusIterator.hasNext()){ + String usedWeightSlackSurplusName=(String)usedWeightSlackSurplusIterator.next(); + allWeightBuffer.write(usedWeightSlackSurplusName+":"+df.format(weightSlackSurplusMap.get(usedWeightSlackSurplusName).getValue())+System.getProperty("line.separator")); + } + allWeightBuffer.close(); + }catch (IOException e){ + allDataString="failed"; + } + return allDataString; + } + + public String getAllGoalString(){ + String goalString=""; + Map gMap = SolverData.getConstraintDataMap(); + Set goalKeySet=gMap.keySet(); + ArrayList gKeyArrayList=new ArrayList(); + Iterator ki=goalKeySet.iterator(); + while (ki.hasNext()){ + gKeyArrayList.add((String) ki.next()); + } + Collections.sort(gKeyArrayList, String.CASE_INSENSITIVE_ORDER); + for (int i=0; i multiplier = ee.getMultiplier(); + Set mKeySet = multiplier.keySet(); + Iterator mi = mKeySet.iterator(); + while (mi.hasNext()){ + String variable=mi.next(); + Number value=multiplier.get(variable).getData(); + double value1=value.doubleValue(); + if (goalString.endsWith(":")){ + if (value1==1.0){ + goalString=goalString+variable; + }else if (value1==-1.0){ + goalString=goalString+"-"+variable; + }else{ + goalString=goalString+df.format(value)+variable; + } + }else{ + if (value1==1.0){ + goalString=goalString+"+"+variable; + }else if (value1 == -1.0){ + goalString=goalString+"-"+variable; + }else if(value1>=0){ + goalString=goalString+"+"+df.format(value)+variable; + }else{ + goalString=goalString+df.format(value)+variable; + } + } + } + Number value=ee.getValue().getData(); + double value1=value.doubleValue(); + if (value1>0){ + goalString=goalString+"+"+df.format(value)+ec.getSign()+"0#"; + }else if(value1<0){ + goalString=goalString+df.format(value)+ec.getSign()+"0#"; + }else{ + goalString=goalString+ec.getSign()+"0#"; + } + } + } + if (goalString.endsWith("#")) goalString=goalString.substring(0, goalString.length()-1); + return goalString; + } + + public String getAllGoalFile(){ + String allgoal="allgoalretrieved"; + Map gMap = SolverData.getConstraintDataMap(); + Set goalKeySet=gMap.keySet(); + ArrayList gKeyArrayList=new ArrayList(); + Iterator ki=goalKeySet.iterator(); + while (ki.hasNext()){ + gKeyArrayList.add((String) ki.next()); + } + Collections.sort(gKeyArrayList, String.CASE_INSENSITIVE_ORDER); + + try{ + File dataFolder= new File(dataDir); + dataFolder.mkdirs(); + File allGoalFile = new File(dataFolder, "allgoals.dat"); + FileOutputStream allGoalStream = new FileOutputStream(allGoalFile); + OutputStreamWriter allGoalWriter = new OutputStreamWriter(allGoalStream); + BufferedWriter allGoalBuffer = new BufferedWriter(allGoalWriter); + + for (int i=0; i multiplier = ee.getMultiplier(); + Set mKeySet = multiplier.keySet(); + Iterator mi = mKeySet.iterator(); + while (mi.hasNext()){ + String variable=mi.next(); + Number value=multiplier.get(variable).getData(); + double value1=value.doubleValue(); + if (goalString.endsWith(":")){ + if (value1==1.0){ + goalString=goalString+variable; + }else if (value1==-1.0){ + goalString=goalString+"-"+variable; + }else{ + goalString=goalString+df.format(value)+variable; + } + }else{ + if (value1==1.0){ + goalString=goalString+"+"+variable; + }else if (value1 == -1.0){ + goalString=goalString+"-"+variable; + }else if(value1>=0){ + goalString=goalString+"+"+df.format(value)+variable; + }else{ + goalString=goalString+df.format(value)+variable; + } + } + } + Number value=ee.getValue().getData(); + double value1=value.doubleValue(); + if (value1>0){ + goalString=goalString+"+"+df.format(value)+ec.getSign()+"0"+System.getProperty("line.separator"); + }else if(value1<0){ + goalString=goalString+df.format(value)+ec.getSign()+"0"+System.getProperty("line.separator"); + }else{ + goalString=goalString+ec.getSign()+"0"+System.getProperty("line.separator"); + } + allGoalBuffer.write(goalString); + } + } + allGoalBuffer.close(); + }catch (IOException e){ + return "failed"; + } + return allgoal; + } + + public String getWatch(String vGNameString){ + String dataString=""; + StudyDataSet sds=ControlData.currStudyDataSet; + String modelName=sds.getModelList().get(ControlData.currCycleIndex); + ModelDataSet mds=sds.getModelDataSetMap().get(modelName); + Map parameterMap = sds.getParameterMap(); + Map tsMap = mds.tsMap; + Map dvMap = SolverData.getDvarMap(); + Map svMap = mds.svMap; + Map svFutMap = mds.svFutMap; + Map asMap = mds.asMap; + Map gMap = SolverData.getConstraintDataMap(); + Map partsMap=new HashMap(); + + String[] vGNames; + if (vGNameString.contains("#")){ + vGNames=vGNameString.split("#"); + }else{ + vGNames=new String[1]; + vGNames[0]=vGNameString; + } + ArrayList controlGoals=new ArrayList(); + IntDouble intDouble; + for (int i=0; i multiplier = ee.getMultiplier(); + Set mKeySet = multiplier.keySet(); + Iterator mi = mKeySet.iterator(); + boolean hasData = true; + while (mi.hasNext()){ + String variable=mi.next(); + Number value=multiplier.get(variable).getData(); + double value1=value.doubleValue(); + if (dataString.endsWith(":")){ + if (value1==1.0){ + dataString=dataString+variable; + }else if (value1==-1.0){ + dataString=dataString+"-"+variable; + }else{ + dataString=dataString+df.format(value)+variable; + } + }else{ + if (value1==1.0){ + dataString=dataString+"+"+variable; + }else if (value1 == -1.0){ + dataString=dataString+"-"+variable; + }else if(value1>=0){ + dataString=dataString+"+"+df.format(value)+variable; + }else{ + dataString=dataString+df.format(value)+variable; + } + } + if (!(variable.startsWith("surplus__") || variable.startsWith("slack__"))){ + IntDouble id = dvMap.get(variable).getData(); + if (id==null){ + hasData=false; + }else{ + double variableValue=id.getData().doubleValue(); + lhs=lhs+value1*variableValue; + } + } + } + Number value=ee.getValue().getData(); + double value1=value.doubleValue(); + if (value1>0){ + dataString=dataString+"+"+df.format(value)+ec.getSign()+"0#"; + }else if(value1<0){ + dataString=dataString+df.format(value)+ec.getSign()+"0#"; + }else{ + dataString=dataString+ec.getSign()+"0#"; + } + lhs=lhs+value1; + if (Math.abs(lhs)<=0.00001 && hasData){ + controlGoals.add(vGName); + } + } + }else{ + dataString=dataString+vGName+":"+"N/A#"; + } + } + if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); + + dataString=dataString+"!"; + for (String controlGoal:controlGoals){ + dataString=dataString+controlGoal+":"; + } + if (dataString.endsWith(":")) dataString=dataString.substring(0, dataString.length()-1); + + dataString=dataString+"&"; + for (String variable: partsMap.keySet()){ + dataString=dataString+variable+":"+partsMap.get(variable)+"#"; + } + if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); + + return dataString; + } + + public String getAllControlGoalName(){ + String goalNames=""; + Map gMap = SolverData.getConstraintDataMap(); + Map dvMap = SolverData.getDvarMap(); + Set goalKeySet=gMap.keySet(); + Iterator ki=goalKeySet.iterator(); + while (ki.hasNext()){ + double lhs=0.0; + String goalName=(String)ki.next(); + EvalConstraint ec=gMap.get(goalName); + if (ec!=null){ + EvalExpression ee=ec.getEvalExpression(); + Map multiplier = ee.getMultiplier(); + Set mKeySet = multiplier.keySet(); + Iterator mi = mKeySet.iterator(); + boolean hasData = true; + while (mi.hasNext()){ + String variable=mi.next(); + double value1=multiplier.get(variable).getData().doubleValue(); + if (!(variable.startsWith("surplus__") || variable.startsWith("slack__"))){ + IntDouble id = dvMap.get(variable).getData(); + if (id ==null){ + hasData=false; + }else{ + double variableValue=id.getData().doubleValue(); + lhs=lhs+variableValue*value1; + } + } + } + double value1=ee.getValue().getData().doubleValue(); + lhs=lhs+value1; + if (Math.abs(lhs)<=0.00001 && hasData) goalNames=goalNames+goalName+":"; + } + } + if (goalNames.endsWith(":")) goalNames=goalNames.substring(0, goalNames.length()-1); + return goalNames; + } + + public String getTimeseriesDetail(String variableNames){ + monitorVarNames=variableNames.split("#"); + monitorVarTimeStep=ControlData.timeStep; + controllerDebug.updateVarMonitor(); + + String dataString=""; + String variableName=monitorVarNames[0]; + String entryName=DssOperation.entryNameTS(variableName, ControlData.timeStep); + HashMap dvAliasTSMap = DataTimeSeries.dvAliasTS; + + if (dvAliasTSMap.containsKey(entryName)){ + DssDataSetFixLength ddsf = dvAliasTSMap.get(entryName); + double[] dataArray = ddsf.getData(); + ParallelVars prvs = TimeOperation.findTime(0); + int currIndex; + if (ControlData.timeStep.equals("1MON")){ + currIndex=ValueEvaluation.timeSeriesIndex(ddsf, prvs); + }else{ + currIndex=ValueEvaluation.timeSeriesIndex(ddsf, prvs)-1; + } + for (int i=0; i<=currIndex; i++){ + double value; + value=dataArray[i]; + if (!(value==-901.0 || value==-902.0)){ + int timestepListed=i-currIndex; + prvs = TimeOperation.findTime(timestepListed); + dataString=dataString+timestepListed+":"+prvs.dataMonth+"-"+prvs.dataDay+"-"+prvs.dataYear+":"+df.format(value)+"#"; + } + } + }else{ + HashMap svTSMap = DataTimeSeries.svTS; + if (svTSMap.containsKey(entryName)){ + DssDataSet dds = svTSMap.get(entryName); + ArrayList dataArrayList = dds.getData(); + ParallelVars prvs = TimeOperation.findTime(0); + int currIndex=ValueEvaluation.timeSeriesIndex(dds, prvs); + for (int i=0; i indexList=new ArrayList(); + Map futureArray= new HashMap(); + if (mds.svList.contains(variableName)){ + Map svFutMap = mds.svFutMap; + Set keySet=svFutMap.keySet(); + for (String key:keySet){ + if (key.startsWith(variableName+"__fut__")){ + String[] splittedKey=key.split("__fut__"); + if (splittedKey.length>1){ + int index = Integer.parseInt(splittedKey[1]); + IntDouble intDouble=svFutMap.get(key).getData(); + if (intDouble != null) { + indexList.add(index); + futureArray.put(index, intDouble.getData()); + } + } + } + } + }else if (mds.dvList.contains(variableName)){ + Map dvMap = SolverData.getDvarMap(); + Set keySet=dvMap.keySet(); + for (String key:keySet){ + if (key.startsWith(variableName+"__fut__")){ + String[] splittedKey=key.split("__fut__"); + if (splittedKey.length>1){ + int index = Integer.parseInt(splittedKey[1]); + IntDouble intDouble=dvMap.get(key).getData(); + if (intDouble != null){ + indexList.add(index); + futureArray.put(index, intDouble.getData()); + } + } + } + } + } + Collections.sort(indexList); + for (int i=0; i modelTimeStepList = sds.getModelTimeStepList(); + ArrayList ml = sds.getModelList(); + ArrayList> dvAliasTSCycles = DataTimeSeries.dvAliasTSCycles; + boolean variableFound=false; + for (int cycleIndex=1; cycleIndex<=ControlData.currCycleIndex+1; cycleIndex++){ + String entryNameTS=DssOperation.entryNameTS(variableName, modelTimeStepList.get(cycleIndex-1)); + HashMap dvAliasTSCycle = dvAliasTSCycles.get(cycleIndex-1); + if (dvAliasTSCycle.containsKey(entryNameTS)){ + variableFound=true; + DssDataSetFixLength dds = dvAliasTSCycle.get(entryNameTS); + int index=ControlData.currTimeStep.get(cycleIndex-1); + if (dds!=null){ + double[] data=dds.getData(); + String cycle=ml.get(cycleIndex-1); + if (cycleIndex==ControlData.currCycleIndex+1){ + dataString=dataString+cycleIndex+":"+cycle+":"+df.format(data[index])+"#";; + }else{ + if (index>=1){ + dataString=dataString+cycleIndex+":"+cycle+":"+df.format(data[index-1])+"#";; + } + } + } + } + } + if (!variableFound){ + Map> varCycleValue = sds.getVarCycleValueMap(); + Map> varCycleIndexValue = sds.getVarCycleIndexValueMap(); + if (varCycleValue.containsKey(variableName)){ + Map cycleValue = varCycleValue.get(variableName); + int cycleIndex=1; + for (String cycle: ml){ + if (cycleIndex<=ControlData.currCycleIndex+1){ + if (cycleValue.containsKey(cycle)){ + IntDouble id=cycleValue.get(cycle); + if (id!=null) dataString=dataString+cycleIndex+":"+cycle+":"+df.format(id.getData())+"#"; + }else if (varCycleIndexValue.containsKey(variableName)){ + Map cycleIndexValue = varCycleIndexValue.get(variableName); + if (cycleIndexValue.containsKey(cycle)){ + IntDouble id=cycleIndexValue.get(cycle); + if (id!=null) dataString=dataString+cycleIndex+":"+cycle+":"+df.format(id.getData())+"#"; + } + } + } + cycleIndex=cycleIndex+1; + } + }else{ + Map> varTimeArrayCycleValue = sds.getVarTimeArrayCycleValueMap(); + if (varTimeArrayCycleValue.containsKey(variableName)){ + Map cycleValue = varTimeArrayCycleValue.get(variableName); + int cycleIndex=1; + for (String cycle: ml){ + if (cycleIndex<=ControlData.currCycleIndex+1){ + if (cycleValue.containsKey(cycle)){ + IntDouble id=cycleValue.get(cycle); + if (id!=null) dataString=dataString+cycleIndex+":"+cycle+":"+df.format(id.getData())+"#"; + }else if (varCycleIndexValue.containsKey(variableName)){ + Map cycleIndexValue = varCycleIndexValue.get(variableName); + if (cycleIndexValue.containsKey(cycle)){ + IntDouble id=cycleIndexValue.get(cycle); + if (id!=null) dataString=dataString+cycleIndex+":"+cycle+":"+df.format(id.getData())+"#"; + } + } + } + cycleIndex=cycleIndex+1; + } + }else{ + if (varCycleIndexValue.containsKey(variableName)){ + Map cycleValue = varCycleIndexValue.get(variableName); + int cycleIndex=1; + for (String cycle: ml){ + if (cycleValue.containsKey(cycle) && cycleIndex<=ControlData.currCycleIndex+1){ + IntDouble id=cycleValue.get(cycle); + if (id!=null) dataString=dataString+cycleIndex+":"+cycle+":"+df.format(id.getData())+"#"; + } + cycleIndex=cycleIndex+1; + } + } + } + } + } + if (dataString.endsWith("#")) dataString=dataString.substring(0, dataString.length()-1); + return dataString; + } + + public boolean modifyTimeSeries(String[] requestParts){ + boolean isModified=false; + String[] varStrings=requestParts[1].split("#"); + String varName=varStrings[0]; + int index=Integer.parseInt(varStrings[1]); + double value=Double.parseDouble(varStrings[2]); + String entryName=DssOperation.entryNameTS(varName, monitorVarTimeStep); + HashMap dvAliasTSMap = DataTimeSeries.dvAliasTS; + if (dvAliasTSMap.containsKey(entryName)){ + DssDataSetFixLength ddsf = dvAliasTSMap.get(entryName); + double[] dataArray = ddsf.getData(); + ParallelVars prvs = TimeOperation.findTime(index); + int tsIndex=ValueEvaluation.timeSeriesIndex(ddsf, prvs)-1; + dataArray[tsIndex]=value; + isModified=true; + }else{ + HashMap svTSMap = DataTimeSeries.svTS; + if (svTSMap.containsKey(entryName)){ + DssDataSet dds = svTSMap.get(entryName); + ArrayList dataArrayList = dds.getData(); + ParallelVars prvs = TimeOperation.findTime(index); + int tsIndex=ValueEvaluation.timeSeriesIndex(dds, prvs); + dataArrayList.set(tsIndex, value); + isModified=true; + } + } + return isModified; + } + + public boolean modifyCycle(String[] requestParts){ + boolean isModified=false; + String[] varStrings=requestParts[1].split("#"); + String varName=varStrings[0]; + String cycle=varStrings[1]; + double value=Double.parseDouble(varStrings[2]); + StudyDataSet sds = ControlData.currStudyDataSet; + Map> varCycleValue = sds.getVarCycleValueMap(); + if (varCycleValue.containsKey(varName)){ + Map cycleValue = varCycleValue.get(varName); + if (cycleValue.containsKey(cycle)){ + cycleValue.put(cycle, new IntDouble(value, false)); + isModified=true; + } + }else{ + Map> varTimeArrayCycleValue = sds.getVarTimeArrayCycleValueMap(); + if (varTimeArrayCycleValue.containsKey(varName)){ + Map cycleValue = varTimeArrayCycleValue.get(varName); + cycleValue.put(cycle, new IntDouble(value, false)); + isModified=true; + } + } + return isModified; + } + + public String getDataString(){ + String dataString=""; + for (int i=0; i>(totalCycleNumber); + //for (int i=0; i dvAliasTSCycle = new HashMap(); + // DataTimeSeries.dvAliasTSCycles.add(dvAliasTSCycle); + //} + } + + public void setSelectedOutputCycles(){ + String strSelectedCycleOutput = ControlData.selectedCycleOutput.replace("\'", ""); + ControlData.selectedCycles = strSelectedCycleOutput.split(","); + } + + public static void main(String[] args){ + int argsSize=args.length; + String[] modArgs=new String[argsSize-2]; + for (int i=0; i<=argsSize-3; i++){ + modArgs[i]=args[i+2]; + } + int requestPort=Integer.parseInt(args[0]); + int eventPort=Integer.parseInt(args[1]); + new DebugInterface(requestPort, eventPort, modArgs); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/Error.java b/wrims-core/src/main/java/wrimsv2/components/Error.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/components/Error.java rename to wrims-core/src/main/java/wrimsv2/components/Error.java index 1feac792f..12c43b916 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/Error.java +++ b/wrims-core/src/main/java/wrimsv2/components/Error.java @@ -1,278 +1,278 @@ -package wrimsv2.components; - -import java.util.ArrayList; -import java.io.File; -import java.io.FileWriter; -import java.io.PrintWriter; -import java.io.IOException; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.External; -import wrimsv2.commondata.wresldata.Goal; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.commondata.wresldata.Timeseries; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.ilp.ILP; -import wrimsv2.wreslparser.elements.StudyUtils; -import wrimsv2.wreslparser.elements.Tools; - -public class Error { - public static ArrayList error_grammer = new ArrayList (); - public static ArrayList error_evaluation= new ArrayList (); - public static ArrayList error_solving=new ArrayList(); - public static ArrayList error_engine=new ArrayList(); - public static ArrayList error_config=new ArrayList(); - public static ArrayList error_initial=new ArrayList(); - public static ArrayList error_deviation=new ArrayList(); - - public static void writeGrammerErrorFile(String fileName){ - - String errorFileFullPath=FilePaths.mainDirectory+fileName; - try{ - FileWriter errorFile = new FileWriter(errorFileFullPath); - PrintWriter out = new PrintWriter(errorFile); - - for (int i=0; i(); - Error.error_evaluation = new ArrayList(); - Error.error_grammer = new ArrayList(); - Error.error_solving = new ArrayList(); - Error.error_config = new ArrayList(); - Error.error_initial = new ArrayList(); - Error.error_deviation = new ArrayList(); - } - - public static String getCurrentDateCycleModel(){ - - ArrayList modelList=ControlData.currStudyDataSet.getModelList(); - String modelName = modelList.get(ControlData.currCycleIndex); - int cycleIndex = ControlData.currCycleIndex + 1 ; - - return ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+ " cycle "+cycleIndex+ " ("+modelName +")"; - - } -} - +package wrimsv2.components; + +import java.util.ArrayList; +import java.io.File; +import java.io.FileWriter; +import java.io.PrintWriter; +import java.io.IOException; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.External; +import wrimsv2.commondata.wresldata.Goal; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.commondata.wresldata.Timeseries; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.ilp.ILP; +import wrimsv2.wreslparser.elements.StudyUtils; +import wrimsv2.wreslparser.elements.Tools; + +public class Error { + public static ArrayList error_grammer = new ArrayList (); + public static ArrayList error_evaluation= new ArrayList (); + public static ArrayList error_solving=new ArrayList(); + public static ArrayList error_engine=new ArrayList(); + public static ArrayList error_config=new ArrayList(); + public static ArrayList error_initial=new ArrayList(); + public static ArrayList error_deviation=new ArrayList(); + + public static void writeGrammerErrorFile(String fileName){ + + String errorFileFullPath=FilePaths.mainDirectory+fileName; + try{ + FileWriter errorFile = new FileWriter(errorFileFullPath); + PrintWriter out = new PrintWriter(errorFile); + + for (int i=0; i(); + Error.error_evaluation = new ArrayList(); + Error.error_grammer = new ArrayList(); + Error.error_solving = new ArrayList(); + Error.error_config = new ArrayList(); + Error.error_initial = new ArrayList(); + Error.error_deviation = new ArrayList(); + } + + public static String getCurrentDateCycleModel(){ + + ArrayList modelList=ControlData.currStudyDataSet.getModelList(); + String modelName = modelList.get(ControlData.currCycleIndex); + int cycleIndex = ControlData.currCycleIndex + 1 ; + + return ControlData.currYear+"/"+ControlData.currMonth+"/"+ControlData.currDay+ " cycle "+cycleIndex+ " ("+modelName +")"; + + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/FilePaths.java b/wrims-core/src/main/java/wrimsv2/components/FilePaths.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/components/FilePaths.java rename to wrims-core/src/main/java/wrimsv2/components/FilePaths.java index 709b0fbbe..43c484c00 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/FilePaths.java +++ b/wrims-core/src/main/java/wrimsv2/components/FilePaths.java @@ -1,116 +1,116 @@ -package wrimsv2.components; - -import java.io.File; - -public class FilePaths { - public static String groundwaterDir=""; //for groundwater use. - public static String fullMainPath=""; - public static String mainFile=""; - public static String mainDirectory=""; - public static String fullSvarFilePath=""; - public static String fullSvarFile2Path=""; - public static String svarFile=""; - public static String svarFileDirectory=""; - public static String fullDvarDssPath=""; - public static String dvarDssFile=""; - public static String dvarDssDirectory=""; - public static String fullDvarHDF5Path=""; - public static String fullCsvPath=""; - public static String fullInitFilePath=""; - public static String initFile=""; - public static String initFileDirectory=""; - public static String fullIlpPath=""; - public static String ilpFile=""; - public static String ilpFileDirectory=""; - public static String csvFolderName=""; - public static String lookupSubDirectory=""; - public static String sqlScenarioName=""; - - - public static void setMainFilePaths(String fullPath){ - fullMainPath=fullPath; - int index=fullPath.lastIndexOf(File.separator); - mainDirectory=fullPath.substring(0,index+1); - mainFile=fullPath.substring(index+1); - } - - public static void setSvarFilePaths(String fullPath){ - fullSvarFilePath=fullPath; - int index=fullPath.lastIndexOf(File.separator); - svarFileDirectory=fullPath.substring(0,index+1); - svarFile=fullPath.substring(index+1); - } - - public static void setSvarFile2Paths(String fullPath){ - fullSvarFile2Path=fullPath; - } - - public static void setDvarFilePaths(String fullPath){ - if (fullPath.toLowerCase().endsWith(".h5")){ - ControlData.outputType=1; - fullDvarHDF5Path=fullPath; - int index=fullPath.lastIndexOf("."); - fullDvarDssPath=fullPath.substring(0, index+1)+"dss"; - }else if (fullPath.toLowerCase().endsWith(".mysqlc")){ - ControlData.outputType=2; - int index1=fullPath.lastIndexOf(File.separator); - int index2=fullPath.lastIndexOf("."); - sqlScenarioName=fullPath.substring(index1+1,index2); - fullDvarDssPath=fullPath.substring(0, index2+1)+"dss"; - }else if (fullPath.toLowerCase().endsWith(".mysqlr")){ - ControlData.outputType=3; - int index1=fullPath.lastIndexOf(File.separator); - int index2=fullPath.lastIndexOf("."); - sqlScenarioName=fullPath.substring(index1+1,index2); - fullDvarDssPath=fullPath.substring(0, index2+1)+"dss"; - }else if (fullPath.toLowerCase().endsWith(".sqlsvr")){ - ControlData.outputType=4; - int index1=fullPath.lastIndexOf(File.separator); - int index2=fullPath.lastIndexOf("."); - sqlScenarioName=fullPath.substring(index1+1,index2); - fullDvarDssPath=fullPath.substring(0, index2+1)+"dss"; - }else if (fullPath.toLowerCase().endsWith(".csv")){ - ControlData.outputType=5; - int index1=fullPath.lastIndexOf(File.separator); - int index2=fullPath.lastIndexOf("."); - sqlScenarioName=fullPath.substring(index1+1,index2); - fullDvarDssPath=fullPath.substring(0, index2+1)+"dss"; - fullCsvPath=fullPath; - }else{ - ControlData.outputType=0; - fullDvarDssPath=fullPath; - } - int index=fullPath.lastIndexOf(File.separator); - dvarDssDirectory=fullPath.substring(0,index+1); - dvarDssFile=fullPath.substring(index+1); - } - - public static void setInitFilePaths(String fullPath){ - fullInitFilePath=fullPath; - int index=fullPath.lastIndexOf(File.separator); - initFileDirectory=fullPath.substring(0,index+1); - initFile=fullPath.substring(index+1); - } - - public static void clear(){ - - groundwaterDir=""; - fullMainPath=""; - mainFile=""; - mainDirectory=""; - fullSvarFilePath=""; - svarFile=""; - svarFileDirectory=""; - fullDvarDssPath=""; - dvarDssFile=""; - dvarDssDirectory=""; - fullInitFilePath=""; - initFile=""; - initFileDirectory=""; - fullIlpPath=""; - ilpFile=""; - ilpFileDirectory=""; - csvFolderName=""; - } - -} +package wrimsv2.components; + +import java.io.File; + +public class FilePaths { + public static String groundwaterDir=""; //for groundwater use. + public static String fullMainPath=""; + public static String mainFile=""; + public static String mainDirectory=""; + public static String fullSvarFilePath=""; + public static String fullSvarFile2Path=""; + public static String svarFile=""; + public static String svarFileDirectory=""; + public static String fullDvarDssPath=""; + public static String dvarDssFile=""; + public static String dvarDssDirectory=""; + public static String fullDvarHDF5Path=""; + public static String fullCsvPath=""; + public static String fullInitFilePath=""; + public static String initFile=""; + public static String initFileDirectory=""; + public static String fullIlpPath=""; + public static String ilpFile=""; + public static String ilpFileDirectory=""; + public static String csvFolderName=""; + public static String lookupSubDirectory=""; + public static String sqlScenarioName=""; + + + public static void setMainFilePaths(String fullPath){ + fullMainPath=fullPath; + int index=fullPath.lastIndexOf(File.separator); + mainDirectory=fullPath.substring(0,index+1); + mainFile=fullPath.substring(index+1); + } + + public static void setSvarFilePaths(String fullPath){ + fullSvarFilePath=fullPath; + int index=fullPath.lastIndexOf(File.separator); + svarFileDirectory=fullPath.substring(0,index+1); + svarFile=fullPath.substring(index+1); + } + + public static void setSvarFile2Paths(String fullPath){ + fullSvarFile2Path=fullPath; + } + + public static void setDvarFilePaths(String fullPath){ + if (fullPath.toLowerCase().endsWith(".h5")){ + ControlData.outputType=1; + fullDvarHDF5Path=fullPath; + int index=fullPath.lastIndexOf("."); + fullDvarDssPath=fullPath.substring(0, index+1)+"dss"; + }else if (fullPath.toLowerCase().endsWith(".mysqlc")){ + ControlData.outputType=2; + int index1=fullPath.lastIndexOf(File.separator); + int index2=fullPath.lastIndexOf("."); + sqlScenarioName=fullPath.substring(index1+1,index2); + fullDvarDssPath=fullPath.substring(0, index2+1)+"dss"; + }else if (fullPath.toLowerCase().endsWith(".mysqlr")){ + ControlData.outputType=3; + int index1=fullPath.lastIndexOf(File.separator); + int index2=fullPath.lastIndexOf("."); + sqlScenarioName=fullPath.substring(index1+1,index2); + fullDvarDssPath=fullPath.substring(0, index2+1)+"dss"; + }else if (fullPath.toLowerCase().endsWith(".sqlsvr")){ + ControlData.outputType=4; + int index1=fullPath.lastIndexOf(File.separator); + int index2=fullPath.lastIndexOf("."); + sqlScenarioName=fullPath.substring(index1+1,index2); + fullDvarDssPath=fullPath.substring(0, index2+1)+"dss"; + }else if (fullPath.toLowerCase().endsWith(".csv")){ + ControlData.outputType=5; + int index1=fullPath.lastIndexOf(File.separator); + int index2=fullPath.lastIndexOf("."); + sqlScenarioName=fullPath.substring(index1+1,index2); + fullDvarDssPath=fullPath.substring(0, index2+1)+"dss"; + fullCsvPath=fullPath; + }else{ + ControlData.outputType=0; + fullDvarDssPath=fullPath; + } + int index=fullPath.lastIndexOf(File.separator); + dvarDssDirectory=fullPath.substring(0,index+1); + dvarDssFile=fullPath.substring(index+1); + } + + public static void setInitFilePaths(String fullPath){ + fullInitFilePath=fullPath; + int index=fullPath.lastIndexOf(File.separator); + initFileDirectory=fullPath.substring(0,index+1); + initFile=fullPath.substring(index+1); + } + + public static void clear(){ + + groundwaterDir=""; + fullMainPath=""; + mainFile=""; + mainDirectory=""; + fullSvarFilePath=""; + svarFile=""; + svarFileDirectory=""; + fullDvarDssPath=""; + dvarDssFile=""; + dvarDssDirectory=""; + fullInitFilePath=""; + initFile=""; + initFileDirectory=""; + fullIlpPath=""; + ilpFile=""; + ilpFileDirectory=""; + csvFolderName=""; + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/IncFileCollector.java b/wrims-core/src/main/java/wrimsv2/components/IncFileCollector.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/components/IncFileCollector.java rename to wrims-core/src/main/java/wrimsv2/components/IncFileCollector.java index 9e4268841..4372d9b35 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/IncFileCollector.java +++ b/wrims-core/src/main/java/wrimsv2/components/IncFileCollector.java @@ -1,251 +1,251 @@ -package wrimsv2.components; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import org.antlr.runtime.ANTLRFileStream; -import org.antlr.runtime.CharStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; -import org.apache.commons.io.FileUtils; - -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslplus.elements.IncFileSimple; -import wrimsv2.wreslplus.elements.LookupTableSimple; -import wrimsv2.wreslplus.elements.ResourceUtils; -import wrimsv2.wreslplus.grammar.IncFileFinderLexer; -import wrimsv2.wreslplus.grammar.IncFileFinderParser; - -public class IncFileCollector { - - public static LinkedHashSet incFileList_all; - public static LinkedHashSet lookupTableList_all; - public static int number_of_errors; - private static ArrayList tempList ; - private static String baseDir; // this is the parent of run folder, e.g., baseDir="d:\study" if main wresl is d:\study\run\main.wresl - private static String runDir; - private static String mainFilePath; - private static final String logFileName = "=FileCollector=.log"; - private static String lookupSubDir=""; - - - public IncFileCollector(String mainWreslPath, String targetDir){ - - new IncFileCollector(mainWreslPath,targetDir,null); - } - - - public IncFileCollector(String mainWreslPath, String targetDir, String lookupSubDir){ - - // args[0] is main wresl file absolute path - // args[1] is optional. If specified, this is the target folder where all the include files will be copied into. - // args[2] is optional. If specified, this is the subfolder where lookup tables reside. - - initialize(mainWreslPath); - collect(); - - // if the target folder (second argument) is specified, - // then the inc files will be copy to the target folder. - - if (targetDir!=null && targetDir.trim().length()>0 ) { - - if (lookupSubDir!=null && lookupSubDir.trim().length()>0) { - IncFileCollector.lookupSubDir = lookupSubDir.trim(); - } - - copyWreslsAndLookupTablesTo(targetDir.trim()); - } - - if (number_of_errors==0) { - LogUtils.importantMsg("IncFileFinder completed successfully."); - } - } - - public static void initialize(String mainFilePath){ - - number_of_errors = 0; - IncFileCollector.mainFilePath = mainFilePath; - - - try { - LogUtils.setLogFile(new File(mainFilePath).getParentFile().getCanonicalPath(), logFileName); - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - //baseDir= new File(mainFilePath).getParentFile().getParent(); - runDir =new File(mainFilePath).getParent(); - - incFileList_all = new LinkedHashSet(); - incFileList_all.add(mainFilePath); - - lookupTableList_all = new LinkedHashSet(); - - } - - public static void collect() { - - // call initialize() before using collect() - - ArrayList ifs_array = new ArrayList(); - ifs_array.add(new IncFileSimple(mainFilePath)); - - searchIncFiles(ifs_array); - -// for (String s: lookupTableList_all){ -// System.out.println(s); -// } - - } - - public static void searchIncFiles(ArrayList ifs_array){ - - for (IncFileSimple ifs : ifs_array) { - - tempList = parseWresl(ifs); - - if (tempList!=null && tempList.size()>0) { - - searchIncFiles(tempList); - } - } - } - - public static ArrayList parseWresl(IncFileSimple ifs) { - - IncFileFinderParser parser = null; - - LogUtils.importantMsg("Parsing file: "+ifs.absPath); - - try { - parser= initParser(ifs); - if (parser !=null){ - parser.wreslFile(); - } else { - return null; - //System.exit(1); - } - - for (IncFileSimple fs: parser.incFileSimpleList){ - incFileList_all.add(fs.absPath); - } - - for (LookupTableSimple lts: parser.lookupTableSimpleList){ - lookupTableList_all.add(lts.tableName); - } - - return parser.incFileSimpleList; - - } - catch (RecognitionException e) { - - e.printStackTrace(); - } - - return null; - } - - public static IncFileFinderParser initParser(IncFileSimple ifs) throws RecognitionException { - - CharStream stream; - - try { - stream = new ANTLRFileStream(ifs.absPath, "UTF8"); - } catch (IOException e) { - LogUtils.warningMsgLocation(ifs.fromWresl, ifs.line, "File not found: "+ifs.absPath); - return null; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - - IncFileFinderLexer lexer = new IncFileFinderLexer(stream); - - TokenStream tokenStream = new CommonTokenStream(lexer); - - IncFileFinderParser parser = new IncFileFinderParser(tokenStream); - - try { - parser.currentAbsolutePath = new File(ifs.absPath).getCanonicalPath().toLowerCase(); - parser.currentAbsoluteParent = new File(ifs.absPath).getCanonicalFile().getParent().toLowerCase(); - //String pathRelativeToRunDir = ResourceUtils.getRelativePath(parser.currentAbsoluteParent, GlobalData.runDir, File.separator); - - lexer.currentAbsolutePath = parser.currentAbsolutePath; - } - catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return parser; - - } - - private static void copyWreslsAndLookupTablesTo(String targetDir) { - - File targetDirF = new File(targetDir); - - int idex = runDir.indexOf(":"); - - File targetLookupDirF = new File(new File(targetDir, runDir.substring(idex+1)), "Lookup" ); - File srcLookupDirF = new File(runDir, "Lookup"); - - if (lookupSubDir.length()>0) { - targetLookupDirF = new File(targetLookupDirF, lookupSubDir); - srcLookupDirF = new File(srcLookupDirF, lookupSubDir); - } - - try { - LogUtils.importantMsg("Wresl files will be copied to: "+ targetDirF.getCanonicalPath()); - LogUtils.importantMsg("Lookup tables will be copied to: "+ targetLookupDirF.getCanonicalPath()); - } catch (IOException e1) { - targetDirF.mkdirs(); - targetLookupDirF.mkdirs(); - } - - for (String s: incFileList_all){ - - //String relativePath = ResourceUtils.getRelativePath(s, baseDir, File.separator); - int idx = s.indexOf(":"); - String absPathWithoutDrive = s.substring(idx+1); - //System.out.println(absPathWithoutDrive); - - try { - File targetPath = new File(targetDir,absPathWithoutDrive); - FileUtils.copyFile(new File(s), targetPath); - } catch (IOException e) { - LogUtils.warningMsg("File not found: "+s); - } - } - - // copy lookup tables - for (String s: lookupTableList_all){ - - File targetPath = new File(targetLookupDirF, s+".table"); - File srcPath = new File(srcLookupDirF, s+".table"); - try { - FileUtils.copyFile(srcPath, targetPath); - } catch (IOException e) { - LogUtils.errMsg("Lookup table IO exception, probably not found? "+srcPath); - } - } - - } - - public static void main(String[] args){ - - //args = new String[3]; - //args[0]="D:\\cvwrsm\\trunk\\CalGUI\\Scenarios\\Run_Details\\DEFAULT\\Run\\main.wresl"; - //args[0]="D:\\cvwrsm\\trunk\\calsim30\\calsim30_bo\\conv\\Run\\mainCONV_30_SA.wresl"; - //args[1]="z:\\cs3"; // optional. target folder - //args[2]="lookupSubFolderName"; // optional. - - new IncFileCollector(args[0],args[1],args[2]); - - } - +package wrimsv2.components; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import org.antlr.runtime.ANTLRFileStream; +import org.antlr.runtime.CharStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.TokenStream; +import org.apache.commons.io.FileUtils; + +import wrimsv2.wreslparser.elements.LogUtils; +import wrimsv2.wreslplus.elements.IncFileSimple; +import wrimsv2.wreslplus.elements.LookupTableSimple; +import wrimsv2.wreslplus.elements.ResourceUtils; +import wrimsv2.wreslplus.grammar.IncFileFinderLexer; +import wrimsv2.wreslplus.grammar.IncFileFinderParser; + +public class IncFileCollector { + + public static LinkedHashSet incFileList_all; + public static LinkedHashSet lookupTableList_all; + public static int number_of_errors; + private static ArrayList tempList ; + private static String baseDir; // this is the parent of run folder, e.g., baseDir="d:\study" if main wresl is d:\study\run\main.wresl + private static String runDir; + private static String mainFilePath; + private static final String logFileName = "=FileCollector=.log"; + private static String lookupSubDir=""; + + + public IncFileCollector(String mainWreslPath, String targetDir){ + + new IncFileCollector(mainWreslPath,targetDir,null); + } + + + public IncFileCollector(String mainWreslPath, String targetDir, String lookupSubDir){ + + // args[0] is main wresl file absolute path + // args[1] is optional. If specified, this is the target folder where all the include files will be copied into. + // args[2] is optional. If specified, this is the subfolder where lookup tables reside. + + initialize(mainWreslPath); + collect(); + + // if the target folder (second argument) is specified, + // then the inc files will be copy to the target folder. + + if (targetDir!=null && targetDir.trim().length()>0 ) { + + if (lookupSubDir!=null && lookupSubDir.trim().length()>0) { + IncFileCollector.lookupSubDir = lookupSubDir.trim(); + } + + copyWreslsAndLookupTablesTo(targetDir.trim()); + } + + if (number_of_errors==0) { + LogUtils.importantMsg("IncFileFinder completed successfully."); + } + } + + public static void initialize(String mainFilePath){ + + number_of_errors = 0; + IncFileCollector.mainFilePath = mainFilePath; + + + try { + LogUtils.setLogFile(new File(mainFilePath).getParentFile().getCanonicalPath(), logFileName); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + //baseDir= new File(mainFilePath).getParentFile().getParent(); + runDir =new File(mainFilePath).getParent(); + + incFileList_all = new LinkedHashSet(); + incFileList_all.add(mainFilePath); + + lookupTableList_all = new LinkedHashSet(); + + } + + public static void collect() { + + // call initialize() before using collect() + + ArrayList ifs_array = new ArrayList(); + ifs_array.add(new IncFileSimple(mainFilePath)); + + searchIncFiles(ifs_array); + +// for (String s: lookupTableList_all){ +// System.out.println(s); +// } + + } + + public static void searchIncFiles(ArrayList ifs_array){ + + for (IncFileSimple ifs : ifs_array) { + + tempList = parseWresl(ifs); + + if (tempList!=null && tempList.size()>0) { + + searchIncFiles(tempList); + } + } + } + + public static ArrayList parseWresl(IncFileSimple ifs) { + + IncFileFinderParser parser = null; + + LogUtils.importantMsg("Parsing file: "+ifs.absPath); + + try { + parser= initParser(ifs); + if (parser !=null){ + parser.wreslFile(); + } else { + return null; + //System.exit(1); + } + + for (IncFileSimple fs: parser.incFileSimpleList){ + incFileList_all.add(fs.absPath); + } + + for (LookupTableSimple lts: parser.lookupTableSimpleList){ + lookupTableList_all.add(lts.tableName); + } + + return parser.incFileSimpleList; + + } + catch (RecognitionException e) { + + e.printStackTrace(); + } + + return null; + } + + public static IncFileFinderParser initParser(IncFileSimple ifs) throws RecognitionException { + + CharStream stream; + + try { + stream = new ANTLRFileStream(ifs.absPath, "UTF8"); + } catch (IOException e) { + LogUtils.warningMsgLocation(ifs.fromWresl, ifs.line, "File not found: "+ifs.absPath); + return null; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + + IncFileFinderLexer lexer = new IncFileFinderLexer(stream); + + TokenStream tokenStream = new CommonTokenStream(lexer); + + IncFileFinderParser parser = new IncFileFinderParser(tokenStream); + + try { + parser.currentAbsolutePath = new File(ifs.absPath).getCanonicalPath().toLowerCase(); + parser.currentAbsoluteParent = new File(ifs.absPath).getCanonicalFile().getParent().toLowerCase(); + //String pathRelativeToRunDir = ResourceUtils.getRelativePath(parser.currentAbsoluteParent, GlobalData.runDir, File.separator); + + lexer.currentAbsolutePath = parser.currentAbsolutePath; + } + catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return parser; + + } + + private static void copyWreslsAndLookupTablesTo(String targetDir) { + + File targetDirF = new File(targetDir); + + int idex = runDir.indexOf(":"); + + File targetLookupDirF = new File(new File(targetDir, runDir.substring(idex+1)), "Lookup" ); + File srcLookupDirF = new File(runDir, "Lookup"); + + if (lookupSubDir.length()>0) { + targetLookupDirF = new File(targetLookupDirF, lookupSubDir); + srcLookupDirF = new File(srcLookupDirF, lookupSubDir); + } + + try { + LogUtils.importantMsg("Wresl files will be copied to: "+ targetDirF.getCanonicalPath()); + LogUtils.importantMsg("Lookup tables will be copied to: "+ targetLookupDirF.getCanonicalPath()); + } catch (IOException e1) { + targetDirF.mkdirs(); + targetLookupDirF.mkdirs(); + } + + for (String s: incFileList_all){ + + //String relativePath = ResourceUtils.getRelativePath(s, baseDir, File.separator); + int idx = s.indexOf(":"); + String absPathWithoutDrive = s.substring(idx+1); + //System.out.println(absPathWithoutDrive); + + try { + File targetPath = new File(targetDir,absPathWithoutDrive); + FileUtils.copyFile(new File(s), targetPath); + } catch (IOException e) { + LogUtils.warningMsg("File not found: "+s); + } + } + + // copy lookup tables + for (String s: lookupTableList_all){ + + File targetPath = new File(targetLookupDirF, s+".table"); + File srcPath = new File(srcLookupDirF, s+".table"); + try { + FileUtils.copyFile(srcPath, targetPath); + } catch (IOException e) { + LogUtils.errMsg("Lookup table IO exception, probably not found? "+srcPath); + } + } + + } + + public static void main(String[] args){ + + //args = new String[3]; + //args[0]="D:\\cvwrsm\\trunk\\CalGUI\\Scenarios\\Run_Details\\DEFAULT\\Run\\main.wresl"; + //args[0]="D:\\cvwrsm\\trunk\\calsim30\\calsim30_bo\\conv\\Run\\mainCONV_30_SA.wresl"; + //args[1]="z:\\cs3"; // optional. target folder + //args[2]="lookupSubFolderName"; // optional. + + new IncFileCollector(args[0],args[1],args[2]); + + } + } \ No newline at end of file diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/IntDouble.java b/wrims-core/src/main/java/wrimsv2/components/IntDouble.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/components/IntDouble.java rename to wrims-core/src/main/java/wrimsv2/components/IntDouble.java index 1a633c3da..22d5b1349 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/IntDouble.java +++ b/wrims-core/src/main/java/wrimsv2/components/IntDouble.java @@ -1,68 +1,68 @@ -package wrimsv2.components; - -import java.io.Serializable; - -public class IntDouble{ - private Number data; - private boolean isInteger; - private String argName=""; - private int index; - - public IntDouble() { - } - - public IntDouble(Number value, boolean isInt) { - data=value; - isInteger=isInt; - argName=""; - } - - public IntDouble(Number value, boolean isInt, String name, int index) { - data=value; - isInteger=isInt; - argName=name; - this.index=index; - } - - public Number getData(){ - return data; - } - - public void setData (Number value){ - data=value; - } - - public boolean isInt(){ - return isInteger; - } - - public void setInt(boolean isInt){ - isInteger=isInt; - } - - public IntDouble copyOf(){ - IntDouble newIntDouble; - if (isInteger){ - newIntDouble= new IntDouble(data.intValue(), isInteger); - }else{ - newIntDouble= new IntDouble(data.doubleValue(), isInteger); - } - return newIntDouble; - } - - public String getName(){ - return argName; - } - - public void setName(String argName){ - this.argName=argName; - } - - public int getIndex(){ - return index; - } - - public void setIndex(int index){ - this.index=index; - } -} +package wrimsv2.components; + +import java.io.Serializable; + +public class IntDouble{ + private Number data; + private boolean isInteger; + private String argName=""; + private int index; + + public IntDouble() { + } + + public IntDouble(Number value, boolean isInt) { + data=value; + isInteger=isInt; + argName=""; + } + + public IntDouble(Number value, boolean isInt, String name, int index) { + data=value; + isInteger=isInt; + argName=name; + this.index=index; + } + + public Number getData(){ + return data; + } + + public void setData (Number value){ + data=value; + } + + public boolean isInt(){ + return isInteger; + } + + public void setInt(boolean isInt){ + isInteger=isInt; + } + + public IntDouble copyOf(){ + IntDouble newIntDouble; + if (isInteger){ + newIntDouble= new IntDouble(data.intValue(), isInteger); + }else{ + newIntDouble= new IntDouble(data.doubleValue(), isInteger); + } + return newIntDouble; + } + + public String getName(){ + return argName; + } + + public void setName(String argName){ + this.argName=argName; + } + + public int getIndex(){ + return index; + } + + public void setIndex(int index){ + this.index=index; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/LoadParameter.java b/wrims-core/src/main/java/wrimsv2/components/LoadParameter.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/components/LoadParameter.java rename to wrims-core/src/main/java/wrimsv2/components/LoadParameter.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/PreRunModel.java b/wrims-core/src/main/java/wrimsv2/components/PreRunModel.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/components/PreRunModel.java rename to wrims-core/src/main/java/wrimsv2/components/PreRunModel.java index fbe59bd23..d05d8e92b 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/PreRunModel.java +++ b/wrims-core/src/main/java/wrimsv2/components/PreRunModel.java @@ -1,242 +1,242 @@ -package wrimsv2.components; - -import hec.heclib.dss.HecDss; -import hec.heclib.dss.HecDssCatalog; -import hec.heclib.dss.HecTimeSeries; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.External; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Timeseries; -import wrimsv2.evaluator.CondensedReferenceCacheAndRead; -import wrimsv2.evaluator.DataTimeSeries; -import wrimsv2.evaluator.DssDataSetFixLength; -import wrimsv2.evaluator.DssOperation; -import wrimsv2.evaluator.TimeOperation; -import wrimsv2.evaluator.CondensedReferenceCacheAndRead.CondensedReferenceCache; -import wrimsv2.external.LoadAllDll; -import wrimsv2.hdf5.HDF5Reader; -import wrimsv2.hdf5.HDF5Writer; - -public class PreRunModel { - public PreRunModel(StudyDataSet sds){ - setSelectedOutputCycles(); - - ControlData.currStudyDataSet=sds; - VariableTimeStep.procCycleTimeStep(sds); - ControlData.totalTimeStep=VariableTimeStep.getTotalTimeStep(sds); - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - ControlData.monthlyStartTime=new Date(ControlData.startYear-1900, ControlData.startMonth-1, TimeOperation.numberOfDays(ControlData.startMonth, ControlData.startYear)); - ControlData.dailyStartTime=new Date(ControlData.startYear-1900, ControlData.startMonth-1, ControlData.startDay); - - /* - ControlData.writer = new DSSDataWriter(FilePaths.fullDvarDssPath); - try { - ControlData.writer.openDSSFile(); - } catch (Exception e) { - ControlData.writer.closeDSSFile(); - Error.addEngineError("Could not open dv file. "+e); - return; - } - */ - - try { - ControlData.dvDss = HecDss.open(FilePaths.fullDvarDssPath); - } catch (Exception e) { - Error.addEngineError("Could not open dv file. "+e); - ControlData.dvDss.close(); - return; - } - - if (!(new File(FilePaths.fullInitFilePath)).exists()){ - System.out.println("Error: Initial file "+ FilePaths.fullInitFilePath+" doesn't exist."); - System.out.println("=======Run Complete Unsuccessfully======="); - System.exit(1); - } - if (!(new File(FilePaths.fullSvarFilePath)).exists()){ - System.out.println("Error: Svar file "+ FilePaths.fullSvarFilePath+" doesn't exist."); - System.out.println("=======Run Complete Unsuccessfully======="); - System.exit(1); - } - ControlData.allTsMap=sds.getTimeseriesMap(); - - HecTimeSeries.setMessageLevel(0); - long t1 = Calendar.getInstance().getTimeInMillis(); - if (FilePaths.svarFile.toLowerCase().endsWith(".h5")){ - HDF5Reader.readTimeseries(); - }else{ - //if (ControlData.genSVCatalog) DSSUtil.generateCatalog(FilePaths.fullSvarFilePath); - //ControlData.groupSvar= DSSUtil.createGroup("local", FilePaths.fullSvarFilePath); - HecDssCatalog catalog = new HecDssCatalog(FilePaths.fullSvarFilePath); - ControlData.cacheSvar = CondensedReferenceCacheAndRead.createCondensedCache(FilePaths.fullSvarFilePath, "*"); - if (!FilePaths.fullSvarFile2Path.equals("")){ - //if (ControlData.genSVCatalog) DSSUtil.generateCatalog(FilePaths.fullSvarFile2Path); - //ControlData.groupSvar2= DSSUtil.createGroup("local", FilePaths.fullSvarFile2Path); - HecDssCatalog catalog2 = new HecDssCatalog(FilePaths.fullSvarFile2Path); - ControlData.cacheSvar2 = CondensedReferenceCacheAndRead.createCondensedCache(FilePaths.fullSvarFile2Path, "*"); - } - readTimeseries(); - } - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_readTs=ControlData.t_readTs+(int) (t2-t1); - - if (FilePaths.initFile.toLowerCase().endsWith(".h5")){ - ControlData.initHDF5=true; - HDF5Reader.readInitialData(); - }else{ - ControlData.initHDF5=false; - //DSSUtil.generateCatalog(FilePaths.fullInitFilePath); - //ControlData.groupInit= DSSUtil.createGroup("local", FilePaths.fullInitFilePath); - HecDssCatalog catalog = new HecDssCatalog(FilePaths.fullInitFilePath); - ControlData.cacheInit = CondensedReferenceCacheAndRead.createCondensedCache(FilePaths.fullInitFilePath, "*"); - } - initialDvarAliasTS(); - - for (int i=0; i tsMap=ControlData.currStudyDataSet.getTimeseriesMap(); - Map> tsTimeStepMap=ControlData.currStudyDataSet.getTimeseriesTimeStepMap(); - ControlData.currEvalTypeIndex=6; - Set tsKeySet=tsMap.keySet(); - Iterator iterator=tsKeySet.iterator(); - while(iterator.hasNext()){ - String tsName=(String)iterator.next(); - //System.out.println("Reading svar timeseries "+tsName); - //To Do: in the svar class, add flag to see if svTS has been loaded - if (!DataTimeSeries.lookSvDss.contains(tsName)){ - ArrayList timeStepList=tsTimeStepMap.get(tsName); - for (String timeStep:timeStepList){ - DssOperation.getSVTimeseries(tsName, FilePaths.fullSvarFilePath, timeStep, 1); - if (!FilePaths.fullSvarFile2Path.equals("")){ - DssOperation.getSVTimeseries(tsName, FilePaths.fullSvarFile2Path, timeStep, 2); - } - String entryNameTS=DssOperation.entryNameTS(tsName, timeStep); - DataTimeSeries.lookSvDss.add(entryNameTS); - } - } - } - System.out.println("Timeseries Reading Done."); - } - - public void initialDvarAliasTS(){ - DataTimeSeries.dvAliasTS=new HashMap(); - //if (ControlData.outputCycleToDss) { - ControlData.cycleDataStartYear=ControlData.startYear; - ControlData.cycleDataStartMonth=ControlData.startMonth; - ControlData.cycleDataStartDay=ControlData.startDay; - int totalCycleNumber=ControlData.currStudyDataSet.getModelList().size(); - DataTimeSeries.dvAliasTSCycles=new ArrayList>(totalCycleNumber); - for (int i=0; i dvAliasTSCycle = new HashMap(); - DataTimeSeries.dvAliasTSCycles.add(dvAliasTSCycle); - } - //} - } - - public void processExternal(){ - ModelDataSet mds=ControlData.currModelDataSet; - ArrayList exList = mds.exList; - Map exMap =mds.exMap; - ControlData.currExMap=exMap; - ControlData.currEvalTypeIndex=4; - for (String exName: exList){ - if (!ControlData.allExternalFunction.containsKey(exName)){ - ControlData.currEvalName=exName; - External external=exMap.get(exName); - ControlData.allExternalFunction.put(exName, external.type); - if (external.type.endsWith(".dll") && !ControlData.allDll.contains(exName)){ - ControlData.allDll.add(external.type); - } - } - } - new LoadAllDll(ControlData.allDll); - System.out.println("Load dlls for Cycle "+(ControlData.currCycleIndex+1)+" done"); - } - - public void setSelectedOutputCycles(){ - String strSelectedCycleOutput = ControlData.selectedCycleOutput.replace("\'", ""); - ControlData.selectedCycles = strSelectedCycleOutput.split(","); - } - - public void setGroundwaterInitFile(){ - if (FilePaths.groundwaterDir!=null || !FilePaths.groundwaterDir.equals("")){ - File orig = new File(FilePaths.groundwaterDir+"\\CVGroundwater.in"); - if (orig.exists()){ - File des = new File(FilePaths.groundwaterDir+"\\CVGroundwater_bk.in"); - try { - Files.copy(orig.toPath(), des.toPath(), StandardCopyOption.REPLACE_EXISTING); - } catch (IOException e) { - e.printStackTrace(); - } - setGroundwaterInitFilePath(des, orig); - } - } - } - - public void setGroundwaterInitFilePath(File backup, File input){ - try { - FileReader fr = new FileReader(backup); - BufferedReader br = new BufferedReader(fr); - FileWriter fw = new FileWriter(input); - BufferedWriter bw = new BufferedWriter(fw); - String line; - int lineCount=1; - while ((line = br.readLine()) != null) { - if (line.toUpperCase().contains("11: INITIAL CONDITIONS DATA FILE")){ - if (ControlData.startMonth==1){ - String initMonth="DEC"; - int initYear=ControlData.startYear-1; - line="Restart\\CVInitial_Restart_"+initMonth+initYear+".dat /11: INITIAL CONDITIONS DATA FILE (INPUT, REQUIRED)"; - }else{ - String initMonth=TimeOperation.monthName(ControlData.startMonth-1); - int initYear=ControlData.startYear; - line="Restart\\CVInitial_Restart_"+initMonth+initYear+".dat /11: INITIAL CONDITIONS DATA FILE (INPUT, REQUIRED)"; - } - } - bw.write(line+"\n"); - lineCount++; - } - br.close(); - bw.close(); - fr.close(); - fw.close(); - } - catch (Exception e) { - e.printStackTrace(); - } - } -} +package wrimsv2.components; + +import hec.heclib.dss.HecDss; +import hec.heclib.dss.HecDssCatalog; +import hec.heclib.dss.HecTimeSeries; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.External; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.Timeseries; +import wrimsv2.evaluator.CondensedReferenceCacheAndRead; +import wrimsv2.evaluator.DataTimeSeries; +import wrimsv2.evaluator.DssDataSetFixLength; +import wrimsv2.evaluator.DssOperation; +import wrimsv2.evaluator.TimeOperation; +import wrimsv2.evaluator.CondensedReferenceCacheAndRead.CondensedReferenceCache; +import wrimsv2.external.LoadAllDll; +import wrimsv2.hdf5.HDF5Reader; +import wrimsv2.hdf5.HDF5Writer; + +public class PreRunModel { + public PreRunModel(StudyDataSet sds){ + setSelectedOutputCycles(); + + ControlData.currStudyDataSet=sds; + VariableTimeStep.procCycleTimeStep(sds); + ControlData.totalTimeStep=VariableTimeStep.getTotalTimeStep(sds); + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + ControlData.monthlyStartTime=new Date(ControlData.startYear-1900, ControlData.startMonth-1, TimeOperation.numberOfDays(ControlData.startMonth, ControlData.startYear)); + ControlData.dailyStartTime=new Date(ControlData.startYear-1900, ControlData.startMonth-1, ControlData.startDay); + + /* + ControlData.writer = new DSSDataWriter(FilePaths.fullDvarDssPath); + try { + ControlData.writer.openDSSFile(); + } catch (Exception e) { + ControlData.writer.closeDSSFile(); + Error.addEngineError("Could not open dv file. "+e); + return; + } + */ + + try { + ControlData.dvDss = HecDss.open(FilePaths.fullDvarDssPath); + } catch (Exception e) { + Error.addEngineError("Could not open dv file. "+e); + ControlData.dvDss.close(); + return; + } + + if (!(new File(FilePaths.fullInitFilePath)).exists()){ + System.out.println("Error: Initial file "+ FilePaths.fullInitFilePath+" doesn't exist."); + System.out.println("=======Run Complete Unsuccessfully======="); + System.exit(1); + } + if (!(new File(FilePaths.fullSvarFilePath)).exists()){ + System.out.println("Error: Svar file "+ FilePaths.fullSvarFilePath+" doesn't exist."); + System.out.println("=======Run Complete Unsuccessfully======="); + System.exit(1); + } + ControlData.allTsMap=sds.getTimeseriesMap(); + + HecTimeSeries.setMessageLevel(0); + long t1 = Calendar.getInstance().getTimeInMillis(); + if (FilePaths.svarFile.toLowerCase().endsWith(".h5")){ + HDF5Reader.readTimeseries(); + }else{ + //if (ControlData.genSVCatalog) DSSUtil.generateCatalog(FilePaths.fullSvarFilePath); + //ControlData.groupSvar= DSSUtil.createGroup("local", FilePaths.fullSvarFilePath); + HecDssCatalog catalog = new HecDssCatalog(FilePaths.fullSvarFilePath); + ControlData.cacheSvar = CondensedReferenceCacheAndRead.createCondensedCache(FilePaths.fullSvarFilePath, "*"); + if (!FilePaths.fullSvarFile2Path.equals("")){ + //if (ControlData.genSVCatalog) DSSUtil.generateCatalog(FilePaths.fullSvarFile2Path); + //ControlData.groupSvar2= DSSUtil.createGroup("local", FilePaths.fullSvarFile2Path); + HecDssCatalog catalog2 = new HecDssCatalog(FilePaths.fullSvarFile2Path); + ControlData.cacheSvar2 = CondensedReferenceCacheAndRead.createCondensedCache(FilePaths.fullSvarFile2Path, "*"); + } + readTimeseries(); + } + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_readTs=ControlData.t_readTs+(int) (t2-t1); + + if (FilePaths.initFile.toLowerCase().endsWith(".h5")){ + ControlData.initHDF5=true; + HDF5Reader.readInitialData(); + }else{ + ControlData.initHDF5=false; + //DSSUtil.generateCatalog(FilePaths.fullInitFilePath); + //ControlData.groupInit= DSSUtil.createGroup("local", FilePaths.fullInitFilePath); + HecDssCatalog catalog = new HecDssCatalog(FilePaths.fullInitFilePath); + ControlData.cacheInit = CondensedReferenceCacheAndRead.createCondensedCache(FilePaths.fullInitFilePath, "*"); + } + initialDvarAliasTS(); + + for (int i=0; i tsMap=ControlData.currStudyDataSet.getTimeseriesMap(); + Map> tsTimeStepMap=ControlData.currStudyDataSet.getTimeseriesTimeStepMap(); + ControlData.currEvalTypeIndex=6; + Set tsKeySet=tsMap.keySet(); + Iterator iterator=tsKeySet.iterator(); + while(iterator.hasNext()){ + String tsName=(String)iterator.next(); + //System.out.println("Reading svar timeseries "+tsName); + //To Do: in the svar class, add flag to see if svTS has been loaded + if (!DataTimeSeries.lookSvDss.contains(tsName)){ + ArrayList timeStepList=tsTimeStepMap.get(tsName); + for (String timeStep:timeStepList){ + DssOperation.getSVTimeseries(tsName, FilePaths.fullSvarFilePath, timeStep, 1); + if (!FilePaths.fullSvarFile2Path.equals("")){ + DssOperation.getSVTimeseries(tsName, FilePaths.fullSvarFile2Path, timeStep, 2); + } + String entryNameTS=DssOperation.entryNameTS(tsName, timeStep); + DataTimeSeries.lookSvDss.add(entryNameTS); + } + } + } + System.out.println("Timeseries Reading Done."); + } + + public void initialDvarAliasTS(){ + DataTimeSeries.dvAliasTS=new HashMap(); + //if (ControlData.outputCycleToDss) { + ControlData.cycleDataStartYear=ControlData.startYear; + ControlData.cycleDataStartMonth=ControlData.startMonth; + ControlData.cycleDataStartDay=ControlData.startDay; + int totalCycleNumber=ControlData.currStudyDataSet.getModelList().size(); + DataTimeSeries.dvAliasTSCycles=new ArrayList>(totalCycleNumber); + for (int i=0; i dvAliasTSCycle = new HashMap(); + DataTimeSeries.dvAliasTSCycles.add(dvAliasTSCycle); + } + //} + } + + public void processExternal(){ + ModelDataSet mds=ControlData.currModelDataSet; + ArrayList exList = mds.exList; + Map exMap =mds.exMap; + ControlData.currExMap=exMap; + ControlData.currEvalTypeIndex=4; + for (String exName: exList){ + if (!ControlData.allExternalFunction.containsKey(exName)){ + ControlData.currEvalName=exName; + External external=exMap.get(exName); + ControlData.allExternalFunction.put(exName, external.type); + if (external.type.endsWith(".dll") && !ControlData.allDll.contains(exName)){ + ControlData.allDll.add(external.type); + } + } + } + new LoadAllDll(ControlData.allDll); + System.out.println("Load dlls for Cycle "+(ControlData.currCycleIndex+1)+" done"); + } + + public void setSelectedOutputCycles(){ + String strSelectedCycleOutput = ControlData.selectedCycleOutput.replace("\'", ""); + ControlData.selectedCycles = strSelectedCycleOutput.split(","); + } + + public void setGroundwaterInitFile(){ + if (FilePaths.groundwaterDir!=null || !FilePaths.groundwaterDir.equals("")){ + File orig = new File(FilePaths.groundwaterDir+"\\CVGroundwater.in"); + if (orig.exists()){ + File des = new File(FilePaths.groundwaterDir+"\\CVGroundwater_bk.in"); + try { + Files.copy(orig.toPath(), des.toPath(), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + e.printStackTrace(); + } + setGroundwaterInitFilePath(des, orig); + } + } + } + + public void setGroundwaterInitFilePath(File backup, File input){ + try { + FileReader fr = new FileReader(backup); + BufferedReader br = new BufferedReader(fr); + FileWriter fw = new FileWriter(input); + BufferedWriter bw = new BufferedWriter(fw); + String line; + int lineCount=1; + while ((line = br.readLine()) != null) { + if (line.toUpperCase().contains("11: INITIAL CONDITIONS DATA FILE")){ + if (ControlData.startMonth==1){ + String initMonth="DEC"; + int initYear=ControlData.startYear-1; + line="Restart\\CVInitial_Restart_"+initMonth+initYear+".dat /11: INITIAL CONDITIONS DATA FILE (INPUT, REQUIRED)"; + }else{ + String initMonth=TimeOperation.monthName(ControlData.startMonth-1); + int initYear=ControlData.startYear; + line="Restart\\CVInitial_Restart_"+initMonth+initYear+".dat /11: INITIAL CONDITIONS DATA FILE (INPUT, REQUIRED)"; + } + } + bw.write(line+"\n"); + lineCount++; + } + br.close(); + bw.close(); + fr.close(); + fw.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/TimeUsage.java b/wrims-core/src/main/java/wrimsv2/components/TimeUsage.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/components/TimeUsage.java rename to wrims-core/src/main/java/wrimsv2/components/TimeUsage.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/components/VariableTimeStep.java b/wrims-core/src/main/java/wrimsv2/components/VariableTimeStep.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/components/VariableTimeStep.java rename to wrims-core/src/main/java/wrimsv2/components/VariableTimeStep.java index 6a200e0bd..6c8d00abe 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/components/VariableTimeStep.java +++ b/wrims-core/src/main/java/wrimsv2/components/VariableTimeStep.java @@ -1,188 +1,188 @@ -package wrimsv2.components; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.evaluator.TimeOperation; - -public class VariableTimeStep { - - public static void setCycleTimeStep(StudyDataSet sds){ - String timeStep=sds.getModelTimeStepList().get(ControlData.currCycleIndex); - if (timeStep.equals(Param.undefined)){ - ControlData.timeStep=ControlData.defaultTimeStep; - ControlData.partE=ControlData.defaultTimeStep; - }else{ - ControlData.timeStep=timeStep; - ControlData.partE=timeStep; - } - } - - public static void setCycleEndDate(StudyDataSet sds){ - ArrayList timeStepList=sds.getModelTimeStepList(); - String definedTimeStep; - if (ControlData.cycleTimeStepPriority==2.0){ - addOneMonthToCycleEndDate(); - }else if (ControlData.cycleTimeStepPriority==1.0){ - addOneDayToCycleEndDate(); - } - } - - public static void setCycleStartDate(int day, int month, int year){ - ControlData.cycleStartDay=day; - ControlData.cycleStartMonth=month; - ControlData.cycleStartYear=year; - } - - private static void addOneMonthToCycleEndDate(){ - ControlData.cycleEndMonth=ControlData.cycleStartMonth+1; - ControlData.cycleEndYear=ControlData.cycleStartYear; - if (ControlData.cycleEndMonth>12){ - ControlData.cycleEndMonth=ControlData.cycleEndMonth-12; - ControlData.cycleEndYear=ControlData.cycleEndYear+1; - } - ControlData.cycleEndDay=1; - } - - public static void currTimeAddOneMonth(){ - ControlData.currMonth=ControlData.currMonth+1; - ControlData.currYear=ControlData.currYear; - if (ControlData.currMonth>12){ - ControlData.currMonth=ControlData.currMonth-12; - ControlData.currYear=ControlData.currYear+1; - } - ControlData.currDay=TimeOperation.numberOfDays(ControlData.currMonth, ControlData.currYear); - } - - public static void currTimeAddOneDay(){ - Calendar c = GregorianCalendar.getInstance(); - c.set(ControlData.currYear, ControlData.currMonth-1, ControlData.currDay); - c.add(Calendar.DATE, 1); - ControlData.currYear = c.get(Calendar.YEAR); - ControlData.currMonth = c.get(Calendar.MONTH)+1; - ControlData.currDay = c.get(Calendar.DAY_OF_MONTH); - - - } - - private static void addOneDayToCycleEndDate(){ - Date startDate = new Date (ControlData.cycleStartYear-1900, ControlData.cycleStartMonth-1, ControlData.cycleStartDay); - Calendar c = Calendar.getInstance(); - c.setTime(startDate); - c.add(Calendar.DATE, 1); - Date cycleEndDate =c.getTime(); - ControlData.cycleEndMonth=cycleEndDate.getMonth()+1; - ControlData.cycleEndYear=cycleEndDate.getYear()+1900; - ControlData.cycleEndDay=cycleEndDate.getDate(); - } - - public static ArrayList getTotalTimeStep(StudyDataSet sds){ - ArrayList timeStepList=sds.getModelTimeStepList(); - ControlData.totalTimeStep=new ArrayList(); - for (String timeStep: timeStepList){ - if (timeStep.equals("1MON")){ - if (ControlData.yearOutputSection<0){ - ControlData.totalTimeStep.add((ControlData.endYear-ControlData.startYear)*12+(ControlData.endMonth-ControlData.startMonth)+1); - }else{ - ControlData.totalTimeStep.add(ControlData.yearOutputSection*12+ControlData.monMemSection); - } - }else{ - if (ControlData.yearOutputSection<0){ - Date startDate = new Date (ControlData.startYear-1900, ControlData.startMonth-1, ControlData.startDay); - Date endDate=new Date (ControlData.endYear-1900, ControlData.endMonth-1, ControlData.endDay); - //long startTime=startDate.getTime(); - //long endTime=endDate.getTime(); - //double timestep=(endTime-startTime)/(24*60*60*1000l)+1; - Calendar c1=Calendar.getInstance(); - c1.setTime(startDate); - Calendar c2=Calendar.getInstance(); - c2.setTime(endDate); - double timestep = Duration.between(c1.toInstant(), c2.toInstant()).toDays()+1; - ControlData.totalTimeStep.add((int)timestep); - }else{ - ControlData.totalTimeStep.add(ControlData.yearOutputSection*366+ControlData.monMemSection*31); - } - } - } - return ControlData.totalTimeStep; - } - - public static int getTotalTimeStep(String timeStep){ - if (timeStep.equals("1MON")){ - return (ControlData.endYear-ControlData.startYear)*12+(ControlData.endMonth-ControlData.startMonth)+1; - }else{ - Date startDate = new Date (ControlData.startYear-1900, ControlData.startMonth-1, ControlData.startDay); - Date endDate=new Date (ControlData.endYear-1900, ControlData.endMonth-1, ControlData.endDay); - //long startTime=startDate.getTime(); - //long endTime=endDate.getTime(); - //double timestep=(endTime-startTime)/(24*60*60*1000l)+1; - Calendar c1=Calendar.getInstance(); - c1.setTime(startDate); - Calendar c2=Calendar.getInstance(); - c2.setTime(endDate); - double timestep = Duration.between(c1.toInstant(), c2.toInstant()).toDays()+1; - return (int)timestep; - } - } - - public static void procCycleTimeStep(StudyDataSet sds){ - ArrayList timeStepList=sds.getModelTimeStepList(); - ControlData.cycleTimeStepPriority=0; - for (int i=0; i modelList){ - ControlData.currTimeStep=new ArrayList(); - for (int i=0; i timeStepList=sds.getModelTimeStepList(); + String definedTimeStep; + if (ControlData.cycleTimeStepPriority==2.0){ + addOneMonthToCycleEndDate(); + }else if (ControlData.cycleTimeStepPriority==1.0){ + addOneDayToCycleEndDate(); + } + } + + public static void setCycleStartDate(int day, int month, int year){ + ControlData.cycleStartDay=day; + ControlData.cycleStartMonth=month; + ControlData.cycleStartYear=year; + } + + private static void addOneMonthToCycleEndDate(){ + ControlData.cycleEndMonth=ControlData.cycleStartMonth+1; + ControlData.cycleEndYear=ControlData.cycleStartYear; + if (ControlData.cycleEndMonth>12){ + ControlData.cycleEndMonth=ControlData.cycleEndMonth-12; + ControlData.cycleEndYear=ControlData.cycleEndYear+1; + } + ControlData.cycleEndDay=1; + } + + public static void currTimeAddOneMonth(){ + ControlData.currMonth=ControlData.currMonth+1; + ControlData.currYear=ControlData.currYear; + if (ControlData.currMonth>12){ + ControlData.currMonth=ControlData.currMonth-12; + ControlData.currYear=ControlData.currYear+1; + } + ControlData.currDay=TimeOperation.numberOfDays(ControlData.currMonth, ControlData.currYear); + } + + public static void currTimeAddOneDay(){ + Calendar c = GregorianCalendar.getInstance(); + c.set(ControlData.currYear, ControlData.currMonth-1, ControlData.currDay); + c.add(Calendar.DATE, 1); + ControlData.currYear = c.get(Calendar.YEAR); + ControlData.currMonth = c.get(Calendar.MONTH)+1; + ControlData.currDay = c.get(Calendar.DAY_OF_MONTH); + + + } + + private static void addOneDayToCycleEndDate(){ + Date startDate = new Date (ControlData.cycleStartYear-1900, ControlData.cycleStartMonth-1, ControlData.cycleStartDay); + Calendar c = Calendar.getInstance(); + c.setTime(startDate); + c.add(Calendar.DATE, 1); + Date cycleEndDate =c.getTime(); + ControlData.cycleEndMonth=cycleEndDate.getMonth()+1; + ControlData.cycleEndYear=cycleEndDate.getYear()+1900; + ControlData.cycleEndDay=cycleEndDate.getDate(); + } + + public static ArrayList getTotalTimeStep(StudyDataSet sds){ + ArrayList timeStepList=sds.getModelTimeStepList(); + ControlData.totalTimeStep=new ArrayList(); + for (String timeStep: timeStepList){ + if (timeStep.equals("1MON")){ + if (ControlData.yearOutputSection<0){ + ControlData.totalTimeStep.add((ControlData.endYear-ControlData.startYear)*12+(ControlData.endMonth-ControlData.startMonth)+1); + }else{ + ControlData.totalTimeStep.add(ControlData.yearOutputSection*12+ControlData.monMemSection); + } + }else{ + if (ControlData.yearOutputSection<0){ + Date startDate = new Date (ControlData.startYear-1900, ControlData.startMonth-1, ControlData.startDay); + Date endDate=new Date (ControlData.endYear-1900, ControlData.endMonth-1, ControlData.endDay); + //long startTime=startDate.getTime(); + //long endTime=endDate.getTime(); + //double timestep=(endTime-startTime)/(24*60*60*1000l)+1; + Calendar c1=Calendar.getInstance(); + c1.setTime(startDate); + Calendar c2=Calendar.getInstance(); + c2.setTime(endDate); + double timestep = Duration.between(c1.toInstant(), c2.toInstant()).toDays()+1; + ControlData.totalTimeStep.add((int)timestep); + }else{ + ControlData.totalTimeStep.add(ControlData.yearOutputSection*366+ControlData.monMemSection*31); + } + } + } + return ControlData.totalTimeStep; + } + + public static int getTotalTimeStep(String timeStep){ + if (timeStep.equals("1MON")){ + return (ControlData.endYear-ControlData.startYear)*12+(ControlData.endMonth-ControlData.startMonth)+1; + }else{ + Date startDate = new Date (ControlData.startYear-1900, ControlData.startMonth-1, ControlData.startDay); + Date endDate=new Date (ControlData.endYear-1900, ControlData.endMonth-1, ControlData.endDay); + //long startTime=startDate.getTime(); + //long endTime=endDate.getTime(); + //double timestep=(endTime-startTime)/(24*60*60*1000l)+1; + Calendar c1=Calendar.getInstance(); + c1.setTime(startDate); + Calendar c2=Calendar.getInstance(); + c2.setTime(endDate); + double timestep = Duration.between(c1.toInstant(), c2.toInstant()).toDays()+1; + return (int)timestep; + } + } + + public static void procCycleTimeStep(StudyDataSet sds){ + ArrayList timeStepList=sds.getModelTimeStepList(); + ControlData.cycleTimeStepPriority=0; + for (int i=0; i modelList){ + ControlData.currTimeStep=new ArrayList(); + for (int i=0; i argsMap; - - public static LinkedHashMap paramMap = new LinkedHashMap(); - - public static void loadArgs(String[] args) { - - // for Error.log header - ControlData.currEvalTypeIndex=8; - - // print version number then exit - if (args.length==1 && args[0].equalsIgnoreCase("-version") ) { - - System.out.println("WRIMS "+new BuildProps().getVN()); - System.exit(0); - } - - - - argsMap = new HashMap(); - - for (int i = 0; i < args.length; i++) { - - try { - String key = args[i].substring(0, args[i].indexOf("=")); - String val = args[i].substring(args[i].indexOf("=") + 1, args[i].length()); - val=val.replaceAll("\"", ""); - - argsMap.put(key.toLowerCase(), val); - - } - catch (Exception e) { - System.out.println("Example: "); - System.out.println("-config=\"D:\\test\\example.config\""); -// System.out.println("Example: "); -// System.out.println("-mainwresl=\"C:\\study\\main.wresl\""); - System.exit(1); - } - - //System.out.println(argsMap); - - } - - - - // load config file - if (argsMap.keySet().contains("-config")) { - - String configFilePath = FilenameUtils.removeExtension(argsMap.get("-config"))+".config"; - argsMap.put("-config", configFilePath); - - System.out.println("\nWARNING!! Config file and RUN directory must be placed in the same folder! \n"); - System.out.println("Loading config file: "+argsMap.get("-config")); - StudyUtils.configFilePath = argsMap.get("-config"); - loadConfig(StudyUtils.configFilePath); - if (Error.getTotalError()>0) { - Error.writeErrorLog(); - } - - // compile to serial object named *.par - } else if (argsMap.keySet().contains("-mainwresl")) { - - System.out.println("Compiling main wresl file: "+argsMap.get("-mainwresl")); - StudyUtils.compileOnly = true; - FilePaths.setMainFilePaths(argsMap.get("-mainwresl")); - - } else if (argsMap.keySet().contains("-mainwreslplus")) { - - System.out.println("Compiling main wresl file: "+argsMap.get("-mainwreslplus")); - StudyUtils.compileOnly = true; - StudyUtils.useWreslPlus=true; - FilePaths.setMainFilePaths(argsMap.get("-mainwreslplus")); - - }else { - System.out.println("Example: "); - System.out.println("-config=\"D:\\test\\example.config\""); -// System.out.println("Example: "); -// System.out.println("-mainwresl=\"C:\\study\\main.wresl\""); - System.exit(1); - } - - } - - private static void loadConfig(String configFile) { - - //StudyUtils.config_errors = 0; // reset - String k=null; - - Map configMap = new HashMap(); - - configMap = checkConfigFile(configFile); - - String mainfile = configMap.get("mainfile").toLowerCase(); - - String mainFilePath = ""; - - if (mainfile.contains(":")){ - mainFilePath = new File(mainfile).getAbsolutePath(); - } else { - mainFilePath = new File(StudyUtils.configDir, mainfile).getAbsolutePath(); - } - - File validatedAbsFile = new File(mainFilePath).getAbsoluteFile(); - if (!validatedAbsFile.exists()) { - Error.addConfigError("File not found: " + mainFilePath); - Error.writeErrorLog(); - } - - if (mainfile.endsWith(".par")) { - StudyUtils.loadParserData = true; - StudyUtils.parserDataPath = mainFilePath; - FilePaths.setMainFilePaths(mainFilePath); - } - else if (mainfile.endsWith(".wresl")) { - FilePaths.setMainFilePaths(mainFilePath); - } - else { - Error.addConfigError("Invalid main file extension: " + configMap.get("mainfile")); - Error.writeErrorLog(); - //System.out.println("Invalid main file extension: " + configMap.get("mainfile")); - //System.out.println("Specify either *.wresl or *.par"); - //System.exit(1); - } - - // FilePaths.mainDirectory = configMap.get("maindir"); - System.out.println("MainFile: "+FilePaths.fullMainPath); - - // CbcLibName // default is jCbc and it's not used for version selection - k = "cbclibname"; - if (configMap.keySet().contains(k)){ - - CbcSolver.cbcLibName = configMap.get(k); - } - // need to know jCbc version to determine solving options - System.loadLibrary(CbcSolver.cbcLibName); - System.out.println("CbcLibName: "+CbcSolver.cbcLibName); - - try { - - if (configMap.get("groundwaterdir").length()>0) { - if (configMap.get("groundwaterdir").contains(":")){ - FilePaths.groundwaterDir = new File(configMap.get("groundwaterdir")).getCanonicalPath()+File.separator; - } else { - FilePaths.groundwaterDir = new File(StudyUtils.configDir, configMap.get("groundwaterdir")).getCanonicalPath()+File.separator; - } - System.out.println("GroundWaterDir: "+FilePaths.groundwaterDir); - } else { - FilePaths.groundwaterDir = "None"; - } - - if (configMap.get("svarfile").contains(":")){ - FilePaths.setSvarFilePaths(new File(configMap.get("svarfile")).getCanonicalPath()); - } else { - FilePaths.setSvarFilePaths(new File(StudyUtils.configDir, configMap.get("svarfile")).getCanonicalPath()); - } - System.out.println("SvarFile: "+FilePaths.fullSvarFilePath); - - if (configMap.get("svarfile2").equals("")){ - FilePaths.setSvarFile2Paths(""); - }else{ - if (configMap.get("svarfile2").contains(":")){ - FilePaths.setSvarFile2Paths(new File(configMap.get("svarfile2")).getCanonicalPath()); - } else { - FilePaths.setSvarFile2Paths(new File(StudyUtils.configDir, configMap.get("svarfile2")).getCanonicalPath()); - } - System.out.println("SvarFile2: "+FilePaths.fullSvarFile2Path); - } - - if (configMap.get("initfile").contains(":")){ - FilePaths.setInitFilePaths(new File(configMap.get("initfile")).getCanonicalPath()); - } else { - FilePaths.setInitFilePaths(new File(StudyUtils.configDir, configMap.get("initfile")).getCanonicalPath()); - } - System.out.println("InitFile: "+FilePaths.fullInitFilePath); - - if (configMap.get("dvarfile").contains(":")) { - FilePaths.setDvarFilePaths(new File(configMap.get("dvarfile")).getCanonicalPath()); - } else { - FilePaths.setDvarFilePaths(new File(StudyUtils.configDir, configMap.get("dvarfile")).getCanonicalPath()); - } - System.out.println("DvarFile: "+FilePaths.fullDvarDssPath); - - } catch (IOException e){ - Error.addConfigError("Invalid file path in config file"); - Error.writeErrorLog(); - //System.out.println("Invalid file path"); - e.printStackTrace(); - } - - StudyUtils.configFileName = new File(configFile).getName(); - - FilePaths.csvFolderName = ""; - - if (configMap.get("showwresllog").equalsIgnoreCase("no") || configMap.get("showwresllog").equalsIgnoreCase("false")){ - ControlData.showWreslLog = false; - } - if (configMap.get("lookupsubdir").length()>0 ){ - FilePaths.lookupSubDirectory = configMap.get("lookupsubdir"); - System.out.println("LookupSubDir: "+FilePaths.lookupSubDirectory); - } - //ControlData.showWreslLog = !(configMap.get("showwresllog").equalsIgnoreCase("no")); - - ControlData.svDvPartF = configMap.get("svarfpart"); - ControlData.initPartF = configMap.get("initfpart"); - ControlData.partA = configMap.get("svarapart"); - ControlData.partE = configMap.get("timestep"); - ControlData.timeStep = configMap.get("timestep"); - - ControlData.startYear = Integer.parseInt(configMap.get("startyear")); - ControlData.startMonth = Integer.parseInt(configMap.get("startmonth")); - ControlData.startDay = Integer.parseInt(configMap.get("startday")); - - ControlData.endYear = Integer.parseInt(configMap.get("stopyear")); - ControlData.endMonth = Integer.parseInt(configMap.get("stopmonth")); - ControlData.endDay = Integer.parseInt(configMap.get("stopday")); - - ControlData.solverName = configMap.get("solver"); - - ControlData.currYear = ControlData.startYear; - ControlData.currMonth = ControlData.startMonth; - ControlData.currDay = ControlData.startDay; - - System.out.println("TimeStep: "+ControlData.timeStep); - System.out.println("SvarAPart: "+ControlData.partA); - System.out.println("SvarFPart: "+ControlData.svDvPartF); - System.out.println("InitFPart: "+ControlData.initPartF); - System.out.println("StartYear: "+ControlData.startYear); - System.out.println("StartMonth: "+ControlData.startMonth); - System.out.println("StartDay: "+ControlData.startDay); - System.out.println("StopYear: "+ControlData.endYear); - System.out.println("StopMonth: "+ControlData.endMonth); - System.out.println("StopDay: "+ControlData.endDay); - System.out.println("Solver: "+ControlData.solverName); - - final String[] solvers = {"xa","xalog","clp0","clp1","clp","lpsolve","gurobi","cbc0","cbc1","cbc"}; - - if (!Arrays.asList(solvers).contains(ControlData.solverName.toLowerCase())){ - Error.addConfigError("Solver name not recognized: "+ControlData.solverName); - Error.writeErrorLog(); - } else if (ControlData.solverName.toLowerCase().contains("cbc")) { - CbcSolver.cbcVersion = jCbc.getVersion(); - System.out.println("CbcVersion: "+CbcSolver.cbcVersion); - if (CbcSolver.cbcVersion.contains("2.9.9")) { - CbcSolver.usejCbc2021 = true; - if (CbcSolver.cbcVersion.contains("2.9.9.2")) { - CbcSolver.usejCbc2021a = true; - } - CbcSolver.cbcViolationCheck = false; // can overwrite - ControlData.useCbcWarmStart = true; // cannot overwrite - } else { - CbcSolver.cbcViolationCheck = true; // can overwrite - ControlData.useCbcWarmStart = false; // cannot overwrite - } - System.out.println("Cbc2021: "+CbcSolver.usejCbc2021); - System.out.println("Cbc2021a: "+CbcSolver.usejCbc2021a); - } - - // SendAliasToDvar default is false - if (configMap.keySet().contains("sendaliastodvar")){ - - String s = configMap.get("sendaliastodvar"); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - ControlData.sendAliasToDvar = true; - } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ - ControlData.sendAliasToDvar = false; - } else { - ControlData.sendAliasToDvar = false; - } - - } - System.out.println("SendAliasToDvar: "+ControlData.sendAliasToDvar); - - - // PrefixInitToDvarFile - if (configMap.keySet().contains("prefixinittodvarfile")){ - - String s = configMap.get("prefixinittodvarfile"); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - ControlData.writeInitToDVOutput = true; - } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ - ControlData.writeInitToDVOutput = false; - } else { - ControlData.writeInitToDVOutput = false; - } - }else{ - ControlData.writeInitToDVOutput = true; - } - System.out.println("PrefixInitToDvarFile: "+ControlData.writeInitToDVOutput); - - // SolveCompare - k = "solvecompare"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - if (s.equalsIgnoreCase("xa_cbc")){ - ControlData.cbc_debug_routeXA = false; - ControlData.cbc_debug_routeCbc = true; - } else if (s.equalsIgnoreCase("cbc_xa")) { - ControlData.cbc_debug_routeXA = true; - ControlData.cbc_debug_routeCbc = false; - } else { - ControlData.cbc_debug_routeXA = false; - ControlData.cbc_debug_routeCbc = false; - } - }else{ - ControlData.cbc_debug_routeXA = false; - ControlData.cbc_debug_routeCbc = false; - } - System.out.println("SolveCompare (use XA solution as base): "+ControlData.cbc_debug_routeXA); - System.out.println("SolveCompare (use Cbc solution as base): "+ControlData.cbc_debug_routeCbc); - - // watch variable - if (configMap.keySet().contains("watch")){ - - String s = configMap.get("watch").toLowerCase(); - ControlData.watchList = s.split(","); - - System.out.println("Watch: "+Arrays.toString(ControlData.watchList)); - - } - - // watch variable tolerance - k = "watcht"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - ControlData.watchList_tolerance = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println("watchT: Error reading config value"); - } - - } - System.out.println("watchT: "+ControlData.watchList_tolerance); - - // CbcDebugObjDiff // default is false - k = "cbcdebugobjdiff"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - CbcSolver.debugObjDiff = true; - } else { - CbcSolver.debugObjDiff = false; - } - }else{ - CbcSolver.debugObjDiff = false; - } - System.out.println("CbcDebugObjDiff: "+CbcSolver.debugObjDiff); - - // CbcObjLog // default is true - k = "cbcobjlog"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - CbcSolver.logObj = true; - } else { - CbcSolver.logObj = false; - } - }else{ - CbcSolver.logObj = true; - } - System.out.println("CbcObjLog: "+CbcSolver.logObj); - - // CbcLogNativeLp // default is false - k = "cbclognativelp"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - ControlData.cbcLogNativeLp = true; - } else { - ControlData.cbcLogNativeLp = false; - } - }else{ - ControlData.cbcLogNativeLp = false; - } - System.out.println("CbcLogNativeLp: "+ControlData.cbcLogNativeLp); - - // CbcWarmStart // default is false - k = "cbcwarmstart"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - ControlData.useCbcWarmStart = true; - } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ - ControlData.useCbcWarmStart = false; - } - } - // warmstart is true if cbc2021 is true - if (CbcSolver.usejCbc2021) { - ControlData.useCbcWarmStart = true; - } - System.out.println("CbcWarmStart: "+ControlData.useCbcWarmStart); - - // CbcViolationCheck default {cbc2021:false, otherwise:true} - k = "cbcviolationcheck"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - CbcSolver.cbcViolationCheck = true; - } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ - CbcSolver.cbcViolationCheck = false; - } - - } - System.out.println("CbcViolationCheck: "+CbcSolver.cbcViolationCheck); - - - // CbcSolveFunction // default is SolveFull - k = "cbcsolvefunction"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - if (s.equalsIgnoreCase("solveu")){ - CbcSolver.solvFunc=CbcSolver.solvU; - } else if (s.equalsIgnoreCase("solve2")){ - CbcSolver.solvFunc=CbcSolver.solv2; - } else if (s.equalsIgnoreCase("solve3")){ - CbcSolver.solvFunc=CbcSolver.solv3; - } else if (s.equalsIgnoreCase("callCbc")){ - CbcSolver.solvFunc=CbcSolver.solvCallCbc; - } else { - CbcSolver.solvFunc=CbcSolver.solvFull; - } - }else{ - CbcSolver.solvFunc=CbcSolver.solvFull; - } - System.out.println("CbcSolveFunction: "+CbcSolver.solvFunc); - - // CbcToleranceZero // default is 1e-11 ControlData.zeroTolerance - k = "cbctolerancezero"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - ControlData.zeroTolerance = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println("CbcToleranceZero: Error reading config value"); - } - - } - System.out.println("CbcToleranceZero: "+ControlData.zeroTolerance); - - - // CbcToleranceInteger default 1e-9 - k = "cbctoleranceinteger"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.integerT = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println("CbcToleranceInteger: Error reading config value"); - } - - } - System.out.println("CbcToleranceInteger: "+CbcSolver.integerT); - - // CbcLowerBoundZeroCheck default max(solve_2_primalT_relax*10, 1e-6) - k = "cbclowerboundzerocheck"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.lowerBoundZero_check = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println("CbcLowerBoundZeroCheck: Error reading config value"); - } - - } - System.out.println("CbcLowerBoundZeroCheck: "+CbcSolver.lowerBoundZero_check); - - // CbcToleranceIntegerCheck default 1e-8 - k = "cbctoleranceintegercheck"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.integerT_check = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println("CbcToleranceIntegercheck: Error reading config value"); - } - - } - System.out.println("CbcToleranceIntegercheck: "+CbcSolver.integerT_check); - - // CbcSolutionRounding default is true - k = "cbcsolutionrounding"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - CbcSolver.cbcSolutionRounding = true; - } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ - CbcSolver.cbcSolutionRounding = false; - } else { - CbcSolver.cbcSolutionRounding = true; - } - }else{ - CbcSolver.cbcSolutionRounding = true; - } - System.out.println("CbcSolutionRounding: "+CbcSolver.cbcSolutionRounding); - - // CbcViolationRetry default is true - k = "cbcviolationretry"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - CbcSolver.cbcViolationRetry = true; - } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ - CbcSolver.cbcViolationRetry = false; - } else { - CbcSolver.cbcViolationRetry = true; - } - }else{ - CbcSolver.cbcViolationRetry = true; - } - System.out.println("CbcViolationRetry: "+CbcSolver.cbcViolationRetry); - - -// // XAIntegerT -// k = "xaintegert"; -// if (configMap.keySet().contains(k)){ -// -// String s = configMap.get(k); -// -// try { -// ControlData.xaIntegerT = Double.parseDouble(s); -// } catch (NumberFormatException e) { -// System.out.println("XAIntegerT: Error reading config value"); -// } -// -// } -// System.out.println("XAIntegerT: "+ControlData.xaIntegerT); - - -// // xasort // default is unknown -// k = "xasort"; -// if (configMap.keySet().contains(k)){ -// -// String s = configMap.get(k).toLowerCase(); -// -// if (s.equals("yes")||s.equals("no")||s.equals("col")||s.equals("row")){ -// ControlData.xaSort=s; -// } else { -// System.out.println("XASort: No | Yes | Row | Col");; -// } -// } -// System.out.println("XASort: "+ControlData.xaSort); - - // CbcHintTimeMax // default is 100 sec - k = "cbchinttimemax"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.cbcHintTimeMax = Integer.parseInt(s); - } catch (NumberFormatException e) { - System.out.println("CbcHintTimeMax: Error reading config value"); - } - - } - System.out.println("CbcHintTimeMax: "+CbcSolver.cbcHintTimeMax); - - // CbcHintRelaxPenalty // default is 9000 - k = "cbchintrelaxpenalty"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.cbcHintRelaxPenalty = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println("CbcHintRelaxPenalty: Error reading config value"); - } - - } - System.out.println("CbcHintRelaxPenalty: "+CbcSolver.cbcHintRelaxPenalty); - - - // CbcTolerancePrimal // default is 1e-9 - k = "cbctoleranceprimal"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.solve_2_primalT = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println("CbcTolerancePrimal: Error reading config value"); - } - - } - System.out.println("CbcTolerancePrimal: "+CbcSolver.solve_2_primalT); - - // CbcTolerancePrimalRelax // default is 1e-7 - k = "cbctoleranceprimalrelax"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.solve_2_primalT_relax = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println("CbcTolerancePrimalRelax: Error reading config value"); - } - - } - System.out.println("CbcTolerancePrimalRelax: "+CbcSolver.solve_2_primalT_relax); - ControlData.relationTolerance = Math.max(CbcSolver.solve_2_primalT_relax*10, 1e-6); - - // CbcSolveWhsPrimalT // default is 1e-9 - k = "cbctolerancewarmprimal"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.solve_whs_primalT = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println("CbcToleranceWarmPrimal: Error reading config value"); - } - - } - System.out.println("CbcToleranceWarmPrimal: "+CbcSolver.solve_whs_primalT); - - // CbcLogStartDate // default is 999900 - k = "cbclogstartdate"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.cbcLogStartDate = Integer.parseInt(s); - } catch (NumberFormatException e) { - System.out.println("CbcLogStartDate: Error reading config value"); - } - - } - System.out.println("CbcLogStartDate: "+CbcSolver.cbcLogStartDate); - - // CbcLogStopDate // default is 999900 - k = "cbclogstopdate"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.cbcLogStopDate = Integer.parseInt(s); - } catch (NumberFormatException e) { - System.out.println("CbcLogStopDate: Error reading config value"); - } - - } - System.out.println("CbcLogStopDate: "+CbcSolver.cbcLogStopDate); - - // LogIfObjDiff - k = "logifobjdiff"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.log_if_obj_diff = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println("LogIfObjDiff: Error reading config value"); - } - - } - System.out.println("LogIfObjDiff: "+CbcSolver.log_if_obj_diff); - - // RecordIfObjDiff - k = "recordifobjdiff"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - try { - CbcSolver.record_if_obj_diff = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println("RecordIfObjDiff: Error reading config value"); - } - - } - System.out.println("RecordIfObjDiff: "+CbcSolver.record_if_obj_diff); - - k = "CbcWhsScaling"; //default is true - CbcSolver.whsScaling = readBoolean(configMap, k, true); - System.out.println(k+": "+CbcSolver.whsScaling); - - k = "CbcWhsSafe"; //default is false - CbcSolver.whsSafe = readBoolean(configMap, k, false); - System.out.println(k+": "+CbcSolver.whsSafe); - - k = "CbcDebugDeviation"; //default is false - CbcSolver.debugDeviation = readBoolean(configMap, k, false); - System.out.println(k+": "+CbcSolver.debugDeviation); - - if (CbcSolver.debugDeviation){ - - k = "CbcDebugDeviationMin"; // default is 200 - CbcSolver.debugDeviationMin = readDouble(configMap, k, 200); - System.out.println(k+": "+CbcSolver.debugDeviationMin); - - k = "CbcDebugDeviationWeightMin"; // default is 5E5 - CbcSolver.debugDeviationWeightMin = readDouble(configMap, k, 5E5); - System.out.println(k+": "+CbcSolver.debugDeviationWeightMin); - - k = "CbcDebugDeviationWeightMultiply"; // default is 100 - CbcSolver.debugDeviationWeightMultiply = readDouble(configMap, k, 100); - System.out.println(k+": "+CbcSolver.debugDeviationWeightMultiply); - - k = "CbcDebugDeviationFindMissing"; //default is false - CbcSolver.debugDeviationFindMissing = readBoolean(configMap, k, false); - System.out.println(k+": "+CbcSolver.debugDeviationFindMissing); - - } - - // Warm2ndSolveFunction // default is Solve2 - k = "warm2ndsolvefunction"; - if (configMap.keySet().contains(k)){ - - String s = configMap.get(k); - - if (s.equalsIgnoreCase("solve3")){ - CbcSolver.warm_2nd_solvFunc=CbcSolver.solv3; - } else { - CbcSolver.warm_2nd_solvFunc=CbcSolver.solv2; - } - }else{ - CbcSolver.warm_2nd_solvFunc=CbcSolver.solv2; - } - System.out.println("Warm2ndSolveFunction: "+CbcSolver.warm_2nd_solvFunc); - - // ParserCheckVarUndefined - if (configMap.keySet().contains("parsercheckvarundefined")){ - - String s = configMap.get("parsercheckvarundefined"); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - StudyUtils.parserCheckVarUndefined = true; - } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ - StudyUtils.parserCheckVarUndefined = false; - } else { - StudyUtils.parserCheckVarUndefined = true; - } - }else{ - StudyUtils.parserCheckVarUndefined = true; - } - System.out.println("ParserCheckVarUndefined: "+StudyUtils.parserCheckVarUndefined); - - - if (ControlData.solverName.equalsIgnoreCase("lpsolve")) { - - // LpSolveConfigFile - if (configMap.keySet().contains("lpsolveconfigfile")) { - - String f = configMap.get("lpsolveconfigfile"); - - try { - - File sf = new File(StudyUtils.configDir, f); - if (sf.exists()) { - LPSolveSolver.configFile = sf.getCanonicalPath(); - } else { - //System.out.println("#Error: LpSolveConfigFile not found: " + f); - Error.addConfigError("LpSolveConfigFile not found: " + f); - Error.writeErrorLog(); - } - - } catch (Exception e) { - Error.addConfigError("LpSolveConfigFile not found: " + f); - Error.writeErrorLog(); - //System.out.println("#Error: LpSolveConfigFile not found: " + f); - e.printStackTrace(); - } - } else { - Error.addConfigError("LpSolveConfigFile not defined. "); - Error.writeErrorLog(); - //System.out.println("#Error: LpSolveConfigFile not defined. "); - } - - System.out.println("LpSolveConfigFile: "+LPSolveSolver.configFile); - - - // LpSolveNumberOfRetries default is 0 retry - if (configMap.keySet().contains("lpsolvenumberofretries")){ - - String s = configMap.get("lpsolvenumberofretries"); - - try { - LPSolveSolver.numberOfRetries = Integer.parseInt(s); - - } catch (Exception e) { - //System.out.println("#Error: LpSolveNumberOfRetries not recognized: " + s); - Error.addConfigError("LpSolveNumberOfRetries not recognized: " + s); - Error.writeErrorLog(); - - } - } - System.out.println("LpSolveNumberOfRetries: "+LPSolveSolver.numberOfRetries); - - - } - - // processed only for ILP - - // TODO: lpsolve and ilp log is binded. need to enable direct linking instead of reading file - if(ControlData.solverName.equalsIgnoreCase("XALOG")){ - configMap.put("ilplog","yes"); - ILP.loggingCplexLp = true; - }else if (ControlData.solverName.equalsIgnoreCase("cbc0")||ControlData.solverName.equalsIgnoreCase("cbc1")) { - configMap.put("ilplog","yes"); - configMap.put("ilplogallcycles","yes"); - ILP.loggingCplexLp = true; - }else if (ControlData.solverName.equalsIgnoreCase("clp0")||ControlData.solverName.equalsIgnoreCase("clp1")) { - configMap.put("ilplog","yes"); - configMap.put("ilplogallcycles","yes"); - ILP.loggingCplexLp = true; - }else if (ControlData.solverName.equalsIgnoreCase("lpsolve")) { - configMap.put("ilplog","yes"); - ILP.loggingLpSolve = true; - }else if (ControlData.solverName.equalsIgnoreCase("Gurobi")) { - configMap.put("ilplog","yes"); - ILP.loggingCplexLp = true; - } - - String strIlpLog = configMap.get("ilplog"); - if (strIlpLog.equalsIgnoreCase("yes") || strIlpLog.equalsIgnoreCase("true")) { - - ILP.logging = true; - // IlpLogAllCycles - // default is false - if (configMap.keySet().contains("ilplogallcycles")) { - - String s = configMap.get("ilplogallcycles"); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")) { - ILP.loggingAllCycles = true; - } - else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")) { - ILP.loggingAllCycles = false; - } - else { - ILP.loggingAllCycles = true; - } - } - // IlpLogVarValue - // default is false - if (configMap.keySet().contains("ilplogvarvalue")) { - - String s = configMap.get("ilplogvarvalue"); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")) { - ILP.loggingVariableValue = true; - } - else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")) { - ILP.loggingVariableValue = false; - } - else { - ILP.loggingVariableValue = false; - } - } - - // ilplogvarvalueround - // default is false - if (configMap.keySet().contains("ilplogvarvalueround")) { - - String s = configMap.get("ilplogvarvalueround"); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")) { - ILP.loggingVariableValueRound = true; - } else { - ILP.loggingVariableValueRound = false; - } - } - - // ilplogvarvalueround10 - // default is false - if (configMap.keySet().contains("ilplogvarvalueround10")) { - - String s = configMap.get("ilplogvarvalueround10"); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")) { - ILP.loggingVariableValueRound10 = true; - } else { - ILP.loggingVariableValueRound10 = false; - } - } - - // IlpLogMaximumFractionDigits - // default is 8 - if (configMap.keySet().contains("ilplogmaximumfractiondigits")) { - - String s = configMap.get("ilplogmaximumfractiondigits"); - int d; - - try { - d = Integer.parseInt(s); - ILP.maximumFractionDigits = d; - - } - catch (Exception e) { - - Error.addConfigError("IlpLogMaximumFractionDigits not recognized: " + s); - Error.writeErrorLog(); - } - } - - if (configMap.keySet().contains("ilplogformat")) { - - String s = configMap.get("ilplogformat"); - - if (s.toLowerCase().contains("cplexlp")) { - ILP.loggingCplexLp = true; - System.out.println("IlpLogFormat: " + "CplexLp"); - } - if (s.toLowerCase().contains("mpmodel")) { - ILP.loggingMPModel = true; - System.out.println("IlpLogFormat: " + "MPModel"); - } - if (s.toLowerCase().contains("ampl")) { - ILP.loggingAmpl = true; - System.out.println("IlpLogFormat: " + "Ampl"); - } - if (s.toLowerCase().contains("lpsolve")) { - ILP.loggingLpSolve = true; - System.out.println("IlpLogFormat: " + "LpSolve"); - } - } - - System.out.println("IlpLog: " + ILP.logging); - System.out.println("IlpLogAllCycles: " + ILP.loggingAllCycles); - System.out.println("IlpLogVarValue: " + ILP.loggingVariableValue); - System.out.println("IlpLogMaximumFractionDigits: " + ILP.maximumFractionDigits); - - } - - String strIlpLogUsageMemory = configMap.get("ilplogusagememory"); - if (strIlpLogUsageMemory.equalsIgnoreCase("yes") || strIlpLogUsageMemory.equalsIgnoreCase("true")) { - ILP.loggingUsageMemeory = true; - }else{ - ILP.loggingUsageMemeory = false; - } - System.out.println("IlpLogUsageMemory: " + ILP.loggingUsageMemeory); - - String s = configMap.get("wreslplus"); - - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - StudyUtils.useWreslPlus = true; - } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ - StudyUtils.useWreslPlus = false; - } else { - StudyUtils.useWreslPlus = false; - } - System.out.println("WreslPlus: " + StudyUtils.useWreslPlus); - - String enableProgressLog = configMap.get("enableprogresslog"); - - if (enableProgressLog.equalsIgnoreCase("yes") || enableProgressLog.equalsIgnoreCase("true")){ - ControlData.enableProgressLog = true; - } - System.out.println("enableProgressLog: " + ControlData.enableProgressLog); - - String allowSvTsInit = configMap.get("allowsvtsinit"); - if (allowSvTsInit.equalsIgnoreCase("yes") || allowSvTsInit.equalsIgnoreCase("true")){ - ControlData.allowSvTsInit = true; - } else { - ControlData.allowSvTsInit = false; - } - System.out.println("AllowSvTsInit: " + ControlData.allowSvTsInit); - - String allRestartFiles = configMap.get("allrestartfiles"); - if (allRestartFiles.equalsIgnoreCase("yes") || allRestartFiles.equalsIgnoreCase("true")){ - ControlData.allRestartFiles = true; - } else { - ControlData.allRestartFiles = false; - } - System.out.println("AllRestartFiles: " + ControlData.allRestartFiles); - - ControlData.numberRestartFiles = Integer.parseInt(configMap.get("numberrestartfiles")); - System.out.println("NumberRestartFiles: " + ControlData.numberRestartFiles); - - ControlData.databaseURL = configMap.get("databaseurl"); - ControlData.sqlGroup = configMap.get("sqlgroup"); - ControlData.ovOption = Integer.parseInt(configMap.get("ovoption")); - ControlData.ovFile = configMap.get("ovfile"); - System.out.println("ovOption: " + ControlData.ovOption); - - String outputCycleDataToDss = configMap.get("outputcycledatatodss"); - if (outputCycleDataToDss.equalsIgnoreCase("yes") || outputCycleDataToDss.equalsIgnoreCase("true")){ - ControlData.isOutputCycle=true; - }else{ - ControlData.isOutputCycle=false; - } - System.out.println("OutputCycleDataToDSS: " + ControlData.isOutputCycle); - - String outputAllCycleData = configMap.get("outputallcycledata"); - if (outputAllCycleData.equalsIgnoreCase("yes") || outputAllCycleData.equalsIgnoreCase("true")){ - ControlData.outputAllCycles=true; - }else{ - ControlData.outputAllCycles=false; - } - System.out.println("OutputAllCycleData: " + ControlData.outputAllCycles); - - ControlData.selectedCycleOutput = configMap.get("selectedcycleoutput"); - System.out.println("SelectedOutputCycles: " + ControlData.selectedCycleOutput); - - String showRunTimeMessage = configMap.get("showruntimemessage"); - if (showRunTimeMessage.equalsIgnoreCase("yes") || showRunTimeMessage.equalsIgnoreCase("true")){ - ControlData.showRunTimeMessage=true; - }else{ - ControlData.showRunTimeMessage=false; - } - System.out.println("ShowRunTimeMessage: " + ControlData.showRunTimeMessage); - - String printGWFuncCalls = configMap.get("printgwfunccalls"); - if (printGWFuncCalls.equalsIgnoreCase("yes") || printGWFuncCalls.equalsIgnoreCase("true")){ - ControlData.printGWFuncCalls=true; - }else{ - ControlData.printGWFuncCalls=false; - } - System.out.println("PrintGWFuncCalls: " + ControlData.printGWFuncCalls); - - k = "NameSorting"; //default is false - ControlData.isNameSorting = readBoolean(configMap, k, false); - System.out.println(k+": "+ControlData.isNameSorting); - - k = "YearOutputSection"; - ControlData.yearOutputSection = (int)Math.round(readDouble(configMap, k, -1)); - System.out.println(k+": "+ControlData.yearOutputSection); - - k = "MonthMemorySection"; - ControlData.monMemSection = (int)Math.round(readDouble(configMap, k, -1)); - System.out.println(k+": "+ControlData.monMemSection); - - String unchangeGWRestart = configMap.get("unchangegwrestart"); - if (unchangeGWRestart.equalsIgnoreCase("yes") || unchangeGWRestart.equalsIgnoreCase("true")){ - ControlData.unchangeGWRestart=true; - }else{ - ControlData.unchangeGWRestart=false; - } - System.out.println("KeepGWRestartatStartDate: " + ControlData.unchangeGWRestart); - - String genSVCatalog = configMap.get("gensvcatalog"); - if (genSVCatalog.equalsIgnoreCase("yes") || genSVCatalog.equalsIgnoreCase("true")){ - ControlData.genSVCatalog=true; - }else{ - ControlData.genSVCatalog=false; - } - System.out.println("GenSVCatalog: " + ControlData.genSVCatalog); - - //if (Error.getTotalError()<1) readParameter(configFile); - -// if (Error.getTotalError()<1 && paramMap.size()>0) { -// System.out.println("--------------------------------------------"); -// for (String k: paramMap.keySet()){ -// ParamTemp pt = paramMap.get(k); -// System.out.println("Parameter:: "+k+": "+pt.expression ); -// } -// } - - - - -// if (configMap.keySet().contains("lpsolveparamheader")){ -// -// String s = configMap.get("lpsolveparamheader"); -// -// String delimiter = "[\\+]"; -// String [] pheaders = s.split(delimiter); -// -// //LPSolveSolver.paramHeader = new ArrayList(); -// -// System.out.println( "s:"+s); -// -// for (int i=1;i<=pheaders.length;i++){ -// System.out.println( pheaders[i-1]); -// } -// -// for (int i=1;i<=pheaders.length;i++){ -// -// String h = pheaders[i-1]; -// -// LPSolveSolver.paramHeader.add(h); -// -// //System.out.println("LpSolveParamFile: "+pf); -// switch (i){ -// case 1 : System.out.println("default LpSolveParamHeader: "+h); break; -// case 2 : System.out.println("2nd try LpSolveParamHeader: "+h); break; -// case 3 : System.out.println("3rd try LpSolveParamHeader: "+h); break; -// default : System.out.println( i+"th try LpSolveParamHeader: "+h); break; -// } -// -// } -// -// -// } - //System.out.println("Ignored... SetAmplOption: option presolve_eps 1e-13;"); - - - - // System.out.println("gw: "+FilePaths.groundwaterDir); - // System.out.println("svd: "+FilePaths.svarDssDirectory); - // System.out.println("sv: "+FilePaths.svarDssFile); - // System.out.println("initD: "+FilePaths.initDssDirectory); - // System.out.println("init: "+FilePaths.initDssFile); - // - // - // System.out.println(FilePaths.mainDirectory); - // System.out.println(FilePaths.groundwaterDir); - // System.out.println(FilePaths.csvFolderName); - // - // System.out.println(ControlData.svDvPartF); - // System.out.println(ControlData.initPartF); - // System.out.println(ControlData.partA); - // System.out.println(ControlData.partE); - // System.out.println(ControlData.timeStep); - // - // System.out.println(ControlData.startYear); - // System.out.println(ControlData.startMonth); - // System.out.println(ControlData.startDay); - // - // System.out.println(ControlData.endYear); - // System.out.println(ControlData.endMonth); - // System.out.println(ControlData.endDay); - // - // System.out.println(ControlData.solverName); - // System.out.println(ControlData.currYear); - // System.out.println(ControlData.currMonth); - // System.out.println(ControlData.currDay); - // System.out.println(ControlData.writeDssStartYear); - // System.out.println(ControlData.writeDssStartMonth); - // System.out.println(ControlData.writeDssStartDay); - // - // System.out.println(ControlData.totalTimeStep); - // System.exit(0); - - } - - private static Map checkConfigFile(String configFilePath) { - - final File configFile = new File(configFilePath); - - - try { - StudyUtils.configFileCanonicalPath = configFile.getCanonicalPath(); - StudyUtils.configDir = configFile.getParentFile().getCanonicalPath(); - } catch (Exception e) { - - Error.addConfigError("Config file not found: " + configFilePath); - - } finally { - if (!configFile.exists()){ - - Error.addConfigError("Config file not found: " + configFilePath); - - } - } - - Map configMap = setDefaultConfig(); - - try { - - Scanner scanner = new Scanner(configFile); - while (scanner.hasNextLine()) { - String line = scanner.nextLine(); - - line = line.trim(); - line = line.replace('\t', ' '); - //System.out.println(line); - if (line.indexOf("#") > -1) { - line = line.substring(0, line.indexOf("#")); - line = line.trim(); - } - if (line.indexOf(" ") < 0) continue; - if (line.lastIndexOf(" ") + 1 >= line.length()) continue; - if (line.length() < 5) continue; - - //System.out.println(line); - - String key = line.substring(0, line.indexOf(" ")); - - String value = line.substring(key.length(), line.length()); - - value = value.trim(); - value = value + " "; - if (value.startsWith("\"")) { - value = value.substring(1, value.lastIndexOf("\"")); - value = value.replace("\"", ""); - } - else { - value = value.substring(0, value.indexOf(" ")); - value = value.replace("\"", ""); - } - - // break at the line "End Config" - if (key.equalsIgnoreCase("end") & value.equalsIgnoreCase("config") ) break; - - configMap.put(key.toLowerCase(), value); - } - - } - catch (Exception e) { - - Error.addConfigError("Invalid Config File: " + configFilePath); - - } - - - // check missing fields - String[] requiredFields = { "MainFile", "Solver", "DvarFile", "SvarFile", "SvarAPart", - "SvarFPart", "InitFile", "InitFPart", "TimeStep", "StartYear", "StartMonth" }; - - for (String k : requiredFields) { - if (!configMap.keySet().contains(k.toLowerCase())) { - - Error.addConfigError("Config file missing field: " + k); - Error.writeErrorLog(); - - } - } - - // convert number of steps to end date - int bYr= Integer.parseInt(configMap.get("startyear")); - int bMon= Integer.parseInt(configMap.get("startmonth")); - - if (configMap.keySet().contains("numberofsteps")){ - - int nsteps = Integer.parseInt(configMap.get("numberofsteps")); - - int iBegin = bYr*12 + bMon; - int iEnd = iBegin + nsteps -1 ; - - int eYr = iEnd/12; - int eMon = iEnd%12; - - configMap.put("stopyear", Integer.toString(eYr)); - configMap.put("stopmonth", Integer.toString(eMon)); - - } else { - // check missing fields - String[] endDateFields = {"StopYear", "StopMonth"}; - - for (String k : endDateFields) { - if (!configMap.keySet().contains(k.toLowerCase())) { - - Error.addConfigError("Config file missing field: " + k); - Error.writeErrorLog(); - - } - } - } - - // if start day and end day are not specified, fill-in start day and end day - - if (!configMap.containsKey("startday")) { - configMap.put("startday", "1"); - } - - int endYr= Integer.parseInt(configMap.get("stopyear")); - int endMon= Integer.parseInt(configMap.get("stopmonth")); - int endday= TimeOperation.numberOfDays(endMon, endYr); - - if (!configMap.containsKey("stopday")) { - configMap.put("stopday", Integer.toString(endday)); - } - - ControlData.defaultTimeStep=configMap.get("timestep").toUpperCase(); - - // TODO: duplcate codes. clean it up! - - File mf = null; - String mainfile = configMap.get("mainfile"); - - if (mainfile.contains(":")){ - mf = new File(mainfile); - } else { - mf = new File(StudyUtils.configDir, mainfile); - } - - - try { - mf.getCanonicalPath(); - } - catch (IOException e) { - - Error.addConfigError("Main file not found: "+mf.getAbsolutePath()); - Error.writeErrorLog(); - - } - - return configMap; - - } - - private static Map setDefaultConfig() { - - Map configMap = new HashMap(); - - configMap.put("saveparserdata".toLowerCase(), "No"); - configMap.put("solver".toLowerCase(), "XA"); - configMap.put("timestep".toLowerCase(), "1MON"); - configMap.put("showwresllog".toLowerCase(), "yes"); - configMap.put("groundwaterdir".toLowerCase(), ""); - configMap.put("lookupsubdir".toLowerCase(), ""); - configMap.put("IlpLog".toLowerCase(), "no"); - configMap.put("IlpLogVarValue".toLowerCase(), "no"); - configMap.put("IlpLogUsageMemory".toLowerCase(), "no"); - configMap.put("WreslPlus".toLowerCase(), "no"); - configMap.put("AllowSvTsInit".toLowerCase(), "no"); - configMap.put("DatabaseURL".toLowerCase(), "none"); - configMap.put("SQLGroup".toLowerCase(), "calsim"); - configMap.put("ovOption".toLowerCase(), "0"); - configMap.put("enableProgressLog".toLowerCase(), "No"); - configMap.put("OutputCycleDataToDss".toLowerCase(), "No"); - configMap.put("outputAllCycleData".toLowerCase(), "yes"); - configMap.put("SelectedCycleOutput".toLowerCase(), "\'\'"); - configMap.put("ShowRunTimeMessage".toLowerCase(), "No"); - configMap.put("svarfile2".toLowerCase(), ""); - configMap.put("AllRestartFiles".toLowerCase(), "No"); - configMap.put("NumberRestartFiles".toLowerCase(), "12"); - configMap.put("PrintGWfuncCalls".toLowerCase(), "No"); - configMap.put("NameSorting".toLowerCase(), "No"); - configMap.put("YearOutputSection".toLowerCase(), "-1"); - configMap.put("MonthMemorySection".toLowerCase(), "-1"); - configMap.put("unchangeGWRestart".toLowerCase(), "no"); - configMap.put("GenSVCatalog".toLowerCase(), "yes"); - return configMap; - - } - - private static void readParameter(String configFilePath) { - - final File configFile = new File(configFilePath); - - boolean isParameter = false; - - paramMap = new LinkedHashMap(); - - try { - - Scanner scanner = new Scanner(configFile); - while (scanner.hasNextLine()) { - String line = scanner.nextLine(); - - line = line.trim(); - line = line.replace('\t', ' '); - //System.out.println(line); - if (line.indexOf("#") > -1) { - line = line.substring(0, line.indexOf("#")); - line = line.trim(); - } - if (line.indexOf(" ") < 0) continue; - if (line.lastIndexOf(" ") + 1 >= line.length()) continue; - if (line.length() < 5) continue; - - //System.out.println(line); - - String key = line.substring(0, line.indexOf(" ")); - - String value = line.substring(key.length(), line.length()); - - value = value.trim(); - value = value + " "; - if (value.startsWith("\"")) { - value = value.substring(1, value.lastIndexOf("\"")); - value = value.replace("\"", ""); - } - else { - value = value.substring(0, value.indexOf(" ")); - value = value.replace("\"", ""); - } - - // break at the line "End Parameter" - if (key.equalsIgnoreCase("end") & value.equalsIgnoreCase("initial") ) break; - - if (key.equalsIgnoreCase("begin") & value.equalsIgnoreCase("initial") ) { - isParameter = true; - System.out.println("--------------------------------------------"); - continue; - } - - if (isParameter) { - - if (paramMap.keySet().contains(key.toLowerCase())) { - - Error.addConfigError("Initial variable ["+key+"] is redefined"); - - } - - ParamTemp pt = new ParamTemp(); - pt.id = key; - pt.expression = value.toLowerCase(); - - System.out.println("Initial variable:: "+pt.id.toLowerCase()+": "+pt.expression ); - - try { - //pt.dependants = checkExpression(pt.expression); - Float.parseFloat(pt.expression); - } catch (Exception e) { - Error.addConfigError("Initial variable ["+key+"] in Config file must be assigned with a number, but it's ["+pt.expression+"]"); - } - - paramMap.put(key.toLowerCase(), pt); - } - } - - } - catch (Exception e) { - - Error.addConfigError("Exception in parsing [Initial] section: " + configFilePath); - - } - - //return paramMap; - - } - - private static Set checkExpression(String text) throws RecognitionException { - - WreslPlusParser parser = ParserUtils.initParserSimple(text); - - parser.expression_simple(); - - return parser.dependants; - - } - - private static boolean readBoolean(Map cM, String name, boolean defaultV){ - - String l = name.toLowerCase(); - if (cM.keySet().contains(l)) { - String s = cM.get(l); - if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ - return true; - } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ - return false; - } - } - return defaultV; - } - - private static double readDouble(Map cM, String name, double defaultV){ - - double returnV = defaultV; - String l = name.toLowerCase(); - if (cM.keySet().contains(l)){ - String s = cM.get(l); - try { - returnV = Double.parseDouble(s); - } catch (NumberFormatException e) { - System.out.println(name+": Error reading config value"); - } - } - return returnV; - } - - // private static void loadConfig2(String loadFile) throws IOException { - // - // try { - // XmlDocument doc = XmlDocument.createXmlDocument( - // new FileInputStream(loadFile), false); - // fromXml(doc.getDocumentElement()); - // } catch (Exception e) { - // e.printStackTrace(); - // throw new IOException("Invalid config file: " + loadFile); - // } - // - // } - - // private static void fromXml(Element se) { - // - // _parserdataversion = se.getAttribute("parserdataversion"); - // _groundwaterfolder = se.getAttribute("groundwaterfolder"); - // _wreslfile = se.getAttribute("wreslfile"); - // _svfile = se.getAttribute("svfile"); - // _dvfile = se.getAttribute("dvfile"); - // _initfile = se.getAttribute("initfile"); - // - // _svfileapart = se.getAttribute("svfileapart"); - // _svfilefpart = se.getAttribute("svfilefpart"); - // _initfilefpart = se.getAttribute("initfilefpart"); - // - // String startMonth = se.getAttribute("startmo"); - // String startYear = se.getAttribute("startyr"); - // String stopMonth = se.getAttribute("stopmo"); - // String stopYear = se.getAttribute("stopyr"); - // - // try { - // - // _startmo = TimeOperation.monthValue(startMonth.toLowerCase()); - // _startyr = Integer.parseInt(startYear); - // _stopmo = TimeOperation.monthValue(stopMonth.toLowerCase()); - // _stopyr = Integer.parseInt(stopYear); - // - // - // } catch (Exception e) { - // System.out.println(e.getMessage()); - // } - // - // - // FilePaths.setMainFilePaths(_wreslfile); - // FilePaths.groundwaterDir= _groundwaterfolder; - // FilePaths.setSvarDssPaths(_svfile); - // FilePaths.setInitDssPaths(_initfile); - // FilePaths.setDvarDssPaths(_dvfile); - // FilePaths.csvFolderName = ""; - // - // ControlData.svDvPartF = _svfilefpart; - // ControlData.initPartF = _initfilefpart; - // ControlData.partA = _svfileapart; - // ControlData.partE = _ts; - // ControlData.timeStep = _ts; - // - // ControlData.startYear = _startyr; - // ControlData.startMonth = _startmo; - // ControlData.startDay = TimeOperation.numberOfDays(_startmo, _startyr); - // - // ControlData.endYear = _stopyr; - // ControlData.endMonth = _stopmo; - // ControlData.endDay = TimeOperation.numberOfDays(_stopmo, _stopyr); - // - // ControlData.solverName= _solver; - // ControlData.currYear=ControlData.startYear; - // ControlData.currMonth=ControlData.startMonth; - // ControlData.currDay=ControlData.startDay; - // ControlData.writeDssStartYear=ControlData.startYear; - // ControlData.writeDssStartMonth=ControlData.startMonth; - // ControlData.writeDssStartDay=ControlData.startDay; - // - // ControlData.totalTimeStep = ControllerBatch.getTotalTimeStep(); - // } - -} +package wrimsv2.config; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Scanner; +import java.util.Set; + +import org.antlr.runtime.RecognitionException; +import org.apache.commons.io.FilenameUtils; +import org.coinor.cbc.jCbc; + +import wrimsv2.components.BuildProps; +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; +import wrimsv2.components.Error; +import wrimsv2.evaluator.TimeOperation; +import wrimsv2.ilp.ILP; +import wrimsv2.solver.CbcSolver; +import wrimsv2.solver.LPSolveSolver; +import wrimsv2.wreslparser.elements.StudyUtils; +import wrimsv2.wreslplus.elements.ParamTemp; +import wrimsv2.wreslplus.elements.ParserUtils; +import wrimsv2.wreslplus.grammar.WreslPlusParser; + +public class ConfigUtils { + + private static Map argsMap; + + public static LinkedHashMap paramMap = new LinkedHashMap(); + + public static void loadArgs(String[] args) { + + // for Error.log header + ControlData.currEvalTypeIndex=8; + + // print version number then exit + if (args.length==1 && args[0].equalsIgnoreCase("-version") ) { + + System.out.println("WRIMS "+new BuildProps().getVN()); + System.exit(0); + } + + + + argsMap = new HashMap(); + + for (int i = 0; i < args.length; i++) { + + try { + String key = args[i].substring(0, args[i].indexOf("=")); + String val = args[i].substring(args[i].indexOf("=") + 1, args[i].length()); + val=val.replaceAll("\"", ""); + + argsMap.put(key.toLowerCase(), val); + + } + catch (Exception e) { + System.out.println("Example: "); + System.out.println("-config=\"D:\\test\\example.config\""); +// System.out.println("Example: "); +// System.out.println("-mainwresl=\"C:\\study\\main.wresl\""); + System.exit(1); + } + + //System.out.println(argsMap); + + } + + + + // load config file + if (argsMap.keySet().contains("-config")) { + + String configFilePath = FilenameUtils.removeExtension(argsMap.get("-config"))+".config"; + argsMap.put("-config", configFilePath); + + System.out.println("\nWARNING!! Config file and RUN directory must be placed in the same folder! \n"); + System.out.println("Loading config file: "+argsMap.get("-config")); + StudyUtils.configFilePath = argsMap.get("-config"); + loadConfig(StudyUtils.configFilePath); + if (Error.getTotalError()>0) { + Error.writeErrorLog(); + } + + // compile to serial object named *.par + } else if (argsMap.keySet().contains("-mainwresl")) { + + System.out.println("Compiling main wresl file: "+argsMap.get("-mainwresl")); + StudyUtils.compileOnly = true; + FilePaths.setMainFilePaths(argsMap.get("-mainwresl")); + + } else if (argsMap.keySet().contains("-mainwreslplus")) { + + System.out.println("Compiling main wresl file: "+argsMap.get("-mainwreslplus")); + StudyUtils.compileOnly = true; + StudyUtils.useWreslPlus=true; + FilePaths.setMainFilePaths(argsMap.get("-mainwreslplus")); + + }else { + System.out.println("Example: "); + System.out.println("-config=\"D:\\test\\example.config\""); +// System.out.println("Example: "); +// System.out.println("-mainwresl=\"C:\\study\\main.wresl\""); + System.exit(1); + } + + } + + private static void loadConfig(String configFile) { + + //StudyUtils.config_errors = 0; // reset + String k=null; + + Map configMap = new HashMap(); + + configMap = checkConfigFile(configFile); + + String mainfile = configMap.get("mainfile").toLowerCase(); + + String mainFilePath = ""; + + if (mainfile.contains(":")){ + mainFilePath = new File(mainfile).getAbsolutePath(); + } else { + mainFilePath = new File(StudyUtils.configDir, mainfile).getAbsolutePath(); + } + + File validatedAbsFile = new File(mainFilePath).getAbsoluteFile(); + if (!validatedAbsFile.exists()) { + Error.addConfigError("File not found: " + mainFilePath); + Error.writeErrorLog(); + } + + if (mainfile.endsWith(".par")) { + StudyUtils.loadParserData = true; + StudyUtils.parserDataPath = mainFilePath; + FilePaths.setMainFilePaths(mainFilePath); + } + else if (mainfile.endsWith(".wresl")) { + FilePaths.setMainFilePaths(mainFilePath); + } + else { + Error.addConfigError("Invalid main file extension: " + configMap.get("mainfile")); + Error.writeErrorLog(); + //System.out.println("Invalid main file extension: " + configMap.get("mainfile")); + //System.out.println("Specify either *.wresl or *.par"); + //System.exit(1); + } + + // FilePaths.mainDirectory = configMap.get("maindir"); + System.out.println("MainFile: "+FilePaths.fullMainPath); + + // CbcLibName // default is jCbc and it's not used for version selection + k = "cbclibname"; + if (configMap.keySet().contains(k)){ + + CbcSolver.cbcLibName = configMap.get(k); + } + // need to know jCbc version to determine solving options + System.loadLibrary(CbcSolver.cbcLibName); + System.out.println("CbcLibName: "+CbcSolver.cbcLibName); + + try { + + if (configMap.get("groundwaterdir").length()>0) { + if (configMap.get("groundwaterdir").contains(":")){ + FilePaths.groundwaterDir = new File(configMap.get("groundwaterdir")).getCanonicalPath()+File.separator; + } else { + FilePaths.groundwaterDir = new File(StudyUtils.configDir, configMap.get("groundwaterdir")).getCanonicalPath()+File.separator; + } + System.out.println("GroundWaterDir: "+FilePaths.groundwaterDir); + } else { + FilePaths.groundwaterDir = "None"; + } + + if (configMap.get("svarfile").contains(":")){ + FilePaths.setSvarFilePaths(new File(configMap.get("svarfile")).getCanonicalPath()); + } else { + FilePaths.setSvarFilePaths(new File(StudyUtils.configDir, configMap.get("svarfile")).getCanonicalPath()); + } + System.out.println("SvarFile: "+FilePaths.fullSvarFilePath); + + if (configMap.get("svarfile2").equals("")){ + FilePaths.setSvarFile2Paths(""); + }else{ + if (configMap.get("svarfile2").contains(":")){ + FilePaths.setSvarFile2Paths(new File(configMap.get("svarfile2")).getCanonicalPath()); + } else { + FilePaths.setSvarFile2Paths(new File(StudyUtils.configDir, configMap.get("svarfile2")).getCanonicalPath()); + } + System.out.println("SvarFile2: "+FilePaths.fullSvarFile2Path); + } + + if (configMap.get("initfile").contains(":")){ + FilePaths.setInitFilePaths(new File(configMap.get("initfile")).getCanonicalPath()); + } else { + FilePaths.setInitFilePaths(new File(StudyUtils.configDir, configMap.get("initfile")).getCanonicalPath()); + } + System.out.println("InitFile: "+FilePaths.fullInitFilePath); + + if (configMap.get("dvarfile").contains(":")) { + FilePaths.setDvarFilePaths(new File(configMap.get("dvarfile")).getCanonicalPath()); + } else { + FilePaths.setDvarFilePaths(new File(StudyUtils.configDir, configMap.get("dvarfile")).getCanonicalPath()); + } + System.out.println("DvarFile: "+FilePaths.fullDvarDssPath); + + } catch (IOException e){ + Error.addConfigError("Invalid file path in config file"); + Error.writeErrorLog(); + //System.out.println("Invalid file path"); + e.printStackTrace(); + } + + StudyUtils.configFileName = new File(configFile).getName(); + + FilePaths.csvFolderName = ""; + + if (configMap.get("showwresllog").equalsIgnoreCase("no") || configMap.get("showwresllog").equalsIgnoreCase("false")){ + ControlData.showWreslLog = false; + } + if (configMap.get("lookupsubdir").length()>0 ){ + FilePaths.lookupSubDirectory = configMap.get("lookupsubdir"); + System.out.println("LookupSubDir: "+FilePaths.lookupSubDirectory); + } + //ControlData.showWreslLog = !(configMap.get("showwresllog").equalsIgnoreCase("no")); + + ControlData.svDvPartF = configMap.get("svarfpart"); + ControlData.initPartF = configMap.get("initfpart"); + ControlData.partA = configMap.get("svarapart"); + ControlData.partE = configMap.get("timestep"); + ControlData.timeStep = configMap.get("timestep"); + + ControlData.startYear = Integer.parseInt(configMap.get("startyear")); + ControlData.startMonth = Integer.parseInt(configMap.get("startmonth")); + ControlData.startDay = Integer.parseInt(configMap.get("startday")); + + ControlData.endYear = Integer.parseInt(configMap.get("stopyear")); + ControlData.endMonth = Integer.parseInt(configMap.get("stopmonth")); + ControlData.endDay = Integer.parseInt(configMap.get("stopday")); + + ControlData.solverName = configMap.get("solver"); + + ControlData.currYear = ControlData.startYear; + ControlData.currMonth = ControlData.startMonth; + ControlData.currDay = ControlData.startDay; + + System.out.println("TimeStep: "+ControlData.timeStep); + System.out.println("SvarAPart: "+ControlData.partA); + System.out.println("SvarFPart: "+ControlData.svDvPartF); + System.out.println("InitFPart: "+ControlData.initPartF); + System.out.println("StartYear: "+ControlData.startYear); + System.out.println("StartMonth: "+ControlData.startMonth); + System.out.println("StartDay: "+ControlData.startDay); + System.out.println("StopYear: "+ControlData.endYear); + System.out.println("StopMonth: "+ControlData.endMonth); + System.out.println("StopDay: "+ControlData.endDay); + System.out.println("Solver: "+ControlData.solverName); + + final String[] solvers = {"xa","xalog","clp0","clp1","clp","lpsolve","gurobi","cbc0","cbc1","cbc"}; + + if (!Arrays.asList(solvers).contains(ControlData.solverName.toLowerCase())){ + Error.addConfigError("Solver name not recognized: "+ControlData.solverName); + Error.writeErrorLog(); + } else if (ControlData.solverName.toLowerCase().contains("cbc")) { + CbcSolver.cbcVersion = jCbc.getVersion(); + System.out.println("CbcVersion: "+CbcSolver.cbcVersion); + if (CbcSolver.cbcVersion.contains("2.9.9")) { + CbcSolver.usejCbc2021 = true; + if (CbcSolver.cbcVersion.contains("2.9.9.2")) { + CbcSolver.usejCbc2021a = true; + } + CbcSolver.cbcViolationCheck = false; // can overwrite + ControlData.useCbcWarmStart = true; // cannot overwrite + } else { + CbcSolver.cbcViolationCheck = true; // can overwrite + ControlData.useCbcWarmStart = false; // cannot overwrite + } + System.out.println("Cbc2021: "+CbcSolver.usejCbc2021); + System.out.println("Cbc2021a: "+CbcSolver.usejCbc2021a); + } + + // SendAliasToDvar default is false + if (configMap.keySet().contains("sendaliastodvar")){ + + String s = configMap.get("sendaliastodvar"); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + ControlData.sendAliasToDvar = true; + } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ + ControlData.sendAliasToDvar = false; + } else { + ControlData.sendAliasToDvar = false; + } + + } + System.out.println("SendAliasToDvar: "+ControlData.sendAliasToDvar); + + + // PrefixInitToDvarFile + if (configMap.keySet().contains("prefixinittodvarfile")){ + + String s = configMap.get("prefixinittodvarfile"); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + ControlData.writeInitToDVOutput = true; + } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ + ControlData.writeInitToDVOutput = false; + } else { + ControlData.writeInitToDVOutput = false; + } + }else{ + ControlData.writeInitToDVOutput = true; + } + System.out.println("PrefixInitToDvarFile: "+ControlData.writeInitToDVOutput); + + // SolveCompare + k = "solvecompare"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + if (s.equalsIgnoreCase("xa_cbc")){ + ControlData.cbc_debug_routeXA = false; + ControlData.cbc_debug_routeCbc = true; + } else if (s.equalsIgnoreCase("cbc_xa")) { + ControlData.cbc_debug_routeXA = true; + ControlData.cbc_debug_routeCbc = false; + } else { + ControlData.cbc_debug_routeXA = false; + ControlData.cbc_debug_routeCbc = false; + } + }else{ + ControlData.cbc_debug_routeXA = false; + ControlData.cbc_debug_routeCbc = false; + } + System.out.println("SolveCompare (use XA solution as base): "+ControlData.cbc_debug_routeXA); + System.out.println("SolveCompare (use Cbc solution as base): "+ControlData.cbc_debug_routeCbc); + + // watch variable + if (configMap.keySet().contains("watch")){ + + String s = configMap.get("watch").toLowerCase(); + ControlData.watchList = s.split(","); + + System.out.println("Watch: "+Arrays.toString(ControlData.watchList)); + + } + + // watch variable tolerance + k = "watcht"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + ControlData.watchList_tolerance = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("watchT: Error reading config value"); + } + + } + System.out.println("watchT: "+ControlData.watchList_tolerance); + + // CbcDebugObjDiff // default is false + k = "cbcdebugobjdiff"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + CbcSolver.debugObjDiff = true; + } else { + CbcSolver.debugObjDiff = false; + } + }else{ + CbcSolver.debugObjDiff = false; + } + System.out.println("CbcDebugObjDiff: "+CbcSolver.debugObjDiff); + + // CbcObjLog // default is true + k = "cbcobjlog"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + CbcSolver.logObj = true; + } else { + CbcSolver.logObj = false; + } + }else{ + CbcSolver.logObj = true; + } + System.out.println("CbcObjLog: "+CbcSolver.logObj); + + // CbcLogNativeLp // default is false + k = "cbclognativelp"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + ControlData.cbcLogNativeLp = true; + } else { + ControlData.cbcLogNativeLp = false; + } + }else{ + ControlData.cbcLogNativeLp = false; + } + System.out.println("CbcLogNativeLp: "+ControlData.cbcLogNativeLp); + + // CbcWarmStart // default is false + k = "cbcwarmstart"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + ControlData.useCbcWarmStart = true; + } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ + ControlData.useCbcWarmStart = false; + } + } + // warmstart is true if cbc2021 is true + if (CbcSolver.usejCbc2021) { + ControlData.useCbcWarmStart = true; + } + System.out.println("CbcWarmStart: "+ControlData.useCbcWarmStart); + + // CbcViolationCheck default {cbc2021:false, otherwise:true} + k = "cbcviolationcheck"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + CbcSolver.cbcViolationCheck = true; + } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ + CbcSolver.cbcViolationCheck = false; + } + + } + System.out.println("CbcViolationCheck: "+CbcSolver.cbcViolationCheck); + + + // CbcSolveFunction // default is SolveFull + k = "cbcsolvefunction"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + if (s.equalsIgnoreCase("solveu")){ + CbcSolver.solvFunc=CbcSolver.solvU; + } else if (s.equalsIgnoreCase("solve2")){ + CbcSolver.solvFunc=CbcSolver.solv2; + } else if (s.equalsIgnoreCase("solve3")){ + CbcSolver.solvFunc=CbcSolver.solv3; + } else if (s.equalsIgnoreCase("callCbc")){ + CbcSolver.solvFunc=CbcSolver.solvCallCbc; + } else { + CbcSolver.solvFunc=CbcSolver.solvFull; + } + }else{ + CbcSolver.solvFunc=CbcSolver.solvFull; + } + System.out.println("CbcSolveFunction: "+CbcSolver.solvFunc); + + // CbcToleranceZero // default is 1e-11 ControlData.zeroTolerance + k = "cbctolerancezero"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + ControlData.zeroTolerance = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("CbcToleranceZero: Error reading config value"); + } + + } + System.out.println("CbcToleranceZero: "+ControlData.zeroTolerance); + + + // CbcToleranceInteger default 1e-9 + k = "cbctoleranceinteger"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.integerT = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("CbcToleranceInteger: Error reading config value"); + } + + } + System.out.println("CbcToleranceInteger: "+CbcSolver.integerT); + + // CbcLowerBoundZeroCheck default max(solve_2_primalT_relax*10, 1e-6) + k = "cbclowerboundzerocheck"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.lowerBoundZero_check = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("CbcLowerBoundZeroCheck: Error reading config value"); + } + + } + System.out.println("CbcLowerBoundZeroCheck: "+CbcSolver.lowerBoundZero_check); + + // CbcToleranceIntegerCheck default 1e-8 + k = "cbctoleranceintegercheck"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.integerT_check = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("CbcToleranceIntegercheck: Error reading config value"); + } + + } + System.out.println("CbcToleranceIntegercheck: "+CbcSolver.integerT_check); + + // CbcSolutionRounding default is true + k = "cbcsolutionrounding"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + CbcSolver.cbcSolutionRounding = true; + } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ + CbcSolver.cbcSolutionRounding = false; + } else { + CbcSolver.cbcSolutionRounding = true; + } + }else{ + CbcSolver.cbcSolutionRounding = true; + } + System.out.println("CbcSolutionRounding: "+CbcSolver.cbcSolutionRounding); + + // CbcViolationRetry default is true + k = "cbcviolationretry"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + CbcSolver.cbcViolationRetry = true; + } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ + CbcSolver.cbcViolationRetry = false; + } else { + CbcSolver.cbcViolationRetry = true; + } + }else{ + CbcSolver.cbcViolationRetry = true; + } + System.out.println("CbcViolationRetry: "+CbcSolver.cbcViolationRetry); + + +// // XAIntegerT +// k = "xaintegert"; +// if (configMap.keySet().contains(k)){ +// +// String s = configMap.get(k); +// +// try { +// ControlData.xaIntegerT = Double.parseDouble(s); +// } catch (NumberFormatException e) { +// System.out.println("XAIntegerT: Error reading config value"); +// } +// +// } +// System.out.println("XAIntegerT: "+ControlData.xaIntegerT); + + +// // xasort // default is unknown +// k = "xasort"; +// if (configMap.keySet().contains(k)){ +// +// String s = configMap.get(k).toLowerCase(); +// +// if (s.equals("yes")||s.equals("no")||s.equals("col")||s.equals("row")){ +// ControlData.xaSort=s; +// } else { +// System.out.println("XASort: No | Yes | Row | Col");; +// } +// } +// System.out.println("XASort: "+ControlData.xaSort); + + // CbcHintTimeMax // default is 100 sec + k = "cbchinttimemax"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.cbcHintTimeMax = Integer.parseInt(s); + } catch (NumberFormatException e) { + System.out.println("CbcHintTimeMax: Error reading config value"); + } + + } + System.out.println("CbcHintTimeMax: "+CbcSolver.cbcHintTimeMax); + + // CbcHintRelaxPenalty // default is 9000 + k = "cbchintrelaxpenalty"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.cbcHintRelaxPenalty = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("CbcHintRelaxPenalty: Error reading config value"); + } + + } + System.out.println("CbcHintRelaxPenalty: "+CbcSolver.cbcHintRelaxPenalty); + + + // CbcTolerancePrimal // default is 1e-9 + k = "cbctoleranceprimal"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.solve_2_primalT = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("CbcTolerancePrimal: Error reading config value"); + } + + } + System.out.println("CbcTolerancePrimal: "+CbcSolver.solve_2_primalT); + + // CbcTolerancePrimalRelax // default is 1e-7 + k = "cbctoleranceprimalrelax"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.solve_2_primalT_relax = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("CbcTolerancePrimalRelax: Error reading config value"); + } + + } + System.out.println("CbcTolerancePrimalRelax: "+CbcSolver.solve_2_primalT_relax); + ControlData.relationTolerance = Math.max(CbcSolver.solve_2_primalT_relax*10, 1e-6); + + // CbcSolveWhsPrimalT // default is 1e-9 + k = "cbctolerancewarmprimal"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.solve_whs_primalT = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("CbcToleranceWarmPrimal: Error reading config value"); + } + + } + System.out.println("CbcToleranceWarmPrimal: "+CbcSolver.solve_whs_primalT); + + // CbcLogStartDate // default is 999900 + k = "cbclogstartdate"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.cbcLogStartDate = Integer.parseInt(s); + } catch (NumberFormatException e) { + System.out.println("CbcLogStartDate: Error reading config value"); + } + + } + System.out.println("CbcLogStartDate: "+CbcSolver.cbcLogStartDate); + + // CbcLogStopDate // default is 999900 + k = "cbclogstopdate"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.cbcLogStopDate = Integer.parseInt(s); + } catch (NumberFormatException e) { + System.out.println("CbcLogStopDate: Error reading config value"); + } + + } + System.out.println("CbcLogStopDate: "+CbcSolver.cbcLogStopDate); + + // LogIfObjDiff + k = "logifobjdiff"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.log_if_obj_diff = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("LogIfObjDiff: Error reading config value"); + } + + } + System.out.println("LogIfObjDiff: "+CbcSolver.log_if_obj_diff); + + // RecordIfObjDiff + k = "recordifobjdiff"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + try { + CbcSolver.record_if_obj_diff = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("RecordIfObjDiff: Error reading config value"); + } + + } + System.out.println("RecordIfObjDiff: "+CbcSolver.record_if_obj_diff); + + k = "CbcWhsScaling"; //default is true + CbcSolver.whsScaling = readBoolean(configMap, k, true); + System.out.println(k+": "+CbcSolver.whsScaling); + + k = "CbcWhsSafe"; //default is false + CbcSolver.whsSafe = readBoolean(configMap, k, false); + System.out.println(k+": "+CbcSolver.whsSafe); + + k = "CbcDebugDeviation"; //default is false + CbcSolver.debugDeviation = readBoolean(configMap, k, false); + System.out.println(k+": "+CbcSolver.debugDeviation); + + if (CbcSolver.debugDeviation){ + + k = "CbcDebugDeviationMin"; // default is 200 + CbcSolver.debugDeviationMin = readDouble(configMap, k, 200); + System.out.println(k+": "+CbcSolver.debugDeviationMin); + + k = "CbcDebugDeviationWeightMin"; // default is 5E5 + CbcSolver.debugDeviationWeightMin = readDouble(configMap, k, 5E5); + System.out.println(k+": "+CbcSolver.debugDeviationWeightMin); + + k = "CbcDebugDeviationWeightMultiply"; // default is 100 + CbcSolver.debugDeviationWeightMultiply = readDouble(configMap, k, 100); + System.out.println(k+": "+CbcSolver.debugDeviationWeightMultiply); + + k = "CbcDebugDeviationFindMissing"; //default is false + CbcSolver.debugDeviationFindMissing = readBoolean(configMap, k, false); + System.out.println(k+": "+CbcSolver.debugDeviationFindMissing); + + } + + // Warm2ndSolveFunction // default is Solve2 + k = "warm2ndsolvefunction"; + if (configMap.keySet().contains(k)){ + + String s = configMap.get(k); + + if (s.equalsIgnoreCase("solve3")){ + CbcSolver.warm_2nd_solvFunc=CbcSolver.solv3; + } else { + CbcSolver.warm_2nd_solvFunc=CbcSolver.solv2; + } + }else{ + CbcSolver.warm_2nd_solvFunc=CbcSolver.solv2; + } + System.out.println("Warm2ndSolveFunction: "+CbcSolver.warm_2nd_solvFunc); + + // ParserCheckVarUndefined + if (configMap.keySet().contains("parsercheckvarundefined")){ + + String s = configMap.get("parsercheckvarundefined"); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + StudyUtils.parserCheckVarUndefined = true; + } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ + StudyUtils.parserCheckVarUndefined = false; + } else { + StudyUtils.parserCheckVarUndefined = true; + } + }else{ + StudyUtils.parserCheckVarUndefined = true; + } + System.out.println("ParserCheckVarUndefined: "+StudyUtils.parserCheckVarUndefined); + + + if (ControlData.solverName.equalsIgnoreCase("lpsolve")) { + + // LpSolveConfigFile + if (configMap.keySet().contains("lpsolveconfigfile")) { + + String f = configMap.get("lpsolveconfigfile"); + + try { + + File sf = new File(StudyUtils.configDir, f); + if (sf.exists()) { + LPSolveSolver.configFile = sf.getCanonicalPath(); + } else { + //System.out.println("#Error: LpSolveConfigFile not found: " + f); + Error.addConfigError("LpSolveConfigFile not found: " + f); + Error.writeErrorLog(); + } + + } catch (Exception e) { + Error.addConfigError("LpSolveConfigFile not found: " + f); + Error.writeErrorLog(); + //System.out.println("#Error: LpSolveConfigFile not found: " + f); + e.printStackTrace(); + } + } else { + Error.addConfigError("LpSolveConfigFile not defined. "); + Error.writeErrorLog(); + //System.out.println("#Error: LpSolveConfigFile not defined. "); + } + + System.out.println("LpSolveConfigFile: "+LPSolveSolver.configFile); + + + // LpSolveNumberOfRetries default is 0 retry + if (configMap.keySet().contains("lpsolvenumberofretries")){ + + String s = configMap.get("lpsolvenumberofretries"); + + try { + LPSolveSolver.numberOfRetries = Integer.parseInt(s); + + } catch (Exception e) { + //System.out.println("#Error: LpSolveNumberOfRetries not recognized: " + s); + Error.addConfigError("LpSolveNumberOfRetries not recognized: " + s); + Error.writeErrorLog(); + + } + } + System.out.println("LpSolveNumberOfRetries: "+LPSolveSolver.numberOfRetries); + + + } + + // processed only for ILP + + // TODO: lpsolve and ilp log is binded. need to enable direct linking instead of reading file + if(ControlData.solverName.equalsIgnoreCase("XALOG")){ + configMap.put("ilplog","yes"); + ILP.loggingCplexLp = true; + }else if (ControlData.solverName.equalsIgnoreCase("cbc0")||ControlData.solverName.equalsIgnoreCase("cbc1")) { + configMap.put("ilplog","yes"); + configMap.put("ilplogallcycles","yes"); + ILP.loggingCplexLp = true; + }else if (ControlData.solverName.equalsIgnoreCase("clp0")||ControlData.solverName.equalsIgnoreCase("clp1")) { + configMap.put("ilplog","yes"); + configMap.put("ilplogallcycles","yes"); + ILP.loggingCplexLp = true; + }else if (ControlData.solverName.equalsIgnoreCase("lpsolve")) { + configMap.put("ilplog","yes"); + ILP.loggingLpSolve = true; + }else if (ControlData.solverName.equalsIgnoreCase("Gurobi")) { + configMap.put("ilplog","yes"); + ILP.loggingCplexLp = true; + } + + String strIlpLog = configMap.get("ilplog"); + if (strIlpLog.equalsIgnoreCase("yes") || strIlpLog.equalsIgnoreCase("true")) { + + ILP.logging = true; + // IlpLogAllCycles + // default is false + if (configMap.keySet().contains("ilplogallcycles")) { + + String s = configMap.get("ilplogallcycles"); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")) { + ILP.loggingAllCycles = true; + } + else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")) { + ILP.loggingAllCycles = false; + } + else { + ILP.loggingAllCycles = true; + } + } + // IlpLogVarValue + // default is false + if (configMap.keySet().contains("ilplogvarvalue")) { + + String s = configMap.get("ilplogvarvalue"); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")) { + ILP.loggingVariableValue = true; + } + else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")) { + ILP.loggingVariableValue = false; + } + else { + ILP.loggingVariableValue = false; + } + } + + // ilplogvarvalueround + // default is false + if (configMap.keySet().contains("ilplogvarvalueround")) { + + String s = configMap.get("ilplogvarvalueround"); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")) { + ILP.loggingVariableValueRound = true; + } else { + ILP.loggingVariableValueRound = false; + } + } + + // ilplogvarvalueround10 + // default is false + if (configMap.keySet().contains("ilplogvarvalueround10")) { + + String s = configMap.get("ilplogvarvalueround10"); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")) { + ILP.loggingVariableValueRound10 = true; + } else { + ILP.loggingVariableValueRound10 = false; + } + } + + // IlpLogMaximumFractionDigits + // default is 8 + if (configMap.keySet().contains("ilplogmaximumfractiondigits")) { + + String s = configMap.get("ilplogmaximumfractiondigits"); + int d; + + try { + d = Integer.parseInt(s); + ILP.maximumFractionDigits = d; + + } + catch (Exception e) { + + Error.addConfigError("IlpLogMaximumFractionDigits not recognized: " + s); + Error.writeErrorLog(); + } + } + + if (configMap.keySet().contains("ilplogformat")) { + + String s = configMap.get("ilplogformat"); + + if (s.toLowerCase().contains("cplexlp")) { + ILP.loggingCplexLp = true; + System.out.println("IlpLogFormat: " + "CplexLp"); + } + if (s.toLowerCase().contains("mpmodel")) { + ILP.loggingMPModel = true; + System.out.println("IlpLogFormat: " + "MPModel"); + } + if (s.toLowerCase().contains("ampl")) { + ILP.loggingAmpl = true; + System.out.println("IlpLogFormat: " + "Ampl"); + } + if (s.toLowerCase().contains("lpsolve")) { + ILP.loggingLpSolve = true; + System.out.println("IlpLogFormat: " + "LpSolve"); + } + } + + System.out.println("IlpLog: " + ILP.logging); + System.out.println("IlpLogAllCycles: " + ILP.loggingAllCycles); + System.out.println("IlpLogVarValue: " + ILP.loggingVariableValue); + System.out.println("IlpLogMaximumFractionDigits: " + ILP.maximumFractionDigits); + + } + + String strIlpLogUsageMemory = configMap.get("ilplogusagememory"); + if (strIlpLogUsageMemory.equalsIgnoreCase("yes") || strIlpLogUsageMemory.equalsIgnoreCase("true")) { + ILP.loggingUsageMemeory = true; + }else{ + ILP.loggingUsageMemeory = false; + } + System.out.println("IlpLogUsageMemory: " + ILP.loggingUsageMemeory); + + String s = configMap.get("wreslplus"); + + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + StudyUtils.useWreslPlus = true; + } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ + StudyUtils.useWreslPlus = false; + } else { + StudyUtils.useWreslPlus = false; + } + System.out.println("WreslPlus: " + StudyUtils.useWreslPlus); + + String enableProgressLog = configMap.get("enableprogresslog"); + + if (enableProgressLog.equalsIgnoreCase("yes") || enableProgressLog.equalsIgnoreCase("true")){ + ControlData.enableProgressLog = true; + } + System.out.println("enableProgressLog: " + ControlData.enableProgressLog); + + String allowSvTsInit = configMap.get("allowsvtsinit"); + if (allowSvTsInit.equalsIgnoreCase("yes") || allowSvTsInit.equalsIgnoreCase("true")){ + ControlData.allowSvTsInit = true; + } else { + ControlData.allowSvTsInit = false; + } + System.out.println("AllowSvTsInit: " + ControlData.allowSvTsInit); + + String allRestartFiles = configMap.get("allrestartfiles"); + if (allRestartFiles.equalsIgnoreCase("yes") || allRestartFiles.equalsIgnoreCase("true")){ + ControlData.allRestartFiles = true; + } else { + ControlData.allRestartFiles = false; + } + System.out.println("AllRestartFiles: " + ControlData.allRestartFiles); + + ControlData.numberRestartFiles = Integer.parseInt(configMap.get("numberrestartfiles")); + System.out.println("NumberRestartFiles: " + ControlData.numberRestartFiles); + + ControlData.databaseURL = configMap.get("databaseurl"); + ControlData.sqlGroup = configMap.get("sqlgroup"); + ControlData.ovOption = Integer.parseInt(configMap.get("ovoption")); + ControlData.ovFile = configMap.get("ovfile"); + System.out.println("ovOption: " + ControlData.ovOption); + + String outputCycleDataToDss = configMap.get("outputcycledatatodss"); + if (outputCycleDataToDss.equalsIgnoreCase("yes") || outputCycleDataToDss.equalsIgnoreCase("true")){ + ControlData.isOutputCycle=true; + }else{ + ControlData.isOutputCycle=false; + } + System.out.println("OutputCycleDataToDSS: " + ControlData.isOutputCycle); + + String outputAllCycleData = configMap.get("outputallcycledata"); + if (outputAllCycleData.equalsIgnoreCase("yes") || outputAllCycleData.equalsIgnoreCase("true")){ + ControlData.outputAllCycles=true; + }else{ + ControlData.outputAllCycles=false; + } + System.out.println("OutputAllCycleData: " + ControlData.outputAllCycles); + + ControlData.selectedCycleOutput = configMap.get("selectedcycleoutput"); + System.out.println("SelectedOutputCycles: " + ControlData.selectedCycleOutput); + + String showRunTimeMessage = configMap.get("showruntimemessage"); + if (showRunTimeMessage.equalsIgnoreCase("yes") || showRunTimeMessage.equalsIgnoreCase("true")){ + ControlData.showRunTimeMessage=true; + }else{ + ControlData.showRunTimeMessage=false; + } + System.out.println("ShowRunTimeMessage: " + ControlData.showRunTimeMessage); + + String printGWFuncCalls = configMap.get("printgwfunccalls"); + if (printGWFuncCalls.equalsIgnoreCase("yes") || printGWFuncCalls.equalsIgnoreCase("true")){ + ControlData.printGWFuncCalls=true; + }else{ + ControlData.printGWFuncCalls=false; + } + System.out.println("PrintGWFuncCalls: " + ControlData.printGWFuncCalls); + + k = "NameSorting"; //default is false + ControlData.isNameSorting = readBoolean(configMap, k, false); + System.out.println(k+": "+ControlData.isNameSorting); + + k = "YearOutputSection"; + ControlData.yearOutputSection = (int)Math.round(readDouble(configMap, k, -1)); + System.out.println(k+": "+ControlData.yearOutputSection); + + k = "MonthMemorySection"; + ControlData.monMemSection = (int)Math.round(readDouble(configMap, k, -1)); + System.out.println(k+": "+ControlData.monMemSection); + + String unchangeGWRestart = configMap.get("unchangegwrestart"); + if (unchangeGWRestart.equalsIgnoreCase("yes") || unchangeGWRestart.equalsIgnoreCase("true")){ + ControlData.unchangeGWRestart=true; + }else{ + ControlData.unchangeGWRestart=false; + } + System.out.println("KeepGWRestartatStartDate: " + ControlData.unchangeGWRestart); + + String genSVCatalog = configMap.get("gensvcatalog"); + if (genSVCatalog.equalsIgnoreCase("yes") || genSVCatalog.equalsIgnoreCase("true")){ + ControlData.genSVCatalog=true; + }else{ + ControlData.genSVCatalog=false; + } + System.out.println("GenSVCatalog: " + ControlData.genSVCatalog); + + //if (Error.getTotalError()<1) readParameter(configFile); + +// if (Error.getTotalError()<1 && paramMap.size()>0) { +// System.out.println("--------------------------------------------"); +// for (String k: paramMap.keySet()){ +// ParamTemp pt = paramMap.get(k); +// System.out.println("Parameter:: "+k+": "+pt.expression ); +// } +// } + + + + +// if (configMap.keySet().contains("lpsolveparamheader")){ +// +// String s = configMap.get("lpsolveparamheader"); +// +// String delimiter = "[\\+]"; +// String [] pheaders = s.split(delimiter); +// +// //LPSolveSolver.paramHeader = new ArrayList(); +// +// System.out.println( "s:"+s); +// +// for (int i=1;i<=pheaders.length;i++){ +// System.out.println( pheaders[i-1]); +// } +// +// for (int i=1;i<=pheaders.length;i++){ +// +// String h = pheaders[i-1]; +// +// LPSolveSolver.paramHeader.add(h); +// +// //System.out.println("LpSolveParamFile: "+pf); +// switch (i){ +// case 1 : System.out.println("default LpSolveParamHeader: "+h); break; +// case 2 : System.out.println("2nd try LpSolveParamHeader: "+h); break; +// case 3 : System.out.println("3rd try LpSolveParamHeader: "+h); break; +// default : System.out.println( i+"th try LpSolveParamHeader: "+h); break; +// } +// +// } +// +// +// } + //System.out.println("Ignored... SetAmplOption: option presolve_eps 1e-13;"); + + + + // System.out.println("gw: "+FilePaths.groundwaterDir); + // System.out.println("svd: "+FilePaths.svarDssDirectory); + // System.out.println("sv: "+FilePaths.svarDssFile); + // System.out.println("initD: "+FilePaths.initDssDirectory); + // System.out.println("init: "+FilePaths.initDssFile); + // + // + // System.out.println(FilePaths.mainDirectory); + // System.out.println(FilePaths.groundwaterDir); + // System.out.println(FilePaths.csvFolderName); + // + // System.out.println(ControlData.svDvPartF); + // System.out.println(ControlData.initPartF); + // System.out.println(ControlData.partA); + // System.out.println(ControlData.partE); + // System.out.println(ControlData.timeStep); + // + // System.out.println(ControlData.startYear); + // System.out.println(ControlData.startMonth); + // System.out.println(ControlData.startDay); + // + // System.out.println(ControlData.endYear); + // System.out.println(ControlData.endMonth); + // System.out.println(ControlData.endDay); + // + // System.out.println(ControlData.solverName); + // System.out.println(ControlData.currYear); + // System.out.println(ControlData.currMonth); + // System.out.println(ControlData.currDay); + // System.out.println(ControlData.writeDssStartYear); + // System.out.println(ControlData.writeDssStartMonth); + // System.out.println(ControlData.writeDssStartDay); + // + // System.out.println(ControlData.totalTimeStep); + // System.exit(0); + + } + + private static Map checkConfigFile(String configFilePath) { + + final File configFile = new File(configFilePath); + + + try { + StudyUtils.configFileCanonicalPath = configFile.getCanonicalPath(); + StudyUtils.configDir = configFile.getParentFile().getCanonicalPath(); + } catch (Exception e) { + + Error.addConfigError("Config file not found: " + configFilePath); + + } finally { + if (!configFile.exists()){ + + Error.addConfigError("Config file not found: " + configFilePath); + + } + } + + Map configMap = setDefaultConfig(); + + try { + + Scanner scanner = new Scanner(configFile); + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + + line = line.trim(); + line = line.replace('\t', ' '); + //System.out.println(line); + if (line.indexOf("#") > -1) { + line = line.substring(0, line.indexOf("#")); + line = line.trim(); + } + if (line.indexOf(" ") < 0) continue; + if (line.lastIndexOf(" ") + 1 >= line.length()) continue; + if (line.length() < 5) continue; + + //System.out.println(line); + + String key = line.substring(0, line.indexOf(" ")); + + String value = line.substring(key.length(), line.length()); + + value = value.trim(); + value = value + " "; + if (value.startsWith("\"")) { + value = value.substring(1, value.lastIndexOf("\"")); + value = value.replace("\"", ""); + } + else { + value = value.substring(0, value.indexOf(" ")); + value = value.replace("\"", ""); + } + + // break at the line "End Config" + if (key.equalsIgnoreCase("end") & value.equalsIgnoreCase("config") ) break; + + configMap.put(key.toLowerCase(), value); + } + + } + catch (Exception e) { + + Error.addConfigError("Invalid Config File: " + configFilePath); + + } + + + // check missing fields + String[] requiredFields = { "MainFile", "Solver", "DvarFile", "SvarFile", "SvarAPart", + "SvarFPart", "InitFile", "InitFPart", "TimeStep", "StartYear", "StartMonth" }; + + for (String k : requiredFields) { + if (!configMap.keySet().contains(k.toLowerCase())) { + + Error.addConfigError("Config file missing field: " + k); + Error.writeErrorLog(); + + } + } + + // convert number of steps to end date + int bYr= Integer.parseInt(configMap.get("startyear")); + int bMon= Integer.parseInt(configMap.get("startmonth")); + + if (configMap.keySet().contains("numberofsteps")){ + + int nsteps = Integer.parseInt(configMap.get("numberofsteps")); + + int iBegin = bYr*12 + bMon; + int iEnd = iBegin + nsteps -1 ; + + int eYr = iEnd/12; + int eMon = iEnd%12; + + configMap.put("stopyear", Integer.toString(eYr)); + configMap.put("stopmonth", Integer.toString(eMon)); + + } else { + // check missing fields + String[] endDateFields = {"StopYear", "StopMonth"}; + + for (String k : endDateFields) { + if (!configMap.keySet().contains(k.toLowerCase())) { + + Error.addConfigError("Config file missing field: " + k); + Error.writeErrorLog(); + + } + } + } + + // if start day and end day are not specified, fill-in start day and end day + + if (!configMap.containsKey("startday")) { + configMap.put("startday", "1"); + } + + int endYr= Integer.parseInt(configMap.get("stopyear")); + int endMon= Integer.parseInt(configMap.get("stopmonth")); + int endday= TimeOperation.numberOfDays(endMon, endYr); + + if (!configMap.containsKey("stopday")) { + configMap.put("stopday", Integer.toString(endday)); + } + + ControlData.defaultTimeStep=configMap.get("timestep").toUpperCase(); + + // TODO: duplcate codes. clean it up! + + File mf = null; + String mainfile = configMap.get("mainfile"); + + if (mainfile.contains(":")){ + mf = new File(mainfile); + } else { + mf = new File(StudyUtils.configDir, mainfile); + } + + + try { + mf.getCanonicalPath(); + } + catch (IOException e) { + + Error.addConfigError("Main file not found: "+mf.getAbsolutePath()); + Error.writeErrorLog(); + + } + + return configMap; + + } + + private static Map setDefaultConfig() { + + Map configMap = new HashMap(); + + configMap.put("saveparserdata".toLowerCase(), "No"); + configMap.put("solver".toLowerCase(), "XA"); + configMap.put("timestep".toLowerCase(), "1MON"); + configMap.put("showwresllog".toLowerCase(), "yes"); + configMap.put("groundwaterdir".toLowerCase(), ""); + configMap.put("lookupsubdir".toLowerCase(), ""); + configMap.put("IlpLog".toLowerCase(), "no"); + configMap.put("IlpLogVarValue".toLowerCase(), "no"); + configMap.put("IlpLogUsageMemory".toLowerCase(), "no"); + configMap.put("WreslPlus".toLowerCase(), "no"); + configMap.put("AllowSvTsInit".toLowerCase(), "no"); + configMap.put("DatabaseURL".toLowerCase(), "none"); + configMap.put("SQLGroup".toLowerCase(), "calsim"); + configMap.put("ovOption".toLowerCase(), "0"); + configMap.put("enableProgressLog".toLowerCase(), "No"); + configMap.put("OutputCycleDataToDss".toLowerCase(), "No"); + configMap.put("outputAllCycleData".toLowerCase(), "yes"); + configMap.put("SelectedCycleOutput".toLowerCase(), "\'\'"); + configMap.put("ShowRunTimeMessage".toLowerCase(), "No"); + configMap.put("svarfile2".toLowerCase(), ""); + configMap.put("AllRestartFiles".toLowerCase(), "No"); + configMap.put("NumberRestartFiles".toLowerCase(), "12"); + configMap.put("PrintGWfuncCalls".toLowerCase(), "No"); + configMap.put("NameSorting".toLowerCase(), "No"); + configMap.put("YearOutputSection".toLowerCase(), "-1"); + configMap.put("MonthMemorySection".toLowerCase(), "-1"); + configMap.put("unchangeGWRestart".toLowerCase(), "no"); + configMap.put("GenSVCatalog".toLowerCase(), "yes"); + return configMap; + + } + + private static void readParameter(String configFilePath) { + + final File configFile = new File(configFilePath); + + boolean isParameter = false; + + paramMap = new LinkedHashMap(); + + try { + + Scanner scanner = new Scanner(configFile); + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + + line = line.trim(); + line = line.replace('\t', ' '); + //System.out.println(line); + if (line.indexOf("#") > -1) { + line = line.substring(0, line.indexOf("#")); + line = line.trim(); + } + if (line.indexOf(" ") < 0) continue; + if (line.lastIndexOf(" ") + 1 >= line.length()) continue; + if (line.length() < 5) continue; + + //System.out.println(line); + + String key = line.substring(0, line.indexOf(" ")); + + String value = line.substring(key.length(), line.length()); + + value = value.trim(); + value = value + " "; + if (value.startsWith("\"")) { + value = value.substring(1, value.lastIndexOf("\"")); + value = value.replace("\"", ""); + } + else { + value = value.substring(0, value.indexOf(" ")); + value = value.replace("\"", ""); + } + + // break at the line "End Parameter" + if (key.equalsIgnoreCase("end") & value.equalsIgnoreCase("initial") ) break; + + if (key.equalsIgnoreCase("begin") & value.equalsIgnoreCase("initial") ) { + isParameter = true; + System.out.println("--------------------------------------------"); + continue; + } + + if (isParameter) { + + if (paramMap.keySet().contains(key.toLowerCase())) { + + Error.addConfigError("Initial variable ["+key+"] is redefined"); + + } + + ParamTemp pt = new ParamTemp(); + pt.id = key; + pt.expression = value.toLowerCase(); + + System.out.println("Initial variable:: "+pt.id.toLowerCase()+": "+pt.expression ); + + try { + //pt.dependants = checkExpression(pt.expression); + Float.parseFloat(pt.expression); + } catch (Exception e) { + Error.addConfigError("Initial variable ["+key+"] in Config file must be assigned with a number, but it's ["+pt.expression+"]"); + } + + paramMap.put(key.toLowerCase(), pt); + } + } + + } + catch (Exception e) { + + Error.addConfigError("Exception in parsing [Initial] section: " + configFilePath); + + } + + //return paramMap; + + } + + private static Set checkExpression(String text) throws RecognitionException { + + WreslPlusParser parser = ParserUtils.initParserSimple(text); + + parser.expression_simple(); + + return parser.dependants; + + } + + private static boolean readBoolean(Map cM, String name, boolean defaultV){ + + String l = name.toLowerCase(); + if (cM.keySet().contains(l)) { + String s = cM.get(l); + if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true")){ + return true; + } else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("false")){ + return false; + } + } + return defaultV; + } + + private static double readDouble(Map cM, String name, double defaultV){ + + double returnV = defaultV; + String l = name.toLowerCase(); + if (cM.keySet().contains(l)){ + String s = cM.get(l); + try { + returnV = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println(name+": Error reading config value"); + } + } + return returnV; + } + + // private static void loadConfig2(String loadFile) throws IOException { + // + // try { + // XmlDocument doc = XmlDocument.createXmlDocument( + // new FileInputStream(loadFile), false); + // fromXml(doc.getDocumentElement()); + // } catch (Exception e) { + // e.printStackTrace(); + // throw new IOException("Invalid config file: " + loadFile); + // } + // + // } + + // private static void fromXml(Element se) { + // + // _parserdataversion = se.getAttribute("parserdataversion"); + // _groundwaterfolder = se.getAttribute("groundwaterfolder"); + // _wreslfile = se.getAttribute("wreslfile"); + // _svfile = se.getAttribute("svfile"); + // _dvfile = se.getAttribute("dvfile"); + // _initfile = se.getAttribute("initfile"); + // + // _svfileapart = se.getAttribute("svfileapart"); + // _svfilefpart = se.getAttribute("svfilefpart"); + // _initfilefpart = se.getAttribute("initfilefpart"); + // + // String startMonth = se.getAttribute("startmo"); + // String startYear = se.getAttribute("startyr"); + // String stopMonth = se.getAttribute("stopmo"); + // String stopYear = se.getAttribute("stopyr"); + // + // try { + // + // _startmo = TimeOperation.monthValue(startMonth.toLowerCase()); + // _startyr = Integer.parseInt(startYear); + // _stopmo = TimeOperation.monthValue(stopMonth.toLowerCase()); + // _stopyr = Integer.parseInt(stopYear); + // + // + // } catch (Exception e) { + // System.out.println(e.getMessage()); + // } + // + // + // FilePaths.setMainFilePaths(_wreslfile); + // FilePaths.groundwaterDir= _groundwaterfolder; + // FilePaths.setSvarDssPaths(_svfile); + // FilePaths.setInitDssPaths(_initfile); + // FilePaths.setDvarDssPaths(_dvfile); + // FilePaths.csvFolderName = ""; + // + // ControlData.svDvPartF = _svfilefpart; + // ControlData.initPartF = _initfilefpart; + // ControlData.partA = _svfileapart; + // ControlData.partE = _ts; + // ControlData.timeStep = _ts; + // + // ControlData.startYear = _startyr; + // ControlData.startMonth = _startmo; + // ControlData.startDay = TimeOperation.numberOfDays(_startmo, _startyr); + // + // ControlData.endYear = _stopyr; + // ControlData.endMonth = _stopmo; + // ControlData.endDay = TimeOperation.numberOfDays(_stopmo, _stopyr); + // + // ControlData.solverName= _solver; + // ControlData.currYear=ControlData.startYear; + // ControlData.currMonth=ControlData.startMonth; + // ControlData.currDay=ControlData.startDay; + // ControlData.writeDssStartYear=ControlData.startYear; + // ControlData.writeDssStartMonth=ControlData.startMonth; + // ControlData.writeDssStartDay=ControlData.startDay; + // + // ControlData.totalTimeStep = ControllerBatch.getTotalTimeStep(); + // } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/debug/ChangeSolver.java b/wrims-core/src/main/java/wrimsv2/debug/ChangeSolver.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/debug/ChangeSolver.java rename to wrims-core/src/main/java/wrimsv2/debug/ChangeSolver.java index fcecb4651..d126b6884 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/debug/ChangeSolver.java +++ b/wrims-core/src/main/java/wrimsv2/debug/ChangeSolver.java @@ -1,32 +1,32 @@ -package wrimsv2.debug; - -import java.io.File; - -import wrimsv2.components.Error; -import wrimsv2.components.FilePaths; -import wrimsv2.solver.LPSolveSolver; -import wrimsv2.wreslparser.elements.StudyUtils; - -public class ChangeSolver { - - public static void loadLPSolveConfigFile(){ - //To Do: temporary set up - String f="callite.lpsolve"; - - try { - - File sf = new File(StudyUtils.configDir, f); - if (sf.exists()) { - LPSolveSolver.configFile = sf.getCanonicalPath(); - } else { - Error.addConfigError("LpSolveConfigFile not found: " + f); - Error.writeErrorLog(); - } - - } catch (Exception e) { - Error.addConfigError("LpSolveConfigFile not found: " + f); - Error.writeErrorLog(); - e.printStackTrace(); - } - } -} +package wrimsv2.debug; + +import java.io.File; + +import wrimsv2.components.Error; +import wrimsv2.components.FilePaths; +import wrimsv2.solver.LPSolveSolver; +import wrimsv2.wreslparser.elements.StudyUtils; + +public class ChangeSolver { + + public static void loadLPSolveConfigFile(){ + //To Do: temporary set up + String f="callite.lpsolve"; + + try { + + File sf = new File(StudyUtils.configDir, f); + if (sf.exists()) { + LPSolveSolver.configFile = sf.getCanonicalPath(); + } else { + Error.addConfigError("LpSolveConfigFile not found: " + f); + Error.writeErrorLog(); + } + + } catch (Exception e) { + Error.addConfigError("LpSolveConfigFile not found: " + f); + Error.writeErrorLog(); + e.printStackTrace(); + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/debug/Compile.java b/wrims-core/src/main/java/wrimsv2/debug/Compile.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/debug/Compile.java rename to wrims-core/src/main/java/wrimsv2/debug/Compile.java index 4a33288cc..6ab27695d 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/debug/Compile.java +++ b/wrims-core/src/main/java/wrimsv2/debug/Compile.java @@ -1,31 +1,31 @@ -package wrimsv2.debug; - -import java.io.IOException; - -import org.apache.commons.io.FilenameUtils; - -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; -import wrimsv2.wreslparser.elements.StudyUtils; - -public class Compile { - public static StudyDataSet checkStudy(String inMainWreslPath, boolean useWreslPlus) throws IOException { - - StudyUtils.useWreslPlus=useWreslPlus; - - FilePaths.setMainFilePaths(inMainWreslPath); - - String mainFileName = FilenameUtils.removeExtension(FilePaths.mainFile); - - String csvFolderName = "=WreslCheck_"+mainFileName+"="; - String logFileName = "=WreslCheck_"+mainFileName+"=.log"; - - if (!ControlData.outputWreslCSV) { - csvFolderName = ""; // disable csv output - } - - return StudyUtils.checkStudy(inMainWreslPath, logFileName, csvFolderName, ControlData.sendAliasToDvar); - - } -} +package wrimsv2.debug; + +import java.io.IOException; + +import org.apache.commons.io.FilenameUtils; + +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; +import wrimsv2.wreslparser.elements.StudyUtils; + +public class Compile { + public static StudyDataSet checkStudy(String inMainWreslPath, boolean useWreslPlus) throws IOException { + + StudyUtils.useWreslPlus=useWreslPlus; + + FilePaths.setMainFilePaths(inMainWreslPath); + + String mainFileName = FilenameUtils.removeExtension(FilePaths.mainFile); + + String csvFolderName = "=WreslCheck_"+mainFileName+"="; + String logFileName = "=WreslCheck_"+mainFileName+"=.log"; + + if (!ControlData.outputWreslCSV) { + csvFolderName = ""; // disable csv output + } + + return StudyUtils.checkStudy(inMainWreslPath, logFileName, csvFolderName, ControlData.sendAliasToDvar); + + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/debug/FilterGoal.java b/wrims-core/src/main/java/wrimsv2/debug/FilterGoal.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/debug/FilterGoal.java rename to wrims-core/src/main/java/wrimsv2/debug/FilterGoal.java index 8cd809998..04dbcce74 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/debug/FilterGoal.java +++ b/wrims-core/src/main/java/wrimsv2/debug/FilterGoal.java @@ -1,40 +1,40 @@ -package wrimsv2.debug; - -public class FilterGoal { - private String alias="None"; - private String tolerance="0.0"; - private String control="n"; - private String content=""; - - public String getAlias(){ - return alias; - } - - public void setAlias(String alias){ - this.alias=alias; - } - - public String getTolerance(){ - return tolerance; - } - - public void setTolerance(String tolerance){ - this.tolerance=tolerance; - } - - public String getContent(){ - return content; - } - - public void setContent(String content){ - this.content=content; - } - - public String getControl(){ - return control; - } - - public void setControl(String control){ - this.control=control; - } -} +package wrimsv2.debug; + +public class FilterGoal { + private String alias="None"; + private String tolerance="0.0"; + private String control="n"; + private String content=""; + + public String getAlias(){ + return alias; + } + + public void setAlias(String alias){ + this.alias=alias; + } + + public String getTolerance(){ + return tolerance; + } + + public void setTolerance(String tolerance){ + this.tolerance=tolerance; + } + + public String getContent(){ + return content; + } + + public void setContent(String content){ + this.content=content; + } + + public String getControl(){ + return control; + } + + public void setControl(String control){ + this.control=control; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/debug/ReLoadSVDss.java b/wrims-core/src/main/java/wrimsv2/debug/ReLoadSVDss.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/debug/ReLoadSVDss.java rename to wrims-core/src/main/java/wrimsv2/debug/ReLoadSVDss.java index b6cd82463..e6385d786 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/debug/ReLoadSVDss.java +++ b/wrims-core/src/main/java/wrimsv2/debug/ReLoadSVDss.java @@ -1,73 +1,73 @@ -package wrimsv2.debug; - -import hec.heclib.dss.HecDss; -import hec.heclib.dss.HecDssCatalog; - -import java.io.File; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.External; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Timeseries; -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; -import wrimsv2.evaluator.CondensedReferenceCacheAndRead; -import wrimsv2.evaluator.DataTimeSeries; -import wrimsv2.evaluator.DssDataSetFixLength; -import wrimsv2.evaluator.DssOperation; -import wrimsv2.external.LoadAllDll; - -public class ReLoadSVDss { - public ReLoadSVDss(StudyDataSet sds){ - ControlData.currStudyDataSet=sds; - - if (!(new File(FilePaths.fullSvarFilePath)).exists()){ - System.out.println("Error: Svar file "+ FilePaths.fullSvarFilePath+" doesn't exist."); - System.out.println("=======Run Complete Unsuccessfully======="); - System.exit(0); - } - try { - HecDssCatalog catalog = new HecDssCatalog(FilePaths.fullSvarFilePath); - ControlData.cacheSvar = CondensedReferenceCacheAndRead.createCondensedCache(FilePaths.fullSvarFilePath, "*"); - if (!FilePaths.fullSvarFile2Path.equals("")){ - HecDssCatalog catalog2 = new HecDssCatalog(FilePaths.fullSvarFile2Path); - ControlData.cacheSvar2 = CondensedReferenceCacheAndRead.createCondensedCache(FilePaths.fullSvarFile2Path, "*"); - } - ControlData.allTsMap=sds.getTimeseriesMap(); - readTimeseries(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void readTimeseries(){ - Map tsMap=ControlData.currStudyDataSet.getTimeseriesMap(); - Map> tsTimeStepMap=ControlData.currStudyDataSet.getTimeseriesTimeStepMap(); - ControlData.currEvalTypeIndex=6; - Set tsKeySet=tsMap.keySet(); - Iterator iterator=tsKeySet.iterator(); - while(iterator.hasNext()){ - String tsName=(String)iterator.next(); - //System.out.println("Reading svar timeseries "+tsName); - //To Do: in the svar class, add flag to see if svTS has been loaded - if (!DataTimeSeries.lookSvDss.contains(tsName)){ - ArrayList timeStepList=tsTimeStepMap.get(tsName); - for (String timeStep:timeStepList){ - DssOperation.getSVTimeseries(tsName, FilePaths.fullSvarFilePath, timeStep, 1); - if (!FilePaths.fullSvarFile2Path.equals("")){ - DssOperation.getSVTimeseries(tsName, FilePaths.fullSvarFile2Path, timeStep, 2); - } - String entryNameTS=DssOperation.entryNameTS(tsName, timeStep); - DataTimeSeries.lookSvDss.add(entryNameTS); - } - } - } - System.out.println("Timeseries Reading Done."); - } -} +package wrimsv2.debug; + +import hec.heclib.dss.HecDss; +import hec.heclib.dss.HecDssCatalog; + +import java.io.File; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.External; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.Timeseries; +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; +import wrimsv2.evaluator.CondensedReferenceCacheAndRead; +import wrimsv2.evaluator.DataTimeSeries; +import wrimsv2.evaluator.DssDataSetFixLength; +import wrimsv2.evaluator.DssOperation; +import wrimsv2.external.LoadAllDll; + +public class ReLoadSVDss { + public ReLoadSVDss(StudyDataSet sds){ + ControlData.currStudyDataSet=sds; + + if (!(new File(FilePaths.fullSvarFilePath)).exists()){ + System.out.println("Error: Svar file "+ FilePaths.fullSvarFilePath+" doesn't exist."); + System.out.println("=======Run Complete Unsuccessfully======="); + System.exit(0); + } + try { + HecDssCatalog catalog = new HecDssCatalog(FilePaths.fullSvarFilePath); + ControlData.cacheSvar = CondensedReferenceCacheAndRead.createCondensedCache(FilePaths.fullSvarFilePath, "*"); + if (!FilePaths.fullSvarFile2Path.equals("")){ + HecDssCatalog catalog2 = new HecDssCatalog(FilePaths.fullSvarFile2Path); + ControlData.cacheSvar2 = CondensedReferenceCacheAndRead.createCondensedCache(FilePaths.fullSvarFile2Path, "*"); + } + ControlData.allTsMap=sds.getTimeseriesMap(); + readTimeseries(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void readTimeseries(){ + Map tsMap=ControlData.currStudyDataSet.getTimeseriesMap(); + Map> tsTimeStepMap=ControlData.currStudyDataSet.getTimeseriesTimeStepMap(); + ControlData.currEvalTypeIndex=6; + Set tsKeySet=tsMap.keySet(); + Iterator iterator=tsKeySet.iterator(); + while(iterator.hasNext()){ + String tsName=(String)iterator.next(); + //System.out.println("Reading svar timeseries "+tsName); + //To Do: in the svar class, add flag to see if svTS has been loaded + if (!DataTimeSeries.lookSvDss.contains(tsName)){ + ArrayList timeStepList=tsTimeStepMap.get(tsName); + for (String timeStep:timeStepList){ + DssOperation.getSVTimeseries(tsName, FilePaths.fullSvarFilePath, timeStep, 1); + if (!FilePaths.fullSvarFile2Path.equals("")){ + DssOperation.getSVTimeseries(tsName, FilePaths.fullSvarFile2Path, timeStep, 2); + } + String entryNameTS=DssOperation.entryNameTS(tsName, timeStep); + DataTimeSeries.lookSvDss.add(entryNameTS); + } + } + } + System.out.println("Timeseries Reading Done."); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/debug/ReProcessExternal.java b/wrims-core/src/main/java/wrimsv2/debug/ReProcessExternal.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/debug/ReProcessExternal.java rename to wrims-core/src/main/java/wrimsv2/debug/ReProcessExternal.java index bb164b689..71524fce3 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/debug/ReProcessExternal.java +++ b/wrims-core/src/main/java/wrimsv2/debug/ReProcessExternal.java @@ -1,43 +1,43 @@ -package wrimsv2.debug; - -import java.util.ArrayList; -import java.util.Map; - -import wrimsv2.commondata.wresldata.External; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.components.ControlData; -import wrimsv2.external.LoadAllDll; - -public class ReProcessExternal { - public ReProcessExternal(StudyDataSet sds){ - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - for (int i=0; i exList = mds.exList; - Map exMap =mds.exMap; - ControlData.currExMap=exMap; - ControlData.currEvalTypeIndex=4; - for (String exName: exList){ - if (!ControlData.allExternalFunction.containsKey(exName)){ - ControlData.currEvalName=exName; - External external=exMap.get(exName); - ControlData.allExternalFunction.put(exName, external.type); - if (external.type.endsWith(".dll") && !ControlData.allDll.contains(exName)){ - ControlData.allDll.add(external.type); - } - } - } - new LoadAllDll(ControlData.allDll); - } -} +package wrimsv2.debug; + +import java.util.ArrayList; +import java.util.Map; + +import wrimsv2.commondata.wresldata.External; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.components.ControlData; +import wrimsv2.external.LoadAllDll; + +public class ReProcessExternal { + public ReProcessExternal(StudyDataSet sds){ + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + for (int i=0; i exList = mds.exList; + Map exMap =mds.exMap; + ControlData.currExMap=exMap; + ControlData.currEvalTypeIndex=4; + for (String exName: exList){ + if (!ControlData.allExternalFunction.containsKey(exName)){ + ControlData.currEvalName=exName; + External external=exMap.get(exName); + ControlData.allExternalFunction.put(exName, external.type); + if (external.type.endsWith(".dll") && !ControlData.allDll.contains(exName)){ + ControlData.allDll.add(external.type); + } + } + } + new LoadAllDll(ControlData.allDll); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/AssignPastCycleVariable.java b/wrims-core/src/main/java/wrimsv2/evaluator/AssignPastCycleVariable.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/AssignPastCycleVariable.java rename to wrims-core/src/main/java/wrimsv2/evaluator/AssignPastCycleVariable.java index f416797d4..e3b9a8a13 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/AssignPastCycleVariable.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/AssignPastCycleVariable.java @@ -1,111 +1,111 @@ -package wrimsv2.evaluator; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.components.ControlData; -import wrimsv2.components.Error; -import wrimsv2.components.IntDouble; - -public class AssignPastCycleVariable { - - private ArrayList modelList; - private Map mdsMap; - private Map> varCycleValueMap; - private String cycleName; - - - public AssignPastCycleVariable(){ - StudyDataSet sds = ControlData.currStudyDataSet; - mdsMap=sds.getModelDataSetMap(); - modelList=sds.getModelList(); - varCycleValueMap=sds.getVarCycleValueMap(); - cycleName=ControlData.currCycleName; - - assignSvar(); - assignAlias(); - assignDvar(); - } - - public void assignSvar(){ - Set svarUsedByLaterCycle = ControlData.currModelDataSet.svarUsedByLaterCycle; - Iterator iterator = svarUsedByLaterCycle.iterator(); - while (iterator.hasNext()){ - String svName=(String)iterator.next(); - boolean isAssigned=false; - int i=ControlData.currCycleIndex-1; - while (!isAssigned && i>=0){ - ModelDataSet mds = mdsMap.get(modelList.get(i)); - Map svMap = mds.svMap; - if (svMap.containsKey(svName)){ - IntDouble id=svMap.get(svName).getData(); - if (id !=null){ - varCycleValueMap.get(svName).put(cycleName, id); - isAssigned=true; - } - } - i=i-1; - } - if (!isAssigned){ - varCycleValueMap.get(svName).put(cycleName, null); - } - } - } - - public void assignAlias(){ - Set aliasUsedByLaterCycle = ControlData.currModelDataSet.aliasUsedByLaterCycle; - Iterator iterator = aliasUsedByLaterCycle.iterator(); - while (iterator.hasNext()){ - String asName=(String)iterator.next(); - boolean isAssigned=false; - int i=ControlData.currCycleIndex-1; - while (!isAssigned && i>=0){ - ModelDataSet mds = mdsMap.get(modelList.get(i)); - Map asMap = mds.asMap; - if (asMap.containsKey(asName)){ - IntDouble id=asMap.get(asName).getData(); - if (id !=null){ - varCycleValueMap.get(asName).put(cycleName, id); - isAssigned=true; - } - } - i=i-1; - } - if (!isAssigned){ - varCycleValueMap.get(asName).put(cycleName, null); - } - } - } - - public void assignDvar(){ - Set dvarUsedByLaterCycle = ControlData.currModelDataSet.dvarUsedByLaterCycle; - Iterator iterator = dvarUsedByLaterCycle.iterator(); - while (iterator.hasNext()){ - String dvName=(String)iterator.next(); - boolean isAssigned=false; - int i=ControlData.currCycleIndex-1; - while (!isAssigned && i>=0){ - ModelDataSet mds = mdsMap.get(modelList.get(i)); - Map dvMap = mds.dvMap; - if (dvMap.containsKey(dvName)){ - IntDouble id=dvMap.get(dvName).getData(); - if (id !=null){ - varCycleValueMap.get(dvName).put(cycleName, id); - isAssigned=true; - } - } - i=i-1; - } - if (!isAssigned){ - varCycleValueMap.get(dvName).put(cycleName, null); - } - } - } -} +package wrimsv2.evaluator; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.components.ControlData; +import wrimsv2.components.Error; +import wrimsv2.components.IntDouble; + +public class AssignPastCycleVariable { + + private ArrayList modelList; + private Map mdsMap; + private Map> varCycleValueMap; + private String cycleName; + + + public AssignPastCycleVariable(){ + StudyDataSet sds = ControlData.currStudyDataSet; + mdsMap=sds.getModelDataSetMap(); + modelList=sds.getModelList(); + varCycleValueMap=sds.getVarCycleValueMap(); + cycleName=ControlData.currCycleName; + + assignSvar(); + assignAlias(); + assignDvar(); + } + + public void assignSvar(){ + Set svarUsedByLaterCycle = ControlData.currModelDataSet.svarUsedByLaterCycle; + Iterator iterator = svarUsedByLaterCycle.iterator(); + while (iterator.hasNext()){ + String svName=(String)iterator.next(); + boolean isAssigned=false; + int i=ControlData.currCycleIndex-1; + while (!isAssigned && i>=0){ + ModelDataSet mds = mdsMap.get(modelList.get(i)); + Map svMap = mds.svMap; + if (svMap.containsKey(svName)){ + IntDouble id=svMap.get(svName).getData(); + if (id !=null){ + varCycleValueMap.get(svName).put(cycleName, id); + isAssigned=true; + } + } + i=i-1; + } + if (!isAssigned){ + varCycleValueMap.get(svName).put(cycleName, null); + } + } + } + + public void assignAlias(){ + Set aliasUsedByLaterCycle = ControlData.currModelDataSet.aliasUsedByLaterCycle; + Iterator iterator = aliasUsedByLaterCycle.iterator(); + while (iterator.hasNext()){ + String asName=(String)iterator.next(); + boolean isAssigned=false; + int i=ControlData.currCycleIndex-1; + while (!isAssigned && i>=0){ + ModelDataSet mds = mdsMap.get(modelList.get(i)); + Map asMap = mds.asMap; + if (asMap.containsKey(asName)){ + IntDouble id=asMap.get(asName).getData(); + if (id !=null){ + varCycleValueMap.get(asName).put(cycleName, id); + isAssigned=true; + } + } + i=i-1; + } + if (!isAssigned){ + varCycleValueMap.get(asName).put(cycleName, null); + } + } + } + + public void assignDvar(){ + Set dvarUsedByLaterCycle = ControlData.currModelDataSet.dvarUsedByLaterCycle; + Iterator iterator = dvarUsedByLaterCycle.iterator(); + while (iterator.hasNext()){ + String dvName=(String)iterator.next(); + boolean isAssigned=false; + int i=ControlData.currCycleIndex-1; + while (!isAssigned && i>=0){ + ModelDataSet mds = mdsMap.get(modelList.get(i)); + Map dvMap = mds.dvMap; + if (dvMap.containsKey(dvName)){ + IntDouble id=dvMap.get(dvName).getData(); + if (id !=null){ + varCycleValueMap.get(dvName).put(cycleName, id); + isAssigned=true; + } + } + i=i-1; + } + if (!isAssigned){ + varCycleValueMap.get(dvName).put(cycleName, null); + } + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/CondensedReferenceCacheAndRead.java b/wrims-core/src/main/java/wrimsv2/evaluator/CondensedReferenceCacheAndRead.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/CondensedReferenceCacheAndRead.java rename to wrims-core/src/main/java/wrimsv2/evaluator/CondensedReferenceCacheAndRead.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/CsvOperation.java b/wrims-core/src/main/java/wrimsv2/evaluator/CsvOperation.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/CsvOperation.java rename to wrims-core/src/main/java/wrimsv2/evaluator/CsvOperation.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/DataTimeSeries.java b/wrims-core/src/main/java/wrimsv2/evaluator/DataTimeSeries.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/DataTimeSeries.java rename to wrims-core/src/main/java/wrimsv2/evaluator/DataTimeSeries.java index 70291607b..b5c601a42 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/DataTimeSeries.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/DataTimeSeries.java @@ -1,70 +1,70 @@ -package wrimsv2.evaluator; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; - -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.components.ControlData; - -public class DataTimeSeries { - public static HashMap svTS = new HashMap (); - public static HashMap dvAliasTS = new HashMap (); - public static ArrayList> dvAliasTSCycles = new ArrayList> (); - public static HashMap svInit = new HashMap (); - public static HashMap dvAliasInit = new HashMap (); - public static ArrayList lookSvDss=new ArrayList(); - public static ArrayList lookInitDss=new ArrayList(); - - public static void saveDataToTimeSeries(String dvName, String entryNameTS, double value, Dvar dvar){ - saveDataToTimeSeries(entryNameTS, value, dvar, 0); - if (dvName.contains("__fut__")){ - String[] dvNameParts = dvName.split("__fut__"); - if (dvNameParts.length==2){ - try{ - int offset=Integer.parseInt(dvNameParts[1]); - String newEntryNameTS=DssOperation.entryNameTS(dvNameParts[0], ControlData.timeStep); - saveDataToTimeSeries(newEntryNameTS, value, dvar, offset); - }catch(NumberFormatException e){ - } - } - } - } - - public static void saveDataToTimeSeries(String entryNameTS, double value, Dvar dvar, int offset){ - if (!dvAliasTS.containsKey(entryNameTS)){ - DssDataSetFixLength dds=new DssDataSetFixLength(); - double[] data=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; - dds.setData(data); - dds.setTimeStep(ControlData.partE); - dds.setStartTime(ControlData.memStartDate); - dds.setUnits(dvar.units); - dds.setKind(dvar.kind); - dvAliasTS.put(entryNameTS,dds); - } - DssDataSetFixLength ddsfl = dvAliasTS.get(entryNameTS); - double[] dataList=ddsfl.getData(); - //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=id.getData().doubleValue(); - Date memStartDate = ddsfl.getStartTime(); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())-1+offset; - if (index dvAliasTSCycle = dvAliasTSCycles.get(cycleIndex); - if (!dvAliasTSCycle.containsKey(entryNameTS)){ - DssDataSetFixLength dds1=new DssDataSetFixLength(); - double[] data1=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; - dds1.setData(data1); - dds1.setTimeStep(ControlData.partE); - dds1.setStartTime(ControlData.memStartDate); - dds1.setUnits(dvar.units); - dds1.setKind(dvar.kind); - dvAliasTSCycle.put(entryNameTS,dds1); - } - double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); - if (index svTS = new HashMap (); + public static HashMap dvAliasTS = new HashMap (); + public static ArrayList> dvAliasTSCycles = new ArrayList> (); + public static HashMap svInit = new HashMap (); + public static HashMap dvAliasInit = new HashMap (); + public static ArrayList lookSvDss=new ArrayList(); + public static ArrayList lookInitDss=new ArrayList(); + + public static void saveDataToTimeSeries(String dvName, String entryNameTS, double value, Dvar dvar){ + saveDataToTimeSeries(entryNameTS, value, dvar, 0); + if (dvName.contains("__fut__")){ + String[] dvNameParts = dvName.split("__fut__"); + if (dvNameParts.length==2){ + try{ + int offset=Integer.parseInt(dvNameParts[1]); + String newEntryNameTS=DssOperation.entryNameTS(dvNameParts[0], ControlData.timeStep); + saveDataToTimeSeries(newEntryNameTS, value, dvar, offset); + }catch(NumberFormatException e){ + } + } + } + } + + public static void saveDataToTimeSeries(String entryNameTS, double value, Dvar dvar, int offset){ + if (!dvAliasTS.containsKey(entryNameTS)){ + DssDataSetFixLength dds=new DssDataSetFixLength(); + double[] data=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; + dds.setData(data); + dds.setTimeStep(ControlData.partE); + dds.setStartTime(ControlData.memStartDate); + dds.setUnits(dvar.units); + dds.setKind(dvar.kind); + dvAliasTS.put(entryNameTS,dds); + } + DssDataSetFixLength ddsfl = dvAliasTS.get(entryNameTS); + double[] dataList=ddsfl.getData(); + //dataList[ControlData.currTimeStep.get(ControlData.currCycleIndex)]=id.getData().doubleValue(); + Date memStartDate = ddsfl.getStartTime(); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())-1+offset; + if (index dvAliasTSCycle = dvAliasTSCycles.get(cycleIndex); + if (!dvAliasTSCycle.containsKey(entryNameTS)){ + DssDataSetFixLength dds1=new DssDataSetFixLength(); + double[] data1=new double[ControlData.totalTimeStep.get(ControlData.currCycleIndex)]; + dds1.setData(data1); + dds1.setTimeStep(ControlData.partE); + dds1.setStartTime(ControlData.memStartDate); + dds1.setUnits(dvar.units); + dds1.setKind(dvar.kind); + dvAliasTSCycle.put(entryNameTS,dds1); + } + double[] dataList1=dvAliasTSCycle.get(entryNameTS).getData(); + if (index data; - private String timeStep; - private String units; - private String convertToUnits=""; - private String kind; - private Date startTime; - private boolean fromDssFile=false; - private int studyStartIndex=-1; - private static HashMap selDataMap=new HashMap(); - - public void setData(ArrayList data){ - this.data=data; - } - - public ArrayList getData(){ - return data; - } - - public void setTimeStep(String timeStep){ - this.timeStep=timeStep; - } - - public void setStartTime(Date st){ - startTime=st; - } - - public Date getStartTime(){ - return startTime; - } - - public String getTimeStep(){ - return timeStep; - } - - public boolean fromDssFile(){ - return fromDssFile; - } - - public void setFromDssFile(boolean fromDssFile){ - this.fromDssFile=fromDssFile; - } - - public void setUnits(String units){ - this.units=units; - } - - public String getConvertToUnits(){ - return convertToUnits; - } - - public void setConvertToUnits(String convertToUnits){ - this.convertToUnits=convertToUnits; - } - - public String getUnits(){ - return units; - } - - public void setKind(String kind){ - this.kind=kind; - } - - public String getKind(){ - return kind; - } - - public void generateStudyStartIndex(){ - Date st=getStartTime(); - //long sTime=st.getTime(); - int sYear=st.getYear()+1900; - int sMonth=st.getMonth()+1; //Originally it should be getMonth()-1. However, dss data store at 24:00 Jan31, 1921 is considered to store at 0:00 Feb 1, 1921 - Date studyStart=new Date(ControlData.startYear-1900, ControlData.startMonth-1, ControlData.startDay); - if (getTimeStep().equals("1MON")){ - studyStartIndex=ControlData.startYear*12+ControlData.startMonth-(sYear*12+sMonth); - }else{ - //double indexValue=(studyStartTime-sTime)/(1000*60*60*24); - Calendar c1=Calendar.getInstance(); - c1.setTime(st); - Calendar c2=Calendar.getInstance(); - c2.setTime(studyStart); - long indexValue = Duration.between(c1.toInstant(), c2.toInstant()).toDays(); - studyStartIndex=(int)indexValue+1; - } - } - - public int getStudyStartIndex(){ - return studyStartIndex; - } - - public ArrayList getTimeseriesDataWithOptions(String selMon, Date selSd, Date selEd){ - ArrayList selData=new ArrayList(); - selDataMap=new HashMap(); - String m1="all"; - String m2="all"; - double sum=0; - if (selMon.length()==3){ - m1=selMon; - m2=selMon; - }else{ - m1=selMon.substring(0, 3); - m2=selMon.substring(3); - } - Date dataDate = startTime; - if (timeStep.equals("1MON")){ - dataDate=TimeOperation.backOneMonth(dataDate); - }else{ - dataDate=TimeOperation.backOneDay(dataDate); - } - Date entryDate=dataDate; - for (int i=0; i optedData, double exc) { - int size = optedData.size(); - if (size==0){ - Error.addEvaluationError("The data in the specified time period and selected month(s) from the timeseries doesn't exist in the Exceedance function."); - return 1.0; - } - Double[] values =optedData.toArray(new Double[size]); - Arrays.sort(values); - if (exc==1){ - return values[0]; - } - double excIndex = (1.0-exc)*size; - if (excIndex>=1.0){ - int index = (int) Math.floor(excIndex); - double fract = excIndex-index; - double value = values[index-1]+fract*(values[index]-values[index-1]); - return value; - }else{ - double value=values[0]-(1.0-excIndex)*(values[1]-values[0]); - return value; - } - } - - public static int getExceedance_tsi(ArrayList optedData, double exc) { - int size = optedData.size(); - if (size==0){ - Error.addEvaluationError("The data in the specified time period and selected month(s) from the timeseries doesn't exist in the Exceedance function."); - return 0; - } - Double[] values =optedData.toArray(new Double[size]); - Arrays.sort(values); - double excIndex = (1.0-exc)*size; - int index=(int)Math.round(excIndex)-1; - if (index<0) index=0; - Date dataDate=selDataMap.get(values[index]); - int dataYear=dataDate.getYear()+1900; - int dataMonth=dataDate.getMonth()+1; //HEC DSS7 uses getMonth()+1. However, Vista/HecDSS6 uses getMonth() because dss data store at 24:00 Jan31, 1921 is considered to store at 0:00 Feb 1, 1921 - int dataDay = dataDate.getDate(); - if (ControlData.timeStep.equals("1MON")){ - return (dataYear-ControlData.currYear)*12+(dataMonth-ControlData.currMonth); - }else{ - Date currDate=new Date (ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - //long dataTime=dataDate.getTime(); - //long currTime=currDate.getTime(); - //double tsi=(dataTime-currTime)/(24*60*60*1000l); - Calendar c1=Calendar.getInstance(); - c1.setTime(currDate); - Calendar c2=Calendar.getInstance(); - c2.setTime(dataDate); - long tsi = Duration.between(c1.toInstant(), c2.toInstant()).toDays(); - return (int)tsi; - } - - } -} +package wrimsv2.evaluator; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; + +import wrimsv2.components.ControlData; +import wrimsv2.components.Error; +import wrimsv2.components.IntDouble; + +public class DssDataSet { + private ArrayList data; + private String timeStep; + private String units; + private String convertToUnits=""; + private String kind; + private Date startTime; + private boolean fromDssFile=false; + private int studyStartIndex=-1; + private static HashMap selDataMap=new HashMap(); + + public void setData(ArrayList data){ + this.data=data; + } + + public ArrayList getData(){ + return data; + } + + public void setTimeStep(String timeStep){ + this.timeStep=timeStep; + } + + public void setStartTime(Date st){ + startTime=st; + } + + public Date getStartTime(){ + return startTime; + } + + public String getTimeStep(){ + return timeStep; + } + + public boolean fromDssFile(){ + return fromDssFile; + } + + public void setFromDssFile(boolean fromDssFile){ + this.fromDssFile=fromDssFile; + } + + public void setUnits(String units){ + this.units=units; + } + + public String getConvertToUnits(){ + return convertToUnits; + } + + public void setConvertToUnits(String convertToUnits){ + this.convertToUnits=convertToUnits; + } + + public String getUnits(){ + return units; + } + + public void setKind(String kind){ + this.kind=kind; + } + + public String getKind(){ + return kind; + } + + public void generateStudyStartIndex(){ + Date st=getStartTime(); + //long sTime=st.getTime(); + int sYear=st.getYear()+1900; + int sMonth=st.getMonth()+1; //Originally it should be getMonth()-1. However, dss data store at 24:00 Jan31, 1921 is considered to store at 0:00 Feb 1, 1921 + Date studyStart=new Date(ControlData.startYear-1900, ControlData.startMonth-1, ControlData.startDay); + if (getTimeStep().equals("1MON")){ + studyStartIndex=ControlData.startYear*12+ControlData.startMonth-(sYear*12+sMonth); + }else{ + //double indexValue=(studyStartTime-sTime)/(1000*60*60*24); + Calendar c1=Calendar.getInstance(); + c1.setTime(st); + Calendar c2=Calendar.getInstance(); + c2.setTime(studyStart); + long indexValue = Duration.between(c1.toInstant(), c2.toInstant()).toDays(); + studyStartIndex=(int)indexValue+1; + } + } + + public int getStudyStartIndex(){ + return studyStartIndex; + } + + public ArrayList getTimeseriesDataWithOptions(String selMon, Date selSd, Date selEd){ + ArrayList selData=new ArrayList(); + selDataMap=new HashMap(); + String m1="all"; + String m2="all"; + double sum=0; + if (selMon.length()==3){ + m1=selMon; + m2=selMon; + }else{ + m1=selMon.substring(0, 3); + m2=selMon.substring(3); + } + Date dataDate = startTime; + if (timeStep.equals("1MON")){ + dataDate=TimeOperation.backOneMonth(dataDate); + }else{ + dataDate=TimeOperation.backOneDay(dataDate); + } + Date entryDate=dataDate; + for (int i=0; i optedData, double exc) { + int size = optedData.size(); + if (size==0){ + Error.addEvaluationError("The data in the specified time period and selected month(s) from the timeseries doesn't exist in the Exceedance function."); + return 1.0; + } + Double[] values =optedData.toArray(new Double[size]); + Arrays.sort(values); + if (exc==1){ + return values[0]; + } + double excIndex = (1.0-exc)*size; + if (excIndex>=1.0){ + int index = (int) Math.floor(excIndex); + double fract = excIndex-index; + double value = values[index-1]+fract*(values[index]-values[index-1]); + return value; + }else{ + double value=values[0]-(1.0-excIndex)*(values[1]-values[0]); + return value; + } + } + + public static int getExceedance_tsi(ArrayList optedData, double exc) { + int size = optedData.size(); + if (size==0){ + Error.addEvaluationError("The data in the specified time period and selected month(s) from the timeseries doesn't exist in the Exceedance function."); + return 0; + } + Double[] values =optedData.toArray(new Double[size]); + Arrays.sort(values); + double excIndex = (1.0-exc)*size; + int index=(int)Math.round(excIndex)-1; + if (index<0) index=0; + Date dataDate=selDataMap.get(values[index]); + int dataYear=dataDate.getYear()+1900; + int dataMonth=dataDate.getMonth()+1; //HEC DSS7 uses getMonth()+1. However, Vista/HecDSS6 uses getMonth() because dss data store at 24:00 Jan31, 1921 is considered to store at 0:00 Feb 1, 1921 + int dataDay = dataDate.getDate(); + if (ControlData.timeStep.equals("1MON")){ + return (dataYear-ControlData.currYear)*12+(dataMonth-ControlData.currMonth); + }else{ + Date currDate=new Date (ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + //long dataTime=dataDate.getTime(); + //long currTime=currDate.getTime(); + //double tsi=(dataTime-currTime)/(24*60*60*1000l); + Calendar c1=Calendar.getInstance(); + c1.setTime(currDate); + Calendar c2=Calendar.getInstance(); + c2.setTime(dataDate); + long tsi = Duration.between(c1.toInstant(), c2.toInstant()).toDays(); + return (int)tsi; + } + + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/DssDataSetFixLength.java b/wrims-core/src/main/java/wrimsv2/evaluator/DssDataSetFixLength.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/DssDataSetFixLength.java rename to wrims-core/src/main/java/wrimsv2/evaluator/DssDataSetFixLength.java index b054b37d6..96f3504bc 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/DssDataSetFixLength.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/DssDataSetFixLength.java @@ -1,61 +1,61 @@ -package wrimsv2.evaluator; - -import java.util.ArrayList; -import java.util.Date; - -public class DssDataSetFixLength { - public double[] data; - private String timeStep; - private String units; - private String kind; - private Date startTime; - private boolean fromDssFile=false; - - public void setData(double[] data){ - this.data=data; - } - - public double[] getData(){ - return data; - } - - public void setTimeStep(String timeStep){ - this.timeStep=timeStep; - } - - public void setStartTime(Date st){ - startTime=st; - } - - public Date getStartTime(){ - return startTime; - } - - public String getTimeStep(){ - return timeStep; - } - - public boolean fromDssFile(){ - return fromDssFile; - } - - public void setFromDssFile(boolean fromDssFile){ - this.fromDssFile=fromDssFile; - } - - public void setUnits(String units){ - this.units=units; - } - - public String getUnits(){ - return units; - } - - public void setKind(String kind){ - this.kind=kind; - } - - public String getKind(){ - return kind; - } -} +package wrimsv2.evaluator; + +import java.util.ArrayList; +import java.util.Date; + +public class DssDataSetFixLength { + public double[] data; + private String timeStep; + private String units; + private String kind; + private Date startTime; + private boolean fromDssFile=false; + + public void setData(double[] data){ + this.data=data; + } + + public double[] getData(){ + return data; + } + + public void setTimeStep(String timeStep){ + this.timeStep=timeStep; + } + + public void setStartTime(Date st){ + startTime=st; + } + + public Date getStartTime(){ + return startTime; + } + + public String getTimeStep(){ + return timeStep; + } + + public boolean fromDssFile(){ + return fromDssFile; + } + + public void setFromDssFile(boolean fromDssFile){ + this.fromDssFile=fromDssFile; + } + + public void setUnits(String units){ + this.units=units; + } + + public String getUnits(){ + return units; + } + + public void setKind(String kind){ + this.kind=kind; + } + + public String getKind(){ + return kind; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/DssOperation.java b/wrims-core/src/main/java/wrimsv2/evaluator/DssOperation.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/DssOperation.java rename to wrims-core/src/main/java/wrimsv2/evaluator/DssOperation.java index 48ac087b1..e6493f499 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/DssOperation.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/DssOperation.java @@ -1,918 +1,911 @@ -package wrimsv2.evaluator; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.commondata.wresldata.Timeseries; -import wrimsv2.components.ControlData; -import wrimsv2.components.Error; -import wrimsv2.components.FilePaths; -import wrimsv2.hdf5.HDF5Reader; -import wrimsv2.parallel.ParallelVars; -import wrimsv2.tools.General; -import hec.heclib.dss.DSSPathname; -import hec.heclib.dss.HecDss; -import hec.heclib.dss.HecTimeSeries; -import hec.heclib.util.HecTime; -import hec.heclib.util.doubleArrayContainer; -import hec.io.TimeSeriesContainer; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import com.esotericsoftware.kryo.util.IdentityMap.Values; -import com.google.common.primitives.Doubles; - -public class DssOperation { - - private static int savedStartMonthlyTimestep; - private static int savedEndMonthlyTimestep; - private static int totalSavedMonthlyTimestep; - private static int savedStartDailyTimestep; - private static int savedEndDailyTimestep; - private static int totalSavedDailyTimestep; - - public static boolean getSVTimeseries(String name, String file, String timeStep, int svFileIndex){ - ControlData.timeStep=timeStep; - ControlData.partE=timeStep; - Timeseries ts=ControlData.allTsMap.get(name); - String partC=ts.kind; - HecTimeSeries hts=getDataForSvar(ControlData.partA.toUpperCase(),ts.dssBPart.toUpperCase(),partC.toUpperCase(),"",timeStep.toUpperCase(), ControlData.svDvPartF.toUpperCase(), svFileIndex, file); - - if (hts==null){ - return false; - } - if (!hts.units().toUpperCase().equals(ts.units.toUpperCase())){ - return false; - } - /* - if (!(hts instanceof RegularTimeSeries)){ - return false; - } - RegularTimeSeries rts=(RegularTimeSeries)ds; - */ - - DssDataSet dds= new DssDataSet(); - ArrayList dataArray= new ArrayList(); - HecTime startTime=hts.startTime(); - int year=startTime.year(); - int month=startTime.month(); - int day = startTime.day(); - doubleArrayContainer values=new doubleArrayContainer(); - hts.getData(values); - if (ts.units.equals("taf") && ts.convertToUnits.equals("cfs")){ - int i=0; - for (double dataEntry : values.array){ - if (dataEntry==-901.0){ - dataArray.add(-901.0); - }else if (dataEntry==-902.0){ - dataArray.add(-902.0); - }else{ - ParallelVars prvs = TimeOperation.findTime(i, year, month, day); - double dataEntryValue=dataEntry*Evaluation.tafcfs("taf_cfs", prvs); - dataArray.add(dataEntryValue); - } - i=i+1; - } - }else if (ts.units.equals("cfs") && ts.convertToUnits.equals("taf")){ - int i=0; - for (double dataEntry : values.array){ - if (dataEntry==-901.0){ - dataArray.add(-901.0); - }else if (dataEntry==-902.0){ - dataArray.add(-902.0); - }else{ - ParallelVars prvs = TimeOperation.findTime(i, year, month, day); - double dataEntryValue=dataEntry*Evaluation.tafcfs("cfs_taf", prvs); - dataArray.add(dataEntryValue); - } - i=i+1; - } - }else{ - for (double dataEntry : values.array){ - dataArray.add(dataEntry); - } - } - dds.setUnits(ts.units); - dds.setConvertToUnits(ts.convertToUnits); - dds.setKind(partC); - dds.setData(dataArray); - dds.setTimeStep(timeStep); - Date startDate=new Date(year-1900, month-1, day); - dds.setStartTime(startDate); - dds.setFromDssFile(true); - dds.generateStudyStartIndex(); - String entryNameTS=DssOperation.entryNameTS(name, timeStep); - DataTimeSeries.svTS.put(entryNameTS, dds); - return true; - } - - public static boolean getSVInitTimeseries(String name){ - - Timeseries ts=ControlData.currTsMap.get(name); - if (ts==null){ - return false; - } - String partC=ts.kind; - HecTimeSeries hts=getDataForInitial(ControlData.partA.toUpperCase(),ts.dssBPart.toUpperCase(),partC.toUpperCase(),"",ControlData.partE.toUpperCase(), ControlData.initPartF.toUpperCase()); - - if (hts==null){ - return false; - } - if (!hts.units().toUpperCase().equals(ts.units.toUpperCase())){ - return false; - } - /* - if (!(ds instanceof RegularTimeSeries)){ - return false; - } - RegularTimeSeries rts=(RegularTimeSeries)ds; - */ - DssDataSet dds= new DssDataSet(); - ArrayList dataArray= new ArrayList(); - HecTime startTime=hts.startTime(); - int year=startTime.year(); - int month=startTime.month(); - int day = startTime.day(); - Date startDate=new Date(year-1900, month-1, day); - doubleArrayContainer values=new doubleArrayContainer(); - hts.getData(values); - if (ts.units.equals("taf") && ts.convertToUnits.equals("cfs")){ - ParallelVars prvs = new ParallelVars(); - prvs.dataYear=year; - prvs.dataMonth=month; - prvs.dataDay=day; - int i=0; - for (double dataEntry : values.array){ - if (dataEntry==-901.0){ - dataArray.add(-901.0); - }else if (dataEntry==-902.0){ - dataArray.add(-902.0); - }else{ - TimeOperation.findTime(i); - dataArray.add(dataEntry*Evaluation.tafcfs("taf_cfs", prvs)); - } - i=i+1; - } - }else if (ts.units.equals("cfs") && ts.convertToUnits.equals("taf")){ - ParallelVars prvs = new ParallelVars(); - prvs.dataYear=year; - prvs.dataMonth=month; - prvs.dataDay=day; - int i=0; - for (double dataEntry : values.array){ - if (dataEntry==-901.0){ - dataArray.add(-901.0); - }else if (dataEntry==-902.0){ - dataArray.add(-902.0); - }else{ - TimeOperation.findTime(i); - dataArray.add(dataEntry*Evaluation.tafcfs("cfs_taf", prvs)); - } - i=i+1; - } - }else{ - for (double dataEntry : values.array){ - dataArray.add(dataEntry); - } - } - dds.setUnits(ts.units); - dds.setConvertToUnits(ts.convertToUnits); - dds.setKind(ts.kind); - dds.setData(dataArray); - dds.setTimeStep(ControlData.partE.toUpperCase()); - dds.setStartTime(startDate); - String entryNameTS=DssOperation.entryNameTS(name, ControlData.timeStep); - DataTimeSeries.svInit.put(entryNameTS, dds); - return true; - } - - public static String regularExp(String part){ - return "^"+part+"$"; - } - - public static boolean getDVAliasInitTimeseries(String name){ - String units; - String partC; - if (ControlData.currDvMap.containsKey(name)){ - Dvar dvar=ControlData.currDvMap.get(name); - partC=dvar.kind; - units=dvar.units; - }else{ - Alias alias=ControlData.currAliasMap.get(name); - partC=alias.kind; - units=alias.units; - } - - HecTimeSeries hts=getDataForInitial(ControlData.partA.toUpperCase(),name.toUpperCase(),partC.toUpperCase(),"",ControlData.partE.toUpperCase(), ControlData.initPartF.toUpperCase()); - if (hts==null){ - Error.addEvaluationError("Intial data of "+name+" in dss file doesn't exist." ); - return false; - } - if (!units.toUpperCase().equals(hts.units().toUpperCase())){ - return false; - } - /* - if (!(ds instanceof RegularTimeSeries)){ - Error.addEvaluationError("Intial data of "+name+" in dss file is not a regular timeseries." ); - return false; - } - RegularTimeSeries rts=(RegularTimeSeries)ds; - */ - DssDataSet dds= new DssDataSet(); - ArrayList dataArray= new ArrayList(); - doubleArrayContainer values=new doubleArrayContainer(); - hts.getData(values); - for (double dataEntry : values.array){ - dataArray.add(dataEntry); - } - dds.setData(dataArray); - dds.setUnits(units); - dds.setKind(partC); - String timeStep=ControlData.partE.toUpperCase(); - dds.setTimeStep(timeStep); - HecTime startTime=hts.startTime(); - int year=startTime.year(); - int month=startTime.month(); - int day = startTime.day(); - Date startDate=new Date(year-1900, month-1, day); - dds.setStartTime(startDate); - String entryNameTS=DssOperation.entryNameTS(name, timeStep); - DataTimeSeries.dvAliasInit.put(entryNameTS, dds); - return true; - } - - /* - public static DataSet getDataFor(String file, String apart, String bpart, String cpart, String dpart, String epart, String fpart){ - dpart = "01JAN1920"; //To Do: this method may be removed - DataReference ref = DSSUtil.createDataReference("local",file,Pathname.createPathname(new String[]{apart, bpart, cpart, dpart, epart, fpart})); - return ref.getData(); - } - */ - - public static synchronized HecTimeSeries getDataForSvar(String apart, String bpart, String cpart, String dpart, String epart, String fpart, int svFileIndex, String filename){ - //DataReference[] refs; - String path="/"+apart+"/"+bpart+"/"+cpart+"/"+dpart+"/"+epart+"/"+fpart+"/"; - HecTimeSeries ts = new HecTimeSeries(); - DSSPathname dssPathname; - if (svFileIndex==1){ - //refs = ControlData.groupSvar.find(new String[]{apart, bpart, cpart, dpart, epart, fpart}); - dssPathname = ControlData.cacheSvar.getNominalPathname(path); - }else{ - //refs = ControlData.groupSvar2.find(new String[]{apart, bpart, cpart, dpart, epart, fpart}); - dssPathname = ControlData.cacheSvar2.getNominalPathname(path); - } - if (dssPathname==null){ - return null; - }else{ - TimeSeriesContainer tsc = new TimeSeriesContainer(); - tsc.fileName = filename; - tsc.fullName = dssPathname.pathname(); - boolean removeMissing = false; - ts.read(tsc, removeMissing); - ts.setUnits(tsc.units); - return ts; - } - /* - if (refs.length==0){ - return null; - } else { - return refs[0].getData(); - } - */ - } - - public static HecTimeSeries getDataForInitial(String apart, String bpart, String cpart, String dpart, String epart, String fpart){ - String path="/"+apart+"/"+bpart+"/"+cpart+"/"+dpart+"/"+epart+"/"+fpart+"/"; - HecTimeSeries ts = new HecTimeSeries(); - //refs = ControlData.groupSvar.find(new String[]{apart, bpart, cpart, dpart, epart, fpart}); - DSSPathname dssPathname = ControlData.cacheInit.getNominalPathname(path); - if (dssPathname==null){ - return null; - }else{ - TimeSeriesContainer tsc = new TimeSeriesContainer(); - tsc.fileName = FilePaths.fullInitFilePath; - tsc.fullName = dssPathname.pathname(); - boolean removeMissing = false; - ts.read(tsc, removeMissing); - ts.setUnits(tsc.units); - return ts; - } - } - - public static void writeInitDvarAliasToDSS() { - System.out.println("writing initial data for dvar and alias to dv dss"); - Set initSet=DataTimeSeries.dvAliasInit.keySet(); - Iterator iterator = initSet.iterator(); - while(iterator.hasNext()){ - String initName=(String)iterator.next(); - DssDataSet dds=DataTimeSeries.dvAliasInit.get(initName); - ArrayList data=dds.getData(); - int size=data.size(); - double[] values=new double[size]; - for (int i=0; i dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(i); - Set dvAliasSet=dvAliasTSCycle.keySet(); - Iterator iterator = dvAliasSet.iterator(); - while(iterator.hasNext()){ - String dvAliasName=(String)iterator.next(); - DssDataSetFixLength ddsfl=dvAliasTSCycle.get(dvAliasName); - double[] values=ddsfl.getData(); - String timestep=ddsfl.getTimeStep(); - int size = values.length; - int nTimestep = TimeOperation.getNumberOfTimestep(ControlData.memStartDate, ControlData.prevOutputDate, timestep); - if (nTimestep<0) nTimestep=0; - double[] values1=new double[size-nTimestep]; - int size1=values1.length; - for (int j=0; j data=dds.getData(); - int size=data.size(); - double[] values=new double[size]; - for (int i=0; i data=dds.getData(); - int size=data.size(); - double[] values=new double[size]; - for (int i=0; i allTsMap = ControlData.allTsMap; - while(iterator.hasNext()){ - String initName=(String)iterator.next(); - DssDataSet dds=DataTimeSeries.svInit.get(initName); - ArrayList data=dds.getData(); - String ctu = "none"; - String units="none"; - if (allTsMap.containsKey(initName)){ - Timeseries ts=allTsMap.get(initName); - units = ts.units; - ctu=ts.convertToUnits; - } - ArrayList values=dds.getData(); - TimeSeriesContainer dc = new TimeSeriesContainer(); - //DSSData dd = new DSSData(); - //dd._dataType=DSSUtil.REGULAR_TIME_SERIES; - dc.type="PER-AVER"; - int size=values.size(); - dc.numberValues=size; - dc.units=dds.getUnits().toUpperCase(); - dc.values=new double[size]; - Date startDate=dds.getStartTime(); - Calendar startCalendar=Calendar.getInstance(); - startCalendar.setTime(startDate); - dc.setStartTime(new HecTime(startCalendar)); - startDate.setTime(startDate.getTime()-1*24*60*60); - int year=startDate.getYear()+1900; - int month=startDate.getMonth()+1; - int day=startDate.getDate(); - //String startDateStr=TimeOperation.dssTimeEndDay(year, month, day); - //long startJulmin = TimeFactory.getInstance().createTime(startDateStr).getTimeInMinutes(); - if (units.equals("taf") && ctu.equals("cfs")){ - for (int i=0; i dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(i); - Set dvAliasSet=dvAliasTSCycle.keySet(); - Iterator iterator = dvAliasSet.iterator(); - while(iterator.hasNext()){ - String dvAliasName=(String)iterator.next(); - DssDataSetFixLength ddsfl=dvAliasTSCycle.get(dvAliasName); - String timestep=ddsfl.getTimeStep(); - double[] values=ddsfl.getData(); - double[] modValues; - if (timestep.equals("1MON")){ - modValues=new double[totalSavedMonthlyTimestep]; - for (int j=savedStartMonthlyTimestep; j<=savedEndMonthlyTimestep; j++){ - modValues[j-savedStartMonthlyTimestep]=values[j]; - } - }else{ - modValues=new double[totalSavedDailyTimestep]; - for (int j=savedStartDailyTimestep; j<=savedEndDailyTimestep; j++){ - modValues[j-savedStartDailyTimestep]=values[j]; - } - } - TimeSeriesContainer dc = new TimeSeriesContainer(); - //dd._dataType=DSSUtil.REGULAR_TIME_SERIES; - dc.type="PER-AVER"; - dc.numberValues=modValues.length; - dc.units=ddsfl.getUnits().toUpperCase(); - dc.values = modValues; - //boolean storeFlags = false; - dc.setName("/"+ControlData.partA+"_Cycle"+cycleI+"/"+DssOperation.getTSName(dvAliasName)+"/"+ddsfl.getKind()+"//"+timestep+"/"+ControlData.svDvPartF+"/"); - //Date startDate=ddsfl.getStartTime(); - Date startDate=new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); - Calendar startCalendar=Calendar.getInstance(); - startCalendar.setTime(startDate); - dc.setStartTime(new HecTime(startCalendar)); - try { - dss.put(dc); - } catch (Exception e) { - e.printStackTrace(); - } - //String startDateStr=TimeOperation.dssTimeEndDay(startDate.getYear()+1900, startDate.getMonth()+1, startDate.getDate()); - //long startJulmin = TimeFactory.getInstance().createTime(startDateStr).getTimeInMinutes(); - //writer.storeTimeSeriesData(pathName, startJulmin, dd, storeFlags); - dc.values=null; - values=null; - } - } - } - System.gc(); - } - - public static void saveSvarTSData(HecDss dss, String fileName){ - System.out.println("write svar timeseries to "+fileName); - Set svTsSet=DataTimeSeries.svTS.keySet(); - Iterator iterator = svTsSet.iterator(); - Map allTsMap = ControlData.allTsMap; - while(iterator.hasNext()){ - String svTsName=(String)iterator.next(); - String svName=getTSName(svTsName); - String ctu = "none"; - String units="none"; - if (allTsMap.containsKey(svName)){ - Timeseries ts=allTsMap.get(svName); - units = ts.units; - ctu=ts.convertToUnits; - } - DssDataSet dds=DataTimeSeries.svTS.get(svTsName); - ArrayList values=dds.getData(); - //DSSData dd = new DSSData(); - //dd._dataType=DSSUtil.REGULAR_TIME_SERIES; - TimeSeriesContainer dc = new TimeSeriesContainer(); - dc.type="PER-AVER"; - int size=values.size(); - dc.numberValues=size; - dc.units=dds.getUnits().toUpperCase(); - dc.values=new double[size]; - Date startDate=dds.getStartTime(); - Calendar startCalendar=Calendar.getInstance(); - startCalendar.setTime(startDate); - dc.setStartTime(new HecTime(startCalendar)); - startDate.setTime(startDate.getTime()-1*24*60*60); - int year=startDate.getYear()+1900; - int month=startDate.getMonth()+1; - int day=startDate.getDate(); - //String startDateStr=TimeOperation.dssTimeEndDay(year, month, day); - //long startJulmin = TimeFactory.getInstance().createTime(startDateStr).getTimeInMinutes(); - if (units.equals("taf") && ctu.equals("cfs")){ - for (int i=0; i dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(i); - Set dvAliasSet=dvAliasTSCycle.keySet(); - Iterator iterator = dvAliasSet.iterator(); - while(iterator.hasNext()){ - String dvAliasName=(String)iterator.next(); - DssDataSetFixLength ddsfl=dvAliasTSCycle.get(dvAliasName); - double[] values=ddsfl.getData(); - String timestep=ddsfl.getTimeStep(); - int nTimeStep1 = TimeOperation.getNumberOfTimestep(prevMemDate, memStartDate, timestep)-1; - int nTimeStep2 = TimeOperation.getNumberOfTimestep(prevMemDate, outputDate, timestep)-1; - int size = nTimeStep2-nTimeStep1+1; - //double[] values1=new double[values.length]; - for (int j=0; j dataArray= new ArrayList(); + HecTime startTime=hts.startTime(); + int year=startTime.year(); + int month=startTime.month(); + int day = startTime.day(); + doubleArrayContainer values=new doubleArrayContainer(); + hts.getData(values); + if (ts.units.equals("taf") && ts.convertToUnits.equals("cfs")){ + int i=0; + for (double dataEntry : values.array){ + if (dataEntry==-901.0){ + dataArray.add(-901.0); + }else if (dataEntry==-902.0){ + dataArray.add(-902.0); + }else{ + ParallelVars prvs = TimeOperation.findTime(i, year, month, day); + double dataEntryValue=dataEntry*Evaluation.tafcfs("taf_cfs", prvs); + dataArray.add(dataEntryValue); + } + i=i+1; + } + }else if (ts.units.equals("cfs") && ts.convertToUnits.equals("taf")){ + int i=0; + for (double dataEntry : values.array){ + if (dataEntry==-901.0){ + dataArray.add(-901.0); + }else if (dataEntry==-902.0){ + dataArray.add(-902.0); + }else{ + ParallelVars prvs = TimeOperation.findTime(i, year, month, day); + double dataEntryValue=dataEntry*Evaluation.tafcfs("cfs_taf", prvs); + dataArray.add(dataEntryValue); + } + i=i+1; + } + }else{ + for (double dataEntry : values.array){ + dataArray.add(dataEntry); + } + } + dds.setUnits(ts.units); + dds.setConvertToUnits(ts.convertToUnits); + dds.setKind(partC); + dds.setData(dataArray); + dds.setTimeStep(timeStep); + Date startDate=new Date(year-1900, month-1, day); + dds.setStartTime(startDate); + dds.setFromDssFile(true); + dds.generateStudyStartIndex(); + String entryNameTS=DssOperation.entryNameTS(name, timeStep); + DataTimeSeries.svTS.put(entryNameTS, dds); + return true; + } + + public static boolean getSVInitTimeseries(String name){ + + Timeseries ts=ControlData.currTsMap.get(name); + if (ts==null){ + return false; + } + String partC=ts.kind; + HecTimeSeries hts=getDataForInitial(ControlData.partA.toUpperCase(),ts.dssBPart.toUpperCase(),partC.toUpperCase(),"",ControlData.partE.toUpperCase(), ControlData.initPartF.toUpperCase()); + + if (hts==null){ + return false; + } + if (!hts.units().toUpperCase().equals(ts.units.toUpperCase())){ + return false; + } + /* + if (!(ds instanceof RegularTimeSeries)){ + return false; + } + RegularTimeSeries rts=(RegularTimeSeries)ds; + */ + DssDataSet dds= new DssDataSet(); + ArrayList dataArray= new ArrayList(); + HecTime startTime=hts.startTime(); + int year=startTime.year(); + int month=startTime.month(); + int day = startTime.day(); + Date startDate=new Date(year-1900, month-1, day); + doubleArrayContainer values=new doubleArrayContainer(); + hts.getData(values); + if (ts.units.equals("taf") && ts.convertToUnits.equals("cfs")){ + ParallelVars prvs = new ParallelVars(); + prvs.dataYear=year; + prvs.dataMonth=month; + prvs.dataDay=day; + int i=0; + for (double dataEntry : values.array){ + if (dataEntry==-901.0){ + dataArray.add(-901.0); + }else if (dataEntry==-902.0){ + dataArray.add(-902.0); + }else{ + TimeOperation.findTime(i); + dataArray.add(dataEntry*Evaluation.tafcfs("taf_cfs", prvs)); + } + i=i+1; + } + }else if (ts.units.equals("cfs") && ts.convertToUnits.equals("taf")){ + ParallelVars prvs = new ParallelVars(); + prvs.dataYear=year; + prvs.dataMonth=month; + prvs.dataDay=day; + int i=0; + for (double dataEntry : values.array){ + if (dataEntry==-901.0){ + dataArray.add(-901.0); + }else if (dataEntry==-902.0){ + dataArray.add(-902.0); + }else{ + TimeOperation.findTime(i); + dataArray.add(dataEntry*Evaluation.tafcfs("cfs_taf", prvs)); + } + i=i+1; + } + }else{ + for (double dataEntry : values.array){ + dataArray.add(dataEntry); + } + } + dds.setUnits(ts.units); + dds.setConvertToUnits(ts.convertToUnits); + dds.setKind(ts.kind); + dds.setData(dataArray); + dds.setTimeStep(ControlData.partE.toUpperCase()); + dds.setStartTime(startDate); + String entryNameTS=DssOperation.entryNameTS(name, ControlData.timeStep); + DataTimeSeries.svInit.put(entryNameTS, dds); + return true; + } + + public static String regularExp(String part){ + return "^"+part+"$"; + } + + public static boolean getDVAliasInitTimeseries(String name){ + String units; + String partC; + if (ControlData.currDvMap.containsKey(name)){ + Dvar dvar=ControlData.currDvMap.get(name); + partC=dvar.kind; + units=dvar.units; + }else{ + Alias alias=ControlData.currAliasMap.get(name); + partC=alias.kind; + units=alias.units; + } + + HecTimeSeries hts=getDataForInitial(ControlData.partA.toUpperCase(),name.toUpperCase(),partC.toUpperCase(),"",ControlData.partE.toUpperCase(), ControlData.initPartF.toUpperCase()); + if (hts==null){ + Error.addEvaluationError("Intial data of "+name+" in dss file doesn't exist." ); + return false; + } + if (!units.toUpperCase().equals(hts.units().toUpperCase())){ + return false; + } + /* + if (!(ds instanceof RegularTimeSeries)){ + Error.addEvaluationError("Intial data of "+name+" in dss file is not a regular timeseries." ); + return false; + } + RegularTimeSeries rts=(RegularTimeSeries)ds; + */ + DssDataSet dds= new DssDataSet(); + ArrayList dataArray= new ArrayList(); + doubleArrayContainer values=new doubleArrayContainer(); + hts.getData(values); + for (double dataEntry : values.array){ + dataArray.add(dataEntry); + } + dds.setData(dataArray); + dds.setUnits(units); + dds.setKind(partC); + String timeStep=ControlData.partE.toUpperCase(); + dds.setTimeStep(timeStep); + HecTime startTime=hts.startTime(); + int year=startTime.year(); + int month=startTime.month(); + int day = startTime.day(); + Date startDate=new Date(year-1900, month-1, day); + dds.setStartTime(startDate); + String entryNameTS=DssOperation.entryNameTS(name, timeStep); + DataTimeSeries.dvAliasInit.put(entryNameTS, dds); + return true; + } + + /* + public static DataSet getDataFor(String file, String apart, String bpart, String cpart, String dpart, String epart, String fpart){ + dpart = "01JAN1920"; //To Do: this method may be removed + DataReference ref = DSSUtil.createDataReference("local",file,Pathname.createPathname(new String[]{apart, bpart, cpart, dpart, epart, fpart})); + return ref.getData(); + } + */ + + public static synchronized HecTimeSeries getDataForSvar(String apart, String bpart, String cpart, String dpart, String epart, String fpart, int svFileIndex, String filename){ + //DataReference[] refs; + String path="/"+apart+"/"+bpart+"/"+cpart+"/"+dpart+"/"+epart+"/"+fpart+"/"; + HecTimeSeries ts = new HecTimeSeries(); + DSSPathname dssPathname; + if (svFileIndex==1){ + //refs = ControlData.groupSvar.find(new String[]{apart, bpart, cpart, dpart, epart, fpart}); + dssPathname = ControlData.cacheSvar.getNominalPathname(path); + }else{ + //refs = ControlData.groupSvar2.find(new String[]{apart, bpart, cpart, dpart, epart, fpart}); + dssPathname = ControlData.cacheSvar2.getNominalPathname(path); + } + if (dssPathname==null){ + return null; + }else{ + TimeSeriesContainer tsc = new TimeSeriesContainer(); + tsc.fileName = filename; + tsc.fullName = dssPathname.pathname(); + boolean removeMissing = false; + ts.read(tsc, removeMissing); + ts.setUnits(tsc.units); + return ts; + } + /* + if (refs.length==0){ + return null; + } else { + return refs[0].getData(); + } + */ + } + + public static HecTimeSeries getDataForInitial(String apart, String bpart, String cpart, String dpart, String epart, String fpart){ + String path="/"+apart+"/"+bpart+"/"+cpart+"/"+dpart+"/"+epart+"/"+fpart+"/"; + HecTimeSeries ts = new HecTimeSeries(); + //refs = ControlData.groupSvar.find(new String[]{apart, bpart, cpart, dpart, epart, fpart}); + DSSPathname dssPathname = ControlData.cacheInit.getNominalPathname(path); + if (dssPathname==null){ + return null; + }else{ + TimeSeriesContainer tsc = new TimeSeriesContainer(); + tsc.fileName = FilePaths.fullInitFilePath; + tsc.fullName = dssPathname.pathname(); + boolean removeMissing = false; + ts.read(tsc, removeMissing); + ts.setUnits(tsc.units); + return ts; + } + } + + public static void writeInitDvarAliasToDSS() { + System.out.println("writing initial data for dvar and alias to dv dss"); + Set initSet=DataTimeSeries.dvAliasInit.keySet(); + Iterator iterator = initSet.iterator(); + while(iterator.hasNext()){ + String initName=(String)iterator.next(); + DssDataSet dds=DataTimeSeries.dvAliasInit.get(initName); + ArrayList data=dds.getData(); + int size=data.size(); + double[] values=new double[size]; + for (int i=0; i dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(i); + Set dvAliasSet=dvAliasTSCycle.keySet(); + Iterator iterator = dvAliasSet.iterator(); + while(iterator.hasNext()){ + String dvAliasName=(String)iterator.next(); + DssDataSetFixLength ddsfl=dvAliasTSCycle.get(dvAliasName); + double[] values=ddsfl.getData(); + String timestep=ddsfl.getTimeStep(); + int size = values.length; + int nTimestep = TimeOperation.getNumberOfTimestep(ControlData.memStartDate, ControlData.prevOutputDate, timestep); + if (nTimestep<0) nTimestep=0; + double[] values1=new double[size-nTimestep]; + int size1=values1.length; + for (int j=0; j data=dds.getData(); + int size=data.size(); + double[] values=new double[size]; + for (int i=0; i data=dds.getData(); + int size=data.size(); + double[] values=new double[size]; + for (int i=0; i allTsMap = ControlData.allTsMap; + while(iterator.hasNext()){ + String initName=(String)iterator.next(); + DssDataSet dds=DataTimeSeries.svInit.get(initName); + ArrayList data=dds.getData(); + String ctu = "none"; + String units="none"; + if (allTsMap.containsKey(initName)){ + Timeseries ts=allTsMap.get(initName); + units = ts.units; + ctu=ts.convertToUnits; + } + ArrayList values=dds.getData(); + TimeSeriesContainer dc = new TimeSeriesContainer(); + //DSSData dd = new DSSData(); + //dd._dataType=DSSUtil.REGULAR_TIME_SERIES; + dc.type="PER-AVER"; + int size=values.size(); + dc.numberValues=size; + dc.units=dds.getUnits().toUpperCase(); + dc.values=new double[size]; + Date startDate=dds.getStartTime(); + Calendar startCalendar=Calendar.getInstance(); + startCalendar.setTime(startDate); + dc.setStartTime(new HecTime(startCalendar)); + startDate.setTime(startDate.getTime()-1*24*60*60); + int year=startDate.getYear()+1900; + int month=startDate.getMonth()+1; + int day=startDate.getDate(); + //String startDateStr=TimeOperation.dssTimeEndDay(year, month, day); + //long startJulmin = TimeFactory.getInstance().createTime(startDateStr).getTimeInMinutes(); + if (units.equals("taf") && ctu.equals("cfs")){ + for (int i=0; i dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(i); + Set dvAliasSet=dvAliasTSCycle.keySet(); + Iterator iterator = dvAliasSet.iterator(); + while(iterator.hasNext()){ + String dvAliasName=(String)iterator.next(); + DssDataSetFixLength ddsfl=dvAliasTSCycle.get(dvAliasName); + String timestep=ddsfl.getTimeStep(); + double[] values=ddsfl.getData(); + double[] modValues; + if (timestep.equals("1MON")){ + modValues=new double[totalSavedMonthlyTimestep]; + for (int j=savedStartMonthlyTimestep; j<=savedEndMonthlyTimestep; j++){ + modValues[j-savedStartMonthlyTimestep]=values[j]; + } + }else{ + modValues=new double[totalSavedDailyTimestep]; + for (int j=savedStartDailyTimestep; j<=savedEndDailyTimestep; j++){ + modValues[j-savedStartDailyTimestep]=values[j]; + } + } + TimeSeriesContainer dc = new TimeSeriesContainer(); + //dd._dataType=DSSUtil.REGULAR_TIME_SERIES; + dc.type="PER-AVER"; + dc.numberValues=modValues.length; + dc.units=ddsfl.getUnits().toUpperCase(); + dc.values = modValues; + //boolean storeFlags = false; + dc.setName("/"+ControlData.partA+"_Cycle"+cycleI+"/"+DssOperation.getTSName(dvAliasName)+"/"+ddsfl.getKind()+"//"+timestep+"/"+ControlData.svDvPartF+"/"); + //Date startDate=ddsfl.getStartTime(); + Date startDate=new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); + Calendar startCalendar=Calendar.getInstance(); + startCalendar.setTime(startDate); + dc.setStartTime(new HecTime(startCalendar)); + try { + dss.put(dc); + } catch (Exception e) { + e.printStackTrace(); + } + //String startDateStr=TimeOperation.dssTimeEndDay(startDate.getYear()+1900, startDate.getMonth()+1, startDate.getDate()); + //long startJulmin = TimeFactory.getInstance().createTime(startDateStr).getTimeInMinutes(); + //writer.storeTimeSeriesData(pathName, startJulmin, dd, storeFlags); + dc.values=null; + values=null; + } + } + } + System.gc(); + } + + public static void saveSvarTSData(HecDss dss, String fileName){ + System.out.println("write svar timeseries to "+fileName); + Set svTsSet=DataTimeSeries.svTS.keySet(); + Iterator iterator = svTsSet.iterator(); + Map allTsMap = ControlData.allTsMap; + while(iterator.hasNext()){ + String svTsName=(String)iterator.next(); + String svName=getTSName(svTsName); + String ctu = "none"; + String units="none"; + if (allTsMap.containsKey(svName)){ + Timeseries ts=allTsMap.get(svName); + units = ts.units; + ctu=ts.convertToUnits; + } + DssDataSet dds=DataTimeSeries.svTS.get(svTsName); + ArrayList values=dds.getData(); + //DSSData dd = new DSSData(); + //dd._dataType=DSSUtil.REGULAR_TIME_SERIES; + TimeSeriesContainer dc = new TimeSeriesContainer(); + dc.type="PER-AVER"; + int size=values.size(); + dc.numberValues=size; + dc.units=dds.getUnits().toUpperCase(); + dc.values=new double[size]; + Date startDate=dds.getStartTime(); + Calendar startCalendar=Calendar.getInstance(); + startCalendar.setTime(startDate); + dc.setStartTime(new HecTime(startCalendar)); + startDate.setTime(startDate.getTime()-1*24*60*60); + int year=startDate.getYear()+1900; + int month=startDate.getMonth()+1; + int day=startDate.getDate(); + //String startDateStr=TimeOperation.dssTimeEndDay(year, month, day); + //long startJulmin = TimeFactory.getInstance().createTime(startDateStr).getTimeInMinutes(); + if (units.equals("taf") && ctu.equals("cfs")){ + for (int i=0; i dvAliasTSCycle = DataTimeSeries.dvAliasTSCycles.get(i); + Set dvAliasSet=dvAliasTSCycle.keySet(); + Iterator iterator = dvAliasSet.iterator(); + while(iterator.hasNext()){ + String dvAliasName=(String)iterator.next(); + DssDataSetFixLength ddsfl=dvAliasTSCycle.get(dvAliasName); + double[] values=ddsfl.getData(); + String timestep=ddsfl.getTimeStep(); + int nTimeStep1 = TimeOperation.getNumberOfTimestep(prevMemDate, memStartDate, timestep)-1; + int nTimeStep2 = TimeOperation.getNumberOfTimestep(prevMemDate, outputDate, timestep)-1; + int size = nTimeStep2-nTimeStep1+1; + //double[] values1=new double[values.length]; + for (int j=0; j multiplier; - - public EvalExpression(){ - intDouble=new IntDouble(0, true); - multiplier = new LinkedHashMap(); - } - - public EvalExpression(IntDouble id){ - intDouble=id; - multiplier = new LinkedHashMap(); - } - - public IntDouble getValue(){ - return intDouble; - } - - public void setValue(IntDouble intDouble){ - this.intDouble=intDouble; - } - - public LinkedHashMap getMultiplier(){ - return multiplier; - } - - public void setMultiplier(LinkedHashMap multiplier){ - this.multiplier=multiplier; - } - - public boolean isNumeric(){ - if (multiplier.size()==0){ - return true; - }else{ - return false; - } - } - - public EvalExpression copyOf(){ - EvalExpression evalExpression = new EvalExpression(); - evalExpression.setMultiplier(copyOfMultiplier()); - evalExpression.setValue(intDouble.copyOf()); - return evalExpression; - } - - public LinkedHashMap copyOfMultiplier(){ - LinkedHashMap newMultiplier=new LinkedHashMap(); - Set multCollection = multiplier.keySet(); - Iterator multIterator = multCollection.iterator(); - - while(multIterator.hasNext()){ - String multName=(String)multIterator.next(); - newMultiplier.put(multName, multiplier.get(multName).copyOf()); - } - return newMultiplier; - } -} +package wrimsv2.evaluator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Set; + +import wrimsv2.components.ControlData; +import wrimsv2.components.IntDouble; + +public class EvalExpression { + private IntDouble intDouble; + private LinkedHashMap multiplier; + + public EvalExpression(){ + intDouble=new IntDouble(0, true); + multiplier = new LinkedHashMap(); + } + + public EvalExpression(IntDouble id){ + intDouble=id; + multiplier = new LinkedHashMap(); + } + + public IntDouble getValue(){ + return intDouble; + } + + public void setValue(IntDouble intDouble){ + this.intDouble=intDouble; + } + + public LinkedHashMap getMultiplier(){ + return multiplier; + } + + public void setMultiplier(LinkedHashMap multiplier){ + this.multiplier=multiplier; + } + + public boolean isNumeric(){ + if (multiplier.size()==0){ + return true; + }else{ + return false; + } + } + + public EvalExpression copyOf(){ + EvalExpression evalExpression = new EvalExpression(); + evalExpression.setMultiplier(copyOfMultiplier()); + evalExpression.setValue(intDouble.copyOf()); + return evalExpression; + } + + public LinkedHashMap copyOfMultiplier(){ + LinkedHashMap newMultiplier=new LinkedHashMap(); + Set multCollection = multiplier.keySet(); + Iterator multIterator = multCollection.iterator(); + + while(multIterator.hasNext()){ + String multName=(String)multIterator.next(); + newMultiplier.put(multName, multiplier.get(multName).copyOf()); + } + return newMultiplier; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/Evaluation.java b/wrims-core/src/main/java/wrimsv2/evaluator/Evaluation.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/Evaluation.java rename to wrims-core/src/main/java/wrimsv2/evaluator/Evaluation.java index dff0cd633..4025cf71f 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/Evaluation.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/Evaluation.java @@ -1,1933 +1,1930 @@ -package wrimsv2.evaluator; -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.components.ControlData; -import wrimsv2.components.Error; -import wrimsv2.components.FilePaths; -import wrimsv2.components.IntDouble; -import wrimsv2.external.*; -import wrimsv2.hdf5.HDF5Reader; -import wrimsv2.parallel.ParallelVars; -import wrimsv2.solver.CbcSolver; - -import java.time.Duration; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.ArrayList; -import java.util.Set; -import java.util.Stack; -import java.util.Date; - -public class Evaluation { - public static double convertStringToDouble(String text){ - return Double.valueOf(text); - } - - public static int convertStringToInt(String text){ - return Integer.valueOf(text); - } - - public static String convertDoubleToString(double value){ - return Double.toString(value); - } - - public static String convertIntToString(int value){ - return Integer.toString(value); - } - - public static boolean relationStatement(EvalExpression ee1, EvalExpression ee2, String relation){ - if (!ee1.isNumeric() || !ee2.isNumeric()){ - Error.addEvaluationError("Decision variable can't be used in define condition"); - } - - double value1=ee1.getValue().getData().doubleValue(); - double value2=ee2.getValue().getData().doubleValue(); - - if (relation.equals("==")) { - if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ - if (value1>=value2-ControlData.relationTolerance && value1<=value2+ControlData.relationTolerance){ - return true; - }else{ - return false; - } - }else{ - if (value1==value2){ - return true; - }else{ - return false; - } - } - }else if (relation.equals(">")){ - if (value1>value2){ - return true; - }else{ - return false; - } - }else if (relation.equals("<")){ - if (value1=")){ - if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ - if (value1>=value2-ControlData.relationTolerance){ - return true; - }else{ - return false; - } - }else{ - if (value1>=value2){ - return true; - }else{ - return false; - } - } - }else{ - if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ - if (value1<=value2+ControlData.relationTolerance){ - return true; - }else{ - return false; - } - }else{ - if (value1<=value2){ - return true; - }else{ - return false; - } - } - } - } - - public static boolean range(String m1, String m2){ - return TimeOperation.range(ControlData.currMonth, m1, m2); - } - - public static boolean relationStatementSeries(boolean r1, boolean r2, String s){ - if (s.equals(".and.")) { - return (r1 && r2); - }else{ - return (r1 || r2); - } - } - - public static EvalConstraint constraintStatement (EvalExpression ee1, EvalExpression ee2, String s) { - EvalExpression ee=substract(ee1, ee2); - EvalConstraint ec=new EvalConstraint(); - ec.setEvalExpression(ee); - ec.setSign(s); - return ec; - } - - public static EvalExpression term_knownTS(IntDouble result){ - return new EvalExpression(result); - } - - public static EvalExpression term_IDENT (String ident, Stack sumIndex){ - if (sumIndex.size()>0){ - LoopIndex li=sumIndex.pop(); - if (li.getName().equals(ident) && li.getIndexStart()){ - sumIndex.push(li); - EvalExpression ee = new EvalExpression(); - IntDouble id = new IntDouble(li.getValue(),true, ident, 0); - ee.setValue(id); - return ee; - } - sumIndex.push(li); - } - if (ControlData.currSvMap.containsKey(ident)){ - EvalExpression ee=new EvalExpression(); - IntDouble id0 = ControlData.currSvMap.get(ident).getData(); - IntDouble id1 = new IntDouble(id0.getData(), id0.isInt(), ident, 0); - ee.setValue(id1); - return ee; - }else if (ControlData.currTsMap.containsKey(ident)){ - EvalExpression ee=new EvalExpression(); - IntDouble id0 = ControlData.currTsMap.get(ident).getData(); - IntDouble id1 = new IntDouble(id0.getData(), id0.isInt(), ident, 0); - ee.setValue(id1); - return ee; - }else if (ControlData.isPostProcessing && ControlData.currDvMap.containsKey(ident)){ - EvalExpression ee=new EvalExpression(); - IntDouble id0 = ControlData.currDvMap.get(ident).getData(); - IntDouble id1 = new IntDouble(id0.getData(), id0.isInt(), ident, 0); - ee.setValue(id1); - return ee; - }else if (ControlData.isPostProcessing && ControlData.currAliasMap.containsKey(ident)){ - EvalExpression ee=new EvalExpression(); - IntDouble id0 = ControlData.currAliasMap.get(ident).getData(); - if (id0==null) { - Error.addEvaluationError(ident+" is not defined before it is used."); - IntDouble id1=new IntDouble(1.0, false, ident, 0); - ee.setValue(id1); - return ee; - } - IntDouble id1 = new IntDouble(id0.getData(), id0.isInt(), ident, 0); - ee.setValue(id1); - return ee; - }else if (!ControlData.isPostProcessing && ControlData.currAliasMap.containsKey(ident) && !ControlData.currDvMap.containsKey(ident)){ - EvalExpression ee=new EvalExpression(); - IntDouble id0=new IntDouble(1.0, false, ident, 0); - ee.setValue(id0); - Error.addEvaluationError("Alias "+ident+" should not appear in constraint. "); - return ee; - } else if (ControlData.parameterMap.containsKey(ident)){ - EvalExpression ee=new EvalExpression(); - IntDouble id0=ControlData.parameterMap.get(ident).getData(); - ee.setValue(id0); - return ee; - } else if (!ControlData.isPostProcessing && !ControlData.currAliasMap.containsKey(ident) && !ControlData.currDvMap.containsKey(ident) && !ControlData.currDvSlackSurplusMap.containsKey(ident)){ - EvalExpression ee=new EvalExpression(); - IntDouble id0=new IntDouble(1.0, false, ident, 0); - ee.setValue(id0); - Error.addEvaluationError(ident+" is not defined before used."); - return ee; - } - - EvalExpression ee=new EvalExpression(); - IntDouble id0 = new IntDouble (0, true, ident, 0); - ee.setValue(id0); - HashMap multiplier=ee.getMultiplier(); - IntDouble id; - if (ControlData.currDvMap.containsKey(ident)){ - Dvar dv = ControlData.currDvMap.get(ident); - if (dv.integer.equals(Param.yes)){ - id= new IntDouble(1,true, ident, 0); - }else{ - id= new IntDouble(1.0,false, ident, 0); - } - }else{ - id= new IntDouble(1.0,false, ident, 0); - } - multiplier.put(ident, id); - return ee; - } - - public static EvalExpression term_SVAR (String ident){ - IntDouble data; - if (!ControlData.currSvMap.containsKey(ident)){ - if (!ControlData.currTsMap.containsKey(ident)){ - Error.addEvaluationError("State variable "+ident+" is not defined before used."); - IntDouble id=new IntDouble(1.0, false, ident, 0); - return new EvalExpression(id); - }else{ - data=ControlData.currTsMap.get(ident).getData(); - } - }else{ - data=ControlData.currSvMap.get(ident).getData(); - } - - if (data == null){ - Error.addEvaluationError("The value of state variable "+ident+" is not defined before used."); - IntDouble id=new IntDouble(1.0, false, ident, 0); - return new EvalExpression(id); - } - return new EvalExpression(new IntDouble(data.getData(), data.isInt(), ident, 0)); - } - - public static EvalExpression term_INTEGER (String integer){ - IntDouble id = new IntDouble(convertStringToInt(integer), true); - return new EvalExpression(id); - } - - public static EvalExpression term_FLOAT (String floatValue){ - IntDouble id = new IntDouble(convertStringToDouble(floatValue), false); - return new EvalExpression(id); - } - - public static EvalExpression unary (String s, EvalExpression ee){ - if (s !=null && s.equals("-")){ - if (ee.getValue().isInt()){ - int value=-ee.getValue().getData().intValue(); - ee.getValue().setData(value); - }else{ - double value=-ee.getValue().getData().doubleValue(); - ee.getValue().setData(value); - } - Map multiplier=ee.getMultiplier(); - for (String dvar : multiplier.keySet()) { - IntDouble id=multiplier.get(dvar); - if (id.isInt()){ - id.setData(-id.getData().intValue()); - }else{ - id.setData(-id.getData().doubleValue()); - } - multiplier.put(dvar, id); - } - } - return ee; - } - - public static EvalExpression mult(EvalExpression ee1, EvalExpression ee2){ - if (ee1.isNumeric()){ - IntDouble id1=ee1.getValue(); - IntDouble id2=ee2.getValue(); - ee2.setValue(multiplyOperation(id1,id2)); - Map multiplier=ee2.getMultiplier(); - Set keySet=multiplier.keySet(); - Iterator iterator=(Iterator) keySet.iterator(); - while (iterator.hasNext()) { - String dvar=(String) iterator.next(); - IntDouble id3=multiplyOperation(id1,multiplier.get(dvar)); - if (id3.getData().doubleValue()==0.0){ - iterator.remove(); - }else{ - multiplier.put(dvar, id3); - } - } - return ee2; - }else{ - if (ee2.isNumeric()){ - IntDouble id2=ee2.getValue(); - IntDouble id1=ee1.getValue(); - ee1.setValue(multiplyOperation(id2,id1)); - Map multiplier=ee1.getMultiplier(); - Set keySet=multiplier.keySet(); - Iterator iterator=(Iterator) keySet.iterator(); - while (iterator.hasNext()) { - String dvar=(String) iterator.next(); - IntDouble id3=multiplyOperation(id2,multiplier.get(dvar)); - if (id3.getData().doubleValue()==0.0){ - iterator.remove(); - }else{ - multiplier.put(dvar, id3); - } - } - return ee1; - }else{ - Error.addEvaluationError("Decision variable multiply decision variable appears. The problem is not linear."); - return ee1; - } - } - } - - public static IntDouble multiplyOperation(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().intValue()*id2.getData().intValue(), true); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().intValue()*id2.getData().doubleValue(), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()*id2.getData().intValue(), false); - }else{ - id=new IntDouble(id1.getData().doubleValue()*id2.getData().doubleValue(), false); - } - return id; - } - - public static EvalExpression divide(EvalExpression ee1, EvalExpression ee2){ - if (ee2.isNumeric()){ - IntDouble id2=ee2.getValue(); - IntDouble id1=ee1.getValue(); - if (id2.getData().doubleValue() ==0.0){ - if (id1.getData().doubleValue()==0.0 && ee1.isNumeric()){ - return ee1; - }else{ - Error.addEvaluationError("0.0 appears in divisor"); - } - return ee1; - } - ee1.setValue(divideOperation(id1,id2)); - Map multiplier=ee1.getMultiplier(); - for (String dvar : multiplier.keySet()) { - multiplier.put(dvar, divideOperation(multiplier.get(dvar),id2)); - } - return ee1; - }else{ - Error.addEvaluationError("Decision variable appears in divisor. The problem is not linear."); - return ee1; - } - } - - public static IntDouble divideOperation(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().intValue()/id2.getData().intValue(), true); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().intValue()/id2.getData().doubleValue(), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()/id2.getData().intValue(), false); - }else{ - id=new IntDouble(id1.getData().doubleValue()/id2.getData().doubleValue(), false); - } - return id; - } - - public static EvalExpression mod(EvalExpression ee1, EvalExpression ee2){ - if (ee1.isNumeric() && ee2.isNumeric()){ - IntDouble id1=ee1.getValue(); - IntDouble id2=ee2.getValue(); - ee1.setValue(modOperation(id1,id2)); - return ee1; - }else{ - Error.addEvaluationError("Decision variable appears in MOD calcualtion. The problem is not linear."); - return ee1; - } - } - - public static IntDouble modOperation(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id2.getData().doubleValue()==0.0){ - Error.addEvaluationError("Mod function uses 0 as divider."); - return new IntDouble(1.0, false); - } - if (id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().intValue()%id2.getData().intValue(), true); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().intValue()%id2.getData().doubleValue(), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()%id2.getData().intValue(), false); - }else{ - id=new IntDouble(id1.getData().doubleValue()%id2.getData().doubleValue(), false); - } - return id; - } - - public static EvalExpression round(EvalExpression ee1){ - if (ee1.isNumeric()){ - IntDouble id1=ee1.getValue(); - ee1.setValue(ValueEvaluation.round(id1)); - return ee1; - }else{ - Error.addEvaluationError("The arguement for the rounded variable is not numeric."); - return ee1; - } - } - - public static EvalExpression add(EvalExpression ee1, EvalExpression ee2){ - IntDouble id1=ee1.getValue(); - IntDouble id2=ee2.getValue(); - ee1.setValue(addOperation(id1,id2)); - Map multiplier1=ee1.getMultiplier(); - Map multiplier2=ee2.getMultiplier(); - for (String dvar : multiplier2.keySet()) { - if (multiplier1.containsKey(dvar)){ - IntDouble id3=addOperation(multiplier1.get(dvar),multiplier2.get(dvar)); - if (id3.getData().doubleValue()==0.0){ - multiplier1.remove(dvar); - }else{ - multiplier1.put(dvar, id3); - } - }else{ - multiplier1.put(dvar, multiplier2.get(dvar)); - } - } - return ee1; - } - - public static IntDouble addOperation(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().intValue()+id2.getData().intValue(), true); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().intValue()+id2.getData().doubleValue(), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()+id2.getData().intValue(), false); - }else{ - id=new IntDouble(id1.getData().doubleValue()+id2.getData().doubleValue(), false); - } - return id; - } - - public static EvalExpression substract(EvalExpression ee1, EvalExpression ee2){ - IntDouble id1=ee1.getValue(); - IntDouble id2=ee2.getValue(); - ee1.setValue(substractOperation(id1,id2)); - Map multiplier1=ee1.getMultiplier(); - Map multiplier2=ee2.getMultiplier(); - for (String dvar : multiplier2.keySet()) { - if (multiplier1.containsKey(dvar)){ - IntDouble id3=substractOperation(multiplier1.get(dvar),multiplier2.get(dvar)); - if (id3.getData().doubleValue()==0.0){ - multiplier1.remove(dvar); - }else{ - multiplier1.put(dvar, id3); - } - }else{ - IntDouble id0=new IntDouble(0,true); - multiplier1.put(dvar, substractOperation(id0,multiplier2.get(dvar))); - } - } - return ee1; - } - - public static IntDouble substractOperation(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().intValue()-id2.getData().intValue(), true); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().intValue()-id2.getData().doubleValue(), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()-id2.getData().intValue(), false); - }else{ - id=new IntDouble(id1.getData().doubleValue()-id2.getData().doubleValue(), false); - } - return id; - } - - public static EvalExpression noArgFunction(String ident){ - Class function; - IntDouble result; - try { - function = Class.forName("wrimsv2.external.Function"+ident); - - Stack stack = new Stack(); - - ExternalFunction ef; - if (ControlData.allExternalFunctionMap.containsKey(ident)){ - ef=ControlData.allExternalFunctionMap.get(ident); - }else{ - ef = (ExternalFunction)function.newInstance(); - ControlData.allExternalFunctionMap.put(ident, ef); - } - ef.execute(stack); - String valueString=stack.pop().toString(); - - if (valueString.contains(".")){ - result = new IntDouble(Double.parseDouble(valueString), false); - return new EvalExpression(result); - }else{ - result = new IntDouble(Integer.parseInt(valueString), true); - return new EvalExpression(result); - } - - } catch (Exception e) { - Error.addEvaluationError("The function " +ident+" has an error."); - e.printStackTrace(); - result=new IntDouble (1.0,false); - return new EvalExpression(result); - } - } - - public static EvalExpression argFunction(String ident, ArrayList> eeArray, Stack sumIndex){ - IntDouble result; - if (eeArray.size()==1){ - if (ControlData.currSvMap.containsKey(ident)||ControlData.currTsMap.containsKey(ident)||ControlData.currDvMap.containsKey(ident)||ControlData.currAliasMap.containsKey(ident)||ControlData.currDvSlackSurplusMap.containsKey(ident)) { - ArrayList eeArray1 = eeArray.get(0); - if (eeArray1.size()==1){ - String idName = eeArray1.get(0).getValue().getName(); - for (int k=0; k<12; k++){ - if (idName.equals(TimeOperation.month_const[k])){ - Error.addEvaluationError(idName+" can't be used in "+ident+"("+idName+")"); - return new EvalExpression(new IntDouble (1.0, false)); - } - } - return getTimeSeries(ident, eeArray1, sumIndex); - }else{ - Error.addEvaluationError("Variable "+ident+" has number of indexes different from 1."); - return new EvalExpression(new IntDouble (1.0, false)); - } - } - } - - Class function; - try { - function = Class.forName("wrimsv2.external.Function"+ident); - - Stack stack = new Stack(); - for (int i=0; i eeArray1=eeArray.get(i); - int size=eeArray1.size(); - if (size ==1){ - EvalExpression ee = eeArray1.get(0); - if (!ee.isNumeric()){ - int ai=i+1; - Error.addEvaluationError("The function " +ident+" has an unkown argument at argument index of "+ai+"."); - result=new IntDouble (0.0,false); - return new EvalExpression(result); - } - - IntDouble id=ee.getValue(); - if (id.isInt()){ - int value=id.getData().intValue(); - stack.push(value); - }else{ - double value=id.getData().doubleValue(); - stack.push(value); - } - }else if (size>1){ - Number[] valueArray = new Number[size]; - for (int j=0; j1){ - for (int i=0; i eeArray1=eeArray.get(i); - int size=eeArray1.size(); - if (size ==1){ - EvalExpression ee = eeArray1.get(0); - if (!ee.isNumeric()){ - int ai=i+1; - Error.addEvaluationError("The function " +ident+" has an unkown argument at argument index of "+ai+"."); - result=new IntDouble (0.0,false); - return new EvalExpression(result); - } - - IntDouble id=ee.getValue(); - if (id.isInt()){ - int value=(Integer) stack.pop(); - ValueEvaluation.setSvarIntValue(id, value); - }else{ - double value=(Double) stack.pop(); - ValueEvaluation.setSvarDoubleValue(id, value); - } - }else if (size>1){ - IntDouble id=eeArray1.get(0).getValue(); - if (id.isInt()){ - int[] valueArray = new int[size]; - valueArray=(int[])stack.pop(); - for (int j=0; j eeArray, Stack sumIndex){ - IntDouble result; - boolean isSumIndex=false; - int indexValue=0; - boolean isIndexStart=true; - ParallelVars prvs; - - EvalExpression ee=eeArray.get(0); - - if (!ee.isNumeric()){ - HashMap multiplier=ee.getMultiplier(); - if (multiplier.size()==1){ - LoopIndex li=sumIndex.pop(); - String indexName=li.getName(); - indexValue=li.getValue(); - isIndexStart=li.getIndexStart(); - sumIndex.push(li); - if (!(multiplier.containsKey(indexName) && multiplier.get(indexName).getData().doubleValue()==1.0 && ee.getValue().getData().doubleValue()==0.0)){ - Error.addEvaluationError("The index of "+ident+" contains decision variable."); - result=new IntDouble (0.0,false); - return new EvalExpression(result); - }else{ - isSumIndex=true; - } - }else{ - Error.addEvaluationError("The index of "+ident+" contains decision variable."); - result=new IntDouble (0.0,false); - return new EvalExpression(result); - } - } - - IntDouble id=ee.getValue(); - if (!id.isInt()){ - Error.addEvaluationError("The index of "+ident+" should be integer."); - result=new IntDouble (0.0,false); - return new EvalExpression(result); - } - - if (isSumIndex){ - if (isIndexStart){ - prvs=TimeOperation.findTime(indexValue); - }else{ - result=new IntDouble (1.0,false); - return new EvalExpression(result); - } - }else{ - prvs=TimeOperation.findTime(id.getData().intValue()); - } - - double value; - int idValue=id.getData().intValue(); - if (ControlData.currDvMap.containsKey(ident)){ - if (idValue<0){ - value=dvarAliasTimeSeries(ident,idValue, prvs); - }else if (idValue==0){ - LinkedHashMap multiplier = new LinkedHashMap(); - multiplier.put(ident, new IntDouble(1, true)); - EvalExpression eeResult=new EvalExpression(); - eeResult.setMultiplier(multiplier); - return eeResult; - }else{ - String futDvName=ident+"__fut__"+idValue; - if (SolverData.getDvarMap().containsKey(futDvName)){ - LinkedHashMap multiplier = new LinkedHashMap(); - multiplier.put(futDvName, new IntDouble(1, true)); - EvalExpression eeResult=new EvalExpression(); - eeResult.setMultiplier(multiplier); - return eeResult; - }else{ - Error.addEvaluationError("Time Array Dvar "+futDvName+" is used without definition."); - result=new IntDouble (1.0, false); - return new EvalExpression(result); - } - } - }else if (ControlData.currDvSlackSurplusMap.containsKey(ident)){ - if (idValue==0){ - LinkedHashMap multiplier = new LinkedHashMap(); - multiplier.put(ident, new IntDouble(1, true)); - EvalExpression eeResult=new EvalExpression(); - eeResult.setMultiplier(multiplier); - return eeResult; - }else if (idValue>0){ - String futDvSlackSurplusName=ident+"__fut__"+idValue; - LinkedHashMap multiplier = new LinkedHashMap(); - multiplier.put(futDvSlackSurplusName, new IntDouble(1, true)); - EvalExpression eeResult=new EvalExpression(); - eeResult.setMultiplier(multiplier); - return eeResult; - }else{ - Error.addEvaluationError("Slack surplus index of "+ident+", "+idValue+"<0. THe index has to be larger than 0."); - result=new IntDouble (1.0,false); - return new EvalExpression(result); - } - }else if (ControlData.currAliasMap.containsKey(ident)){ - value=dvarAliasTimeSeries(ident,idValue, prvs); - }else{ - if (ControlData.currSvMap.containsKey(ident)){ - if (idValue==0) { - result = ControlData.currSvMap.get(ident).getData(); - return new EvalExpression(result.copyOf()); - }else if(idValue>0){ - String futSvName=ident+"__fut__"+idValue; - if (ControlData.currSvFutMap.containsKey(futSvName)){ - result=ControlData.currSvFutMap.get(futSvName).getData(); - return new EvalExpression(result.copyOf()); - }else{ - if (!ControlData.ignoreError) Error.addEvaluationError(futSvName+", the future value of "+ident+" is used before defined."); - result=new IntDouble (1.0,false); - return new EvalExpression(result); - } - } - } - value=svarTimeSeries(ident, idValue, prvs); - } - - result=new IntDouble (value, false); - return new EvalExpression(result); - } - - public static double svarTimeSeries(String ident, int idValue, ParallelVars prvs){ - int index; - String entryNameTS=DssOperation.entryNameTS(ident, ControlData.timeStep); - if (DataTimeSeries.svTS.containsKey(entryNameTS)){ - DssDataSet dds=DataTimeSeries.svTS.get(entryNameTS); - index =timeSeriesIndex(dds, prvs); - ArrayList data=dds.getData(); - if (index>=0 && index=dds.getStudyStartIndex()){ - double value=data.get(index); - if (dds.fromDssFile()){ - if (value != -901.0 && value != -902.0){ - return value; - } - }else{ - return value; - } - } - } - if (DataTimeSeries.svInit.containsKey(entryNameTS)){ - DssDataSet dds=DataTimeSeries.svInit.get(entryNameTS); - index =timeSeriesIndex(dds, prvs); - ArrayList data=dds.getData(); - if (index>=0 && index data=dds.getData(); - if (index>=0 && index data=dds.getData(); - if (index>=0 && index=currTime){ - Error.addEvaluationError("The timeseries data for decision variable/alias "+ident+" is not available at or after current simulation period."); - return 1.0; - }else if(dataTime>=startTime && dataTime data=dds.getData(); - if (index>=0 && index0){ - Error.addEvaluationError("Can't access decision variable after the current time step."); - } - - /* - int index=indexValue+ControlData.currTimeStep.get(ControlData.currCycleIndex); - if (index>=0){ - if (indexValue>=0 && (ControlData.currEvalTypeIndex==0 || ControlData.currEvalTypeIndex==7)){ - Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); - return 1.0; - }else{ - DssDataSetFixLength dds=DataTimeSeries.dvAliasTS.get(entryNameTS); - if (dds==null){ - Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); - return 1.0; - } - double[] data=dds.getData(); - return data[index]; - } - } - */ - - DssDataSetFixLength ddsfl=DataTimeSeries.dvAliasTS.get(entryNameTS); - if (ddsfl!=null){ - Date memStartDate = ddsfl.getStartTime(); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+indexValue-1; - double[] datafl=ddsfl.getData(); - if (index>=datafl.length){ - Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); - return 1.0; - }else if (index>=0){ - return datafl[index]; - } - } - - if (!DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ - if (!getDVAliasInitTimeseries(ident)){ - Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +ident); - return 1.0; - } - } - - DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); - int index=timeSeriesIndex(dds, prvs); - ArrayList data=dds.getData(); - if (index>=0 && index0){ - Error.addEvaluationError("Can't access decision variable after the current time step."); - } - - /* - int index=indexValue+ControlData.currTimeStep.get(ControlData.currCycleIndex); - if (index>=0){ - DssDataSetFixLength dds=DataTimeSeries.dvAliasTSCycles.get(ci).get(entryNameTS); - if (dds==null){ - Error.addEvaluationError(ident + " at timestep " +indexValue+" for the No. "+ci+ " cycle doesn't have value"); - return 1.0; - } - double[] data=dds.getData(); - return data[index]; - } - */ - - DssDataSetFixLength ddsfl=DataTimeSeries.dvAliasTSCycles.get(ci).get(entryNameTS); - if (ddsfl!=null){ - Date memStartDate = ddsfl.getStartTime(); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+indexValue-1; - double[] datafl=ddsfl.getData(); - if (index>=datafl.length){ - Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); - return 1.0; - }else if (index>=0){ - return datafl[index]; - } - } - - if (!DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ - if (!getDVAliasInitTimeseries(ident)){ - Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +ident); - return 1.0; - } - } - - DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); - int index=timeSeriesIndex(dds, prvs); - ArrayList data=dds.getData(); - if (index>=0 && index> eeArray, ParallelVars prvs){ - //turn off when multi-dimensional array is used - if (eeArray.size()!=1){ - Error.addEvaluationError("The future index of array variable "+ident+" has to be a single integer."); - return new EvalExpression(new IntDouble(1.0,false)); - } - // - - ArrayList ee2Array = eeArray.get(0); - if (ee2Array.size() !=1){ - Error.addEvaluationError("The future index of array variable "+ident+" has to be a single integer but not a range."); - return new EvalExpression(new IntDouble(1.0,false)); - } - EvalExpression ee2 = ee2Array.get(0); - - if (!ee1.isNumeric() || !ee2.isNumeric()){ - Error.addEvaluationError("The index of array variable "+ident+" has to be an integer."); - return new EvalExpression(new IntDouble(1.0,false)); - } - IntDouble id1=ee1.getValue(); - IntDouble id2=ee2.getValue(); - if (!id1.isInt() || !id2.isInt()){ - Error.addEvaluationError("The index of array variable "+ident+" has to be an integer."); - return new EvalExpression(new IntDouble(1.0,false)); - } - int i1 = id1.getData().intValue(); - int i2 = id2.getData().intValue(); - - if (i1==0){ - EvalExpression ee = new EvalExpression(); - LinkedHashMap multiplier = ee.getMultiplier(); - if (i2==0){ - multiplier.put(ident, new IntDouble(1, true)); - return ee; - }else if (i2>0){ - String vn = ident+"__fut__"+id2; - multiplier.put(vn, new IntDouble(1, true)); - return ee; - } - } - - if (i1>0){ - Error.addEvaluationError("The second index of array variable "+ident+" has to be less than or equal to 0 in constraint statements."); - return new EvalExpression(new IntDouble(1.0,false)); - } - if (i2<0){ - Error.addEvaluationError("The first index of array variable "+ident+" has to be larger than or equal to 0."); - return new EvalExpression(new IntDouble(1.0,false)); - } - if (!ControlData.currDvMap.containsKey(ident) && !ControlData.currAliasMap.containsKey(ident)){ - Error.addEvaluationError("The array variable "+ident+" is not a dvar or alias. The value from the past time step could not be retrieved."); - return new EvalExpression(new IntDouble(1.0,false)); - } - String vn=ident+"__fut__"+i2; - String entryNameTS=DssOperation.entryNameTS(vn, ControlData.timeStep); - if (DataTimeSeries.dvAliasTS.containsKey(entryNameTS)){ - DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); - if (ddsfl!=null){ - Date memStartDate = ddsfl.getStartTime(); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+i1-1; - double[] datafl=ddsfl.getData(); - if (index>=datafl.length){ - Error.addEvaluationError(vn + " at timestep " +i1+" doesn't have value."); - return new EvalExpression(new IntDouble(1.0,false)); - }else if (index>=0){ - return new EvalExpression(new IntDouble(datafl[index], false)); - }else{ - Error.addEvaluationError(vn + " at timestep " +i1+" doesn't have value."); - return new EvalExpression(new IntDouble(1.0,false)); - } - } - - if (DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ - if (!getDVAliasInitTimeseries(ident)){ - Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +vn); - return new EvalExpression(new IntDouble(1.0,false)); - } - - DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); - int index = timeSeriesIndex(dds, prvs); - ArrayList data=dds.getData(); - if (index>=0 && index> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); - IntDouble data=new IntDouble(1.0,false); - if (varCycleValueMap.containsKey(ident)){ - Map var= varCycleValueMap.get(ident); - if (var.containsKey(cycle)){ - data=var.get(cycle); - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - if (data==null){ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return new IntDouble(1.0,false); - } - return new IntDouble(data.getData(),data.isInt()); - } - - public static IntDouble pastCycleIndexNoTimeArray(String ident, int index){ - int ci=ControlData.currCycleIndex+index; - if (ci<0){ - Error.addEvaluationError("The "+ci+" cycle from the current cycle is unvailable."); - return new IntDouble(1.0,false); - } - StudyDataSet sds = ControlData.currStudyDataSet; - String cycle=sds.getModelList().get(ci); - Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); - if (varCycleIndexValueMap.containsKey(ident)){ - Map valueMap = varCycleIndexValueMap.get(ident); - if (valueMap.containsKey(cycle)){ - return valueMap.get(cycle); - } - } - Error.addEvaluationError("Variable "+ident+" is not in "+ index+" from the current cycle - "+cycle); - return new IntDouble(1.0,false); - } - - public static IntDouble pastCycleTimeArray(String ident, String cycle, EvalExpression ee){ - IntDouble data=new IntDouble(1.0,false); - if (!ee.isNumeric()){ - Error.addEvaluationError("Time array index of "+ident+" contains decision variable."); - return data; - } - IntDouble id=ee.getValue(); - if (!id.isInt()){ - Error.addEvaluationError("Time array index of "+ident+" is not an integer."); - return data; - } - int index=id.getData().intValue(); - if (index<0){ - ArrayList eeArray=new ArrayList(); - eeArray.add(ee); - ModelDataSet mds=ControlData.currStudyDataSet.getModelDataSetMap().get(cycle); - EvalExpression ee1; - if (mds.dvMap.containsKey(ident) || mds.asMap.containsKey(ident)){ - ParallelVars prvs=TimeOperation.findTime(index); - //if (ControlData.outputCycleToDss){ - ArrayList ml = ControlData.currStudyDataSet.getModelList(); - int ci=-1; - for (int k=0; k> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); - String varTimeArrayName=ident+"__fut__"+index; - if (varTimeArrayCycleValueMap.containsKey(varTimeArrayName)){ - Map var= varTimeArrayCycleValueMap.get(varTimeArrayName); - if (var.containsKey(cycle)){ - data=var.get(cycle); - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - if (data==null){ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return new IntDouble(1.0,false); - } - return new IntDouble(data.getData(),data.isInt()); - } - - public static IntDouble pastCycleIndexTimeArray(String ident, int pci, EvalExpression ee){ - IntDouble data=new IntDouble(1.0,false); - int ci=ControlData.currCycleIndex+pci; - if (ci<0){ - Error.addEvaluationError("The "+ci+" cycle from the current cycle is unvailable."); - return new IntDouble(1.0,false); - } - if (!ee.isNumeric()){ - Error.addEvaluationError("Time array index of "+ident+" contains decision variable."); - return data; - } - IntDouble id=ee.getValue(); - if (!id.isInt()){ - Error.addEvaluationError("Time array index of "+ident+" is not an integer."); - return data; - } - int index=id.getData().intValue(); - StudyDataSet sds = ControlData.currStudyDataSet; - String cycle=sds.getModelList().get(ci); - if (index<0){ - ArrayList eeArray=new ArrayList(); - eeArray.add(ee); - ModelDataSet mds=ControlData.currStudyDataSet.getModelDataSetMap().get(cycle); - EvalExpression ee1; - if (mds.dvMap.containsKey(ident) || mds.asMap.containsKey(ident)){ - ParallelVars prvs=TimeOperation.findTime(index); - //if (ControlData.outputCycleToDss){ - return new IntDouble(dvarAliasCycleTimeSeries(ident, index, ci, prvs), false); - //}else{ - // return new IntDouble(dvarAliasTimeSeries(ident, index), false); - //} - }else{ - Error.addEvaluationError(ident+" is not a dvar/alias in the cycle of "+cycle+". Only dvar/alias in the past time step of "+index+" and past cycle of "+cycle+" can be used from previous cycles"); - return new IntDouble(1.0, false); - } - }else if(index==0){ - return pastCycleIndexNoTimeArray(ident, pci); - } - Map> varCycleIndexValueMap=sds.getVarCycleIndexValueMap(); - String varTimeArrayName=ident+"__fut__"+index; - if (varCycleIndexValueMap.containsKey(varTimeArrayName)){ - Map var= varCycleIndexValueMap.get(varTimeArrayName); - if (var.containsKey(cycle)){ - data=var.get(cycle); - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - if (data==null){ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return new IntDouble(1.0,false); - } - return new IntDouble(data.getData(),data.isInt()); - } - - public static ArrayList trunk_timeArray(String ident, IntDouble start, IntDouble end){ - ArrayList eeArray=new ArrayList(); - if (!start.isInt()){ - Error.addEvaluationError("The starting index of trunk data for variable " + ident + " is not an integer."); - EvalExpression ee=new EvalExpression(new IntDouble(1.0, false)); - eeArray.add(ee); - return eeArray; - }else if (!end.isInt()){ - Error.addEvaluationError("The ending index of trunk data for variable " + ident + " is not an integer."); - EvalExpression ee=new EvalExpression(new IntDouble(1.0, false)); - eeArray.add(ee); - return eeArray; - } - int si=start.getData().intValue(); - int ei=end.getData().intValue(); - - if (si>ei){ - Error.addEvaluationError("The starting index of trunk data for variable " + ident + " is larger than the ending index"); - EvalExpression ee=new EvalExpression(new IntDouble(1.0, false)); - eeArray.add(ee); - return eeArray; - } - - for (int i=si; i<=ei; i++){ - ArrayList indexArray1=new ArrayList (); - IntDouble index = new IntDouble(i, true); - indexArray1.add(index); - ArrayList> indexArray=new ArrayList> (); - indexArray.add(indexArray1); - IntDouble id=ValueEvaluation.argFunction(ident, indexArray); - id.setIndex(i); - id.setName(ident); - eeArray.add(new EvalExpression(id)); - } - return eeArray; - } - - public static EvalExpression max(EvalExpression ee1, EvalExpression ee2){ - if (!ee1.isNumeric() || !ee2.isNumeric()){ - Error.addEvaluationError("variable inside max function should not contain decision variable."); - } - return new EvalExpression(maxOperation(ee1.getValue(), ee2.getValue())); - } - - public static IntDouble maxOperation(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.max(id1.getData().intValue(),id2.getData().intValue()), true); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else{ - id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - } - return id; - } - - public static EvalExpression min(EvalExpression ee1, EvalExpression ee2){ - if (!ee1.isNumeric() || !ee2.isNumeric()){ - Error.addEvaluationError("variable inside min function should not contain decision variable."); - } - return new EvalExpression((minOperation(ee1.getValue(), ee2.getValue()))); - } - - public static IntDouble minOperation(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.min(id1.getData().intValue(),id2.getData().intValue()), true); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else{ - id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - } - return id; - } - - public static EvalExpression intFunc(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside int function should not contain decision variable."); - } - return new EvalExpression(intOperation(ee1.getValue())); - } - - public static IntDouble intOperation(IntDouble id1){ - IntDouble id; - if (!id1.isInt()){ - id=new IntDouble(((int)id1.getData().doubleValue()), true); - return id; - } - return id1; - } - - public static EvalExpression realFunc(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside int function should not contain decision variable."); - } - return new EvalExpression(realOperation(ee1.getValue())); - } - - public static IntDouble realOperation(IntDouble id1){ - IntDouble id; - if (id1.isInt()){ - id=new IntDouble((id1.getData().doubleValue()), false); - return id; - } - return id1; - } - - public static EvalExpression abs(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside abs function should not contain decision variable."); - } - return new EvalExpression(absOperation(ee1.getValue())); - } - - public static IntDouble absOperation(IntDouble id1){ - IntDouble id; - if (id1.isInt()){ - id=new IntDouble(Math.abs(id1.getData().intValue()), true); - }else{ - id=new IntDouble(Math.abs(id1.getData().doubleValue()), false); - } - return id; - } - - public static EvalExpression exp(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside log function should not contain decision variable."); - } - return new EvalExpression(expOperation(ee1.getValue())); - } - - public static IntDouble expOperation(IntDouble id1){ - IntDouble id; - if (id1.isInt()){ - id=new IntDouble(Math.exp(id1.getData().intValue()), false); - }else{ - id=new IntDouble(Math.exp(id1.getData().doubleValue()), false); - } - return id; - } - - public static EvalExpression log(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside log function should not contain decision variable."); - } - return new EvalExpression(logOperation(ee1.getValue())); - } - - public static IntDouble logOperation(IntDouble id1){ - IntDouble id; - if (id1.isInt()){ - id=new IntDouble(Math.log(id1.getData().intValue()), false); - }else{ - id=new IntDouble(Math.log(id1.getData().doubleValue()), false); - } - return id; - } - - public static EvalExpression log10(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside log10 function should not contain decision variable."); - } - return new EvalExpression(log10Operation(ee1.getValue())); - } - - public static IntDouble log10Operation(IntDouble id1){ - IntDouble id; - if (id1.isInt()){ - id=new IntDouble(Math.log10(id1.getData().intValue()), false); - }else{ - id=new IntDouble(Math.log10(id1.getData().doubleValue()), false); - } - return id; - } - - public static EvalExpression pow(EvalExpression ee1, EvalExpression ee2){ - if (!ee1.isNumeric() || !ee2.isNumeric()){ - Error.addEvaluationError("variable inside pow function should not contain decision variable."); - } - return new EvalExpression(powOperation(ee1.getValue(), ee2.getValue())); - } - - public static IntDouble powOperation(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.pow(id1.getData().intValue(),id2.getData().intValue()), false); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else{ - id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - } - return id; - } - - public static EvalExpression sin(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside sin function should not contain decision variable."); - } - - double degrees = ee1.getValue().getData().doubleValue(); - double radians = Math.toRadians(degrees); - return new EvalExpression(new IntDouble(Math.sin(radians), false)); - } - - public static EvalExpression cos(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside cos function should not contain decision variable."); - } - - double degrees = ee1.getValue().getData().doubleValue(); - double radians = Math.toRadians(degrees); - return new EvalExpression(new IntDouble(Math.cos(radians), false)); - } - - public static EvalExpression tan(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside tan function should not contain decision variable."); - } - - double degrees = ee1.getValue().getData().doubleValue(); - double radians = Math.toRadians(degrees); - return new EvalExpression(new IntDouble(Math.tan(radians), false)); - } - - public static EvalExpression cot(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside cot function should not contain decision variable."); - } - - double degrees = ee1.getValue().getData().doubleValue(); - if (degrees==90.0){ - return new EvalExpression(new IntDouble(0.0, false)); - } - double radians = Math.toRadians(degrees); - return new EvalExpression(new IntDouble(1.0/Math.tan(radians), false)); - } - - public static EvalExpression asin(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside asin function should not contain decision variable."); - } - - double value = ee1.getValue().getData().doubleValue(); - double radians = Math.asin(value); - return new EvalExpression(new IntDouble(Math.toDegrees(radians), false)); - } - - public static EvalExpression acos(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside acos function should not contain decision variable."); - } - - double value = ee1.getValue().getData().doubleValue(); - double radians = Math.acos(value); - return new EvalExpression(new IntDouble(Math.toDegrees(radians), false)); - } - - public static EvalExpression atan(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside atan function should not contain decision variable."); - } - - double value = ee1.getValue().getData().doubleValue(); - double radians = Math.atan(value); - return new EvalExpression(new IntDouble(Math.toDegrees(radians), false)); - } - - public static EvalExpression acot(EvalExpression ee1){ - if (!ee1.isNumeric()){ - Error.addEvaluationError("variable inside acot function should not contain decision variable."); - } - - double value = ee1.getValue().getData().doubleValue(); - if (value == 0.){ - return new EvalExpression(new IntDouble(90.0, false)); - } - double radians = Math.atan(1.0/value); - return new EvalExpression(new IntDouble(Math.toDegrees(radians), false)); - } - - public static EvalExpression exceedance(String tsName, EvalExpression exc_ee, String selMon, String syStr, String smStr, String sdStr, String eyStr, String emStr, String edStr){ - String entryNameTS=DssOperation.entryNameTS(tsName, ControlData.timeStep); - if (DataTimeSeries.svTS.containsKey(entryNameTS)){ - DssDataSet dds = DataTimeSeries.svTS.get(entryNameTS); - int sy = Integer.parseInt(syStr); - int sd = Integer.parseInt(sdStr); - int ey = Integer.parseInt(eyStr); - int ed = Integer.parseInt(edStr); - int sm = TimeOperation.monthValue(smStr); - int em = TimeOperation.monthValue(emStr); - - double exc=1.0; - if (exc_ee.isNumeric()){ - exc=exc_ee.getValue().getData().doubleValue(); - }else{ - Error.addEvaluationError("Exceedance level has unknown variable."); - return new EvalExpression(new IntDouble (1.0, false)); - } - if (exc<=0.0 || exc>1.0){ - Error.addEvaluationError("Exceedance level must be >0.0 and <=1.0"); - return new EvalExpression(new IntDouble (1.0, false)); - } - - Date selSd; - Date selEd; - if (ControlData.timeStep.equals("1MON")){ - selSd=new Date(sy-1900, sm-1, TimeOperation.numberOfDays(sm, sy)); - selEd=new Date(ey-1900, em-1, TimeOperation.numberOfDays(em, ey)); - }else{ - selSd=new Date(sy-1900, sm-1, sd); - selEd=new Date(ey-1900, em-1, ed); - } - - ArrayList optedData=dds.getTimeseriesDataWithOptions(selMon, selSd, selEd); - double value=DssDataSet.getExceedance(optedData, exc); - return new EvalExpression(new IntDouble (value, false)); - }else{ - Error.addEvaluationError(tsName+" is not a timeseries variable used in the Exceendance funciton for the time step of "+ControlData.timeStep+"."); - return new EvalExpression(new IntDouble (1.0, false)); - } - } - - public static EvalExpression exceedance_tsi(String tsName, EvalExpression exc_ee, String selMon, String syStr, String smStr, String sdStr, String eyStr, String emStr, String edStr){ - String entryNameTS=DssOperation.entryNameTS(tsName, ControlData.timeStep); - if (DataTimeSeries.svTS.containsKey(entryNameTS)){ - DssDataSet dds = DataTimeSeries.svTS.get(entryNameTS); - int sy = Integer.parseInt(syStr); - int sd = Integer.parseInt(sdStr); - int ey = Integer.parseInt(eyStr); - int ed = Integer.parseInt(edStr); - int sm = TimeOperation.monthValue(smStr); - int em = TimeOperation.monthValue(emStr); - - double exc=1.0; - if (exc_ee.isNumeric()){ - exc=exc_ee.getValue().getData().doubleValue(); - }else{ - Error.addEvaluationError("Exceedance level has unknown variable."); - return new EvalExpression(new IntDouble (0, true)); - } - if (exc<=0.0 || exc>1.0){ - Error.addEvaluationError("Exceedance level must be >0.0 and <=1.0"); - return new EvalExpression(new IntDouble (0, true)); - } - - Date selSd; - Date selEd; - if (ControlData.timeStep.equals("1MON")){ - selSd=new Date(sy-1900, sm-1, TimeOperation.numberOfDays(sm, sy)); - selEd=new Date(ey-1900, em-1, TimeOperation.numberOfDays(em, ey)); - }else{ - selSd=new Date(sy-1900, sm-1, sd); - selEd=new Date(ey-1900, em-1, ed); - } - - ArrayList optedData=dds.getTimeseriesDataWithOptions(selMon, selSd, selEd); - int tsi=DssDataSet.getExceedance_tsi(optedData, exc); - return new EvalExpression(new IntDouble (tsi, true)); - }else{ - Error.addEvaluationError(tsName+" is not a timeseries variable used in the Exceendance_TSI funciton for the time step of "+ControlData.timeStep+"."); - return new EvalExpression(new IntDouble (0, true)); - } - } - - public static EvalExpression daysIn(){ - int days=TimeOperation.numberOfDays(ControlData.currMonth, ControlData.currYear); - IntDouble id=new IntDouble(days, true); - return new EvalExpression(id); - } - - public static EvalExpression daysInTimeStep(){ - if (ControlData.currTimeStep.equals("1MON")){ - return daysIn(); - }else{ - IntDouble id=new IntDouble(1, true); - return new EvalExpression(id); - } - } - - public static EvalExpression tafcfs_term(String ident, EvalExpression ee, Stack sumIndex){ - ParallelVars prvs = new ParallelVars(); - if (ee==null){ - prvs.dataMonth=ControlData.currMonth; - prvs.dataYear=ControlData.currYear; - }else{ - IntDouble id=new IntDouble(0,true); - if (!ee.isNumeric()){ - HashMap multiplier=ee.getMultiplier(); - if (multiplier.size()==1){ - if (sumIndex.size()>0){ - LoopIndex li=sumIndex.pop(); - String indexName=li.getName(); - int indexValue=li.getValue(); - sumIndex.push(li); - id=new IntDouble(indexValue, true); - }else{ - Error.addEvaluationError("The index of "+ident+" should not contain decision variable."); - } - }else{ - Error.addEvaluationError("The index of "+ident+" should not contain decision variable."); - } - }else{ - id=ee.getValue(); - } - if (!id.isInt()){ - Error.addEvaluationError("The index of "+ident+" should be integer."); - } - prvs=TimeOperation.findTime(id.getData().intValue()); - } - double convert = tafcfs(ident, prvs); - IntDouble id1=new IntDouble(convert, false); - return new EvalExpression(id1); - } - - public static double tafcfs(String ident, ParallelVars prvs){ - double convert; - int days=TimeOperation.numberOfDays(prvs.dataMonth, prvs.dataYear); - if (ident.equals("taf_cfs")){ - if (ControlData.timeStep.equals("1MON")){ - return 504.1666667 / days; - }else{ - return 504.1666667; - } - }else if (ident.equals("cfs_taf")){ - if (ControlData.timeStep.equals("1MON")){ - return days / 504.1666667; - }else{ - return 1 / 504.1666667; - } - }else if (ident.equals("af_cfs")){ - if (ControlData.timeStep.equals("1MON")){ - return 504.1666667 / days / 1000.; - }else{ - return 504.1666667 / 1000.; - } - }else{ - if (ControlData.timeStep.equals("1MON")){ - return days / 504.1666667 * 1000.; - }else{ - return 1 / 504.1666667 * 1000.; - } - } - } - - public static EvalExpression term_YEAR(){ - IntDouble id=new IntDouble(TimeOperation.waterYearValue(), true); - return new EvalExpression(id); - } - - public static EvalExpression term_MONTH(){ - IntDouble id=new IntDouble(TimeOperation.waterMonthValue(ControlData.currMonth), true); - return new EvalExpression(id); - } - - public static EvalExpression term_DAY(){ - IntDouble id=new IntDouble(ControlData.currDay, true); - return new EvalExpression(id); - } - - public static EvalExpression term_MONTH_CONST(String month){ - int monthValue=TimeOperation.monthValue(month); - IntDouble id=new IntDouble(TimeOperation.waterMonthValue(monthValue), true, month, 0); - return new EvalExpression(id); - } - - public static EvalExpression term_PASTMONTH(String pastMonth){ - pastMonth=pastMonth.substring(4); - int pastMonthValue=TimeOperation.monthValue(pastMonth); - int index=pastMonthValue-ControlData.currMonth; - if (index>=0){ - index=index-12; - } - IntDouble id=new IntDouble(index,true); - return new EvalExpression(id); - } - - public static EvalExpression term_ARRAY_ITERATOR(ParallelVars prvs){ - IntDouble id=new IntDouble(prvs.timeArrayIndex, true); - return new EvalExpression(id); - } - - public static void sumExpression_IDENT(String ident, Stack sumIndex){ - //To Do: check if svar, dvar, alias contains ident - LoopIndex li=new LoopIndex(ident, 0, false, 0, 0, 0); - sumIndex.push(li); - } - - public static void initSumExpression(EvalExpression ee1, EvalExpression ee2, String s, Stack sumIndex){ - LoopIndex li = sumIndex.pop(); - li.step=1; - if (!s.equals("")){ - li.step=convertStringToInt(s); - } - if (!ee1.isNumeric() || !ee1.getValue().isInt()){ - Error.addEvaluationError("the starting index should be integer"); - } - if (!ee2.isNumeric() || !ee2.getValue().isInt()){ - Error.addEvaluationError("the ending index should be integer"); - } - li.start=ee1.getValue().getData().intValue(); - li.end=ee2.getValue().getData().intValue(); - li.setValue(li.start); - li.setIndexStart(true); - sumIndex.push(li); - if (li.start>li.end && li.step>0){ - ControlData.ignoreError=true; - }else if (li.start sumIndex){ - ControlData.ignoreError=false; - LoopIndex li=sumIndex.pop(); - if (li.step>=0){ - if (li.start>li.end) { - return new EvalExpression(new IntDouble(0.0, false)); - } - li.start=li.start+li.step; - if (li.start>li.end) return ee; - sumIndex.push(li); - for (int i=li.start; i<=li.end; i=i+li.step){ - li=sumIndex.pop(); - li.setValue(i); - li.setIndexStart(true); - sumIndex.push(li); - ANTLRStringStream stream = new ANTLRStringStream("s: "+expression); - EvaluatorLexer lexer = new EvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - EvaluatorParser evaluator = new EvaluatorParser(tokenStream); - evaluator.setSumIndex(sumIndex); - try{ - evaluator.evaluator(); - }catch (RecognitionException e){ - Error.addEvaluationError(e.toString()); - } - - EvalExpression ee0=evaluator.evalExpression; - ee=add(ee, ee0); - } - }else{ - if (li.start=li.end; i=i+li.step){ - li=sumIndex.pop(); - li.setValue(i); - li.setIndexStart(true); - sumIndex.push(li); - ANTLRStringStream stream = new ANTLRStringStream("s: "+expression); - EvaluatorLexer lexer = new EvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - EvaluatorParser evaluator = new EvaluatorParser(tokenStream); - evaluator.setSumIndex(sumIndex); - try{ - evaluator.evaluator(); - }catch (RecognitionException e){ - Error.addEvaluationError(e.toString()); - } - - EvalExpression ee0=evaluator.evalExpression; - ee=add(ee, ee0); - } - } - sumIndex.pop(); - return ee; - } - - public static Number assignWhereStatement(EvalExpression ee){ - if (ee.isNumeric()){ - return ee.getValue().getData(); - }else{ - return 1.0; - } - } - - public static EvalExpression tableSQL(String table, String select, HashMap where, HashMap given, String use){ - IntDouble id; - if (where==null){ - id=TableOperation.findData(table, select, given, use); - }else{ - id=TableOperation.findData(table, select, where, given, use); - } - return new EvalExpression(id); - } - - public static IntDouble expressionInput(EvalExpression ee){ - if (!ee.isNumeric()){ - Error.addEvaluationError("the value is not numeric and contains decision variable"); - } - return ee.getValue(); - } -} +package wrimsv2.evaluator; +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.TokenStream; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.components.ControlData; +import wrimsv2.components.Error; +import wrimsv2.components.IntDouble; +import wrimsv2.external.*; +import wrimsv2.hdf5.HDF5Reader; +import wrimsv2.parallel.ParallelVars; +import wrimsv2.solver.CbcSolver; + +import java.time.Duration; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.ArrayList; +import java.util.Set; +import java.util.Stack; +import java.util.Date; + +public class Evaluation { + public static double convertStringToDouble(String text){ + return Double.valueOf(text); + } + + public static int convertStringToInt(String text){ + return Integer.valueOf(text); + } + + public static String convertDoubleToString(double value){ + return Double.toString(value); + } + + public static String convertIntToString(int value){ + return Integer.toString(value); + } + + public static boolean relationStatement(EvalExpression ee1, EvalExpression ee2, String relation){ + if (!ee1.isNumeric() || !ee2.isNumeric()){ + Error.addEvaluationError("Decision variable can't be used in define condition"); + } + + double value1=ee1.getValue().getData().doubleValue(); + double value2=ee2.getValue().getData().doubleValue(); + + if (relation.equals("==")) { + if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ + if (value1>=value2-ControlData.relationTolerance && value1<=value2+ControlData.relationTolerance){ + return true; + }else{ + return false; + } + }else{ + if (value1==value2){ + return true; + }else{ + return false; + } + } + }else if (relation.equals(">")){ + if (value1>value2){ + return true; + }else{ + return false; + } + }else if (relation.equals("<")){ + if (value1=")){ + if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ + if (value1>=value2-ControlData.relationTolerance){ + return true; + }else{ + return false; + } + }else{ + if (value1>=value2){ + return true; + }else{ + return false; + } + } + }else{ + if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ + if (value1<=value2+ControlData.relationTolerance){ + return true; + }else{ + return false; + } + }else{ + if (value1<=value2){ + return true; + }else{ + return false; + } + } + } + } + + public static boolean range(String m1, String m2){ + return TimeOperation.range(ControlData.currMonth, m1, m2); + } + + public static boolean relationStatementSeries(boolean r1, boolean r2, String s){ + if (s.equals(".and.")) { + return (r1 && r2); + }else{ + return (r1 || r2); + } + } + + public static EvalConstraint constraintStatement (EvalExpression ee1, EvalExpression ee2, String s) { + EvalExpression ee=substract(ee1, ee2); + EvalConstraint ec=new EvalConstraint(); + ec.setEvalExpression(ee); + ec.setSign(s); + return ec; + } + + public static EvalExpression term_knownTS(IntDouble result){ + return new EvalExpression(result); + } + + public static EvalExpression term_IDENT (String ident, Stack sumIndex){ + if (sumIndex.size()>0){ + LoopIndex li=sumIndex.pop(); + if (li.getName().equals(ident) && li.getIndexStart()){ + sumIndex.push(li); + EvalExpression ee = new EvalExpression(); + IntDouble id = new IntDouble(li.getValue(),true, ident, 0); + ee.setValue(id); + return ee; + } + sumIndex.push(li); + } + if (ControlData.currSvMap.containsKey(ident)){ + EvalExpression ee=new EvalExpression(); + IntDouble id0 = ControlData.currSvMap.get(ident).getData(); + IntDouble id1 = new IntDouble(id0.getData(), id0.isInt(), ident, 0); + ee.setValue(id1); + return ee; + }else if (ControlData.currTsMap.containsKey(ident)){ + EvalExpression ee=new EvalExpression(); + IntDouble id0 = ControlData.currTsMap.get(ident).getData(); + IntDouble id1 = new IntDouble(id0.getData(), id0.isInt(), ident, 0); + ee.setValue(id1); + return ee; + }else if (ControlData.isPostProcessing && ControlData.currDvMap.containsKey(ident)){ + EvalExpression ee=new EvalExpression(); + IntDouble id0 = ControlData.currDvMap.get(ident).getData(); + IntDouble id1 = new IntDouble(id0.getData(), id0.isInt(), ident, 0); + ee.setValue(id1); + return ee; + }else if (ControlData.isPostProcessing && ControlData.currAliasMap.containsKey(ident)){ + EvalExpression ee=new EvalExpression(); + IntDouble id0 = ControlData.currAliasMap.get(ident).getData(); + if (id0==null) { + Error.addEvaluationError(ident+" is not defined before it is used."); + IntDouble id1=new IntDouble(1.0, false, ident, 0); + ee.setValue(id1); + return ee; + } + IntDouble id1 = new IntDouble(id0.getData(), id0.isInt(), ident, 0); + ee.setValue(id1); + return ee; + }else if (!ControlData.isPostProcessing && ControlData.currAliasMap.containsKey(ident) && !ControlData.currDvMap.containsKey(ident)){ + EvalExpression ee=new EvalExpression(); + IntDouble id0=new IntDouble(1.0, false, ident, 0); + ee.setValue(id0); + Error.addEvaluationError("Alias "+ident+" should not appear in constraint. "); + return ee; + } else if (ControlData.parameterMap.containsKey(ident)){ + EvalExpression ee=new EvalExpression(); + IntDouble id0=ControlData.parameterMap.get(ident).getData(); + ee.setValue(id0); + return ee; + } else if (!ControlData.isPostProcessing && !ControlData.currAliasMap.containsKey(ident) && !ControlData.currDvMap.containsKey(ident) && !ControlData.currDvSlackSurplusMap.containsKey(ident)){ + EvalExpression ee=new EvalExpression(); + IntDouble id0=new IntDouble(1.0, false, ident, 0); + ee.setValue(id0); + Error.addEvaluationError(ident+" is not defined before used."); + return ee; + } + + EvalExpression ee=new EvalExpression(); + IntDouble id0 = new IntDouble (0, true, ident, 0); + ee.setValue(id0); + HashMap multiplier=ee.getMultiplier(); + IntDouble id; + if (ControlData.currDvMap.containsKey(ident)){ + Dvar dv = ControlData.currDvMap.get(ident); + if (dv.integer.equals(Param.yes)){ + id= new IntDouble(1,true, ident, 0); + }else{ + id= new IntDouble(1.0,false, ident, 0); + } + }else{ + id= new IntDouble(1.0,false, ident, 0); + } + multiplier.put(ident, id); + return ee; + } + + public static EvalExpression term_SVAR (String ident){ + IntDouble data; + if (!ControlData.currSvMap.containsKey(ident)){ + if (!ControlData.currTsMap.containsKey(ident)){ + Error.addEvaluationError("State variable "+ident+" is not defined before used."); + IntDouble id=new IntDouble(1.0, false, ident, 0); + return new EvalExpression(id); + }else{ + data=ControlData.currTsMap.get(ident).getData(); + } + }else{ + data=ControlData.currSvMap.get(ident).getData(); + } + + if (data == null){ + Error.addEvaluationError("The value of state variable "+ident+" is not defined before used."); + IntDouble id=new IntDouble(1.0, false, ident, 0); + return new EvalExpression(id); + } + return new EvalExpression(new IntDouble(data.getData(), data.isInt(), ident, 0)); + } + + public static EvalExpression term_INTEGER (String integer){ + IntDouble id = new IntDouble(convertStringToInt(integer), true); + return new EvalExpression(id); + } + + public static EvalExpression term_FLOAT (String floatValue){ + IntDouble id = new IntDouble(convertStringToDouble(floatValue), false); + return new EvalExpression(id); + } + + public static EvalExpression unary (String s, EvalExpression ee){ + if (s !=null && s.equals("-")){ + if (ee.getValue().isInt()){ + int value=-ee.getValue().getData().intValue(); + ee.getValue().setData(value); + }else{ + double value=-ee.getValue().getData().doubleValue(); + ee.getValue().setData(value); + } + Map multiplier=ee.getMultiplier(); + for (String dvar : multiplier.keySet()) { + IntDouble id=multiplier.get(dvar); + if (id.isInt()){ + id.setData(-id.getData().intValue()); + }else{ + id.setData(-id.getData().doubleValue()); + } + multiplier.put(dvar, id); + } + } + return ee; + } + + public static EvalExpression mult(EvalExpression ee1, EvalExpression ee2){ + if (ee1.isNumeric()){ + IntDouble id1=ee1.getValue(); + IntDouble id2=ee2.getValue(); + ee2.setValue(multiplyOperation(id1,id2)); + Map multiplier=ee2.getMultiplier(); + Set keySet=multiplier.keySet(); + Iterator iterator=(Iterator) keySet.iterator(); + while (iterator.hasNext()) { + String dvar=(String) iterator.next(); + IntDouble id3=multiplyOperation(id1,multiplier.get(dvar)); + if (id3.getData().doubleValue()==0.0){ + iterator.remove(); + }else{ + multiplier.put(dvar, id3); + } + } + return ee2; + }else{ + if (ee2.isNumeric()){ + IntDouble id2=ee2.getValue(); + IntDouble id1=ee1.getValue(); + ee1.setValue(multiplyOperation(id2,id1)); + Map multiplier=ee1.getMultiplier(); + Set keySet=multiplier.keySet(); + Iterator iterator=(Iterator) keySet.iterator(); + while (iterator.hasNext()) { + String dvar=(String) iterator.next(); + IntDouble id3=multiplyOperation(id2,multiplier.get(dvar)); + if (id3.getData().doubleValue()==0.0){ + iterator.remove(); + }else{ + multiplier.put(dvar, id3); + } + } + return ee1; + }else{ + Error.addEvaluationError("Decision variable multiply decision variable appears. The problem is not linear."); + return ee1; + } + } + } + + public static IntDouble multiplyOperation(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().intValue()*id2.getData().intValue(), true); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().intValue()*id2.getData().doubleValue(), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()*id2.getData().intValue(), false); + }else{ + id=new IntDouble(id1.getData().doubleValue()*id2.getData().doubleValue(), false); + } + return id; + } + + public static EvalExpression divide(EvalExpression ee1, EvalExpression ee2){ + if (ee2.isNumeric()){ + IntDouble id2=ee2.getValue(); + IntDouble id1=ee1.getValue(); + if (id2.getData().doubleValue() ==0.0){ + if (id1.getData().doubleValue()==0.0 && ee1.isNumeric()){ + return ee1; + }else{ + Error.addEvaluationError("0.0 appears in divisor"); + } + return ee1; + } + ee1.setValue(divideOperation(id1,id2)); + Map multiplier=ee1.getMultiplier(); + for (String dvar : multiplier.keySet()) { + multiplier.put(dvar, divideOperation(multiplier.get(dvar),id2)); + } + return ee1; + }else{ + Error.addEvaluationError("Decision variable appears in divisor. The problem is not linear."); + return ee1; + } + } + + public static IntDouble divideOperation(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().intValue()/id2.getData().intValue(), true); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().intValue()/id2.getData().doubleValue(), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()/id2.getData().intValue(), false); + }else{ + id=new IntDouble(id1.getData().doubleValue()/id2.getData().doubleValue(), false); + } + return id; + } + + public static EvalExpression mod(EvalExpression ee1, EvalExpression ee2){ + if (ee1.isNumeric() && ee2.isNumeric()){ + IntDouble id1=ee1.getValue(); + IntDouble id2=ee2.getValue(); + ee1.setValue(modOperation(id1,id2)); + return ee1; + }else{ + Error.addEvaluationError("Decision variable appears in MOD calcualtion. The problem is not linear."); + return ee1; + } + } + + public static IntDouble modOperation(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id2.getData().doubleValue()==0.0){ + Error.addEvaluationError("Mod function uses 0 as divider."); + return new IntDouble(1.0, false); + } + if (id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().intValue()%id2.getData().intValue(), true); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().intValue()%id2.getData().doubleValue(), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()%id2.getData().intValue(), false); + }else{ + id=new IntDouble(id1.getData().doubleValue()%id2.getData().doubleValue(), false); + } + return id; + } + + public static EvalExpression round(EvalExpression ee1){ + if (ee1.isNumeric()){ + IntDouble id1=ee1.getValue(); + ee1.setValue(ValueEvaluation.round(id1)); + return ee1; + }else{ + Error.addEvaluationError("The arguement for the rounded variable is not numeric."); + return ee1; + } + } + + public static EvalExpression add(EvalExpression ee1, EvalExpression ee2){ + IntDouble id1=ee1.getValue(); + IntDouble id2=ee2.getValue(); + ee1.setValue(addOperation(id1,id2)); + Map multiplier1=ee1.getMultiplier(); + Map multiplier2=ee2.getMultiplier(); + for (String dvar : multiplier2.keySet()) { + if (multiplier1.containsKey(dvar)){ + IntDouble id3=addOperation(multiplier1.get(dvar),multiplier2.get(dvar)); + if (id3.getData().doubleValue()==0.0){ + multiplier1.remove(dvar); + }else{ + multiplier1.put(dvar, id3); + } + }else{ + multiplier1.put(dvar, multiplier2.get(dvar)); + } + } + return ee1; + } + + public static IntDouble addOperation(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().intValue()+id2.getData().intValue(), true); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().intValue()+id2.getData().doubleValue(), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()+id2.getData().intValue(), false); + }else{ + id=new IntDouble(id1.getData().doubleValue()+id2.getData().doubleValue(), false); + } + return id; + } + + public static EvalExpression substract(EvalExpression ee1, EvalExpression ee2){ + IntDouble id1=ee1.getValue(); + IntDouble id2=ee2.getValue(); + ee1.setValue(substractOperation(id1,id2)); + Map multiplier1=ee1.getMultiplier(); + Map multiplier2=ee2.getMultiplier(); + for (String dvar : multiplier2.keySet()) { + if (multiplier1.containsKey(dvar)){ + IntDouble id3=substractOperation(multiplier1.get(dvar),multiplier2.get(dvar)); + if (id3.getData().doubleValue()==0.0){ + multiplier1.remove(dvar); + }else{ + multiplier1.put(dvar, id3); + } + }else{ + IntDouble id0=new IntDouble(0,true); + multiplier1.put(dvar, substractOperation(id0,multiplier2.get(dvar))); + } + } + return ee1; + } + + public static IntDouble substractOperation(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().intValue()-id2.getData().intValue(), true); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().intValue()-id2.getData().doubleValue(), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()-id2.getData().intValue(), false); + }else{ + id=new IntDouble(id1.getData().doubleValue()-id2.getData().doubleValue(), false); + } + return id; + } + + public static EvalExpression noArgFunction(String ident){ + Class function; + IntDouble result; + try { + function = Class.forName("wrimsv2.external.Function"+ident); + + Stack stack = new Stack(); + + ExternalFunction ef; + if (ControlData.allExternalFunctionMap.containsKey(ident)){ + ef=ControlData.allExternalFunctionMap.get(ident); + }else{ + ef = (ExternalFunction)function.newInstance(); + ControlData.allExternalFunctionMap.put(ident, ef); + } + ef.execute(stack); + String valueString=stack.pop().toString(); + + if (valueString.contains(".")){ + result = new IntDouble(Double.parseDouble(valueString), false); + return new EvalExpression(result); + }else{ + result = new IntDouble(Integer.parseInt(valueString), true); + return new EvalExpression(result); + } + + } catch (Exception e) { + Error.addEvaluationError("The function " +ident+" has an error."); + e.printStackTrace(); + result=new IntDouble (1.0,false); + return new EvalExpression(result); + } + } + + public static EvalExpression argFunction(String ident, ArrayList> eeArray, Stack sumIndex){ + IntDouble result; + if (eeArray.size()==1){ + if (ControlData.currSvMap.containsKey(ident)||ControlData.currTsMap.containsKey(ident)||ControlData.currDvMap.containsKey(ident)||ControlData.currAliasMap.containsKey(ident)||ControlData.currDvSlackSurplusMap.containsKey(ident)) { + ArrayList eeArray1 = eeArray.get(0); + if (eeArray1.size()==1){ + String idName = eeArray1.get(0).getValue().getName(); + for (int k=0; k<12; k++){ + if (idName.equals(TimeOperation.month_const[k])){ + Error.addEvaluationError(idName+" can't be used in "+ident+"("+idName+")"); + return new EvalExpression(new IntDouble (1.0, false)); + } + } + return getTimeSeries(ident, eeArray1, sumIndex); + }else{ + Error.addEvaluationError("Variable "+ident+" has number of indexes different from 1."); + return new EvalExpression(new IntDouble (1.0, false)); + } + } + } + + Class function; + try { + function = Class.forName("wrimsv2.external.Function"+ident); + + Stack stack = new Stack(); + for (int i=0; i eeArray1=eeArray.get(i); + int size=eeArray1.size(); + if (size ==1){ + EvalExpression ee = eeArray1.get(0); + if (!ee.isNumeric()){ + int ai=i+1; + Error.addEvaluationError("The function " +ident+" has an unkown argument at argument index of "+ai+"."); + result=new IntDouble (0.0,false); + return new EvalExpression(result); + } + + IntDouble id=ee.getValue(); + if (id.isInt()){ + int value=id.getData().intValue(); + stack.push(value); + }else{ + double value=id.getData().doubleValue(); + stack.push(value); + } + }else if (size>1){ + Number[] valueArray = new Number[size]; + for (int j=0; j1){ + for (int i=0; i eeArray1=eeArray.get(i); + int size=eeArray1.size(); + if (size ==1){ + EvalExpression ee = eeArray1.get(0); + if (!ee.isNumeric()){ + int ai=i+1; + Error.addEvaluationError("The function " +ident+" has an unkown argument at argument index of "+ai+"."); + result=new IntDouble (0.0,false); + return new EvalExpression(result); + } + + IntDouble id=ee.getValue(); + if (id.isInt()){ + int value=(Integer) stack.pop(); + ValueEvaluation.setSvarIntValue(id, value); + }else{ + double value=(Double) stack.pop(); + ValueEvaluation.setSvarDoubleValue(id, value); + } + }else if (size>1){ + IntDouble id=eeArray1.get(0).getValue(); + if (id.isInt()){ + int[] valueArray = new int[size]; + valueArray=(int[])stack.pop(); + for (int j=0; j eeArray, Stack sumIndex){ + IntDouble result; + boolean isSumIndex=false; + int indexValue=0; + boolean isIndexStart=true; + ParallelVars prvs; + + EvalExpression ee=eeArray.get(0); + + if (!ee.isNumeric()){ + HashMap multiplier=ee.getMultiplier(); + if (multiplier.size()==1){ + LoopIndex li=sumIndex.pop(); + String indexName=li.getName(); + indexValue=li.getValue(); + isIndexStart=li.getIndexStart(); + sumIndex.push(li); + if (!(multiplier.containsKey(indexName) && multiplier.get(indexName).getData().doubleValue()==1.0 && ee.getValue().getData().doubleValue()==0.0)){ + Error.addEvaluationError("The index of "+ident+" contains decision variable."); + result=new IntDouble (0.0,false); + return new EvalExpression(result); + }else{ + isSumIndex=true; + } + }else{ + Error.addEvaluationError("The index of "+ident+" contains decision variable."); + result=new IntDouble (0.0,false); + return new EvalExpression(result); + } + } + + IntDouble id=ee.getValue(); + if (!id.isInt()){ + Error.addEvaluationError("The index of "+ident+" should be integer."); + result=new IntDouble (0.0,false); + return new EvalExpression(result); + } + + if (isSumIndex){ + if (isIndexStart){ + prvs=TimeOperation.findTime(indexValue); + }else{ + result=new IntDouble (1.0,false); + return new EvalExpression(result); + } + }else{ + prvs=TimeOperation.findTime(id.getData().intValue()); + } + + double value; + int idValue=id.getData().intValue(); + if (ControlData.currDvMap.containsKey(ident)){ + if (idValue<0){ + value=dvarAliasTimeSeries(ident,idValue, prvs); + }else if (idValue==0){ + LinkedHashMap multiplier = new LinkedHashMap(); + multiplier.put(ident, new IntDouble(1, true)); + EvalExpression eeResult=new EvalExpression(); + eeResult.setMultiplier(multiplier); + return eeResult; + }else{ + String futDvName=ident+"__fut__"+idValue; + if (SolverData.getDvarMap().containsKey(futDvName)){ + LinkedHashMap multiplier = new LinkedHashMap(); + multiplier.put(futDvName, new IntDouble(1, true)); + EvalExpression eeResult=new EvalExpression(); + eeResult.setMultiplier(multiplier); + return eeResult; + }else{ + Error.addEvaluationError("Time Array Dvar "+futDvName+" is used without definition."); + result=new IntDouble (1.0, false); + return new EvalExpression(result); + } + } + }else if (ControlData.currDvSlackSurplusMap.containsKey(ident)){ + if (idValue==0){ + LinkedHashMap multiplier = new LinkedHashMap(); + multiplier.put(ident, new IntDouble(1, true)); + EvalExpression eeResult=new EvalExpression(); + eeResult.setMultiplier(multiplier); + return eeResult; + }else if (idValue>0){ + String futDvSlackSurplusName=ident+"__fut__"+idValue; + LinkedHashMap multiplier = new LinkedHashMap(); + multiplier.put(futDvSlackSurplusName, new IntDouble(1, true)); + EvalExpression eeResult=new EvalExpression(); + eeResult.setMultiplier(multiplier); + return eeResult; + }else{ + Error.addEvaluationError("Slack surplus index of "+ident+", "+idValue+"<0. THe index has to be larger than 0."); + result=new IntDouble (1.0,false); + return new EvalExpression(result); + } + }else if (ControlData.currAliasMap.containsKey(ident)){ + value=dvarAliasTimeSeries(ident,idValue, prvs); + }else{ + if (ControlData.currSvMap.containsKey(ident)){ + if (idValue==0) { + result = ControlData.currSvMap.get(ident).getData(); + return new EvalExpression(result.copyOf()); + }else if(idValue>0){ + String futSvName=ident+"__fut__"+idValue; + if (ControlData.currSvFutMap.containsKey(futSvName)){ + result=ControlData.currSvFutMap.get(futSvName).getData(); + return new EvalExpression(result.copyOf()); + }else{ + if (!ControlData.ignoreError) Error.addEvaluationError(futSvName+", the future value of "+ident+" is used before defined."); + result=new IntDouble (1.0,false); + return new EvalExpression(result); + } + } + } + value=svarTimeSeries(ident, idValue, prvs); + } + + result=new IntDouble (value, false); + return new EvalExpression(result); + } + + public static double svarTimeSeries(String ident, int idValue, ParallelVars prvs){ + int index; + String entryNameTS=DssOperation.entryNameTS(ident, ControlData.timeStep); + if (DataTimeSeries.svTS.containsKey(entryNameTS)){ + DssDataSet dds=DataTimeSeries.svTS.get(entryNameTS); + index =timeSeriesIndex(dds, prvs); + ArrayList data=dds.getData(); + if (index>=0 && index=dds.getStudyStartIndex()){ + double value=data.get(index); + if (dds.fromDssFile()){ + if (value != -901.0 && value != -902.0){ + return value; + } + }else{ + return value; + } + } + } + if (DataTimeSeries.svInit.containsKey(entryNameTS)){ + DssDataSet dds=DataTimeSeries.svInit.get(entryNameTS); + index =timeSeriesIndex(dds, prvs); + ArrayList data=dds.getData(); + if (index>=0 && index data=dds.getData(); + if (index>=0 && index data=dds.getData(); + if (index>=0 && index=currTime){ + Error.addEvaluationError("The timeseries data for decision variable/alias "+ident+" is not available at or after current simulation period."); + return 1.0; + }else if(dataTime>=startTime && dataTime data=dds.getData(); + if (index>=0 && index0){ + Error.addEvaluationError("Can't access decision variable after the current time step."); + } + + /* + int index=indexValue+ControlData.currTimeStep.get(ControlData.currCycleIndex); + if (index>=0){ + if (indexValue>=0 && (ControlData.currEvalTypeIndex==0 || ControlData.currEvalTypeIndex==7)){ + Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); + return 1.0; + }else{ + DssDataSetFixLength dds=DataTimeSeries.dvAliasTS.get(entryNameTS); + if (dds==null){ + Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); + return 1.0; + } + double[] data=dds.getData(); + return data[index]; + } + } + */ + + DssDataSetFixLength ddsfl=DataTimeSeries.dvAliasTS.get(entryNameTS); + if (ddsfl!=null){ + Date memStartDate = ddsfl.getStartTime(); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+indexValue-1; + double[] datafl=ddsfl.getData(); + if (index>=datafl.length){ + Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); + return 1.0; + }else if (index>=0){ + return datafl[index]; + } + } + + if (!DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ + if (!getDVAliasInitTimeseries(ident)){ + Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +ident); + return 1.0; + } + } + + DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); + int index=timeSeriesIndex(dds, prvs); + ArrayList data=dds.getData(); + if (index>=0 && index0){ + Error.addEvaluationError("Can't access decision variable after the current time step."); + } + + /* + int index=indexValue+ControlData.currTimeStep.get(ControlData.currCycleIndex); + if (index>=0){ + DssDataSetFixLength dds=DataTimeSeries.dvAliasTSCycles.get(ci).get(entryNameTS); + if (dds==null){ + Error.addEvaluationError(ident + " at timestep " +indexValue+" for the No. "+ci+ " cycle doesn't have value"); + return 1.0; + } + double[] data=dds.getData(); + return data[index]; + } + */ + + DssDataSetFixLength ddsfl=DataTimeSeries.dvAliasTSCycles.get(ci).get(entryNameTS); + if (ddsfl!=null){ + Date memStartDate = ddsfl.getStartTime(); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+indexValue-1; + double[] datafl=ddsfl.getData(); + if (index>=datafl.length){ + Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); + return 1.0; + }else if (index>=0){ + return datafl[index]; + } + } + + if (!DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ + if (!getDVAliasInitTimeseries(ident)){ + Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +ident); + return 1.0; + } + } + + DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); + int index=timeSeriesIndex(dds, prvs); + ArrayList data=dds.getData(); + if (index>=0 && index> eeArray, ParallelVars prvs){ + //turn off when multi-dimensional array is used + if (eeArray.size()!=1){ + Error.addEvaluationError("The future index of array variable "+ident+" has to be a single integer."); + return new EvalExpression(new IntDouble(1.0,false)); + } + // + + ArrayList ee2Array = eeArray.get(0); + if (ee2Array.size() !=1){ + Error.addEvaluationError("The future index of array variable "+ident+" has to be a single integer but not a range."); + return new EvalExpression(new IntDouble(1.0,false)); + } + EvalExpression ee2 = ee2Array.get(0); + + if (!ee1.isNumeric() || !ee2.isNumeric()){ + Error.addEvaluationError("The index of array variable "+ident+" has to be an integer."); + return new EvalExpression(new IntDouble(1.0,false)); + } + IntDouble id1=ee1.getValue(); + IntDouble id2=ee2.getValue(); + if (!id1.isInt() || !id2.isInt()){ + Error.addEvaluationError("The index of array variable "+ident+" has to be an integer."); + return new EvalExpression(new IntDouble(1.0,false)); + } + int i1 = id1.getData().intValue(); + int i2 = id2.getData().intValue(); + + if (i1==0){ + EvalExpression ee = new EvalExpression(); + LinkedHashMap multiplier = ee.getMultiplier(); + if (i2==0){ + multiplier.put(ident, new IntDouble(1, true)); + return ee; + }else if (i2>0){ + String vn = ident+"__fut__"+id2; + multiplier.put(vn, new IntDouble(1, true)); + return ee; + } + } + + if (i1>0){ + Error.addEvaluationError("The second index of array variable "+ident+" has to be less than or equal to 0 in constraint statements."); + return new EvalExpression(new IntDouble(1.0,false)); + } + if (i2<0){ + Error.addEvaluationError("The first index of array variable "+ident+" has to be larger than or equal to 0."); + return new EvalExpression(new IntDouble(1.0,false)); + } + if (!ControlData.currDvMap.containsKey(ident) && !ControlData.currAliasMap.containsKey(ident)){ + Error.addEvaluationError("The array variable "+ident+" is not a dvar or alias. The value from the past time step could not be retrieved."); + return new EvalExpression(new IntDouble(1.0,false)); + } + String vn=ident+"__fut__"+i2; + String entryNameTS=DssOperation.entryNameTS(vn, ControlData.timeStep); + if (DataTimeSeries.dvAliasTS.containsKey(entryNameTS)){ + DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); + if (ddsfl!=null){ + Date memStartDate = ddsfl.getStartTime(); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+i1-1; + double[] datafl=ddsfl.getData(); + if (index>=datafl.length){ + Error.addEvaluationError(vn + " at timestep " +i1+" doesn't have value."); + return new EvalExpression(new IntDouble(1.0,false)); + }else if (index>=0){ + return new EvalExpression(new IntDouble(datafl[index], false)); + }else{ + Error.addEvaluationError(vn + " at timestep " +i1+" doesn't have value."); + return new EvalExpression(new IntDouble(1.0,false)); + } + } + + if (DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ + if (!getDVAliasInitTimeseries(ident)){ + Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +vn); + return new EvalExpression(new IntDouble(1.0,false)); + } + + DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); + int index = timeSeriesIndex(dds, prvs); + ArrayList data=dds.getData(); + if (index>=0 && index> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); + IntDouble data=new IntDouble(1.0,false); + if (varCycleValueMap.containsKey(ident)){ + Map var= varCycleValueMap.get(ident); + if (var.containsKey(cycle)){ + data=var.get(cycle); + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + if (data==null){ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return new IntDouble(1.0,false); + } + return new IntDouble(data.getData(),data.isInt()); + } + + public static IntDouble pastCycleIndexNoTimeArray(String ident, int index){ + int ci=ControlData.currCycleIndex+index; + if (ci<0){ + Error.addEvaluationError("The "+ci+" cycle from the current cycle is unvailable."); + return new IntDouble(1.0,false); + } + StudyDataSet sds = ControlData.currStudyDataSet; + String cycle=sds.getModelList().get(ci); + Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); + if (varCycleIndexValueMap.containsKey(ident)){ + Map valueMap = varCycleIndexValueMap.get(ident); + if (valueMap.containsKey(cycle)){ + return valueMap.get(cycle); + } + } + Error.addEvaluationError("Variable "+ident+" is not in "+ index+" from the current cycle - "+cycle); + return new IntDouble(1.0,false); + } + + public static IntDouble pastCycleTimeArray(String ident, String cycle, EvalExpression ee){ + IntDouble data=new IntDouble(1.0,false); + if (!ee.isNumeric()){ + Error.addEvaluationError("Time array index of "+ident+" contains decision variable."); + return data; + } + IntDouble id=ee.getValue(); + if (!id.isInt()){ + Error.addEvaluationError("Time array index of "+ident+" is not an integer."); + return data; + } + int index=id.getData().intValue(); + if (index<0){ + ArrayList eeArray=new ArrayList(); + eeArray.add(ee); + ModelDataSet mds=ControlData.currStudyDataSet.getModelDataSetMap().get(cycle); + EvalExpression ee1; + if (mds.dvMap.containsKey(ident) || mds.asMap.containsKey(ident)){ + ParallelVars prvs=TimeOperation.findTime(index); + //if (ControlData.outputCycleToDss){ + ArrayList ml = ControlData.currStudyDataSet.getModelList(); + int ci=-1; + for (int k=0; k> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); + String varTimeArrayName=ident+"__fut__"+index; + if (varTimeArrayCycleValueMap.containsKey(varTimeArrayName)){ + Map var= varTimeArrayCycleValueMap.get(varTimeArrayName); + if (var.containsKey(cycle)){ + data=var.get(cycle); + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + if (data==null){ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return new IntDouble(1.0,false); + } + return new IntDouble(data.getData(),data.isInt()); + } + + public static IntDouble pastCycleIndexTimeArray(String ident, int pci, EvalExpression ee){ + IntDouble data=new IntDouble(1.0,false); + int ci=ControlData.currCycleIndex+pci; + if (ci<0){ + Error.addEvaluationError("The "+ci+" cycle from the current cycle is unvailable."); + return new IntDouble(1.0,false); + } + if (!ee.isNumeric()){ + Error.addEvaluationError("Time array index of "+ident+" contains decision variable."); + return data; + } + IntDouble id=ee.getValue(); + if (!id.isInt()){ + Error.addEvaluationError("Time array index of "+ident+" is not an integer."); + return data; + } + int index=id.getData().intValue(); + StudyDataSet sds = ControlData.currStudyDataSet; + String cycle=sds.getModelList().get(ci); + if (index<0){ + ArrayList eeArray=new ArrayList(); + eeArray.add(ee); + ModelDataSet mds=ControlData.currStudyDataSet.getModelDataSetMap().get(cycle); + EvalExpression ee1; + if (mds.dvMap.containsKey(ident) || mds.asMap.containsKey(ident)){ + ParallelVars prvs=TimeOperation.findTime(index); + //if (ControlData.outputCycleToDss){ + return new IntDouble(dvarAliasCycleTimeSeries(ident, index, ci, prvs), false); + //}else{ + // return new IntDouble(dvarAliasTimeSeries(ident, index), false); + //} + }else{ + Error.addEvaluationError(ident+" is not a dvar/alias in the cycle of "+cycle+". Only dvar/alias in the past time step of "+index+" and past cycle of "+cycle+" can be used from previous cycles"); + return new IntDouble(1.0, false); + } + }else if(index==0){ + return pastCycleIndexNoTimeArray(ident, pci); + } + Map> varCycleIndexValueMap=sds.getVarCycleIndexValueMap(); + String varTimeArrayName=ident+"__fut__"+index; + if (varCycleIndexValueMap.containsKey(varTimeArrayName)){ + Map var= varCycleIndexValueMap.get(varTimeArrayName); + if (var.containsKey(cycle)){ + data=var.get(cycle); + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + if (data==null){ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return new IntDouble(1.0,false); + } + return new IntDouble(data.getData(),data.isInt()); + } + + public static ArrayList trunk_timeArray(String ident, IntDouble start, IntDouble end){ + ArrayList eeArray=new ArrayList(); + if (!start.isInt()){ + Error.addEvaluationError("The starting index of trunk data for variable " + ident + " is not an integer."); + EvalExpression ee=new EvalExpression(new IntDouble(1.0, false)); + eeArray.add(ee); + return eeArray; + }else if (!end.isInt()){ + Error.addEvaluationError("The ending index of trunk data for variable " + ident + " is not an integer."); + EvalExpression ee=new EvalExpression(new IntDouble(1.0, false)); + eeArray.add(ee); + return eeArray; + } + int si=start.getData().intValue(); + int ei=end.getData().intValue(); + + if (si>ei){ + Error.addEvaluationError("The starting index of trunk data for variable " + ident + " is larger than the ending index"); + EvalExpression ee=new EvalExpression(new IntDouble(1.0, false)); + eeArray.add(ee); + return eeArray; + } + + for (int i=si; i<=ei; i++){ + ArrayList indexArray1=new ArrayList (); + IntDouble index = new IntDouble(i, true); + indexArray1.add(index); + ArrayList> indexArray=new ArrayList> (); + indexArray.add(indexArray1); + IntDouble id=ValueEvaluation.argFunction(ident, indexArray); + id.setIndex(i); + id.setName(ident); + eeArray.add(new EvalExpression(id)); + } + return eeArray; + } + + public static EvalExpression max(EvalExpression ee1, EvalExpression ee2){ + if (!ee1.isNumeric() || !ee2.isNumeric()){ + Error.addEvaluationError("variable inside max function should not contain decision variable."); + } + return new EvalExpression(maxOperation(ee1.getValue(), ee2.getValue())); + } + + public static IntDouble maxOperation(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.max(id1.getData().intValue(),id2.getData().intValue()), true); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else{ + id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + } + return id; + } + + public static EvalExpression min(EvalExpression ee1, EvalExpression ee2){ + if (!ee1.isNumeric() || !ee2.isNumeric()){ + Error.addEvaluationError("variable inside min function should not contain decision variable."); + } + return new EvalExpression((minOperation(ee1.getValue(), ee2.getValue()))); + } + + public static IntDouble minOperation(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.min(id1.getData().intValue(),id2.getData().intValue()), true); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else{ + id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + } + return id; + } + + public static EvalExpression intFunc(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside int function should not contain decision variable."); + } + return new EvalExpression(intOperation(ee1.getValue())); + } + + public static IntDouble intOperation(IntDouble id1){ + IntDouble id; + if (!id1.isInt()){ + id=new IntDouble(((int)id1.getData().doubleValue()), true); + return id; + } + return id1; + } + + public static EvalExpression realFunc(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside int function should not contain decision variable."); + } + return new EvalExpression(realOperation(ee1.getValue())); + } + + public static IntDouble realOperation(IntDouble id1){ + IntDouble id; + if (id1.isInt()){ + id=new IntDouble((id1.getData().doubleValue()), false); + return id; + } + return id1; + } + + public static EvalExpression abs(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside abs function should not contain decision variable."); + } + return new EvalExpression(absOperation(ee1.getValue())); + } + + public static IntDouble absOperation(IntDouble id1){ + IntDouble id; + if (id1.isInt()){ + id=new IntDouble(Math.abs(id1.getData().intValue()), true); + }else{ + id=new IntDouble(Math.abs(id1.getData().doubleValue()), false); + } + return id; + } + + public static EvalExpression exp(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside log function should not contain decision variable."); + } + return new EvalExpression(expOperation(ee1.getValue())); + } + + public static IntDouble expOperation(IntDouble id1){ + IntDouble id; + if (id1.isInt()){ + id=new IntDouble(Math.exp(id1.getData().intValue()), false); + }else{ + id=new IntDouble(Math.exp(id1.getData().doubleValue()), false); + } + return id; + } + + public static EvalExpression log(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside log function should not contain decision variable."); + } + return new EvalExpression(logOperation(ee1.getValue())); + } + + public static IntDouble logOperation(IntDouble id1){ + IntDouble id; + if (id1.isInt()){ + id=new IntDouble(Math.log(id1.getData().intValue()), false); + }else{ + id=new IntDouble(Math.log(id1.getData().doubleValue()), false); + } + return id; + } + + public static EvalExpression log10(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside log10 function should not contain decision variable."); + } + return new EvalExpression(log10Operation(ee1.getValue())); + } + + public static IntDouble log10Operation(IntDouble id1){ + IntDouble id; + if (id1.isInt()){ + id=new IntDouble(Math.log10(id1.getData().intValue()), false); + }else{ + id=new IntDouble(Math.log10(id1.getData().doubleValue()), false); + } + return id; + } + + public static EvalExpression pow(EvalExpression ee1, EvalExpression ee2){ + if (!ee1.isNumeric() || !ee2.isNumeric()){ + Error.addEvaluationError("variable inside pow function should not contain decision variable."); + } + return new EvalExpression(powOperation(ee1.getValue(), ee2.getValue())); + } + + public static IntDouble powOperation(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.pow(id1.getData().intValue(),id2.getData().intValue()), false); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else{ + id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + } + return id; + } + + public static EvalExpression sin(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside sin function should not contain decision variable."); + } + + double degrees = ee1.getValue().getData().doubleValue(); + double radians = Math.toRadians(degrees); + return new EvalExpression(new IntDouble(Math.sin(radians), false)); + } + + public static EvalExpression cos(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside cos function should not contain decision variable."); + } + + double degrees = ee1.getValue().getData().doubleValue(); + double radians = Math.toRadians(degrees); + return new EvalExpression(new IntDouble(Math.cos(radians), false)); + } + + public static EvalExpression tan(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside tan function should not contain decision variable."); + } + + double degrees = ee1.getValue().getData().doubleValue(); + double radians = Math.toRadians(degrees); + return new EvalExpression(new IntDouble(Math.tan(radians), false)); + } + + public static EvalExpression cot(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside cot function should not contain decision variable."); + } + + double degrees = ee1.getValue().getData().doubleValue(); + if (degrees==90.0){ + return new EvalExpression(new IntDouble(0.0, false)); + } + double radians = Math.toRadians(degrees); + return new EvalExpression(new IntDouble(1.0/Math.tan(radians), false)); + } + + public static EvalExpression asin(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside asin function should not contain decision variable."); + } + + double value = ee1.getValue().getData().doubleValue(); + double radians = Math.asin(value); + return new EvalExpression(new IntDouble(Math.toDegrees(radians), false)); + } + + public static EvalExpression acos(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside acos function should not contain decision variable."); + } + + double value = ee1.getValue().getData().doubleValue(); + double radians = Math.acos(value); + return new EvalExpression(new IntDouble(Math.toDegrees(radians), false)); + } + + public static EvalExpression atan(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside atan function should not contain decision variable."); + } + + double value = ee1.getValue().getData().doubleValue(); + double radians = Math.atan(value); + return new EvalExpression(new IntDouble(Math.toDegrees(radians), false)); + } + + public static EvalExpression acot(EvalExpression ee1){ + if (!ee1.isNumeric()){ + Error.addEvaluationError("variable inside acot function should not contain decision variable."); + } + + double value = ee1.getValue().getData().doubleValue(); + if (value == 0.){ + return new EvalExpression(new IntDouble(90.0, false)); + } + double radians = Math.atan(1.0/value); + return new EvalExpression(new IntDouble(Math.toDegrees(radians), false)); + } + + public static EvalExpression exceedance(String tsName, EvalExpression exc_ee, String selMon, String syStr, String smStr, String sdStr, String eyStr, String emStr, String edStr){ + String entryNameTS=DssOperation.entryNameTS(tsName, ControlData.timeStep); + if (DataTimeSeries.svTS.containsKey(entryNameTS)){ + DssDataSet dds = DataTimeSeries.svTS.get(entryNameTS); + int sy = Integer.parseInt(syStr); + int sd = Integer.parseInt(sdStr); + int ey = Integer.parseInt(eyStr); + int ed = Integer.parseInt(edStr); + int sm = TimeOperation.monthValue(smStr); + int em = TimeOperation.monthValue(emStr); + + double exc=1.0; + if (exc_ee.isNumeric()){ + exc=exc_ee.getValue().getData().doubleValue(); + }else{ + Error.addEvaluationError("Exceedance level has unknown variable."); + return new EvalExpression(new IntDouble (1.0, false)); + } + if (exc<=0.0 || exc>1.0){ + Error.addEvaluationError("Exceedance level must be >0.0 and <=1.0"); + return new EvalExpression(new IntDouble (1.0, false)); + } + + Date selSd; + Date selEd; + if (ControlData.timeStep.equals("1MON")){ + selSd=new Date(sy-1900, sm-1, TimeOperation.numberOfDays(sm, sy)); + selEd=new Date(ey-1900, em-1, TimeOperation.numberOfDays(em, ey)); + }else{ + selSd=new Date(sy-1900, sm-1, sd); + selEd=new Date(ey-1900, em-1, ed); + } + + ArrayList optedData=dds.getTimeseriesDataWithOptions(selMon, selSd, selEd); + double value=DssDataSet.getExceedance(optedData, exc); + return new EvalExpression(new IntDouble (value, false)); + }else{ + Error.addEvaluationError(tsName+" is not a timeseries variable used in the Exceendance funciton for the time step of "+ControlData.timeStep+"."); + return new EvalExpression(new IntDouble (1.0, false)); + } + } + + public static EvalExpression exceedance_tsi(String tsName, EvalExpression exc_ee, String selMon, String syStr, String smStr, String sdStr, String eyStr, String emStr, String edStr){ + String entryNameTS=DssOperation.entryNameTS(tsName, ControlData.timeStep); + if (DataTimeSeries.svTS.containsKey(entryNameTS)){ + DssDataSet dds = DataTimeSeries.svTS.get(entryNameTS); + int sy = Integer.parseInt(syStr); + int sd = Integer.parseInt(sdStr); + int ey = Integer.parseInt(eyStr); + int ed = Integer.parseInt(edStr); + int sm = TimeOperation.monthValue(smStr); + int em = TimeOperation.monthValue(emStr); + + double exc=1.0; + if (exc_ee.isNumeric()){ + exc=exc_ee.getValue().getData().doubleValue(); + }else{ + Error.addEvaluationError("Exceedance level has unknown variable."); + return new EvalExpression(new IntDouble (0, true)); + } + if (exc<=0.0 || exc>1.0){ + Error.addEvaluationError("Exceedance level must be >0.0 and <=1.0"); + return new EvalExpression(new IntDouble (0, true)); + } + + Date selSd; + Date selEd; + if (ControlData.timeStep.equals("1MON")){ + selSd=new Date(sy-1900, sm-1, TimeOperation.numberOfDays(sm, sy)); + selEd=new Date(ey-1900, em-1, TimeOperation.numberOfDays(em, ey)); + }else{ + selSd=new Date(sy-1900, sm-1, sd); + selEd=new Date(ey-1900, em-1, ed); + } + + ArrayList optedData=dds.getTimeseriesDataWithOptions(selMon, selSd, selEd); + int tsi=DssDataSet.getExceedance_tsi(optedData, exc); + return new EvalExpression(new IntDouble (tsi, true)); + }else{ + Error.addEvaluationError(tsName+" is not a timeseries variable used in the Exceendance_TSI funciton for the time step of "+ControlData.timeStep+"."); + return new EvalExpression(new IntDouble (0, true)); + } + } + + public static EvalExpression daysIn(){ + int days=TimeOperation.numberOfDays(ControlData.currMonth, ControlData.currYear); + IntDouble id=new IntDouble(days, true); + return new EvalExpression(id); + } + + public static EvalExpression daysInTimeStep(){ + if (ControlData.currTimeStep.equals("1MON")){ + return daysIn(); + }else{ + IntDouble id=new IntDouble(1, true); + return new EvalExpression(id); + } + } + + public static EvalExpression tafcfs_term(String ident, EvalExpression ee, Stack sumIndex){ + ParallelVars prvs = new ParallelVars(); + if (ee==null){ + prvs.dataMonth=ControlData.currMonth; + prvs.dataYear=ControlData.currYear; + }else{ + IntDouble id=new IntDouble(0,true); + if (!ee.isNumeric()){ + HashMap multiplier=ee.getMultiplier(); + if (multiplier.size()==1){ + if (sumIndex.size()>0){ + LoopIndex li=sumIndex.pop(); + String indexName=li.getName(); + int indexValue=li.getValue(); + sumIndex.push(li); + id=new IntDouble(indexValue, true); + }else{ + Error.addEvaluationError("The index of "+ident+" should not contain decision variable."); + } + }else{ + Error.addEvaluationError("The index of "+ident+" should not contain decision variable."); + } + }else{ + id=ee.getValue(); + } + if (!id.isInt()){ + Error.addEvaluationError("The index of "+ident+" should be integer."); + } + prvs=TimeOperation.findTime(id.getData().intValue()); + } + double convert = tafcfs(ident, prvs); + IntDouble id1=new IntDouble(convert, false); + return new EvalExpression(id1); + } + + public static double tafcfs(String ident, ParallelVars prvs){ + double convert; + int days=TimeOperation.numberOfDays(prvs.dataMonth, prvs.dataYear); + if (ident.equals("taf_cfs")){ + if (ControlData.timeStep.equals("1MON")){ + return 504.1666667 / days; + }else{ + return 504.1666667; + } + }else if (ident.equals("cfs_taf")){ + if (ControlData.timeStep.equals("1MON")){ + return days / 504.1666667; + }else{ + return 1 / 504.1666667; + } + }else if (ident.equals("af_cfs")){ + if (ControlData.timeStep.equals("1MON")){ + return 504.1666667 / days / 1000.; + }else{ + return 504.1666667 / 1000.; + } + }else{ + if (ControlData.timeStep.equals("1MON")){ + return days / 504.1666667 * 1000.; + }else{ + return 1 / 504.1666667 * 1000.; + } + } + } + + public static EvalExpression term_YEAR(){ + IntDouble id=new IntDouble(TimeOperation.waterYearValue(), true); + return new EvalExpression(id); + } + + public static EvalExpression term_MONTH(){ + IntDouble id=new IntDouble(TimeOperation.waterMonthValue(ControlData.currMonth), true); + return new EvalExpression(id); + } + + public static EvalExpression term_DAY(){ + IntDouble id=new IntDouble(ControlData.currDay, true); + return new EvalExpression(id); + } + + public static EvalExpression term_MONTH_CONST(String month){ + int monthValue=TimeOperation.monthValue(month); + IntDouble id=new IntDouble(TimeOperation.waterMonthValue(monthValue), true, month, 0); + return new EvalExpression(id); + } + + public static EvalExpression term_PASTMONTH(String pastMonth){ + pastMonth=pastMonth.substring(4); + int pastMonthValue=TimeOperation.monthValue(pastMonth); + int index=pastMonthValue-ControlData.currMonth; + if (index>=0){ + index=index-12; + } + IntDouble id=new IntDouble(index,true); + return new EvalExpression(id); + } + + public static EvalExpression term_ARRAY_ITERATOR(ParallelVars prvs){ + IntDouble id=new IntDouble(prvs.timeArrayIndex, true); + return new EvalExpression(id); + } + + public static void sumExpression_IDENT(String ident, Stack sumIndex){ + //To Do: check if svar, dvar, alias contains ident + LoopIndex li=new LoopIndex(ident, 0, false, 0, 0, 0); + sumIndex.push(li); + } + + public static void initSumExpression(EvalExpression ee1, EvalExpression ee2, String s, Stack sumIndex){ + LoopIndex li = sumIndex.pop(); + li.step=1; + if (!s.equals("")){ + li.step=convertStringToInt(s); + } + if (!ee1.isNumeric() || !ee1.getValue().isInt()){ + Error.addEvaluationError("the starting index should be integer"); + } + if (!ee2.isNumeric() || !ee2.getValue().isInt()){ + Error.addEvaluationError("the ending index should be integer"); + } + li.start=ee1.getValue().getData().intValue(); + li.end=ee2.getValue().getData().intValue(); + li.setValue(li.start); + li.setIndexStart(true); + sumIndex.push(li); + if (li.start>li.end && li.step>0){ + ControlData.ignoreError=true; + }else if (li.start sumIndex){ + ControlData.ignoreError=false; + LoopIndex li=sumIndex.pop(); + if (li.step>=0){ + if (li.start>li.end) { + return new EvalExpression(new IntDouble(0.0, false)); + } + li.start=li.start+li.step; + if (li.start>li.end) return ee; + sumIndex.push(li); + for (int i=li.start; i<=li.end; i=i+li.step){ + li=sumIndex.pop(); + li.setValue(i); + li.setIndexStart(true); + sumIndex.push(li); + ANTLRStringStream stream = new ANTLRStringStream("s: "+expression); + EvaluatorLexer lexer = new EvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + EvaluatorParser evaluator = new EvaluatorParser(tokenStream); + evaluator.setSumIndex(sumIndex); + try{ + evaluator.evaluator(); + }catch (RecognitionException e){ + Error.addEvaluationError(e.toString()); + } + + EvalExpression ee0=evaluator.evalExpression; + ee=add(ee, ee0); + } + }else{ + if (li.start=li.end; i=i+li.step){ + li=sumIndex.pop(); + li.setValue(i); + li.setIndexStart(true); + sumIndex.push(li); + ANTLRStringStream stream = new ANTLRStringStream("s: "+expression); + EvaluatorLexer lexer = new EvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + EvaluatorParser evaluator = new EvaluatorParser(tokenStream); + evaluator.setSumIndex(sumIndex); + try{ + evaluator.evaluator(); + }catch (RecognitionException e){ + Error.addEvaluationError(e.toString()); + } + + EvalExpression ee0=evaluator.evalExpression; + ee=add(ee, ee0); + } + } + sumIndex.pop(); + return ee; + } + + public static Number assignWhereStatement(EvalExpression ee){ + if (ee.isNumeric()){ + return ee.getValue().getData(); + }else{ + return 1.0; + } + } + + public static EvalExpression tableSQL(String table, String select, HashMap where, HashMap given, String use){ + IntDouble id; + if (where==null){ + id=TableOperation.findData(table, select, given, use); + }else{ + id=TableOperation.findData(table, select, where, given, use); + } + return new EvalExpression(id); + } + + public static IntDouble expressionInput(EvalExpression ee){ + if (!ee.isNumeric()){ + Error.addEvaluationError("the value is not numeric and contains decision variable"); + } + return ee.getValue(); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/LookUpTable.java b/wrims-core/src/main/java/wrimsv2/evaluator/LookUpTable.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/LookUpTable.java rename to wrims-core/src/main/java/wrimsv2/evaluator/LookUpTable.java index cde75156f..3ce90f9b9 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/LookUpTable.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/LookUpTable.java @@ -1,30 +1,30 @@ -package wrimsv2.evaluator; - -import java.util.HashMap; -import java.util.ArrayList; - -public class LookUpTable { - private String name=null; - private HashMap field = new HashMap(); - private ArrayList data=new ArrayList(); - - public String getName(){ - return name; - } - - public void setName(String name){ - this.name=name; - } - - public HashMap getField(){ - return field; - } - - public void setField(HashMap field){ - this.field=field; - } - - public ArrayList getData(){ - return data; - } -} +package wrimsv2.evaluator; + +import java.util.HashMap; +import java.util.ArrayList; + +public class LookUpTable { + private String name=null; + private HashMap field = new HashMap(); + private ArrayList data=new ArrayList(); + + public String getName(){ + return name; + } + + public void setName(String name){ + this.name=name; + } + + public HashMap getField(){ + return field; + } + + public void setField(HashMap field){ + this.field=field; + } + + public ArrayList getData(){ + return data; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/LoopIndex.java b/wrims-core/src/main/java/wrimsv2/evaluator/LoopIndex.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/LoopIndex.java rename to wrims-core/src/main/java/wrimsv2/evaluator/LoopIndex.java index d7cbb1338..a0b9e410c 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/LoopIndex.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/LoopIndex.java @@ -1,43 +1,43 @@ -package wrimsv2.evaluator; - -public class LoopIndex { - private String name; - private int value; - private boolean indexStart; - public int start; - public int end; - public int step; - - public LoopIndex(String name, int value, boolean indexStart, int start, int end, int step){ - this.name=name; - this.value=value; - this.indexStart=indexStart; - this.start=start; - this.end=end; - this.step=step; - } - - public void setName(String name){ - this.name=name; - } - - public void setValue(int value){ - this.value=value; - } - - public String getName(){ - return name; - } - - public int getValue(){ - return value; - } - - public boolean getIndexStart(){ - return indexStart; - } - - public void setIndexStart(boolean indexStart){ - this.indexStart=indexStart; - } -} +package wrimsv2.evaluator; + +public class LoopIndex { + private String name; + private int value; + private boolean indexStart; + public int start; + public int end; + public int step; + + public LoopIndex(String name, int value, boolean indexStart, int start, int end, int step){ + this.name=name; + this.value=value; + this.indexStart=indexStart; + this.start=start; + this.end=end; + this.step=step; + } + + public void setName(String name){ + this.name=name; + } + + public void setValue(int value){ + this.value=value; + } + + public String getName(){ + return name; + } + + public int getValue(){ + return value; + } + + public boolean getIndexStart(){ + return indexStart; + } + + public void setIndexStart(boolean indexStart){ + this.indexStart=indexStart; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/PreEvaluator.java b/wrims-core/src/main/java/wrimsv2/evaluator/PreEvaluator.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/PreEvaluator.java rename to wrims-core/src/main/java/wrimsv2/evaluator/PreEvaluator.java index b197c678a..0958b5d5b 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/PreEvaluator.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/PreEvaluator.java @@ -1,226 +1,226 @@ -package wrimsv2.evaluator; - -import java.util.ArrayList; -import java.util.Map; - -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.Goal; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.components.ControlData; -import wrimsv2.components.Error; -import wrimsv2.components.IntDouble; -import wrimsv2.components.VariableTimeStep; - -public class PreEvaluator { - private ArrayList svList; - private Map svMap; - private ArrayList gList; - private Map gMap; - private ArrayList dvList; - private Map dvMap; - private ArrayList asList; - private Map asMap; - private ArrayList wtList; - private Map wtMap; - private ArrayList wtSlackSurplusList; - private Map wtSlackSurplusMap; - private ArrayList modelConditionList; - - public PreEvaluator(StudyDataSet sds ){ - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - for (int i=0; i modelConditionParsers=new ArrayList(); - for (String modelCondition: modelConditionList){ - //System.out.println("PreEvaluate model condition"+modelCondition); - String evalString="c: "+modelCondition; - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - modelConditionParsers.add(new ValueEvaluatorParser(tokenStream)); - } - sds.setModelConditionParsers(modelConditionParsers); - } - - public void preEvaluateWeight(){ - for (String wtName: wtList){ - //System.out.println("PreEvaluate weight "+wtName); - WeightElement weight=wtMap.get(wtName); - - String evalString="v: "+weight.weight; - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - weight.weightParser = new ValueEvaluatorParser(tokenStream); - - evalString="v: "+weight.timeArraySize; - stream = new ANTLRStringStream(evalString); - lexer = new ValueEvaluatorLexer(stream); - tokenStream = new CommonTokenStream(lexer); - weight.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); - } - } - - public void preEvaluateWeightSlackSurplus(){ - for (String wtSlackSurplusName: wtSlackSurplusList){ - //System.out.println("PreEvaluate weight slack surplus"+wtName); - WeightElement weightSlackSurplus=wtSlackSurplusMap.get(wtSlackSurplusName); - - String evalString="v: "+weightSlackSurplus.weight; - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - weightSlackSurplus.weightParser = new ValueEvaluatorParser(tokenStream); - - evalString="v: "+weightSlackSurplus.timeArraySize; - stream = new ANTLRStringStream(evalString); - lexer = new ValueEvaluatorLexer(stream); - tokenStream = new CommonTokenStream(lexer); - weightSlackSurplus.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); - } - } - - public void preEvaluateAlias(){ - for (String asName: asList){ - //System.out.println("PreEvaluate alias "+asName); - Alias alias=asMap.get(asName); - - String evalString="v: "+alias.expression; - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - alias.expressionParser = new ValueEvaluatorParser(tokenStream); - - evalString="v: "+alias.timeArraySize; - stream = new ANTLRStringStream(evalString); - lexer = new ValueEvaluatorLexer(stream); - tokenStream = new CommonTokenStream(lexer); - alias.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); - } - } - - public void preEvaluateDvar(){ - for (String dvName: dvList){ - //System.out.println("PreEvaluate dvar "+dvName); - Dvar dvar=dvMap.get(dvName); - - String evalString="v: "+dvar.upperBound; - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - dvar.upperBoundParser = new ValueEvaluatorParser(tokenStream); - - evalString="v: "+dvar.lowerBound; - stream = new ANTLRStringStream(evalString); - lexer = new ValueEvaluatorLexer(stream); - tokenStream = new CommonTokenStream(lexer); - dvar.lowerBoundParser = new ValueEvaluatorParser(tokenStream); - - evalString="v: "+dvar.timeArraySize; - stream = new ANTLRStringStream(evalString); - lexer = new ValueEvaluatorLexer(stream); - tokenStream = new CommonTokenStream(lexer); - dvar.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); - } - } - - public void preEvaluateGoal(){ - for (String gName: gList){ - //System.out.println("PreEvaluate constraint "+gName); - Goal goal=gMap.get(gName); - ArrayList caseCondition=goal.caseCondition; - int i=-1; - goal.caseConditionParsers=new ArrayList(); - goal.caseExpressionParsers=new ArrayList(); - while(i<=caseCondition.size()-2){ - i=i+1; - String evalString="c: "+caseCondition.get(i); - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - ValueEvaluatorParser evaluator = new ValueEvaluatorParser(tokenStream); - goal.caseConditionParsers.add(evaluator); - - String evalString1="g: "+goal.caseExpression.get(i); - ANTLRStringStream stream1 = new ANTLRStringStream(evalString1); - EvaluatorLexer lexer1 = new EvaluatorLexer(stream1); - TokenStream tokenStream1 = new CommonTokenStream(lexer1); - EvaluatorParser evaluator1 = new EvaluatorParser(tokenStream1); - goal.caseExpressionParsers.add(evaluator1); - } - String evalString="v: "+goal.timeArraySize; - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - CommonTokenStream tokenStream = new CommonTokenStream(lexer); - goal.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); - } - } - - public void preEvaluateSvar(){ - for (String svName: svList){ - //System.out.println("PreEvaluate svar "+svName); - Svar svar=svMap.get(svName); - ArrayList caseCondition=svar.caseCondition; - int i=-1; - svar.caseConditionParsers=new ArrayList(); - svar.caseExpressionParsers=new ArrayList(); - while(i<=caseCondition.size()-2){ - i=i+1; - String evalString="c: "+caseCondition.get(i); - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - ValueEvaluatorParser evaluator = new ValueEvaluatorParser(tokenStream); - svar.caseConditionParsers.add(evaluator); - - evalString="v: "+svar.caseExpression.get(i); - stream = new ANTLRStringStream(evalString); - lexer = new ValueEvaluatorLexer(stream); - tokenStream = new CommonTokenStream(lexer); - evaluator = new ValueEvaluatorParser(tokenStream); - svar.caseExpressionParsers.add(evaluator); - } - String evalString="v: "+svar.timeArraySize; - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - CommonTokenStream tokenStream = new CommonTokenStream(lexer); - svar.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); - } - } -} +package wrimsv2.evaluator; + +import java.util.ArrayList; +import java.util.Map; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.TokenStream; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.Goal; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.components.ControlData; +import wrimsv2.components.Error; +import wrimsv2.components.IntDouble; +import wrimsv2.components.VariableTimeStep; + +public class PreEvaluator { + private ArrayList svList; + private Map svMap; + private ArrayList gList; + private Map gMap; + private ArrayList dvList; + private Map dvMap; + private ArrayList asList; + private Map asMap; + private ArrayList wtList; + private Map wtMap; + private ArrayList wtSlackSurplusList; + private Map wtSlackSurplusMap; + private ArrayList modelConditionList; + + public PreEvaluator(StudyDataSet sds ){ + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + for (int i=0; i modelConditionParsers=new ArrayList(); + for (String modelCondition: modelConditionList){ + //System.out.println("PreEvaluate model condition"+modelCondition); + String evalString="c: "+modelCondition; + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + modelConditionParsers.add(new ValueEvaluatorParser(tokenStream)); + } + sds.setModelConditionParsers(modelConditionParsers); + } + + public void preEvaluateWeight(){ + for (String wtName: wtList){ + //System.out.println("PreEvaluate weight "+wtName); + WeightElement weight=wtMap.get(wtName); + + String evalString="v: "+weight.weight; + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + weight.weightParser = new ValueEvaluatorParser(tokenStream); + + evalString="v: "+weight.timeArraySize; + stream = new ANTLRStringStream(evalString); + lexer = new ValueEvaluatorLexer(stream); + tokenStream = new CommonTokenStream(lexer); + weight.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); + } + } + + public void preEvaluateWeightSlackSurplus(){ + for (String wtSlackSurplusName: wtSlackSurplusList){ + //System.out.println("PreEvaluate weight slack surplus"+wtName); + WeightElement weightSlackSurplus=wtSlackSurplusMap.get(wtSlackSurplusName); + + String evalString="v: "+weightSlackSurplus.weight; + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + weightSlackSurplus.weightParser = new ValueEvaluatorParser(tokenStream); + + evalString="v: "+weightSlackSurplus.timeArraySize; + stream = new ANTLRStringStream(evalString); + lexer = new ValueEvaluatorLexer(stream); + tokenStream = new CommonTokenStream(lexer); + weightSlackSurplus.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); + } + } + + public void preEvaluateAlias(){ + for (String asName: asList){ + //System.out.println("PreEvaluate alias "+asName); + Alias alias=asMap.get(asName); + + String evalString="v: "+alias.expression; + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + alias.expressionParser = new ValueEvaluatorParser(tokenStream); + + evalString="v: "+alias.timeArraySize; + stream = new ANTLRStringStream(evalString); + lexer = new ValueEvaluatorLexer(stream); + tokenStream = new CommonTokenStream(lexer); + alias.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); + } + } + + public void preEvaluateDvar(){ + for (String dvName: dvList){ + //System.out.println("PreEvaluate dvar "+dvName); + Dvar dvar=dvMap.get(dvName); + + String evalString="v: "+dvar.upperBound; + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + dvar.upperBoundParser = new ValueEvaluatorParser(tokenStream); + + evalString="v: "+dvar.lowerBound; + stream = new ANTLRStringStream(evalString); + lexer = new ValueEvaluatorLexer(stream); + tokenStream = new CommonTokenStream(lexer); + dvar.lowerBoundParser = new ValueEvaluatorParser(tokenStream); + + evalString="v: "+dvar.timeArraySize; + stream = new ANTLRStringStream(evalString); + lexer = new ValueEvaluatorLexer(stream); + tokenStream = new CommonTokenStream(lexer); + dvar.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); + } + } + + public void preEvaluateGoal(){ + for (String gName: gList){ + //System.out.println("PreEvaluate constraint "+gName); + Goal goal=gMap.get(gName); + ArrayList caseCondition=goal.caseCondition; + int i=-1; + goal.caseConditionParsers=new ArrayList(); + goal.caseExpressionParsers=new ArrayList(); + while(i<=caseCondition.size()-2){ + i=i+1; + String evalString="c: "+caseCondition.get(i); + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + ValueEvaluatorParser evaluator = new ValueEvaluatorParser(tokenStream); + goal.caseConditionParsers.add(evaluator); + + String evalString1="g: "+goal.caseExpression.get(i); + ANTLRStringStream stream1 = new ANTLRStringStream(evalString1); + EvaluatorLexer lexer1 = new EvaluatorLexer(stream1); + TokenStream tokenStream1 = new CommonTokenStream(lexer1); + EvaluatorParser evaluator1 = new EvaluatorParser(tokenStream1); + goal.caseExpressionParsers.add(evaluator1); + } + String evalString="v: "+goal.timeArraySize; + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + CommonTokenStream tokenStream = new CommonTokenStream(lexer); + goal.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); + } + } + + public void preEvaluateSvar(){ + for (String svName: svList){ + //System.out.println("PreEvaluate svar "+svName); + Svar svar=svMap.get(svName); + ArrayList caseCondition=svar.caseCondition; + int i=-1; + svar.caseConditionParsers=new ArrayList(); + svar.caseExpressionParsers=new ArrayList(); + while(i<=caseCondition.size()-2){ + i=i+1; + String evalString="c: "+caseCondition.get(i); + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + ValueEvaluatorParser evaluator = new ValueEvaluatorParser(tokenStream); + svar.caseConditionParsers.add(evaluator); + + evalString="v: "+svar.caseExpression.get(i); + stream = new ANTLRStringStream(evalString); + lexer = new ValueEvaluatorLexer(stream); + tokenStream = new CommonTokenStream(lexer); + evaluator = new ValueEvaluatorParser(tokenStream); + svar.caseExpressionParsers.add(evaluator); + } + String evalString="v: "+svar.timeArraySize; + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + CommonTokenStream tokenStream = new CommonTokenStream(lexer); + svar.timeArraySizeParser = new ValueEvaluatorParser(tokenStream); + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/PreEvaluatorTree.java b/wrims-core/src/main/java/wrimsv2/evaluator/PreEvaluatorTree.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/PreEvaluatorTree.java rename to wrims-core/src/main/java/wrimsv2/evaluator/PreEvaluatorTree.java index e60a593ab..ef3f46ab1 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/PreEvaluatorTree.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/PreEvaluatorTree.java @@ -1,86 +1,86 @@ -package wrimsv2.evaluator; - -import java.util.ArrayList; -import java.util.Map; - -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; -import org.antlr.runtime.tree.BufferedTreeNodeStream; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.CommonTreeNodeStream; - -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.components.ControlData; -import wrimsv2.components.Error; -import wrimsv2.components.IntDouble; - -public class PreEvaluatorTree { - private ArrayList svList; - private Map svMap; - - public PreEvaluatorTree(StudyDataSet sds ){ - ArrayList modelList=sds.getModelList(); - Map modelDataSetMap=sds.getModelDataSetMap(); - for (int i=0; i caseCondition=svar.caseCondition; - int i=-1; - svar.caseConditionWalkers=new ArrayList(); - svar.caseExpressionWalkers=new ArrayList(); - while(i<=caseCondition.size()-2){ - i=i+1; - String evalString="c: "+caseCondition.get(i); - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorTreeLexer lexer = new ValueEvaluatorTreeLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - ValueEvaluatorTreeParser evaluator = new ValueEvaluatorTreeParser(tokenStream); - ValueEvaluatorTreeParser.evaluator_return parser_evaluator; - try { - parser_evaluator = evaluator.evaluator(); - CommonTree commonTree = (CommonTree) parser_evaluator.getTree(); - BufferedTreeNodeStream nodeStream = new BufferedTreeNodeStream(commonTree); - nodeStream.setTokenStream(tokenStream); - ValueEvaluatorTreeWalker walker = new ValueEvaluatorTreeWalker(nodeStream); - svar.caseConditionWalkers.add(walker); - } catch (RecognitionException e) { - ControlData.currCycleIndex=0; - ControlData.currEvalName=svName; - Error.addEvaluationError(e.getMessage()); - } - - evalString="v: "+svar.caseExpression.get(i); - stream = new ANTLRStringStream(evalString); - lexer = new ValueEvaluatorTreeLexer(stream); - tokenStream = new CommonTokenStream(lexer); - evaluator = new ValueEvaluatorTreeParser(tokenStream); - try { - parser_evaluator = evaluator.evaluator(); - CommonTree commonTree = (CommonTree) parser_evaluator.getTree(); - BufferedTreeNodeStream nodeStream = new BufferedTreeNodeStream(commonTree); - nodeStream.setTokenStream(tokenStream); - ValueEvaluatorTreeWalker walker = new ValueEvaluatorTreeWalker(nodeStream); - svar.caseExpressionWalkers.add(walker); - } catch (RecognitionException e) { - ControlData.currCycleIndex=0; - ControlData.currEvalName=svName; - Error.addEvaluationError(e.getMessage()); - } - } - } - } -} +package wrimsv2.evaluator; + +import java.util.ArrayList; +import java.util.Map; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.TokenStream; +import org.antlr.runtime.tree.BufferedTreeNodeStream; +import org.antlr.runtime.tree.CommonTree; +import org.antlr.runtime.tree.CommonTreeNodeStream; + +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.components.ControlData; +import wrimsv2.components.Error; +import wrimsv2.components.IntDouble; + +public class PreEvaluatorTree { + private ArrayList svList; + private Map svMap; + + public PreEvaluatorTree(StudyDataSet sds ){ + ArrayList modelList=sds.getModelList(); + Map modelDataSetMap=sds.getModelDataSetMap(); + for (int i=0; i caseCondition=svar.caseCondition; + int i=-1; + svar.caseConditionWalkers=new ArrayList(); + svar.caseExpressionWalkers=new ArrayList(); + while(i<=caseCondition.size()-2){ + i=i+1; + String evalString="c: "+caseCondition.get(i); + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorTreeLexer lexer = new ValueEvaluatorTreeLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + ValueEvaluatorTreeParser evaluator = new ValueEvaluatorTreeParser(tokenStream); + ValueEvaluatorTreeParser.evaluator_return parser_evaluator; + try { + parser_evaluator = evaluator.evaluator(); + CommonTree commonTree = (CommonTree) parser_evaluator.getTree(); + BufferedTreeNodeStream nodeStream = new BufferedTreeNodeStream(commonTree); + nodeStream.setTokenStream(tokenStream); + ValueEvaluatorTreeWalker walker = new ValueEvaluatorTreeWalker(nodeStream); + svar.caseConditionWalkers.add(walker); + } catch (RecognitionException e) { + ControlData.currCycleIndex=0; + ControlData.currEvalName=svName; + Error.addEvaluationError(e.getMessage()); + } + + evalString="v: "+svar.caseExpression.get(i); + stream = new ANTLRStringStream(evalString); + lexer = new ValueEvaluatorTreeLexer(stream); + tokenStream = new CommonTokenStream(lexer); + evaluator = new ValueEvaluatorTreeParser(tokenStream); + try { + parser_evaluator = evaluator.evaluator(); + CommonTree commonTree = (CommonTree) parser_evaluator.getTree(); + BufferedTreeNodeStream nodeStream = new BufferedTreeNodeStream(commonTree); + nodeStream.setTokenStream(tokenStream); + ValueEvaluatorTreeWalker walker = new ValueEvaluatorTreeWalker(nodeStream); + svar.caseExpressionWalkers.add(walker); + } catch (RecognitionException e) { + ControlData.currCycleIndex=0; + ControlData.currEvalName=svName; + Error.addEvaluationError(e.getMessage()); + } + } + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/TableOperation.java b/wrims-core/src/main/java/wrimsv2/evaluator/TableOperation.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/TableOperation.java rename to wrims-core/src/main/java/wrimsv2/evaluator/TableOperation.java index 96e5433c3..c39d31660 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/TableOperation.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/TableOperation.java @@ -1,440 +1,440 @@ -package wrimsv2.evaluator; - -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; -import wrimsv2.components.Error; -import wrimsv2.components.IntDouble; - -import java.io.File; -import java.io.FileInputStream; -import java.io.DataInputStream; -import java.io.BufferedReader; -import java.io.InputStreamReader; - -import java.util.HashMap; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - - -public class TableOperation { - public static boolean retrieveLookUpData (String name){ - String tableFullPath=FilePaths.mainDirectory+"lookup"+File.separator+FilePaths.lookupSubDirectory+File.separator+name+".table"; - try{ - File f = new File(tableFullPath); - if(!f.exists()) { - Error.addEvaluationError("Table "+name+" could not be found."); - return false; - } - - FileInputStream fstream = new FileInputStream(tableFullPath); - DataInputStream in = new DataInputStream(fstream); - BufferedReader br = new BufferedReader(new InputStreamReader(in)); - - String strLine; - boolean isComment =true; - boolean isEnd=false; - int line=0; - strLine=""; - - while (!isEnd && isComment){ - strLine=br.readLine(); - strLine=removeLeadingTailingSpace(strLine); - line=line+1; - if (strLine==null){ - isEnd=true; - }else{ - if (!strLine.startsWith("!")) isComment=false; - } - } - if (strLine==null){ - Error.addEvaluationError("No data exists in the table "+name); - in.close(); - return false; - } - - if (strLine.contains("!")) strLine=removeComment(strLine); - strLine=removeLeadingTailingSpace(strLine); - if (!(strLine.toLowerCase().equals(name))){ - Error.addEvaluationError("The first line after comments in the table "+name+".table should be the file name without extension: "+name); - } - - if ((strLine=br.readLine())==null){ - Error.addEvaluationError("No data exists in the table "+name); - in.close(); - return false; - } - line=line+1; - LookUpTable lut=new LookUpTable(); - if (strLine.contains("!")) strLine=removeComment(strLine); - strLine=removeLeadingTailingSpace(strLine); - String[] fieldNames=strLine.toLowerCase().split("\\s+"); - int fieldSize=fieldNames.length; - for (int i=0; i0) { - TableSeries.tableSeries.put(name,lut); - in.close(); - return true; - } - Error.addEvaluationError("The number of data in the table "+name+" line "+line+" doesn't agree with the number of the field"); - in.close(); - return false; - } - - Number[] dataLine=new Number[fieldSize]; - for (int i=0; i where, HashMap given, String use){ - if (!TableSeries.tableSeries.containsKey(table)){ - if (!retrieveLookUpData(table)){ - return new IntDouble(1.0,false); - } - } - - LookUpTable lut=TableSeries.tableSeries.get(table); - ArrayList data=lut.getData(); - HashMap field= lut.getField(); - int fieldSize=field.size(); - - int selectIndex; - if (field.containsKey(select)){ - selectIndex=field.get(select); - }else{ - Error.addEvaluationError(select+" in the select statement is not a field name in Table "+table); - return new IntDouble(1.0,false); - } - - Set whereSet=where.keySet(); - Iterator iterator=whereSet.iterator(); - int whereSize=where.size(); - int[] whereIndex=new int[whereSize]; - Number[] whereValue=new Number[whereSize]; - int k=0; - while(iterator.hasNext()){ - String whereName=(String)iterator.next(); - if (field.containsKey(whereName)){ - whereIndex[k]=field.get(whereName); - }else{ - Error.addEvaluationError(whereName+" in the where statement is not a field name in Table "+table); - return new IntDouble(1.0,false); - } - whereValue[k]=(Number)where.get(whereName); - k=k+1; - } - - boolean whereTrue; - if (whereSize==0){ - whereTrue=true; - }else{ - whereTrue=false; - } - - Number[] values=new Number[fieldSize]; - int i=-1; - while (i gVList=new ArrayList(); - Map gVMap=new HashMap(); - gVList.add(values[givenIndex]); - gVMap.put(values[givenIndex], values[selectIndex]); - - while (i given, String use){ - if (!TableSeries.tableSeries.containsKey(table)){ - if (!retrieveLookUpData(table)){ - return new IntDouble(1.0,false); - } - } - - LookUpTable lut=TableSeries.tableSeries.get(table); - ArrayList data=lut.getData(); - HashMap field= lut.getField(); - int fieldSize=field.size(); - - int selectIndex; - if (field.containsKey(select)){ - selectIndex=field.get(select); - }else{ - Error.addEvaluationError(select+" in the select statement is not a field name in Table "+table); - return new IntDouble(1.0,false); - } - - if (given==null){ - Error.addEvaluationError("select data from table needs either where statement or given statement."); - return new IntDouble(1.0,false); - } - - Number[] values=new Number[fieldSize]; - - int givenIndex; - Set givenSet=given.keySet(); - Iterator iterator=givenSet.iterator(); - String givenName=(String)iterator.next(); - String valueString; - - if (field.containsKey(givenName)){ - givenIndex=field.get(givenName); - }else{ - Error.addEvaluationError(givenName+" in the given statement is not a field name in Table "+table); - return new IntDouble(1.0,false); - } - Number givenValue=(Number)given.get(givenName); - - ArrayList gVList=new ArrayList(); - Map gVMap=new HashMap(); - - for (int i=0; i gVList, Map gVMap, String use, String table, String givenError){ - double givenValue=given.doubleValue(); - if (gVList.size()==0){ - Error.addEvaluationError("Under the given conditon of "+givenError+" Data not found in Table "+table); - return new IntDouble(1.0,false); - }else if (gVList.size()==1 && use.equals("linear")){ - Number gV=gVList.get(0); - if (givenValue==gV.doubleValue()){ - return new IntDouble(gVMap.get(gV).doubleValue(),false); - }else{ - Error.addEvaluationError("Under the given conditon of "+givenError+" only one value for interpolation in Table "+table); - return new IntDouble(1.0,false); - } - } - - gVList=sortNumberArray(gVList, givenError, table); - - for (int i=0; i=givenValue){ - if (use.equals("minimum")){ - return new IntDouble(gVMap.get(gVList.get(i)).doubleValue(), false); - }else if (use.equals("maximum")){ - return new IntDouble(gVMap.get(gVList.get(j)).doubleValue(), false); - }else if (use.equals("linear")){ - double value=(givenValue-firstValue)/(secondValue-firstValue) - *(gVMap.get(second).doubleValue()-gVMap.get(first).doubleValue())+gVMap.get(first).doubleValue(); - return new IntDouble(value,false); - }else{ - Error.addEvaluationError("Use statement can only be maximum, minimum, or linear in Table"+table); - return new IntDouble(1.0,false); - } - } - } - - if (givenValuegVList.get(gVList.size()-1).doubleValue()){ - if (use.equals("maximum")){ - Error.addEvaluationError("Under the given conditon of "+givenError+" Data not found in Table "+table); - return new IntDouble(1.0,false); - }else if (use.equals("linear")){ - int size=gVList.size(); - Number first=gVList.get(size-2); - Number second=gVList.get(size-1); - double firstValue=first.doubleValue(); - double secondValue=second.doubleValue(); - double value=(givenValue-firstValue)/(secondValue-firstValue) - *(gVMap.get(second).doubleValue()-gVMap.get(first).doubleValue())+gVMap.get(first).doubleValue(); - return new IntDouble(value,false); - }else if (use.equals("minimum")){ - return new IntDouble(gVMap.get(gVList.get(gVList.size()-1)).doubleValue(),false); - }else{ - Error.addEvaluationError("Use statement can only be maximum, minimum, or linear in Table"+table); - return new IntDouble(1.0,false); - } - } - - Error.addEvaluationError("Under the given conditon of "+givenError+" only one value for interpolation in Table "+table); - return new IntDouble(1.0,false); - } - - public static IntDouble generateIntDouble(String valueString){ - double doubleValue=Double.parseDouble(valueString); - return new IntDouble(doubleValue, false); - } - - public static ArrayList sortNumberArray(ArrayList al, String givenError, String table){ - for (int i=0; isecond.doubleValue()){ - al.set(i, second); - al.set(j, first); - }else if (first.doubleValue()==second.doubleValue()){ - Error.addEvaluationError("Under the given conditon of "+givenError+" two data in given column "+first+" , "+second+" has the same value in Table "+table); - } - } - } - return al; - } -} +package wrimsv2.evaluator; + +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; +import wrimsv2.components.Error; +import wrimsv2.components.IntDouble; + +import java.io.File; +import java.io.FileInputStream; +import java.io.DataInputStream; +import java.io.BufferedReader; +import java.io.InputStreamReader; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + + +public class TableOperation { + public static boolean retrieveLookUpData (String name){ + String tableFullPath=FilePaths.mainDirectory+"lookup"+File.separator+FilePaths.lookupSubDirectory+File.separator+name+".table"; + try{ + File f = new File(tableFullPath); + if(!f.exists()) { + Error.addEvaluationError("Table "+name+" could not be found."); + return false; + } + + FileInputStream fstream = new FileInputStream(tableFullPath); + DataInputStream in = new DataInputStream(fstream); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + + String strLine; + boolean isComment =true; + boolean isEnd=false; + int line=0; + strLine=""; + + while (!isEnd && isComment){ + strLine=br.readLine(); + strLine=removeLeadingTailingSpace(strLine); + line=line+1; + if (strLine==null){ + isEnd=true; + }else{ + if (!strLine.startsWith("!")) isComment=false; + } + } + if (strLine==null){ + Error.addEvaluationError("No data exists in the table "+name); + in.close(); + return false; + } + + if (strLine.contains("!")) strLine=removeComment(strLine); + strLine=removeLeadingTailingSpace(strLine); + if (!(strLine.toLowerCase().equals(name))){ + Error.addEvaluationError("The first line after comments in the table "+name+".table should be the file name without extension: "+name); + } + + if ((strLine=br.readLine())==null){ + Error.addEvaluationError("No data exists in the table "+name); + in.close(); + return false; + } + line=line+1; + LookUpTable lut=new LookUpTable(); + if (strLine.contains("!")) strLine=removeComment(strLine); + strLine=removeLeadingTailingSpace(strLine); + String[] fieldNames=strLine.toLowerCase().split("\\s+"); + int fieldSize=fieldNames.length; + for (int i=0; i0) { + TableSeries.tableSeries.put(name,lut); + in.close(); + return true; + } + Error.addEvaluationError("The number of data in the table "+name+" line "+line+" doesn't agree with the number of the field"); + in.close(); + return false; + } + + Number[] dataLine=new Number[fieldSize]; + for (int i=0; i where, HashMap given, String use){ + if (!TableSeries.tableSeries.containsKey(table)){ + if (!retrieveLookUpData(table)){ + return new IntDouble(1.0,false); + } + } + + LookUpTable lut=TableSeries.tableSeries.get(table); + ArrayList data=lut.getData(); + HashMap field= lut.getField(); + int fieldSize=field.size(); + + int selectIndex; + if (field.containsKey(select)){ + selectIndex=field.get(select); + }else{ + Error.addEvaluationError(select+" in the select statement is not a field name in Table "+table); + return new IntDouble(1.0,false); + } + + Set whereSet=where.keySet(); + Iterator iterator=whereSet.iterator(); + int whereSize=where.size(); + int[] whereIndex=new int[whereSize]; + Number[] whereValue=new Number[whereSize]; + int k=0; + while(iterator.hasNext()){ + String whereName=(String)iterator.next(); + if (field.containsKey(whereName)){ + whereIndex[k]=field.get(whereName); + }else{ + Error.addEvaluationError(whereName+" in the where statement is not a field name in Table "+table); + return new IntDouble(1.0,false); + } + whereValue[k]=(Number)where.get(whereName); + k=k+1; + } + + boolean whereTrue; + if (whereSize==0){ + whereTrue=true; + }else{ + whereTrue=false; + } + + Number[] values=new Number[fieldSize]; + int i=-1; + while (i gVList=new ArrayList(); + Map gVMap=new HashMap(); + gVList.add(values[givenIndex]); + gVMap.put(values[givenIndex], values[selectIndex]); + + while (i given, String use){ + if (!TableSeries.tableSeries.containsKey(table)){ + if (!retrieveLookUpData(table)){ + return new IntDouble(1.0,false); + } + } + + LookUpTable lut=TableSeries.tableSeries.get(table); + ArrayList data=lut.getData(); + HashMap field= lut.getField(); + int fieldSize=field.size(); + + int selectIndex; + if (field.containsKey(select)){ + selectIndex=field.get(select); + }else{ + Error.addEvaluationError(select+" in the select statement is not a field name in Table "+table); + return new IntDouble(1.0,false); + } + + if (given==null){ + Error.addEvaluationError("select data from table needs either where statement or given statement."); + return new IntDouble(1.0,false); + } + + Number[] values=new Number[fieldSize]; + + int givenIndex; + Set givenSet=given.keySet(); + Iterator iterator=givenSet.iterator(); + String givenName=(String)iterator.next(); + String valueString; + + if (field.containsKey(givenName)){ + givenIndex=field.get(givenName); + }else{ + Error.addEvaluationError(givenName+" in the given statement is not a field name in Table "+table); + return new IntDouble(1.0,false); + } + Number givenValue=(Number)given.get(givenName); + + ArrayList gVList=new ArrayList(); + Map gVMap=new HashMap(); + + for (int i=0; i gVList, Map gVMap, String use, String table, String givenError){ + double givenValue=given.doubleValue(); + if (gVList.size()==0){ + Error.addEvaluationError("Under the given conditon of "+givenError+" Data not found in Table "+table); + return new IntDouble(1.0,false); + }else if (gVList.size()==1 && use.equals("linear")){ + Number gV=gVList.get(0); + if (givenValue==gV.doubleValue()){ + return new IntDouble(gVMap.get(gV).doubleValue(),false); + }else{ + Error.addEvaluationError("Under the given conditon of "+givenError+" only one value for interpolation in Table "+table); + return new IntDouble(1.0,false); + } + } + + gVList=sortNumberArray(gVList, givenError, table); + + for (int i=0; i=givenValue){ + if (use.equals("minimum")){ + return new IntDouble(gVMap.get(gVList.get(i)).doubleValue(), false); + }else if (use.equals("maximum")){ + return new IntDouble(gVMap.get(gVList.get(j)).doubleValue(), false); + }else if (use.equals("linear")){ + double value=(givenValue-firstValue)/(secondValue-firstValue) + *(gVMap.get(second).doubleValue()-gVMap.get(first).doubleValue())+gVMap.get(first).doubleValue(); + return new IntDouble(value,false); + }else{ + Error.addEvaluationError("Use statement can only be maximum, minimum, or linear in Table"+table); + return new IntDouble(1.0,false); + } + } + } + + if (givenValuegVList.get(gVList.size()-1).doubleValue()){ + if (use.equals("maximum")){ + Error.addEvaluationError("Under the given conditon of "+givenError+" Data not found in Table "+table); + return new IntDouble(1.0,false); + }else if (use.equals("linear")){ + int size=gVList.size(); + Number first=gVList.get(size-2); + Number second=gVList.get(size-1); + double firstValue=first.doubleValue(); + double secondValue=second.doubleValue(); + double value=(givenValue-firstValue)/(secondValue-firstValue) + *(gVMap.get(second).doubleValue()-gVMap.get(first).doubleValue())+gVMap.get(first).doubleValue(); + return new IntDouble(value,false); + }else if (use.equals("minimum")){ + return new IntDouble(gVMap.get(gVList.get(gVList.size()-1)).doubleValue(),false); + }else{ + Error.addEvaluationError("Use statement can only be maximum, minimum, or linear in Table"+table); + return new IntDouble(1.0,false); + } + } + + Error.addEvaluationError("Under the given conditon of "+givenError+" only one value for interpolation in Table "+table); + return new IntDouble(1.0,false); + } + + public static IntDouble generateIntDouble(String valueString){ + double doubleValue=Double.parseDouble(valueString); + return new IntDouble(doubleValue, false); + } + + public static ArrayList sortNumberArray(ArrayList al, String givenError, String table){ + for (int i=0; isecond.doubleValue()){ + al.set(i, second); + al.set(j, first); + }else if (first.doubleValue()==second.doubleValue()){ + Error.addEvaluationError("Under the given conditon of "+givenError+" two data in given column "+first+" , "+second+" has the same value in Table "+table); + } + } + } + return al; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/TableSeries.java b/wrims-core/src/main/java/wrimsv2/evaluator/TableSeries.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/TableSeries.java rename to wrims-core/src/main/java/wrimsv2/evaluator/TableSeries.java index b4e1186a5..3343f98d4 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/TableSeries.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/TableSeries.java @@ -1,7 +1,7 @@ -package wrimsv2.evaluator; - -import java.util.HashMap; - -public class TableSeries { - public static HashMap tableSeries = new HashMap (); -} +package wrimsv2.evaluator; + +import java.util.HashMap; + +public class TableSeries { + public static HashMap tableSeries = new HashMap (); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/TimeOperation.java b/wrims-core/src/main/java/wrimsv2/evaluator/TimeOperation.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/TimeOperation.java rename to wrims-core/src/main/java/wrimsv2/evaluator/TimeOperation.java index 723e36479..77ba60f86 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/TimeOperation.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/TimeOperation.java @@ -1,430 +1,430 @@ -package wrimsv2.evaluator; - -import wrimsv2.components.ControlData; -import wrimsv2.parallel.ParallelVars; - -import java.time.Duration; -import java.util.Calendar; -import java.util.Date; - -public class TimeOperation { - public static String[] month_const={"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"}; - - public static String dssTimeFrame(int year1, int month1, int day1, int year2, int month2, int day2){ - return dayName(day1)+monthName(month1)+year1+" 0100 - "+dayName(day2)+monthName(month2)+year2+" 0000"; - } - - public static String dssTime(int year, int month, int day){ - return dayName(day)+monthName(month)+year+" 0000"; - } - - public static String dssTimeEndDay(int year, int month, int day){ - return dayName(day)+monthName(month)+year+" 2400"; - } - - public static String dayName(int day){ - if (day<10){ - return "0"+Evaluation.convertIntToString(day); - }else{ - return Evaluation.convertIntToString(day); - } - } - - public static int monthValue(String month){ - if (month.equals("jan")){ - return 1; - }else if (month.equals("feb")){ - return 2; - }else if (month.equals("mar")){ - return 3; - }else if (month.equals("apr")){ - return 4; - }else if (month.equals("may")){ - return 5; - }else if (month.equals("jun")){ - return 6; - }else if (month.equals("jul")){ - return 7; - }else if (month.equals("aug")){ - return 8; - }else if (month.equals("sep")){ - return 9; - }else if (month.equals("oct")){ - return 10; - }else if (month.equals("nov")){ - return 11; - }else{ - return 12; - } - } - - public static int waterMonthValue(String month){ - if (month.equals("jan")){ - return 4; - }else if (month.equals("feb")){ - return 5; - }else if (month.equals("mar")){ - return 6; - }else if (month.equals("apr")){ - return 7; - }else if (month.equals("may")){ - return 8; - }else if (month.equals("jun")){ - return 9; - }else if (month.equals("jul")){ - return 10; - }else if (month.equals("aug")){ - return 11; - }else if (month.equals("sep")){ - return 12; - }else if (month.equals("oct")){ - return 1; - }else if (month.equals("nov")){ - return 2; - }else{ - return 3; - } - } - - public static int waterMonthValue(int month){ - if (month>=10){ - return month-9; - }else{ - return month+3; - } - } - - public static int waterYearValue(){ - if (ControlData.currMonth>=10){ - return ControlData.currYear+1; - }else{ - return ControlData.currYear; - } - } - - public static String monthName(int month){ - if (month == 1){ - return "JAN"; - }else if (month == 2){ - return "FEB"; - }else if (month == 3){ - return "MAR"; - }else if (month == 4){ - return "APR"; - }else if (month == 5){ - return "MAY"; - }else if (month == 6){ - return "JUN"; - }else if (month == 7){ - return "JUL"; - }else if (month == 8){ - return "AUG"; - }else if (month == 9){ - return "SEP"; - }else if (month == 10){ - return "OCT"; - }else if (month == 11){ - return "NOV"; - }else{ - return "DEC"; - } - } - - public static String monthNameNumeric(int month){ - if (month == 1){ - return "01"; - }else if (month == 2){ - return "02"; - }else if (month == 3){ - return "03"; - }else if (month == 4){ - return "04"; - }else if (month == 5){ - return "05"; - }else if (month == 6){ - return "06"; - }else if (month == 7){ - return "07"; - }else if (month == 8){ - return "08"; - }else if (month == 9){ - return "09"; - }else if (month == 10){ - return "10"; - }else if (month == 11){ - return "11"; - }else{ - return "12"; - } - } - - public static boolean isLeapYear(int year){ - if (year % 4 == 0) { - if (year % 100 != 0) { - return true; - }else if (year % 400 == 0) { - return true; - }else { - return false; - } - }else{ - return false; - } - } - - public static ParallelVars findTime(int value){ - ParallelVars prvs=new ParallelVars(); - if (ControlData.timeStep.equals("1MON")){ - int detYear=value/12; - int detMonth=value%12; - prvs.dataMonth=ControlData.currMonth+detMonth; - prvs.dataYear=ControlData.currYear+detYear; - if (prvs.dataMonth<1){ - prvs.dataMonth=prvs.dataMonth+12; - prvs.dataYear=prvs.dataYear-1; - }else if (prvs.dataMonth>12){ - prvs.dataMonth=prvs.dataMonth-12; - prvs.dataYear=prvs.dataYear+1; - } - int days=numberOfDays(prvs.dataMonth, prvs.dataYear); - prvs.dataDay=days; - /* - if (ControlData.currDay<=days){ - ParallelVars.dataDay=ControlData.currDay; - }else{ - ParallelVars.dataDay=days-numberOfDays(ControlData.currMonth, ControlData.currYear)+ControlData.currDay; - } - */ - }else if(ControlData.timeStep.equals("1DAY")){ - Date currDate = new Date (ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - Calendar c = Calendar.getInstance(); - c.setTime(currDate); - c.add(Calendar.DATE, value); - Date dataDate = c.getTime(); - prvs.dataDay=dataDate.getDate(); - prvs.dataMonth=dataDate.getMonth()+1; - prvs.dataYear=dataDate.getYear()+1900; - } - return prvs; - } - - public static ParallelVars findTime(int value, int year, int month, int day){ - ParallelVars prvs = new ParallelVars(); - if (ControlData.timeStep.equals("1MON")){ - int detYear=value/12; - int detMonth=value%12; - prvs.dataMonth=month+detMonth; - prvs.dataYear=year+detYear; - if (prvs.dataMonth<1){ - prvs.dataMonth=prvs.dataMonth+12; - prvs.dataYear=prvs.dataYear-1; - }else if (prvs.dataMonth>12){ - prvs.dataMonth=prvs.dataMonth-12; - prvs.dataYear=prvs.dataYear+1; - } - int days=numberOfDays(prvs.dataMonth, prvs.dataYear); - if (day<=days){ - prvs.dataDay=day; - }else{ - prvs.dataDay=days-numberOfDays(month, year)+day; - } - }else if(ControlData.timeStep.equals("1DAY")){ - Date thisDate = new Date (year-1900, month-1, day); - Calendar c = Calendar.getInstance(); - c.setTime(thisDate); - c.add(Calendar.DATE, value); - Date dataDate = c.getTime(); - prvs.dataDay=dataDate.getDate(); - prvs.dataMonth=dataDate.getMonth()+1; - prvs.dataYear=dataDate.getYear()+1900; - } - return prvs; - } - - public static int numberOfDays(int month, int year){ - int days; - if (month==1 || month==3 || month==5 || month==7 - ||month==8 || month==10 ||month==12){ - days=31; - }else if (month==4|| month==6 || month==9 || month==11){ - days=30; - }else { - if (TimeOperation.isLeapYear(year)){ - days=29; - }else{ - days=28; - } - } - return days; - } - - public static int getNumberOfTimestep(Date dateA, Date dateB, String timeStep){ - if (timeStep.equals("1MON")){ - int monthA=dateA.getMonth(); - int yearA=dateA.getYear(); - int monthB=dateB.getMonth(); - int yearB=dateB.getYear(); - int diff=(yearB-yearA)*12+(monthB-monthA)+1; - if (diff<=0) diff=0; - return diff; - }else{ - //long timeA=dateA.getTime(); - //long timeB=dateB.getTime(); - //int diff=Math.round((timeB-timeA)/(1000l*60*60*24))+1; - Calendar c1=Calendar.getInstance(); - c1.setTime(dateA); - Calendar c2=Calendar.getInstance(); - c2.setTime(dateB); - int diff = (int)Duration.between(c1.toInstant(), c2.toInstant()).toDays()+1; - if (diff<=0) diff=0; - return diff; - } - } - - public static Date addOneMonth(Date date){ - int month=date.getMonth()+1; - int year=date.getYear(); - if (month>11){ - month=month-12; - year=year+1; - } - int day=TimeOperation.numberOfDays(month+1, year+1900); - Date newDate = new Date(year, month, day); - return newDate; - } - - public static Date addOneDay(Date date){ - Calendar c = Calendar.getInstance(); - c.setTime(date); - c.add(Calendar.DATE, 1); - Date newDate = c.getTime(); - return newDate; - } - - public static Date backOneMonth(Date date){ - int month=date.getMonth()-1; - int year=date.getYear(); - if (month<0){ - month=month+12; - year=year-1; - } - int day=TimeOperation.numberOfDays(month+1, year+1900); - Date newDate = new Date(year, month, day); - return newDate; - } - - public static Date backOneDay(Date date){ - Calendar c = Calendar.getInstance(); - c.setTime(date); - c.add(Calendar.DATE, -1); - Date newDate = c.getTime(); - return newDate; - } - - public static boolean range(int dataMonth, String m1, String m2){ - int mon1=TimeOperation.monthValue(m1); - int mon2=TimeOperation.monthValue(m2); - - if (mon1<=mon2){ - if (dataMonth>=mon1 && dataMonth<=mon2){ - return true; - }else{ - return false; - } - }else{ - if (dataMonth>=mon1 || dataMonth<=mon2){ - return true; - }else{ - return false; - } - } - } - - public static void initOutputDate(int year){ - //ControlData.outputYear=(ControlData.startYear/year+1)*year; - //ControlData.outputMonth=12; - //ControlData.outputDay=31; - - ControlData.outputYear=ControlData.startYear+year; - ControlData.outputMonth=ControlData.startMonth-1; - if (ControlData.outputMonth==0){ - ControlData.outputYear=ControlData.outputYear-1; - ControlData.outputMonth=12; - } - ControlData.outputDay=numberOfDays(ControlData.outputMonth, ControlData.outputYear); - if (ControlData.timeStep.equals("1MON")){ - ControlData.prevOutputYear=ControlData.startYear; - ControlData.prevOutputMonth=ControlData.startMonth-1; - if (ControlData.prevOutputMonth==0){ - ControlData.prevOutputYear=ControlData.prevOutputYear-1; - ControlData.prevOutputMonth=12; - } - ControlData.prevOutputDay=TimeOperation.numberOfDays(ControlData.prevOutputMonth, ControlData.prevOutputYear); - }else{ - ControlData.prevOutputYear=ControlData.startYear; - ControlData.prevOutputMonth=ControlData.startMonth; - ControlData.prevOutputDay=ControlData.startDay-1; - if (ControlData.prevOutputDay==0){ - ControlData.prevOutputMonth=ControlData.prevOutputMonth-1; - if (ControlData.prevOutputMonth==0){ - ControlData.prevOutputMonth=12; - ControlData.prevOutputYear=ControlData.prevOutputYear-1; - } - ControlData.prevOutputDay=TimeOperation.numberOfDays(ControlData.prevOutputMonth, ControlData.prevOutputYear); - } - } - ControlData.prevOutputDate=new Date(ControlData.prevOutputYear-1900, ControlData.prevOutputMonth-1, ControlData.prevOutputDay); - } - - public static void setOutputDate(int year){ - ControlData.prevOutputYear=ControlData.outputYear; - ControlData.prevOutputMonth=ControlData.outputMonth; - ControlData.prevOutputDay=ControlData.outputDay; - - ControlData.outputYear=ControlData.outputYear+year; - //ControlData.outputMonth=12; - //ControlData.outputDay=31; - - ControlData.prevOutputDate=new Date(ControlData.prevOutputYear-1900, ControlData.prevOutputMonth-1, ControlData.prevOutputDay); - } - - public static void initMemDate(int month){ - ControlData.memStartYear=ControlData.startYear; - ControlData.memStartMonth=ControlData.startMonth; - ControlData.memStartDay=ControlData.startDay; - - ControlData.prevMemYear=ControlData.memStartYear; - ControlData.prevMemMonth=ControlData.memStartMonth; - ControlData.prevMemDay=ControlData.memStartDay; - - ControlData.prevMemDate=new Date(ControlData.prevMemYear-1900, ControlData.prevMemMonth-1, ControlData.prevMemDay); - ControlData.memStartDate=new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); - } - - public static void setMemDate(int month){ - ControlData.prevMemYear=ControlData.memStartYear; - ControlData.prevMemMonth=ControlData.memStartMonth; - ControlData.prevMemDay=ControlData.memStartDay; - - int years = month / 12; - int remainingMonths = month % 12; - ControlData.memStartYear=ControlData.outputYear-years; - ControlData.memStartMonth=ControlData.outputMonth-remainingMonths+1; - if (ControlData.memStartMonth<=0){ - ControlData.memStartYear=ControlData.memStartYear-1; - ControlData.memStartMonth=ControlData.memStartMonth+12; - }else if (ControlData.memStartMonth>12){ - ControlData.memStartYear=ControlData.memStartYear+1; - ControlData.memStartMonth=ControlData.memStartMonth-12; - } - if (ControlData.timeStep.equals("1MON")){ - ControlData.memStartDay=numberOfDays(ControlData.memStartMonth, ControlData.memStartYear); - }else{ - ControlData.memStartDay=1; - } - - ControlData.prevMemDate=new Date(ControlData.prevMemYear-1900, ControlData.prevMemMonth-1, ControlData.prevMemDay); - ControlData.memStartDate=new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); - } - -} +package wrimsv2.evaluator; + +import wrimsv2.components.ControlData; +import wrimsv2.parallel.ParallelVars; + +import java.time.Duration; +import java.util.Calendar; +import java.util.Date; + +public class TimeOperation { + public static String[] month_const={"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"}; + + public static String dssTimeFrame(int year1, int month1, int day1, int year2, int month2, int day2){ + return dayName(day1)+monthName(month1)+year1+" 0100 - "+dayName(day2)+monthName(month2)+year2+" 0000"; + } + + public static String dssTime(int year, int month, int day){ + return dayName(day)+monthName(month)+year+" 0000"; + } + + public static String dssTimeEndDay(int year, int month, int day){ + return dayName(day)+monthName(month)+year+" 2400"; + } + + public static String dayName(int day){ + if (day<10){ + return "0"+Evaluation.convertIntToString(day); + }else{ + return Evaluation.convertIntToString(day); + } + } + + public static int monthValue(String month){ + if (month.equals("jan")){ + return 1; + }else if (month.equals("feb")){ + return 2; + }else if (month.equals("mar")){ + return 3; + }else if (month.equals("apr")){ + return 4; + }else if (month.equals("may")){ + return 5; + }else if (month.equals("jun")){ + return 6; + }else if (month.equals("jul")){ + return 7; + }else if (month.equals("aug")){ + return 8; + }else if (month.equals("sep")){ + return 9; + }else if (month.equals("oct")){ + return 10; + }else if (month.equals("nov")){ + return 11; + }else{ + return 12; + } + } + + public static int waterMonthValue(String month){ + if (month.equals("jan")){ + return 4; + }else if (month.equals("feb")){ + return 5; + }else if (month.equals("mar")){ + return 6; + }else if (month.equals("apr")){ + return 7; + }else if (month.equals("may")){ + return 8; + }else if (month.equals("jun")){ + return 9; + }else if (month.equals("jul")){ + return 10; + }else if (month.equals("aug")){ + return 11; + }else if (month.equals("sep")){ + return 12; + }else if (month.equals("oct")){ + return 1; + }else if (month.equals("nov")){ + return 2; + }else{ + return 3; + } + } + + public static int waterMonthValue(int month){ + if (month>=10){ + return month-9; + }else{ + return month+3; + } + } + + public static int waterYearValue(){ + if (ControlData.currMonth>=10){ + return ControlData.currYear+1; + }else{ + return ControlData.currYear; + } + } + + public static String monthName(int month){ + if (month == 1){ + return "JAN"; + }else if (month == 2){ + return "FEB"; + }else if (month == 3){ + return "MAR"; + }else if (month == 4){ + return "APR"; + }else if (month == 5){ + return "MAY"; + }else if (month == 6){ + return "JUN"; + }else if (month == 7){ + return "JUL"; + }else if (month == 8){ + return "AUG"; + }else if (month == 9){ + return "SEP"; + }else if (month == 10){ + return "OCT"; + }else if (month == 11){ + return "NOV"; + }else{ + return "DEC"; + } + } + + public static String monthNameNumeric(int month){ + if (month == 1){ + return "01"; + }else if (month == 2){ + return "02"; + }else if (month == 3){ + return "03"; + }else if (month == 4){ + return "04"; + }else if (month == 5){ + return "05"; + }else if (month == 6){ + return "06"; + }else if (month == 7){ + return "07"; + }else if (month == 8){ + return "08"; + }else if (month == 9){ + return "09"; + }else if (month == 10){ + return "10"; + }else if (month == 11){ + return "11"; + }else{ + return "12"; + } + } + + public static boolean isLeapYear(int year){ + if (year % 4 == 0) { + if (year % 100 != 0) { + return true; + }else if (year % 400 == 0) { + return true; + }else { + return false; + } + }else{ + return false; + } + } + + public static ParallelVars findTime(int value){ + ParallelVars prvs=new ParallelVars(); + if (ControlData.timeStep.equals("1MON")){ + int detYear=value/12; + int detMonth=value%12; + prvs.dataMonth=ControlData.currMonth+detMonth; + prvs.dataYear=ControlData.currYear+detYear; + if (prvs.dataMonth<1){ + prvs.dataMonth=prvs.dataMonth+12; + prvs.dataYear=prvs.dataYear-1; + }else if (prvs.dataMonth>12){ + prvs.dataMonth=prvs.dataMonth-12; + prvs.dataYear=prvs.dataYear+1; + } + int days=numberOfDays(prvs.dataMonth, prvs.dataYear); + prvs.dataDay=days; + /* + if (ControlData.currDay<=days){ + ParallelVars.dataDay=ControlData.currDay; + }else{ + ParallelVars.dataDay=days-numberOfDays(ControlData.currMonth, ControlData.currYear)+ControlData.currDay; + } + */ + }else if(ControlData.timeStep.equals("1DAY")){ + Date currDate = new Date (ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + Calendar c = Calendar.getInstance(); + c.setTime(currDate); + c.add(Calendar.DATE, value); + Date dataDate = c.getTime(); + prvs.dataDay=dataDate.getDate(); + prvs.dataMonth=dataDate.getMonth()+1; + prvs.dataYear=dataDate.getYear()+1900; + } + return prvs; + } + + public static ParallelVars findTime(int value, int year, int month, int day){ + ParallelVars prvs = new ParallelVars(); + if (ControlData.timeStep.equals("1MON")){ + int detYear=value/12; + int detMonth=value%12; + prvs.dataMonth=month+detMonth; + prvs.dataYear=year+detYear; + if (prvs.dataMonth<1){ + prvs.dataMonth=prvs.dataMonth+12; + prvs.dataYear=prvs.dataYear-1; + }else if (prvs.dataMonth>12){ + prvs.dataMonth=prvs.dataMonth-12; + prvs.dataYear=prvs.dataYear+1; + } + int days=numberOfDays(prvs.dataMonth, prvs.dataYear); + if (day<=days){ + prvs.dataDay=day; + }else{ + prvs.dataDay=days-numberOfDays(month, year)+day; + } + }else if(ControlData.timeStep.equals("1DAY")){ + Date thisDate = new Date (year-1900, month-1, day); + Calendar c = Calendar.getInstance(); + c.setTime(thisDate); + c.add(Calendar.DATE, value); + Date dataDate = c.getTime(); + prvs.dataDay=dataDate.getDate(); + prvs.dataMonth=dataDate.getMonth()+1; + prvs.dataYear=dataDate.getYear()+1900; + } + return prvs; + } + + public static int numberOfDays(int month, int year){ + int days; + if (month==1 || month==3 || month==5 || month==7 + ||month==8 || month==10 ||month==12){ + days=31; + }else if (month==4|| month==6 || month==9 || month==11){ + days=30; + }else { + if (TimeOperation.isLeapYear(year)){ + days=29; + }else{ + days=28; + } + } + return days; + } + + public static int getNumberOfTimestep(Date dateA, Date dateB, String timeStep){ + if (timeStep.equals("1MON")){ + int monthA=dateA.getMonth(); + int yearA=dateA.getYear(); + int monthB=dateB.getMonth(); + int yearB=dateB.getYear(); + int diff=(yearB-yearA)*12+(monthB-monthA)+1; + if (diff<=0) diff=0; + return diff; + }else{ + //long timeA=dateA.getTime(); + //long timeB=dateB.getTime(); + //int diff=Math.round((timeB-timeA)/(1000l*60*60*24))+1; + Calendar c1=Calendar.getInstance(); + c1.setTime(dateA); + Calendar c2=Calendar.getInstance(); + c2.setTime(dateB); + int diff = (int)Duration.between(c1.toInstant(), c2.toInstant()).toDays()+1; + if (diff<=0) diff=0; + return diff; + } + } + + public static Date addOneMonth(Date date){ + int month=date.getMonth()+1; + int year=date.getYear(); + if (month>11){ + month=month-12; + year=year+1; + } + int day=TimeOperation.numberOfDays(month+1, year+1900); + Date newDate = new Date(year, month, day); + return newDate; + } + + public static Date addOneDay(Date date){ + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.add(Calendar.DATE, 1); + Date newDate = c.getTime(); + return newDate; + } + + public static Date backOneMonth(Date date){ + int month=date.getMonth()-1; + int year=date.getYear(); + if (month<0){ + month=month+12; + year=year-1; + } + int day=TimeOperation.numberOfDays(month+1, year+1900); + Date newDate = new Date(year, month, day); + return newDate; + } + + public static Date backOneDay(Date date){ + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.add(Calendar.DATE, -1); + Date newDate = c.getTime(); + return newDate; + } + + public static boolean range(int dataMonth, String m1, String m2){ + int mon1=TimeOperation.monthValue(m1); + int mon2=TimeOperation.monthValue(m2); + + if (mon1<=mon2){ + if (dataMonth>=mon1 && dataMonth<=mon2){ + return true; + }else{ + return false; + } + }else{ + if (dataMonth>=mon1 || dataMonth<=mon2){ + return true; + }else{ + return false; + } + } + } + + public static void initOutputDate(int year){ + //ControlData.outputYear=(ControlData.startYear/year+1)*year; + //ControlData.outputMonth=12; + //ControlData.outputDay=31; + + ControlData.outputYear=ControlData.startYear+year; + ControlData.outputMonth=ControlData.startMonth-1; + if (ControlData.outputMonth==0){ + ControlData.outputYear=ControlData.outputYear-1; + ControlData.outputMonth=12; + } + ControlData.outputDay=numberOfDays(ControlData.outputMonth, ControlData.outputYear); + if (ControlData.timeStep.equals("1MON")){ + ControlData.prevOutputYear=ControlData.startYear; + ControlData.prevOutputMonth=ControlData.startMonth-1; + if (ControlData.prevOutputMonth==0){ + ControlData.prevOutputYear=ControlData.prevOutputYear-1; + ControlData.prevOutputMonth=12; + } + ControlData.prevOutputDay=TimeOperation.numberOfDays(ControlData.prevOutputMonth, ControlData.prevOutputYear); + }else{ + ControlData.prevOutputYear=ControlData.startYear; + ControlData.prevOutputMonth=ControlData.startMonth; + ControlData.prevOutputDay=ControlData.startDay-1; + if (ControlData.prevOutputDay==0){ + ControlData.prevOutputMonth=ControlData.prevOutputMonth-1; + if (ControlData.prevOutputMonth==0){ + ControlData.prevOutputMonth=12; + ControlData.prevOutputYear=ControlData.prevOutputYear-1; + } + ControlData.prevOutputDay=TimeOperation.numberOfDays(ControlData.prevOutputMonth, ControlData.prevOutputYear); + } + } + ControlData.prevOutputDate=new Date(ControlData.prevOutputYear-1900, ControlData.prevOutputMonth-1, ControlData.prevOutputDay); + } + + public static void setOutputDate(int year){ + ControlData.prevOutputYear=ControlData.outputYear; + ControlData.prevOutputMonth=ControlData.outputMonth; + ControlData.prevOutputDay=ControlData.outputDay; + + ControlData.outputYear=ControlData.outputYear+year; + //ControlData.outputMonth=12; + //ControlData.outputDay=31; + + ControlData.prevOutputDate=new Date(ControlData.prevOutputYear-1900, ControlData.prevOutputMonth-1, ControlData.prevOutputDay); + } + + public static void initMemDate(int month){ + ControlData.memStartYear=ControlData.startYear; + ControlData.memStartMonth=ControlData.startMonth; + ControlData.memStartDay=ControlData.startDay; + + ControlData.prevMemYear=ControlData.memStartYear; + ControlData.prevMemMonth=ControlData.memStartMonth; + ControlData.prevMemDay=ControlData.memStartDay; + + ControlData.prevMemDate=new Date(ControlData.prevMemYear-1900, ControlData.prevMemMonth-1, ControlData.prevMemDay); + ControlData.memStartDate=new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); + } + + public static void setMemDate(int month){ + ControlData.prevMemYear=ControlData.memStartYear; + ControlData.prevMemMonth=ControlData.memStartMonth; + ControlData.prevMemDay=ControlData.memStartDay; + + int years = month / 12; + int remainingMonths = month % 12; + ControlData.memStartYear=ControlData.outputYear-years; + ControlData.memStartMonth=ControlData.outputMonth-remainingMonths+1; + if (ControlData.memStartMonth<=0){ + ControlData.memStartYear=ControlData.memStartYear-1; + ControlData.memStartMonth=ControlData.memStartMonth+12; + }else if (ControlData.memStartMonth>12){ + ControlData.memStartYear=ControlData.memStartYear+1; + ControlData.memStartMonth=ControlData.memStartMonth-12; + } + if (ControlData.timeStep.equals("1MON")){ + ControlData.memStartDay=numberOfDays(ControlData.memStartMonth, ControlData.memStartYear); + }else{ + ControlData.memStartDay=1; + } + + ControlData.prevMemDate=new Date(ControlData.prevMemYear-1900, ControlData.prevMemMonth-1, ControlData.prevMemDay); + ControlData.memStartDate=new Date(ControlData.memStartYear-1900, ControlData.memStartMonth-1, ControlData.memStartDay); + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluation.java b/wrims-core/src/main/java/wrimsv2/evaluator/ValueEvaluation.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluation.java rename to wrims-core/src/main/java/wrimsv2/evaluator/ValueEvaluation.java index f0ca37962..2b79b1df3 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/ValueEvaluation.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/ValueEvaluation.java @@ -1,1504 +1,1501 @@ -package wrimsv2.evaluator; -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.components.ControlData; -import wrimsv2.components.Error; -import wrimsv2.components.FilePaths; -import wrimsv2.components.IntDouble; -import wrimsv2.external.*; -import wrimsv2.hdf5.HDF5Reader; -import wrimsv2.parallel.ParallelVars; -import wrimsv2.solver.CbcSolver; - -import java.time.Duration; -import java.util.Arrays; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Map; -import java.util.ArrayList; -import java.util.Stack; -import java.util.Date; - -public class ValueEvaluation { - public static double convertStringToDouble(String text){ - return Double.parseDouble(text); - } - - public static int convertStringToInt(String text){ - return Integer.parseInt(text); - } - - public static String convertDoubleToString(double value){ - return Double.toString(value); - } - - public static String convertIntToString(int value){ - return Integer.toString(value); - } - - public static boolean relationStatement(IntDouble id1, IntDouble id2, String relation){ - double value1=id1.getData().doubleValue(); - double value2=id2.getData().doubleValue(); - - if (relation.equals("==")) { - if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ - if (value1>=value2-ControlData.relationTolerance && value1<=value2+ControlData.relationTolerance){ - return true; - }else{ - return false; - } - }else{ - if (value1==value2){ - return true; - }else{ - return false; - } - } - }else if (relation.equals(">")){ - if (value1>value2){ - return true; - }else{ - return false; - } - }else if (relation.equals("<")){ - if (value1=")){ - if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ - if (value1>=value2-ControlData.relationTolerance){ - return true; - }else{ - return false; - } - }else{ - if (value1>=value2){ - return true; - }else{ - return false; - } - } - }else{ - if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ - if (value1<=value2+ControlData.relationTolerance){ - return true; - }else{ - return false; - } - }else{ - if (value1<=value2){ - return true; - }else{ - return false; - } - } - } - } - - public static boolean range(String m1, String m2){ - return TimeOperation.range(ControlData.currMonth, m1, m2); - } - - public static boolean relationStatementSeries(boolean r1, boolean r2, String s){ - if (s.equals(".and.")) { - return (r1 && r2); - }else{ - return (r1 || r2); - } - } - - public static IntDouble term_knownTS(IntDouble result){ - return result; - } - - public static IntDouble term_IDENT (String ident, Stack sumIndex){ - if (ControlData.currSvMap.containsKey(ident)){ - IntDouble id0=ControlData.currSvMap.get(ident).getData(); - return new IntDouble(id0.getData(),id0.isInt(),ident, 0); - }else if (ControlData.currTsMap.containsKey(ident)){ - IntDouble id0=ControlData.currTsMap.get(ident).getData(); - return new IntDouble(id0.getData(),id0.isInt(), ident, 0); - }else if (ControlData.isPostProcessing && ControlData.currDvMap.containsKey(ident)){ - IntDouble id0=ControlData.currDvMap.get(ident).getData(); - return new IntDouble(id0.getData(),id0.isInt(), ident, 0); - }else if (ControlData.isPostProcessing && ControlData.currAliasMap.containsKey(ident)){ - IntDouble id0=ControlData.currAliasMap.get(ident).getData(); - if (id0==null) { - Error.addEvaluationError(ident+" is not defined before it is used."); - return new IntDouble (1.0, false, ident, 0); - } - return new IntDouble(id0.getData(),id0.isInt(), ident, 0); - } - if (sumIndex.size()>0){ - LoopIndex li=sumIndex.pop(); - if (li.getName().equals(ident) && li.getIndexStart()){ - sumIndex.push(li); - return new IntDouble(li.getValue(),true, ident, 0); - } - sumIndex.push(li); - } - if (ControlData.parameterMap.containsKey(ident)){ - IntDouble id0=ControlData.parameterMap.get(ident).getData(); - return new IntDouble(id0.getData(),id0.isInt(), ident, 0); - } - Error.addEvaluationError(ident+" is not in svar, dvar, alias, or parameter list."); - return new IntDouble (1.0, false, ident, 0); - } - - public static IntDouble term_SVAR (String ident){ - IntDouble data; - if (!ControlData.currSvMap.containsKey(ident)){ - if (!ControlData.currTsMap.containsKey(ident)){ - Error.addEvaluationError("State variable "+ident+" is not defined before used."); - return new IntDouble(1.0, false, ident, 0); - }else{ - data=ControlData.currTsMap.get(ident).getData(); - } - }else{ - data=ControlData.currSvMap.get(ident).getData(); - } - - if (data == null){ - Error.addEvaluationError("The value of state variable "+ident+" is not defined before used."); - return new IntDouble(1.0, false, ident, 0); - } - return new IntDouble(data.getData(), data.isInt(), ident, 0); - } - - public static IntDouble term_INTEGER (String integer){ - return new IntDouble(convertStringToInt(integer), true); - } - - public static IntDouble term_FLOAT (String floatValue){ - return new IntDouble(convertStringToDouble(floatValue), false); - } - - public static IntDouble unary (String s, IntDouble id){ - if (s !=null && s.equals("-")){ - if (id.isInt()){ - int value=-id.getData().intValue(); - return new IntDouble(value, id.isInt()); - }else{ - double value=-id.getData().doubleValue(); - return new IntDouble(value, id.isInt()); - } - }else{ - return id; - } - } - - public static IntDouble mult(IntDouble id1, IntDouble id2){ - IntDouble id; - if (!id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()*id2.getData().doubleValue(), false); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().intValue()*id2.getData().doubleValue(), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()*id2.getData().intValue(), false); - }else{ - id=new IntDouble(id1.getData().intValue()*id2.getData().intValue(), true); - } - return id; - } - - public static IntDouble divide(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id2.getData().doubleValue()==0.0){ - Error.addEvaluationError("divided by 0."); - return new IntDouble(1.0, false); - } - if (!id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()/id2.getData().doubleValue(), false); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().intValue()/id2.getData().doubleValue(), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()/id2.getData().intValue(), false); - }else { - id=new IntDouble(id1.getData().intValue()/id2.getData().intValue(), true); - } - return id; - } - - public static IntDouble mod(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id2.getData().doubleValue()==0.0){ - Error.addEvaluationError("Mod function uses 0 as divider."); - return new IntDouble(1.0, false); - } - if (!id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()%id2.getData().doubleValue(), false); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().intValue()%id2.getData().doubleValue(), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()%id2.getData().intValue(), false); - }else{ - id=new IntDouble(id1.getData().intValue()%id2.getData().intValue(), true); - } - return id; - } - - public static IntDouble round(IntDouble id1){ - IntDouble id; - id=new IntDouble(Math.round(id1.getData().doubleValue()), true); - return id; - } - - public static IntDouble add(IntDouble id1, IntDouble id2){ - IntDouble id; - if (!id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()+id2.getData().doubleValue(), false); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().intValue()+id2.getData().doubleValue(), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()+id2.getData().intValue(), false); - }else { - id=new IntDouble(id1.getData().intValue()+id2.getData().intValue(), true); - } - return id; - } - - public static IntDouble substract(IntDouble id1, IntDouble id2){ - IntDouble id; - if (!id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()-id2.getData().doubleValue(), false); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(id1.getData().intValue()-id2.getData().doubleValue(), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(id1.getData().doubleValue()-id2.getData().intValue(), false); - }else{ - id=new IntDouble(id1.getData().intValue()-id2.getData().intValue(), true); - } - return id; - } - - public static IntDouble noArgFunction(String ident){ - Class function; - IntDouble result; - try { - function = Class.forName("wrimsv2.external.Function"+ident); - - Stack stack = new Stack(); - - ExternalFunction ef; - if (ControlData.allExternalFunctionMap.containsKey(ident)){ - ef=ControlData.allExternalFunctionMap.get(ident); - }else{ - ef = (ExternalFunction)function.newInstance(); - ControlData.allExternalFunctionMap.put(ident, ef); - } - ef.execute(stack); - String valueString=stack.pop().toString(); - - if (valueString.contains(".")){ - return new IntDouble(Double.parseDouble(valueString), false); - }else{ - return new IntDouble(Integer.parseInt(valueString), true); - } - - } catch (Exception e) { - Error.addEvaluationError("The function " +ident+" has an error."); - e.printStackTrace(); - result=new IntDouble (1.0,false); - return result; - } - } - - public static IntDouble argFunction(String ident, ArrayList> idArray){ - IntDouble result; - if (idArray.size()==1){ - if (ControlData.currSvMap.containsKey(ident)||ControlData.currTsMap.containsKey(ident)||ControlData.currDvMap.containsKey(ident)||ControlData.currAliasMap.containsKey(ident)) { - ArrayList idArray1 = idArray.get(0); - if (idArray1.size()==1){ - String idName = idArray1.get(0).getName(); - for (int k=0; k<12; k++){ - if (idName.equals(TimeOperation.month_const[k])){ - Error.addEvaluationError(idName+" can't be used in "+ident+"("+idName+")"); - return new IntDouble (1.0, false); - } - } - return getTimeSeries(ident, idArray1); - }else{ - Error.addEvaluationError("Variable "+ident+" has number of indexes different from 1."); - return new IntDouble (1.0, false); - } - } - } - - Class function; - try { - Stack stack = new Stack(); - for (int i=0; i idArray1 = idArray.get(i); - int size =idArray1.size(); - if (size==1){ - IntDouble id=idArray1.get(0); - if (id.isInt()){ - int value=id.getData().intValue(); - stack.push(value); - }else{ - double value=id.getData().doubleValue(); - stack.push(value); - } - }else if (size>1){ - Number[] valueArray=new Number[size]; - for (int j=0; j1){ - for (int i=0; i idArray1 = idArray.get(i); - int size =idArray1.size(); - if (size==1){ - IntDouble id=idArray1.get(0); - if (id.isInt()){ - int value=(Integer) stack.pop(); - setSvarIntValue(id, value); - }else{ - double value=(Double) stack.pop(); - setSvarDoubleValue(id, value); - } - }else if (size>1){ - IntDouble id=idArray1.get(0); - if (id.isInt()){ - int[] valueArray=new int[size]; - valueArray=(int[])stack.pop(); - for (int j=0; j idArray){ - IntDouble result; - boolean isSumIndex=false; - int indexValue=0; - boolean isIndexStart=true; - - IntDouble id=idArray.get(0); - - if (!id.isInt()){ - Error.addEvaluationError("The index of "+ident+" should be integer."); - result=new IntDouble (1.0,false); - return result; - } - - int idValue=id.getData().intValue(); - ParallelVars prvs = TimeOperation.findTime(idValue); - - double value; - if (ControlData.currDvMap.containsKey(ident)||ControlData.currAliasMap.containsKey(ident)){ - value=dvarAliasTimeSeries(ident,id.getData().intValue(), prvs); - }else{ - if (ControlData.currSvMap.containsKey(ident)){ - if (idValue==0) { - return ControlData.currSvMap.get(ident).getData().copyOf(); - }else if(idValue>0){ - String futSvName=ident+"__fut__"+idValue; - if (ControlData.currSvFutMap.containsKey(futSvName)){ - return ControlData.currSvFutMap.get(futSvName).getData().copyOf(); - }else{ - if (!ControlData.ignoreError) Error.addEvaluationError(futSvName+", the future value of "+ident+" is used before defined."); - return new IntDouble (1.0,false); - } - } - } - value=svarTimeSeries(ident, idValue, prvs); - } - - return new IntDouble (value, false); - } - - public static double svarTimeSeries(String ident, int idValue, ParallelVars prvs){ - int index; - String entryNameTS=DssOperation.entryNameTS(ident, ControlData.timeStep); - if (DataTimeSeries.svTS.containsKey(entryNameTS)){ - DssDataSet dds=DataTimeSeries.svTS.get(entryNameTS); - index =timeSeriesIndex(dds, prvs); - ArrayList data=dds.getData(); - if (index>=0 && index=dds.getStudyStartIndex()){ - double value=data.get(index); - if (dds.fromDssFile()){ - if (value != -901.0 && value != -902.0){ - return value; - } - }else{ - return value; - } - } - } - if (DataTimeSeries.svInit.containsKey(entryNameTS)){ - DssDataSet dds=DataTimeSeries.svInit.get(entryNameTS); - index =timeSeriesIndex(dds, prvs); - ArrayList data=dds.getData(); - if (index>=0 && index data=dds.getData(); - if (index>=0 && index data=dds.getData(); - if (index>=0 && index=currTime){ - Error.addEvaluationError("The timeseries data for decision variable/alias "+ident+" is not available at or after current simulation period."); - return 1.0; - }else if(dataTime>=startTime && dataTime data=dds.getData(); - if (index>=0 && index0){ - if (indexValue>=0 && (ControlData.currEvalTypeIndex==0 || ControlData.currEvalTypeIndex==7)){ - Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); - return 1.0; - } - String newName = ident+"__fut__"+indexValue; - Map dvMap = SolverData.getDvarMap(); - Map asFutMap = ControlData.currModelDataSet.asFutMap; - if (dvMap.containsKey(newName)){ - return dvMap.get(newName).getData().getData().doubleValue(); - }else if(asFutMap.containsKey(newName)){ - return asFutMap.get(newName).getData().getData().doubleValue(); - }else{ - Error.addEvaluationError("Can't access decision variable after the current time step."); - return 1.0; - } - } - - /* - int index=indexValue+ControlData.currTimeStep.get(ControlData.currCycleIndex); - if (index>=0){ - if (indexValue>=0 && (ControlData.currEvalTypeIndex==0 || ControlData.currEvalTypeIndex==7)){ - Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); - return 1.0; - }else{ - DssDataSetFixLength dds=DataTimeSeries.dvAliasTS.get(entryNameTS); - if (dds==null){ - Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); - return 1.0; - } - double[] data=dds.getData(); - return data[index]; - } - } - */ - - DssDataSetFixLength ddsfl=DataTimeSeries.dvAliasTS.get(entryNameTS); - if (ddsfl!=null){ - Date memStartDate = ddsfl.getStartTime(); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+indexValue-1; - double[] datafl=ddsfl.getData(); - if (index>=datafl.length){ - Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); - return 1.0; - }else if (index>=0){ - return datafl[index]; - } - } - - if (!DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ - if (!getDVAliasInitTimeseries(ident)){ - Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +ident); - return 1.0; - } - } - - DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); - int index = timeSeriesIndex(dds, prvs); - ArrayList data=dds.getData(); - if (index>=0 && index0){ - String newName = ident+"__fut__"+indexValue; - Map dvMap = SolverData.getDvarMap(); - Map asFutMap = ControlData.currModelDataSet.asFutMap; - if (dvMap.containsKey(newName)){ - return dvMap.get(newName).getData().getData().doubleValue(); - }else if(asFutMap.containsKey(newName)){ - return asFutMap.get(newName).getData().getData().doubleValue(); - }else{ - Error.addEvaluationError("Can't access decision variable after the current time step."); - return 1.0; - } - } - - /* - int index=indexValue+ControlData.currTimeStep.get(ControlData.currCycleIndex); - if (index>=0){ - DssDataSetFixLength dds=DataTimeSeries.dvAliasTSCycles.get(ci).get(entryNameTS); - if (dds==null){ - Error.addEvaluationError(ident + " at timestep " +indexValue+" of No. "+ci+" cycle doesn't have value."); - return 1.0; - } - double[] data=dds.getData(); - return data[index]; - } - */ - - DssDataSetFixLength ddsfl=DataTimeSeries.dvAliasTSCycles.get(ci).get(entryNameTS); - if (ddsfl!=null){ - Date memStartDate = ddsfl.getStartTime(); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+indexValue-1; - double[] datafl=ddsfl.getData(); - if (index>=datafl.length){ - Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); - return 1.0; - }else if (index>=0){ - return datafl[index]; - } - } - - if (!DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ - if (!getDVAliasInitTimeseries(ident)){ - Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +ident); - return 1.0; - } - } - - DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); - int index = timeSeriesIndex(dds, prvs); - ArrayList data=dds.getData(); - if (index>=0 && index> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); - IntDouble data=new IntDouble(1.0,false); - if (varCycleValueMap.containsKey(ident)){ - Map var= varCycleValueMap.get(ident); - if (var.containsKey(cycle)){ - data=var.get(cycle); - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - if (data==null){ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return new IntDouble(1.0,false); - } - return new IntDouble(data.getData(),data.isInt()); - } - - public static IntDouble pastTSFV(String ident, IntDouble id1, ArrayList> idArray, ParallelVars prvs) { - //turn off when multi-dimensional array is used - if (idArray.size()!=1){ - Error.addEvaluationError("The future index of array variable "+ident+" has to be a single integer."); - return new IntDouble(1.0,false); - } - // - - ArrayList id2Array = idArray.get(0); - if (id2Array.size() !=1){ - Error.addEvaluationError("The future index of array variable "+ident+" has to be a single integer but not a range."); - return new IntDouble(1.0,false); - } - IntDouble id2 = id2Array.get(0); - - if (!id1.isInt() || !id2.isInt()){ - Error.addEvaluationError("The index of array variable "+ident+" has to be an integer."); - return new IntDouble(1.0,false); - } - int i1 = id1.getData().intValue(); - int i2 = id2.getData().intValue(); - - if (i1>=0){ - Error.addEvaluationError("The second index of array variable "+ident+" has to be less than 0 in non-constraint statements."); - return new IntDouble(1.0,false); - } - if (i2<0){ - Error.addEvaluationError("The first index of array variable "+ident+" has to be larger than or equal to 0."); - return new IntDouble(1.0,false); - } - if (!ControlData.currDvMap.containsKey(ident) && !ControlData.currAliasMap.containsKey(ident)){ - Error.addEvaluationError("The array variable "+ident+" is not a dvar or alias. The value from the past time step could not be retrieved."); - return new IntDouble(1.0,false); - } - String vn=ident+"__fut__"+i2; - String entryNameTS=DssOperation.entryNameTS(vn, ControlData.timeStep); - if (DataTimeSeries.dvAliasTS.containsKey(entryNameTS)){ - DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); - if (ddsfl!=null){ - Date memStartDate = ddsfl.getStartTime(); - Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); - int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+i1-1; - double[] datafl=ddsfl.getData(); - if (index>=datafl.length){ - Error.addEvaluationError(vn + " at timestep " +i1+" doesn't have value."); - return new IntDouble(1.0,false); - }else if (index>=0){ - return new IntDouble(datafl[index], false); - } - } - - if (DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ - if (!getDVAliasInitTimeseries(ident)){ - Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +vn); - return new IntDouble(1.0,false); - } - - DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); - int index = timeSeriesIndex(dds, prvs); - ArrayList data=dds.getData(); - if (index>=0 && index> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); - if (varCycleIndexValueMap.containsKey(ident)){ - Map valueMap = varCycleIndexValueMap.get(ident); - if (valueMap.containsKey(cycle)){ - return valueMap.get(cycle); - } - } - Error.addEvaluationError("Variable "+ident+" is not in "+ index+" from the current cycle - "+cycle); - return new IntDouble(1.0,false); - } - - public static IntDouble pastCycleTimeArray(String ident, String cycle, IntDouble id){ - - IntDouble data=new IntDouble(1.0,false); - if (!id.isInt()){ - Error.addEvaluationError("Time array index of "+ident+" is not an integer."); - return data; - } - int index=id.getData().intValue(); - if (index<0){ - ArrayList idArray=new ArrayList(); - idArray.add(id); - ModelDataSet mds=ControlData.currStudyDataSet.getModelDataSetMap().get(cycle); - if (mds.dvMap.containsKey(ident) || mds.asMap.containsKey(ident)){ - ParallelVars prvs = TimeOperation.findTime(index); - //if (ControlData.outputCycleToDss){ - ArrayList ml = ControlData.currStudyDataSet.getModelList(); - int ci=-1; - for (int k=0; k> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); - String varTimeArrayName=ident+"__fut__"+index; - if (varTimeArrayCycleValueMap.containsKey(varTimeArrayName)){ - Map var= varTimeArrayCycleValueMap.get(varTimeArrayName); - if (var.containsKey(cycle)){ - data=var.get(cycle); - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - if (data==null){ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return new IntDouble(1.0,false); - } - return new IntDouble(data.getData(),data.isInt()); - } - - public static IntDouble pastCycleIndexTimeArray(String ident, int pci, IntDouble id){ - IntDouble data=new IntDouble(1.0,false); - int ci=ControlData.currCycleIndex+pci; - if (ci<0){ - Error.addEvaluationError("The "+ci+" cycle from the current cycle is unvailable."); - return new IntDouble(1.0,false); - } - if (!id.isInt()){ - Error.addEvaluationError("Time array index of "+ident+" is not an integer."); - return data; - } - int index=id.getData().intValue(); - StudyDataSet sds = ControlData.currStudyDataSet; - String cycle=sds.getModelList().get(ci); - if (index<0){ - ArrayList idArray=new ArrayList(); - idArray.add(id); - ModelDataSet mds=ControlData.currStudyDataSet.getModelDataSetMap().get(cycle); - if (mds.dvMap.containsKey(ident) || mds.asMap.containsKey(ident)){ - ParallelVars prvs = TimeOperation.findTime(index); - //if (ControlData.outputCycleToDss){ - return new IntDouble(dvarAliasCycleTimeSeries(ident, index, ci, prvs), false); - //}else{ - // return new IntDouble(dvarAliasTimeSeries(ident, index), false); - //} - }else{ - Error.addEvaluationError(ident+" is not a dvar/alias in the cycle of "+cycle+". Only dvar/alias in the past time step of "+index+" and past cycle of "+cycle+" can be used from previous cycles"); - return new IntDouble(1.0, false); - } - }else if(index==0){ - return pastCycleIndexNoTimeArray(ident, pci); - } - Map> varCycleIndexValueMap=sds.getVarCycleIndexValueMap(); - String varTimeArrayName=ident+"__fut__"+index; - if (varCycleIndexValueMap.containsKey(varTimeArrayName)){ - Map var= varCycleIndexValueMap.get(varTimeArrayName); - if (var.containsKey(cycle)){ - data=var.get(cycle); - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - }else{ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return data; - } - if (data==null){ - Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); - return new IntDouble(1.0,false); - } - return new IntDouble(data.getData(),data.isInt()); - } - - public static ArrayList trunk_timeArray(String ident, IntDouble start, IntDouble end){ - ArrayList idArray=new ArrayList(); - if (!start.isInt()){ - Error.addEvaluationError("The starting index of trunk data for variable " + ident + " is not an integer."); - idArray.add(new IntDouble(1.0, false)); - return idArray; - }else if (!end.isInt()){ - Error.addEvaluationError("The ending index of trunk data for variable " + ident + " is not an integer."); - idArray.add(new IntDouble(1.0, false)); - return idArray; - } - int si=start.getData().intValue(); - int ei=end.getData().intValue(); - - if (si>ei){ - Error.addEvaluationError("The starting index of trunk data for variable " + ident + " is larger than the ending index"); - idArray.add(new IntDouble(1.0, false)); - return idArray; - } - - for (int i=si; i<=ei; i++){ - ArrayList indexArray1=new ArrayList (); - IntDouble index = new IntDouble(i, true); - indexArray1.add(index); - ArrayList> indexArray = new ArrayList>(); - indexArray.add(indexArray1); - IntDouble id=ValueEvaluation.argFunction(ident, indexArray); - id.setIndex(i); - id.setName(ident); - idArray.add(id); - } - return idArray; - } - - public static IntDouble max(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.max(id1.getData().intValue(),id2.getData().intValue()), true); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else{ - id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - } - return id; - } - - public static IntDouble min(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.min(id1.getData().intValue(),id2.getData().intValue()), true); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else{ - id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - } - return id; - } - - public static IntDouble intFunc(IntDouble id1){ - IntDouble id; - if (!id1.isInt()){ - id=new IntDouble(((int)id1.getData().doubleValue()), true); - return id; - } - return id1; - } - - public static IntDouble realFunc(IntDouble id1){ - IntDouble id; - if (id1.isInt()){ - id=new IntDouble((id1.getData().doubleValue()), false); - return id; - } - return id1; - } - - public static IntDouble abs(IntDouble id1){ - IntDouble id; - if (id1.isInt()){ - id=new IntDouble(Math.abs(id1.getData().intValue()), true); - }else{ - id=new IntDouble(Math.abs(id1.getData().doubleValue()), false); - } - return id; - } - - public static IntDouble exp(IntDouble id1){ - IntDouble id; - if (id1.isInt()){ - id=new IntDouble(Math.exp(id1.getData().intValue()), false); - }else{ - id=new IntDouble(Math.exp(id1.getData().doubleValue()), false); - } - return id; - } - - public static IntDouble log(IntDouble id1){ - IntDouble id; - if (id1.isInt()){ - id=new IntDouble(Math.log(id1.getData().intValue()), false); - }else{ - id=new IntDouble(Math.log(id1.getData().doubleValue()), false); - } - return id; - } - - public static IntDouble log10(IntDouble id1){ - IntDouble id; - if (id1.isInt()){ - id=new IntDouble(Math.log10(id1.getData().intValue()), false); - }else{ - id=new IntDouble(Math.log10(id1.getData().doubleValue()), false); - } - return id; - } - - public static IntDouble pow(IntDouble id1, IntDouble id2){ - IntDouble id; - if (id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.pow(id1.getData().intValue(),id2.getData().intValue()), false); - }else if (id1.isInt() && !id2.isInt()){ - id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else if (!id1.isInt() && id2.isInt()){ - id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - }else{ - id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); - } - return id; - } - - public static IntDouble sin(IntDouble id1){ - double degrees = id1.getData().doubleValue(); - double radians = Math.toRadians(degrees); - return new IntDouble(Math.sin(radians), false); - } - - public static IntDouble cos(IntDouble id1){ - double degrees = id1.getData().doubleValue(); - double radians = Math.toRadians(degrees); - return new IntDouble(Math.cos(radians), false); - } - - public static IntDouble tan(IntDouble id1){ - double degrees = id1.getData().doubleValue(); - double radians = Math.toRadians(degrees); - return new IntDouble(Math.tan(radians), false); - } - - public static IntDouble cot(IntDouble id1){ - double degrees = id1.getData().doubleValue(); - if (degrees==90.0){ - return new IntDouble(0.0, false); - } - double radians = Math.toRadians(degrees); - return new IntDouble(1.0/Math.tan(radians), false); - } - - public static IntDouble asin(IntDouble id1){ - double value = id1.getData().doubleValue(); - double radians = Math.asin(value); - return new IntDouble(Math.toDegrees(radians), false); - } - - public static IntDouble acos(IntDouble id1){ - double value = id1.getData().doubleValue(); - double radians = Math.acos(value); - return new IntDouble(Math.toDegrees(radians), false); - } - - public static IntDouble atan(IntDouble id1){ - double value = id1.getData().doubleValue(); - double radians = Math.atan(value); - return new IntDouble(Math.toDegrees(radians), false); - } - - public static IntDouble acot(IntDouble id1){ - double value = id1.getData().doubleValue(); - if (value == 0.){ - return new IntDouble(90.0, false); - } - double radians = Math.atan(1.0/value); - return new IntDouble(Math.toDegrees(radians), false); - } - - public static IntDouble exceedance(String tsName, IntDouble exc_id, String selMon, String syStr, String smStr, String sdStr, String eyStr, String emStr, String edStr){ - String entryNameTS=DssOperation.entryNameTS(tsName, ControlData.timeStep); - if (DataTimeSeries.svTS.containsKey(entryNameTS)){ - DssDataSet dds = DataTimeSeries.svTS.get(entryNameTS); - int sy = Integer.parseInt(syStr); - int sd = Integer.parseInt(sdStr); - int ey = Integer.parseInt(eyStr); - int ed = Integer.parseInt(edStr); - int sm = TimeOperation.monthValue(smStr); - int em = TimeOperation.monthValue(emStr); - double exc = exc_id.getData().doubleValue(); - - if (exc<=0.0 || exc>1.0){ - Error.addEvaluationError("Exceedance level must be >0.0 and <=1.0"); - return new IntDouble (1.0, false); - } - - Date selSd; - Date selEd; - if (ControlData.timeStep.equals("1MON")){ - selSd=new Date(sy-1900, sm-1, TimeOperation.numberOfDays(sm, sy)); - selEd=new Date(ey-1900, em-1, TimeOperation.numberOfDays(em, ey)); - }else{ - selSd=new Date(sy-1900, sm-1, sd); - selEd=new Date(ey-1900, em-1, ed); - } - - ArrayList optedData=dds.getTimeseriesDataWithOptions(selMon, selSd, selEd); - double value=DssDataSet.getExceedance(optedData, exc); - return new IntDouble(value, false); - }else{ - Error.addEvaluationError(tsName+" is not a timeseries variable used in the Exceendance funciton for the time step of "+ControlData.timeStep+"."); - return new IntDouble (1.0, false); - } - } - - public static IntDouble exceedance_tsi(String tsName, IntDouble exc_id, String selMon, String syStr, String smStr, String sdStr, String eyStr, String emStr, String edStr){ - String entryNameTS=DssOperation.entryNameTS(tsName, ControlData.timeStep); - if (DataTimeSeries.svTS.containsKey(entryNameTS)){ - DssDataSet dds = DataTimeSeries.svTS.get(entryNameTS); - int sy = Integer.parseInt(syStr); - int sd = Integer.parseInt(sdStr); - int ey = Integer.parseInt(eyStr); - int ed = Integer.parseInt(edStr); - int sm = TimeOperation.monthValue(smStr); - int em = TimeOperation.monthValue(emStr); - double exc = exc_id.getData().doubleValue(); - - if (exc<=0.0 || exc>1.0){ - Error.addEvaluationError("Exceedance level must be >0.0 and <=1.0"); - return new IntDouble (0, true); - } - - Date selSd; - Date selEd; - if (ControlData.timeStep.equals("1MON")){ - selSd=new Date(sy-1900, sm-1, TimeOperation.numberOfDays(sm, sy)); - selEd=new Date(ey-1900, em-1, TimeOperation.numberOfDays(em, ey)); - }else{ - selSd=new Date(sy-1900, sm-1, sd); - selEd=new Date(ey-1900, em-1, ed); - } - - ArrayList optedData=dds.getTimeseriesDataWithOptions(selMon, selSd, selEd); - int tsi=DssDataSet.getExceedance_tsi(optedData, exc); - return new IntDouble(tsi, true); - }else{ - Error.addEvaluationError(tsName+" is not a timeseries variable used in the Exceendance_TSI funciton for the time step of "+ControlData.timeStep+"."); - return new IntDouble (0, true); - } - } - - public static IntDouble daysIn(){ - int days=TimeOperation.numberOfDays(ControlData.currMonth, ControlData.currYear); - return new IntDouble(days, true); - } - - public static IntDouble daysInTimeStep(){ - if (ControlData.currTimeStep.equals("1MON")){ - return daysIn(); - }else{ - IntDouble id=new IntDouble(1, true); - return new IntDouble(1, true); - } - } - - public static IntDouble tafcfs_term(String ident, IntDouble id){ - ParallelVars prvs = new ParallelVars(); - if (id==null){ - prvs.dataMonth=ControlData.currMonth; - prvs.dataYear=ControlData.currYear; - }else{ - if (!id.isInt()){ - Error.addEvaluationError("The index of "+ident+" should be integer."); - } - prvs=TimeOperation.findTime(id.getData().intValue()); - } - double convert = tafcfs(ident, prvs); - return new IntDouble(convert, false); - } - - public static double tafcfs(String ident, ParallelVars prvs){ - double convert; - int days=TimeOperation.numberOfDays(prvs.dataMonth, prvs.dataYear); - if (ident.equals("taf_cfs")){ - if (ControlData.timeStep.equals("1MON")){ - return 504.1666667 / days; - }else{ - return 504.1666667; - } - }else if (ident.equals("cfs_taf")){ - if (ControlData.timeStep.equals("1MON")){ - return days / 504.1666667; - }else{ - return 1 / 504.1666667; - } - }else if (ident.equals("af_cfs")){ - if (ControlData.timeStep.equals("1MON")){ - return 504.1666667 / days / 1000.; - }else{ - return 504.1666667 / 1000.; - } - }else{ - if (ControlData.timeStep.equals("1MON")){ - return days / 504.1666667 * 1000.; - }else{ - return 1 / 504.1666667 * 1000.; - } - } - } - - public static IntDouble term_YEAR(){ - return new IntDouble(TimeOperation.waterYearValue(), true); - } - - public static IntDouble term_MONTH(){ - return new IntDouble(TimeOperation.waterMonthValue(ControlData.currMonth), true); - } - - public static IntDouble term_DAY(){ - return new IntDouble(ControlData.currDay, true); - } - - public static IntDouble term_MONTH_CONST(String month){ - int monthValue=TimeOperation.monthValue(month); - return new IntDouble(TimeOperation.waterMonthValue(monthValue), true, month, 0); - } - - public static IntDouble term_PASTMONTH(String pastMonth){ - pastMonth=pastMonth.substring(4); - int pastMonthValue=TimeOperation.monthValue(pastMonth); - int index=pastMonthValue-ControlData.currMonth; - if (index>=0){ - index=index-12; - } - return new IntDouble(index,true); - } - - public static IntDouble term_ARRAY_ITERATOR(ParallelVars prvs){ - return new IntDouble(prvs.timeArrayIndex, true); - } - - public static void sumExpression_IDENT(String ident, Stack sumIndex){ - //To Do: check if svar, dvar, alias contains ident - LoopIndex li=new LoopIndex(ident, 0, false, 0, 0, 0); - sumIndex.push(li); - } - - public static void initSumExpression(IntDouble id1, IntDouble id2, String s, Stack sumIndex){ - LoopIndex li=sumIndex.pop(); - li.step=1; - if (!s.equals("")){ - li.step=convertStringToInt(s); - } - if (!id1.isInt()){ - Error.addEvaluationError("the starting index should be integer"); - } - if (!id2.isInt()){ - Error.addEvaluationError("the ending index should be integer"); - } - li.start=id1.getData().intValue(); - li.end=id2.getData().intValue(); - li.setValue(li.start); - li.setIndexStart(true); - sumIndex.push(li); - if (li.start>li.end && li.step>0){ - ControlData.ignoreError=true; - }else if (li.start sumIndex){ - ControlData.ignoreError=false; - LoopIndex li=sumIndex.pop(); - if (li.step>=0){ - if (li.start>li.end) return new IntDouble(0.0, false); - li.start=li.start+li.step; - if (li.start>li.end) return id; - sumIndex.push(li); - for (int i=li.start; i<=li.end; i=i+li.step){ - li=sumIndex.pop(); - li.setValue(i); - li.setIndexStart(true); - sumIndex.push(li); - ANTLRStringStream stream = new ANTLRStringStream("v: "+expression); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - ValueEvaluatorParser evaluator = new ValueEvaluatorParser(tokenStream); - evaluator.setSumIndex(sumIndex); - try{ - evaluator.evaluator(); - }catch (RecognitionException e){ - Error.addEvaluationError(e.toString()); - } - - IntDouble id0=evaluator.evalValue; - id=add(id, id0); - } - }else{ - if (li.start=li.end; i=i+li.step){ - li=sumIndex.pop(); - li.setValue(i); - li.setIndexStart(true); - sumIndex.push(li); - ANTLRStringStream stream = new ANTLRStringStream("v: "+expression); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - ValueEvaluatorParser evaluator = new ValueEvaluatorParser(tokenStream); - evaluator.setSumIndex(sumIndex); - try{ - evaluator.evaluator(); - }catch (RecognitionException e){ - Error.addEvaluationError(e.toString()); - } - - IntDouble id0=evaluator.evalValue; - id=add(id, id0); - } - } - sumIndex.pop(); - return id; - } - - public static Number assignWhereStatement(IntDouble id){ - return id.getData(); - } - - public static IntDouble tableSQL(String table, String select, HashMap where, HashMap given, String use){ - IntDouble id; - if (where==null){ - return TableOperation.findData(table, select, given, use); - }else{ - return TableOperation.findData(table, select, where, given, use); - } - } - - public static IntDouble expressionInput(IntDouble id){ - return id; - } - - public static void setSvarIntValue(IntDouble id, int value){ - String name=id.getName(); - int index=id.getIndex(); - - if (ControlData.currSvMap.containsKey(name)){ - if (index==0) { - ControlData.currSvMap.get(name).getData().setData(value); - }else if(index>0){ - String futSvName=name+"__fut__"+index; - if (ControlData.currSvFutMap.containsKey(futSvName)){ - ControlData.currSvFutMap.get(futSvName).getData().setData(value); - } - } - } - } - - public static void setSvarDoubleValue(IntDouble id, double value){ - String name=id.getName(); - int index=id.getIndex(); - - if (ControlData.currSvMap.containsKey(name)){ - if (index==0) { - ControlData.currSvMap.get(name).getData().setData(value); - }else if(index>0){ - String futSvName=name+"__fut__"+index; - if (ControlData.currSvFutMap.containsKey(futSvName)){ - ControlData.currSvFutMap.get(futSvName).getData().setData(value); - } - } - } - } -} +package wrimsv2.evaluator; +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.TokenStream; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.components.ControlData; +import wrimsv2.components.Error; +import wrimsv2.components.IntDouble; +import wrimsv2.external.*; +import wrimsv2.hdf5.HDF5Reader; +import wrimsv2.parallel.ParallelVars; +import wrimsv2.solver.CbcSolver; + +import java.time.Duration; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; +import java.util.ArrayList; +import java.util.Stack; +import java.util.Date; + +public class ValueEvaluation { + public static double convertStringToDouble(String text){ + return Double.parseDouble(text); + } + + public static int convertStringToInt(String text){ + return Integer.parseInt(text); + } + + public static String convertDoubleToString(double value){ + return Double.toString(value); + } + + public static String convertIntToString(int value){ + return Integer.toString(value); + } + + public static boolean relationStatement(IntDouble id1, IntDouble id2, String relation){ + double value1=id1.getData().doubleValue(); + double value2=id2.getData().doubleValue(); + + if (relation.equals("==")) { + if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ + if (value1>=value2-ControlData.relationTolerance && value1<=value2+ControlData.relationTolerance){ + return true; + }else{ + return false; + } + }else{ + if (value1==value2){ + return true; + }else{ + return false; + } + } + }else if (relation.equals(">")){ + if (value1>value2){ + return true; + }else{ + return false; + } + }else if (relation.equals("<")){ + if (value1=")){ + if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ + if (value1>=value2-ControlData.relationTolerance){ + return true; + }else{ + return false; + } + }else{ + if (value1>=value2){ + return true; + }else{ + return false; + } + } + }else{ + if (ControlData.solverName.equalsIgnoreCase("Cbc") && CbcSolver.cbcSolutionRounding){ + if (value1<=value2+ControlData.relationTolerance){ + return true; + }else{ + return false; + } + }else{ + if (value1<=value2){ + return true; + }else{ + return false; + } + } + } + } + + public static boolean range(String m1, String m2){ + return TimeOperation.range(ControlData.currMonth, m1, m2); + } + + public static boolean relationStatementSeries(boolean r1, boolean r2, String s){ + if (s.equals(".and.")) { + return (r1 && r2); + }else{ + return (r1 || r2); + } + } + + public static IntDouble term_knownTS(IntDouble result){ + return result; + } + + public static IntDouble term_IDENT (String ident, Stack sumIndex){ + if (ControlData.currSvMap.containsKey(ident)){ + IntDouble id0=ControlData.currSvMap.get(ident).getData(); + return new IntDouble(id0.getData(),id0.isInt(),ident, 0); + }else if (ControlData.currTsMap.containsKey(ident)){ + IntDouble id0=ControlData.currTsMap.get(ident).getData(); + return new IntDouble(id0.getData(),id0.isInt(), ident, 0); + }else if (ControlData.isPostProcessing && ControlData.currDvMap.containsKey(ident)){ + IntDouble id0=ControlData.currDvMap.get(ident).getData(); + return new IntDouble(id0.getData(),id0.isInt(), ident, 0); + }else if (ControlData.isPostProcessing && ControlData.currAliasMap.containsKey(ident)){ + IntDouble id0=ControlData.currAliasMap.get(ident).getData(); + if (id0==null) { + Error.addEvaluationError(ident+" is not defined before it is used."); + return new IntDouble (1.0, false, ident, 0); + } + return new IntDouble(id0.getData(),id0.isInt(), ident, 0); + } + if (sumIndex.size()>0){ + LoopIndex li=sumIndex.pop(); + if (li.getName().equals(ident) && li.getIndexStart()){ + sumIndex.push(li); + return new IntDouble(li.getValue(),true, ident, 0); + } + sumIndex.push(li); + } + if (ControlData.parameterMap.containsKey(ident)){ + IntDouble id0=ControlData.parameterMap.get(ident).getData(); + return new IntDouble(id0.getData(),id0.isInt(), ident, 0); + } + Error.addEvaluationError(ident+" is not in svar, dvar, alias, or parameter list."); + return new IntDouble (1.0, false, ident, 0); + } + + public static IntDouble term_SVAR (String ident){ + IntDouble data; + if (!ControlData.currSvMap.containsKey(ident)){ + if (!ControlData.currTsMap.containsKey(ident)){ + Error.addEvaluationError("State variable "+ident+" is not defined before used."); + return new IntDouble(1.0, false, ident, 0); + }else{ + data=ControlData.currTsMap.get(ident).getData(); + } + }else{ + data=ControlData.currSvMap.get(ident).getData(); + } + + if (data == null){ + Error.addEvaluationError("The value of state variable "+ident+" is not defined before used."); + return new IntDouble(1.0, false, ident, 0); + } + return new IntDouble(data.getData(), data.isInt(), ident, 0); + } + + public static IntDouble term_INTEGER (String integer){ + return new IntDouble(convertStringToInt(integer), true); + } + + public static IntDouble term_FLOAT (String floatValue){ + return new IntDouble(convertStringToDouble(floatValue), false); + } + + public static IntDouble unary (String s, IntDouble id){ + if (s !=null && s.equals("-")){ + if (id.isInt()){ + int value=-id.getData().intValue(); + return new IntDouble(value, id.isInt()); + }else{ + double value=-id.getData().doubleValue(); + return new IntDouble(value, id.isInt()); + } + }else{ + return id; + } + } + + public static IntDouble mult(IntDouble id1, IntDouble id2){ + IntDouble id; + if (!id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()*id2.getData().doubleValue(), false); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().intValue()*id2.getData().doubleValue(), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()*id2.getData().intValue(), false); + }else{ + id=new IntDouble(id1.getData().intValue()*id2.getData().intValue(), true); + } + return id; + } + + public static IntDouble divide(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id2.getData().doubleValue()==0.0){ + Error.addEvaluationError("divided by 0."); + return new IntDouble(1.0, false); + } + if (!id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()/id2.getData().doubleValue(), false); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().intValue()/id2.getData().doubleValue(), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()/id2.getData().intValue(), false); + }else { + id=new IntDouble(id1.getData().intValue()/id2.getData().intValue(), true); + } + return id; + } + + public static IntDouble mod(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id2.getData().doubleValue()==0.0){ + Error.addEvaluationError("Mod function uses 0 as divider."); + return new IntDouble(1.0, false); + } + if (!id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()%id2.getData().doubleValue(), false); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().intValue()%id2.getData().doubleValue(), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()%id2.getData().intValue(), false); + }else{ + id=new IntDouble(id1.getData().intValue()%id2.getData().intValue(), true); + } + return id; + } + + public static IntDouble round(IntDouble id1){ + IntDouble id; + id=new IntDouble(Math.round(id1.getData().doubleValue()), true); + return id; + } + + public static IntDouble add(IntDouble id1, IntDouble id2){ + IntDouble id; + if (!id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()+id2.getData().doubleValue(), false); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().intValue()+id2.getData().doubleValue(), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()+id2.getData().intValue(), false); + }else { + id=new IntDouble(id1.getData().intValue()+id2.getData().intValue(), true); + } + return id; + } + + public static IntDouble substract(IntDouble id1, IntDouble id2){ + IntDouble id; + if (!id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()-id2.getData().doubleValue(), false); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(id1.getData().intValue()-id2.getData().doubleValue(), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(id1.getData().doubleValue()-id2.getData().intValue(), false); + }else{ + id=new IntDouble(id1.getData().intValue()-id2.getData().intValue(), true); + } + return id; + } + + public static IntDouble noArgFunction(String ident){ + Class function; + IntDouble result; + try { + function = Class.forName("wrimsv2.external.Function"+ident); + + Stack stack = new Stack(); + + ExternalFunction ef; + if (ControlData.allExternalFunctionMap.containsKey(ident)){ + ef=ControlData.allExternalFunctionMap.get(ident); + }else{ + ef = (ExternalFunction)function.newInstance(); + ControlData.allExternalFunctionMap.put(ident, ef); + } + ef.execute(stack); + String valueString=stack.pop().toString(); + + if (valueString.contains(".")){ + return new IntDouble(Double.parseDouble(valueString), false); + }else{ + return new IntDouble(Integer.parseInt(valueString), true); + } + + } catch (Exception e) { + Error.addEvaluationError("The function " +ident+" has an error."); + e.printStackTrace(); + result=new IntDouble (1.0,false); + return result; + } + } + + public static IntDouble argFunction(String ident, ArrayList> idArray){ + IntDouble result; + if (idArray.size()==1){ + if (ControlData.currSvMap.containsKey(ident)||ControlData.currTsMap.containsKey(ident)||ControlData.currDvMap.containsKey(ident)||ControlData.currAliasMap.containsKey(ident)) { + ArrayList idArray1 = idArray.get(0); + if (idArray1.size()==1){ + String idName = idArray1.get(0).getName(); + for (int k=0; k<12; k++){ + if (idName.equals(TimeOperation.month_const[k])){ + Error.addEvaluationError(idName+" can't be used in "+ident+"("+idName+")"); + return new IntDouble (1.0, false); + } + } + return getTimeSeries(ident, idArray1); + }else{ + Error.addEvaluationError("Variable "+ident+" has number of indexes different from 1."); + return new IntDouble (1.0, false); + } + } + } + + Class function; + try { + Stack stack = new Stack(); + for (int i=0; i idArray1 = idArray.get(i); + int size =idArray1.size(); + if (size==1){ + IntDouble id=idArray1.get(0); + if (id.isInt()){ + int value=id.getData().intValue(); + stack.push(value); + }else{ + double value=id.getData().doubleValue(); + stack.push(value); + } + }else if (size>1){ + Number[] valueArray=new Number[size]; + for (int j=0; j1){ + for (int i=0; i idArray1 = idArray.get(i); + int size =idArray1.size(); + if (size==1){ + IntDouble id=idArray1.get(0); + if (id.isInt()){ + int value=(Integer) stack.pop(); + setSvarIntValue(id, value); + }else{ + double value=(Double) stack.pop(); + setSvarDoubleValue(id, value); + } + }else if (size>1){ + IntDouble id=idArray1.get(0); + if (id.isInt()){ + int[] valueArray=new int[size]; + valueArray=(int[])stack.pop(); + for (int j=0; j idArray){ + IntDouble result; + boolean isSumIndex=false; + int indexValue=0; + boolean isIndexStart=true; + + IntDouble id=idArray.get(0); + + if (!id.isInt()){ + Error.addEvaluationError("The index of "+ident+" should be integer."); + result=new IntDouble (1.0,false); + return result; + } + + int idValue=id.getData().intValue(); + ParallelVars prvs = TimeOperation.findTime(idValue); + + double value; + if (ControlData.currDvMap.containsKey(ident)||ControlData.currAliasMap.containsKey(ident)){ + value=dvarAliasTimeSeries(ident,id.getData().intValue(), prvs); + }else{ + if (ControlData.currSvMap.containsKey(ident)){ + if (idValue==0) { + return ControlData.currSvMap.get(ident).getData().copyOf(); + }else if(idValue>0){ + String futSvName=ident+"__fut__"+idValue; + if (ControlData.currSvFutMap.containsKey(futSvName)){ + return ControlData.currSvFutMap.get(futSvName).getData().copyOf(); + }else{ + if (!ControlData.ignoreError) Error.addEvaluationError(futSvName+", the future value of "+ident+" is used before defined."); + return new IntDouble (1.0,false); + } + } + } + value=svarTimeSeries(ident, idValue, prvs); + } + + return new IntDouble (value, false); + } + + public static double svarTimeSeries(String ident, int idValue, ParallelVars prvs){ + int index; + String entryNameTS=DssOperation.entryNameTS(ident, ControlData.timeStep); + if (DataTimeSeries.svTS.containsKey(entryNameTS)){ + DssDataSet dds=DataTimeSeries.svTS.get(entryNameTS); + index =timeSeriesIndex(dds, prvs); + ArrayList data=dds.getData(); + if (index>=0 && index=dds.getStudyStartIndex()){ + double value=data.get(index); + if (dds.fromDssFile()){ + if (value != -901.0 && value != -902.0){ + return value; + } + }else{ + return value; + } + } + } + if (DataTimeSeries.svInit.containsKey(entryNameTS)){ + DssDataSet dds=DataTimeSeries.svInit.get(entryNameTS); + index =timeSeriesIndex(dds, prvs); + ArrayList data=dds.getData(); + if (index>=0 && index data=dds.getData(); + if (index>=0 && index data=dds.getData(); + if (index>=0 && index=currTime){ + Error.addEvaluationError("The timeseries data for decision variable/alias "+ident+" is not available at or after current simulation period."); + return 1.0; + }else if(dataTime>=startTime && dataTime data=dds.getData(); + if (index>=0 && index0){ + if (indexValue>=0 && (ControlData.currEvalTypeIndex==0 || ControlData.currEvalTypeIndex==7)){ + Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); + return 1.0; + } + String newName = ident+"__fut__"+indexValue; + Map dvMap = SolverData.getDvarMap(); + Map asFutMap = ControlData.currModelDataSet.asFutMap; + if (dvMap.containsKey(newName)){ + return dvMap.get(newName).getData().getData().doubleValue(); + }else if(asFutMap.containsKey(newName)){ + return asFutMap.get(newName).getData().getData().doubleValue(); + }else{ + Error.addEvaluationError("Can't access decision variable after the current time step."); + return 1.0; + } + } + + /* + int index=indexValue+ControlData.currTimeStep.get(ControlData.currCycleIndex); + if (index>=0){ + if (indexValue>=0 && (ControlData.currEvalTypeIndex==0 || ControlData.currEvalTypeIndex==7)){ + Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); + return 1.0; + }else{ + DssDataSetFixLength dds=DataTimeSeries.dvAliasTS.get(entryNameTS); + if (dds==null){ + Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); + return 1.0; + } + double[] data=dds.getData(); + return data[index]; + } + } + */ + + DssDataSetFixLength ddsfl=DataTimeSeries.dvAliasTS.get(entryNameTS); + if (ddsfl!=null){ + Date memStartDate = ddsfl.getStartTime(); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+indexValue-1; + double[] datafl=ddsfl.getData(); + if (index>=datafl.length){ + Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); + return 1.0; + }else if (index>=0){ + return datafl[index]; + } + } + + if (!DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ + if (!getDVAliasInitTimeseries(ident)){ + Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +ident); + return 1.0; + } + } + + DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); + int index = timeSeriesIndex(dds, prvs); + ArrayList data=dds.getData(); + if (index>=0 && index0){ + String newName = ident+"__fut__"+indexValue; + Map dvMap = SolverData.getDvarMap(); + Map asFutMap = ControlData.currModelDataSet.asFutMap; + if (dvMap.containsKey(newName)){ + return dvMap.get(newName).getData().getData().doubleValue(); + }else if(asFutMap.containsKey(newName)){ + return asFutMap.get(newName).getData().getData().doubleValue(); + }else{ + Error.addEvaluationError("Can't access decision variable after the current time step."); + return 1.0; + } + } + + /* + int index=indexValue+ControlData.currTimeStep.get(ControlData.currCycleIndex); + if (index>=0){ + DssDataSetFixLength dds=DataTimeSeries.dvAliasTSCycles.get(ci).get(entryNameTS); + if (dds==null){ + Error.addEvaluationError(ident + " at timestep " +indexValue+" of No. "+ci+" cycle doesn't have value."); + return 1.0; + } + double[] data=dds.getData(); + return data[index]; + } + */ + + DssDataSetFixLength ddsfl=DataTimeSeries.dvAliasTSCycles.get(ci).get(entryNameTS); + if (ddsfl!=null){ + Date memStartDate = ddsfl.getStartTime(); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+indexValue-1; + double[] datafl=ddsfl.getData(); + if (index>=datafl.length){ + Error.addEvaluationError(ident + " at timestep " +indexValue+" doesn't have value"); + return 1.0; + }else if (index>=0){ + return datafl[index]; + } + } + + if (!DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ + if (!getDVAliasInitTimeseries(ident)){ + Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +ident); + return 1.0; + } + } + + DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); + int index = timeSeriesIndex(dds, prvs); + ArrayList data=dds.getData(); + if (index>=0 && index> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); + IntDouble data=new IntDouble(1.0,false); + if (varCycleValueMap.containsKey(ident)){ + Map var= varCycleValueMap.get(ident); + if (var.containsKey(cycle)){ + data=var.get(cycle); + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + if (data==null){ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return new IntDouble(1.0,false); + } + return new IntDouble(data.getData(),data.isInt()); + } + + public static IntDouble pastTSFV(String ident, IntDouble id1, ArrayList> idArray, ParallelVars prvs) { + //turn off when multi-dimensional array is used + if (idArray.size()!=1){ + Error.addEvaluationError("The future index of array variable "+ident+" has to be a single integer."); + return new IntDouble(1.0,false); + } + // + + ArrayList id2Array = idArray.get(0); + if (id2Array.size() !=1){ + Error.addEvaluationError("The future index of array variable "+ident+" has to be a single integer but not a range."); + return new IntDouble(1.0,false); + } + IntDouble id2 = id2Array.get(0); + + if (!id1.isInt() || !id2.isInt()){ + Error.addEvaluationError("The index of array variable "+ident+" has to be an integer."); + return new IntDouble(1.0,false); + } + int i1 = id1.getData().intValue(); + int i2 = id2.getData().intValue(); + + if (i1>=0){ + Error.addEvaluationError("The second index of array variable "+ident+" has to be less than 0 in non-constraint statements."); + return new IntDouble(1.0,false); + } + if (i2<0){ + Error.addEvaluationError("The first index of array variable "+ident+" has to be larger than or equal to 0."); + return new IntDouble(1.0,false); + } + if (!ControlData.currDvMap.containsKey(ident) && !ControlData.currAliasMap.containsKey(ident)){ + Error.addEvaluationError("The array variable "+ident+" is not a dvar or alias. The value from the past time step could not be retrieved."); + return new IntDouble(1.0,false); + } + String vn=ident+"__fut__"+i2; + String entryNameTS=DssOperation.entryNameTS(vn, ControlData.timeStep); + if (DataTimeSeries.dvAliasTS.containsKey(entryNameTS)){ + DssDataSetFixLength ddsfl = DataTimeSeries.dvAliasTS.get(entryNameTS); + if (ddsfl!=null){ + Date memStartDate = ddsfl.getStartTime(); + Date currDate = new Date(ControlData.currYear-1900, ControlData.currMonth-1, ControlData.currDay); + int index=TimeOperation.getNumberOfTimestep(memStartDate, currDate, ddsfl.getTimeStep())+i1-1; + double[] datafl=ddsfl.getData(); + if (index>=datafl.length){ + Error.addEvaluationError(vn + " at timestep " +i1+" doesn't have value."); + return new IntDouble(1.0,false); + }else if (index>=0){ + return new IntDouble(datafl[index], false); + } + } + + if (DataTimeSeries.dvAliasInit.containsKey(entryNameTS)){ + if (!getDVAliasInitTimeseries(ident)){ + Error.addEvaluationError("Initial file doesn't have data for decision vairiable/alias " +vn); + return new IntDouble(1.0,false); + } + + DssDataSet dds=DataTimeSeries.dvAliasInit.get(entryNameTS); + int index = timeSeriesIndex(dds, prvs); + ArrayList data=dds.getData(); + if (index>=0 && index> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); + if (varCycleIndexValueMap.containsKey(ident)){ + Map valueMap = varCycleIndexValueMap.get(ident); + if (valueMap.containsKey(cycle)){ + return valueMap.get(cycle); + } + } + Error.addEvaluationError("Variable "+ident+" is not in "+ index+" from the current cycle - "+cycle); + return new IntDouble(1.0,false); + } + + public static IntDouble pastCycleTimeArray(String ident, String cycle, IntDouble id){ + + IntDouble data=new IntDouble(1.0,false); + if (!id.isInt()){ + Error.addEvaluationError("Time array index of "+ident+" is not an integer."); + return data; + } + int index=id.getData().intValue(); + if (index<0){ + ArrayList idArray=new ArrayList(); + idArray.add(id); + ModelDataSet mds=ControlData.currStudyDataSet.getModelDataSetMap().get(cycle); + if (mds.dvMap.containsKey(ident) || mds.asMap.containsKey(ident)){ + ParallelVars prvs = TimeOperation.findTime(index); + //if (ControlData.outputCycleToDss){ + ArrayList ml = ControlData.currStudyDataSet.getModelList(); + int ci=-1; + for (int k=0; k> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); + String varTimeArrayName=ident+"__fut__"+index; + if (varTimeArrayCycleValueMap.containsKey(varTimeArrayName)){ + Map var= varTimeArrayCycleValueMap.get(varTimeArrayName); + if (var.containsKey(cycle)){ + data=var.get(cycle); + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + if (data==null){ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return new IntDouble(1.0,false); + } + return new IntDouble(data.getData(),data.isInt()); + } + + public static IntDouble pastCycleIndexTimeArray(String ident, int pci, IntDouble id){ + IntDouble data=new IntDouble(1.0,false); + int ci=ControlData.currCycleIndex+pci; + if (ci<0){ + Error.addEvaluationError("The "+ci+" cycle from the current cycle is unvailable."); + return new IntDouble(1.0,false); + } + if (!id.isInt()){ + Error.addEvaluationError("Time array index of "+ident+" is not an integer."); + return data; + } + int index=id.getData().intValue(); + StudyDataSet sds = ControlData.currStudyDataSet; + String cycle=sds.getModelList().get(ci); + if (index<0){ + ArrayList idArray=new ArrayList(); + idArray.add(id); + ModelDataSet mds=ControlData.currStudyDataSet.getModelDataSetMap().get(cycle); + if (mds.dvMap.containsKey(ident) || mds.asMap.containsKey(ident)){ + ParallelVars prvs = TimeOperation.findTime(index); + //if (ControlData.outputCycleToDss){ + return new IntDouble(dvarAliasCycleTimeSeries(ident, index, ci, prvs), false); + //}else{ + // return new IntDouble(dvarAliasTimeSeries(ident, index), false); + //} + }else{ + Error.addEvaluationError(ident+" is not a dvar/alias in the cycle of "+cycle+". Only dvar/alias in the past time step of "+index+" and past cycle of "+cycle+" can be used from previous cycles"); + return new IntDouble(1.0, false); + } + }else if(index==0){ + return pastCycleIndexNoTimeArray(ident, pci); + } + Map> varCycleIndexValueMap=sds.getVarCycleIndexValueMap(); + String varTimeArrayName=ident+"__fut__"+index; + if (varCycleIndexValueMap.containsKey(varTimeArrayName)){ + Map var= varCycleIndexValueMap.get(varTimeArrayName); + if (var.containsKey(cycle)){ + data=var.get(cycle); + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + }else{ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return data; + } + if (data==null){ + Error.addEvaluationError("The variable "+ident+" is not defined in the past cycle of "+cycle+"."); + return new IntDouble(1.0,false); + } + return new IntDouble(data.getData(),data.isInt()); + } + + public static ArrayList trunk_timeArray(String ident, IntDouble start, IntDouble end){ + ArrayList idArray=new ArrayList(); + if (!start.isInt()){ + Error.addEvaluationError("The starting index of trunk data for variable " + ident + " is not an integer."); + idArray.add(new IntDouble(1.0, false)); + return idArray; + }else if (!end.isInt()){ + Error.addEvaluationError("The ending index of trunk data for variable " + ident + " is not an integer."); + idArray.add(new IntDouble(1.0, false)); + return idArray; + } + int si=start.getData().intValue(); + int ei=end.getData().intValue(); + + if (si>ei){ + Error.addEvaluationError("The starting index of trunk data for variable " + ident + " is larger than the ending index"); + idArray.add(new IntDouble(1.0, false)); + return idArray; + } + + for (int i=si; i<=ei; i++){ + ArrayList indexArray1=new ArrayList (); + IntDouble index = new IntDouble(i, true); + indexArray1.add(index); + ArrayList> indexArray = new ArrayList>(); + indexArray.add(indexArray1); + IntDouble id=ValueEvaluation.argFunction(ident, indexArray); + id.setIndex(i); + id.setName(ident); + idArray.add(id); + } + return idArray; + } + + public static IntDouble max(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.max(id1.getData().intValue(),id2.getData().intValue()), true); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else{ + id=new IntDouble(Math.max(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + } + return id; + } + + public static IntDouble min(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.min(id1.getData().intValue(),id2.getData().intValue()), true); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else{ + id=new IntDouble(Math.min(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + } + return id; + } + + public static IntDouble intFunc(IntDouble id1){ + IntDouble id; + if (!id1.isInt()){ + id=new IntDouble(((int)id1.getData().doubleValue()), true); + return id; + } + return id1; + } + + public static IntDouble realFunc(IntDouble id1){ + IntDouble id; + if (id1.isInt()){ + id=new IntDouble((id1.getData().doubleValue()), false); + return id; + } + return id1; + } + + public static IntDouble abs(IntDouble id1){ + IntDouble id; + if (id1.isInt()){ + id=new IntDouble(Math.abs(id1.getData().intValue()), true); + }else{ + id=new IntDouble(Math.abs(id1.getData().doubleValue()), false); + } + return id; + } + + public static IntDouble exp(IntDouble id1){ + IntDouble id; + if (id1.isInt()){ + id=new IntDouble(Math.exp(id1.getData().intValue()), false); + }else{ + id=new IntDouble(Math.exp(id1.getData().doubleValue()), false); + } + return id; + } + + public static IntDouble log(IntDouble id1){ + IntDouble id; + if (id1.isInt()){ + id=new IntDouble(Math.log(id1.getData().intValue()), false); + }else{ + id=new IntDouble(Math.log(id1.getData().doubleValue()), false); + } + return id; + } + + public static IntDouble log10(IntDouble id1){ + IntDouble id; + if (id1.isInt()){ + id=new IntDouble(Math.log10(id1.getData().intValue()), false); + }else{ + id=new IntDouble(Math.log10(id1.getData().doubleValue()), false); + } + return id; + } + + public static IntDouble pow(IntDouble id1, IntDouble id2){ + IntDouble id; + if (id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.pow(id1.getData().intValue(),id2.getData().intValue()), false); + }else if (id1.isInt() && !id2.isInt()){ + id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else if (!id1.isInt() && id2.isInt()){ + id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + }else{ + id=new IntDouble(Math.pow(id1.getData().doubleValue(),id2.getData().doubleValue()), false); + } + return id; + } + + public static IntDouble sin(IntDouble id1){ + double degrees = id1.getData().doubleValue(); + double radians = Math.toRadians(degrees); + return new IntDouble(Math.sin(radians), false); + } + + public static IntDouble cos(IntDouble id1){ + double degrees = id1.getData().doubleValue(); + double radians = Math.toRadians(degrees); + return new IntDouble(Math.cos(radians), false); + } + + public static IntDouble tan(IntDouble id1){ + double degrees = id1.getData().doubleValue(); + double radians = Math.toRadians(degrees); + return new IntDouble(Math.tan(radians), false); + } + + public static IntDouble cot(IntDouble id1){ + double degrees = id1.getData().doubleValue(); + if (degrees==90.0){ + return new IntDouble(0.0, false); + } + double radians = Math.toRadians(degrees); + return new IntDouble(1.0/Math.tan(radians), false); + } + + public static IntDouble asin(IntDouble id1){ + double value = id1.getData().doubleValue(); + double radians = Math.asin(value); + return new IntDouble(Math.toDegrees(radians), false); + } + + public static IntDouble acos(IntDouble id1){ + double value = id1.getData().doubleValue(); + double radians = Math.acos(value); + return new IntDouble(Math.toDegrees(radians), false); + } + + public static IntDouble atan(IntDouble id1){ + double value = id1.getData().doubleValue(); + double radians = Math.atan(value); + return new IntDouble(Math.toDegrees(radians), false); + } + + public static IntDouble acot(IntDouble id1){ + double value = id1.getData().doubleValue(); + if (value == 0.){ + return new IntDouble(90.0, false); + } + double radians = Math.atan(1.0/value); + return new IntDouble(Math.toDegrees(radians), false); + } + + public static IntDouble exceedance(String tsName, IntDouble exc_id, String selMon, String syStr, String smStr, String sdStr, String eyStr, String emStr, String edStr){ + String entryNameTS=DssOperation.entryNameTS(tsName, ControlData.timeStep); + if (DataTimeSeries.svTS.containsKey(entryNameTS)){ + DssDataSet dds = DataTimeSeries.svTS.get(entryNameTS); + int sy = Integer.parseInt(syStr); + int sd = Integer.parseInt(sdStr); + int ey = Integer.parseInt(eyStr); + int ed = Integer.parseInt(edStr); + int sm = TimeOperation.monthValue(smStr); + int em = TimeOperation.monthValue(emStr); + double exc = exc_id.getData().doubleValue(); + + if (exc<=0.0 || exc>1.0){ + Error.addEvaluationError("Exceedance level must be >0.0 and <=1.0"); + return new IntDouble (1.0, false); + } + + Date selSd; + Date selEd; + if (ControlData.timeStep.equals("1MON")){ + selSd=new Date(sy-1900, sm-1, TimeOperation.numberOfDays(sm, sy)); + selEd=new Date(ey-1900, em-1, TimeOperation.numberOfDays(em, ey)); + }else{ + selSd=new Date(sy-1900, sm-1, sd); + selEd=new Date(ey-1900, em-1, ed); + } + + ArrayList optedData=dds.getTimeseriesDataWithOptions(selMon, selSd, selEd); + double value=DssDataSet.getExceedance(optedData, exc); + return new IntDouble(value, false); + }else{ + Error.addEvaluationError(tsName+" is not a timeseries variable used in the Exceendance funciton for the time step of "+ControlData.timeStep+"."); + return new IntDouble (1.0, false); + } + } + + public static IntDouble exceedance_tsi(String tsName, IntDouble exc_id, String selMon, String syStr, String smStr, String sdStr, String eyStr, String emStr, String edStr){ + String entryNameTS=DssOperation.entryNameTS(tsName, ControlData.timeStep); + if (DataTimeSeries.svTS.containsKey(entryNameTS)){ + DssDataSet dds = DataTimeSeries.svTS.get(entryNameTS); + int sy = Integer.parseInt(syStr); + int sd = Integer.parseInt(sdStr); + int ey = Integer.parseInt(eyStr); + int ed = Integer.parseInt(edStr); + int sm = TimeOperation.monthValue(smStr); + int em = TimeOperation.monthValue(emStr); + double exc = exc_id.getData().doubleValue(); + + if (exc<=0.0 || exc>1.0){ + Error.addEvaluationError("Exceedance level must be >0.0 and <=1.0"); + return new IntDouble (0, true); + } + + Date selSd; + Date selEd; + if (ControlData.timeStep.equals("1MON")){ + selSd=new Date(sy-1900, sm-1, TimeOperation.numberOfDays(sm, sy)); + selEd=new Date(ey-1900, em-1, TimeOperation.numberOfDays(em, ey)); + }else{ + selSd=new Date(sy-1900, sm-1, sd); + selEd=new Date(ey-1900, em-1, ed); + } + + ArrayList optedData=dds.getTimeseriesDataWithOptions(selMon, selSd, selEd); + int tsi=DssDataSet.getExceedance_tsi(optedData, exc); + return new IntDouble(tsi, true); + }else{ + Error.addEvaluationError(tsName+" is not a timeseries variable used in the Exceendance_TSI funciton for the time step of "+ControlData.timeStep+"."); + return new IntDouble (0, true); + } + } + + public static IntDouble daysIn(){ + int days=TimeOperation.numberOfDays(ControlData.currMonth, ControlData.currYear); + return new IntDouble(days, true); + } + + public static IntDouble daysInTimeStep(){ + if (ControlData.currTimeStep.equals("1MON")){ + return daysIn(); + }else{ + IntDouble id=new IntDouble(1, true); + return new IntDouble(1, true); + } + } + + public static IntDouble tafcfs_term(String ident, IntDouble id){ + ParallelVars prvs = new ParallelVars(); + if (id==null){ + prvs.dataMonth=ControlData.currMonth; + prvs.dataYear=ControlData.currYear; + }else{ + if (!id.isInt()){ + Error.addEvaluationError("The index of "+ident+" should be integer."); + } + prvs=TimeOperation.findTime(id.getData().intValue()); + } + double convert = tafcfs(ident, prvs); + return new IntDouble(convert, false); + } + + public static double tafcfs(String ident, ParallelVars prvs){ + double convert; + int days=TimeOperation.numberOfDays(prvs.dataMonth, prvs.dataYear); + if (ident.equals("taf_cfs")){ + if (ControlData.timeStep.equals("1MON")){ + return 504.1666667 / days; + }else{ + return 504.1666667; + } + }else if (ident.equals("cfs_taf")){ + if (ControlData.timeStep.equals("1MON")){ + return days / 504.1666667; + }else{ + return 1 / 504.1666667; + } + }else if (ident.equals("af_cfs")){ + if (ControlData.timeStep.equals("1MON")){ + return 504.1666667 / days / 1000.; + }else{ + return 504.1666667 / 1000.; + } + }else{ + if (ControlData.timeStep.equals("1MON")){ + return days / 504.1666667 * 1000.; + }else{ + return 1 / 504.1666667 * 1000.; + } + } + } + + public static IntDouble term_YEAR(){ + return new IntDouble(TimeOperation.waterYearValue(), true); + } + + public static IntDouble term_MONTH(){ + return new IntDouble(TimeOperation.waterMonthValue(ControlData.currMonth), true); + } + + public static IntDouble term_DAY(){ + return new IntDouble(ControlData.currDay, true); + } + + public static IntDouble term_MONTH_CONST(String month){ + int monthValue=TimeOperation.monthValue(month); + return new IntDouble(TimeOperation.waterMonthValue(monthValue), true, month, 0); + } + + public static IntDouble term_PASTMONTH(String pastMonth){ + pastMonth=pastMonth.substring(4); + int pastMonthValue=TimeOperation.monthValue(pastMonth); + int index=pastMonthValue-ControlData.currMonth; + if (index>=0){ + index=index-12; + } + return new IntDouble(index,true); + } + + public static IntDouble term_ARRAY_ITERATOR(ParallelVars prvs){ + return new IntDouble(prvs.timeArrayIndex, true); + } + + public static void sumExpression_IDENT(String ident, Stack sumIndex){ + //To Do: check if svar, dvar, alias contains ident + LoopIndex li=new LoopIndex(ident, 0, false, 0, 0, 0); + sumIndex.push(li); + } + + public static void initSumExpression(IntDouble id1, IntDouble id2, String s, Stack sumIndex){ + LoopIndex li=sumIndex.pop(); + li.step=1; + if (!s.equals("")){ + li.step=convertStringToInt(s); + } + if (!id1.isInt()){ + Error.addEvaluationError("the starting index should be integer"); + } + if (!id2.isInt()){ + Error.addEvaluationError("the ending index should be integer"); + } + li.start=id1.getData().intValue(); + li.end=id2.getData().intValue(); + li.setValue(li.start); + li.setIndexStart(true); + sumIndex.push(li); + if (li.start>li.end && li.step>0){ + ControlData.ignoreError=true; + }else if (li.start sumIndex){ + ControlData.ignoreError=false; + LoopIndex li=sumIndex.pop(); + if (li.step>=0){ + if (li.start>li.end) return new IntDouble(0.0, false); + li.start=li.start+li.step; + if (li.start>li.end) return id; + sumIndex.push(li); + for (int i=li.start; i<=li.end; i=i+li.step){ + li=sumIndex.pop(); + li.setValue(i); + li.setIndexStart(true); + sumIndex.push(li); + ANTLRStringStream stream = new ANTLRStringStream("v: "+expression); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + ValueEvaluatorParser evaluator = new ValueEvaluatorParser(tokenStream); + evaluator.setSumIndex(sumIndex); + try{ + evaluator.evaluator(); + }catch (RecognitionException e){ + Error.addEvaluationError(e.toString()); + } + + IntDouble id0=evaluator.evalValue; + id=add(id, id0); + } + }else{ + if (li.start=li.end; i=i+li.step){ + li=sumIndex.pop(); + li.setValue(i); + li.setIndexStart(true); + sumIndex.push(li); + ANTLRStringStream stream = new ANTLRStringStream("v: "+expression); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + ValueEvaluatorParser evaluator = new ValueEvaluatorParser(tokenStream); + evaluator.setSumIndex(sumIndex); + try{ + evaluator.evaluator(); + }catch (RecognitionException e){ + Error.addEvaluationError(e.toString()); + } + + IntDouble id0=evaluator.evalValue; + id=add(id, id0); + } + } + sumIndex.pop(); + return id; + } + + public static Number assignWhereStatement(IntDouble id){ + return id.getData(); + } + + public static IntDouble tableSQL(String table, String select, HashMap where, HashMap given, String use){ + IntDouble id; + if (where==null){ + return TableOperation.findData(table, select, given, use); + }else{ + return TableOperation.findData(table, select, where, given, use); + } + } + + public static IntDouble expressionInput(IntDouble id){ + return id; + } + + public static void setSvarIntValue(IntDouble id, int value){ + String name=id.getName(); + int index=id.getIndex(); + + if (ControlData.currSvMap.containsKey(name)){ + if (index==0) { + ControlData.currSvMap.get(name).getData().setData(value); + }else if(index>0){ + String futSvName=name+"__fut__"+index; + if (ControlData.currSvFutMap.containsKey(futSvName)){ + ControlData.currSvFutMap.get(futSvName).getData().setData(value); + } + } + } + } + + public static void setSvarDoubleValue(IntDouble id, double value){ + String name=id.getName(); + int index=id.getIndex(); + + if (ControlData.currSvMap.containsKey(name)){ + if (index==0) { + ControlData.currSvMap.get(name).getData().setData(value); + }else if(index>0){ + String futSvName=name+"__fut__"+index; + if (ControlData.currSvFutMap.containsKey(futSvName)){ + ControlData.currSvFutMap.get(futSvName).getData().setData(value); + } + } + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/WeightEval.java b/wrims-core/src/main/java/wrimsv2/evaluator/WeightEval.java similarity index 98% rename from wrims_v2/wrims_v2/src/wrimsv2/evaluator/WeightEval.java rename to wrims-core/src/main/java/wrimsv2/evaluator/WeightEval.java index 2339d6e4e..149d40572 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/evaluator/WeightEval.java +++ b/wrims-core/src/main/java/wrimsv2/evaluator/WeightEval.java @@ -2,7 +2,6 @@ import java.io.File; import java.io.FileWriter; -import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; @@ -17,19 +16,14 @@ import org.antlr.runtime.RecognitionException; import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Param; import wrimsv2.commondata.wresldata.StudyDataSet; import wrimsv2.commondata.wresldata.WeightElement; import wrimsv2.components.ControlData; import wrimsv2.components.Error; import wrimsv2.components.FilePaths; import wrimsv2.components.IntDouble; -import wrimsv2.components.PreRunModel; import wrimsv2.ilp.ILP; import wrimsv2.parallel.ParallelVars; -import wrimsv2.solver.CbcSolver; -import wrimsv2.solver.InitialXASolver; -import wrimsv2.solver.XASolver; public class WeightEval { private static double minw=1.0; diff --git a/wrims_v2/wrims_v2/src/wrimsv2/exception/WrimsException.java b/wrims-core/src/main/java/wrimsv2/exception/WrimsException.java similarity index 92% rename from wrims_v2/wrims_v2/src/wrimsv2/exception/WrimsException.java rename to wrims-core/src/main/java/wrimsv2/exception/WrimsException.java index 7c990aed0..b3dcd8c11 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/exception/WrimsException.java +++ b/wrims-core/src/main/java/wrimsv2/exception/WrimsException.java @@ -1,19 +1,19 @@ -package wrimsv2.exception; - - -public class WrimsException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public WrimsException() { - } - - public WrimsException(String message) { - super(message); - } - -} - +package wrimsv2.exception; + + +public class WrimsException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public WrimsException() { + } + + public WrimsException(String message) { + super(message); + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/ExternalFunction.java b/wrims-core/src/main/java/wrimsv2/external/ExternalFunction.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/external/ExternalFunction.java rename to wrims-core/src/main/java/wrimsv2/external/ExternalFunction.java index c2352f00b..afacbac1f 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/ExternalFunction.java +++ b/wrims-core/src/main/java/wrimsv2/external/ExternalFunction.java @@ -1,8 +1,8 @@ -package wrimsv2.external; - -import java.util.*; - -public abstract class ExternalFunction{ - - public abstract void execute(Stack stack); -} +package wrimsv2.external; + +import java.util.*; + +public abstract class ExternalFunction{ + + public abstract void execute(Stack stack); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiona56_allocation.java b/wrims-core/src/main/java/wrimsv2/external/Functiona56_allocation.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiona56_allocation.java rename to wrims-core/src/main/java/wrimsv2/external/Functiona56_allocation.java index c9ad7653d..12f9e33e5 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiona56_allocation.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functiona56_allocation.java @@ -1,419 +1,419 @@ -// ! Last change: R 10 May 2007 -// ! Dan Easton 5/10/2007 -// ! This function allocates Article 56 carryover and spills based on Table A entitlement and carryover request. - -package wrimsv2.external; - -import java.util.*; - - -public class Functiona56_allocation extends ExternalFunction { - private final boolean DEBUG = false; - private float[] _allocation; - public final int ARRAY_SIZE = 31; - - public Functiona56_allocation() { - - } - - public void execute(Stack stack) { - int stackSize = stack.size(); - - if (stackSize == 2) { - //values in reverse order: - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast parameters to correct types: - int contractor = ((Number) param2).intValue(); - int calc = ((Number) param1).intValue(); - - float result = a56_allocation(calc, contractor); - - if (DEBUG) { - System.out.println("*************A56_Allocation call**************"); - System.out.println("result = " + result); - } - - // push the result on the Stack - stack.push(new Float(result)); - - } else if (stackSize == 63) { - //values in reverse order: - Object param63 = stack.pop(); - Object param62 = stack.pop(); - Object param61 = stack.pop(); - Object param60 = stack.pop(); - Object param59 = stack.pop(); - Object param58 = stack.pop(); - Object param57 = stack.pop(); - Object param56 = stack.pop(); - Object param55 = stack.pop(); - Object param54 = stack.pop(); - Object param53 = stack.pop(); - Object param52 = stack.pop(); - Object param51 = stack.pop(); - Object param50 = stack.pop(); - Object param49 = stack.pop(); - Object param48 = stack.pop(); - Object param47 = stack.pop(); - Object param46 = stack.pop(); - Object param45 = stack.pop(); - Object param44 = stack.pop(); - Object param43 = stack.pop(); - Object param42 = stack.pop(); - Object param41 = stack.pop(); - Object param40 = stack.pop(); - Object param39 = stack.pop(); - Object param38 = stack.pop(); - Object param37 = stack.pop(); - Object param36 = stack.pop(); - Object param35 = stack.pop(); - Object param34 = stack.pop(); - Object param33 = stack.pop(); - Object param32 = stack.pop(); - Object param31 = stack.pop(); - Object param30 = stack.pop(); - Object param29 = stack.pop(); - Object param28 = stack.pop(); - Object param27 = stack.pop(); - Object param26 = stack.pop(); - Object param25 = stack.pop(); - Object param24 = stack.pop(); - Object param23 = stack.pop(); - Object param22 = stack.pop(); - Object param21 = stack.pop(); - Object param20 = stack.pop(); - Object param19 = stack.pop(); - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast parameters to correct types: - float req_30 = ((Number) param63).floatValue(); - float ta_30 = ((Number) param62).floatValue(); - float req_29 = ((Number) param61).floatValue(); - float ta_29 = ((Number) param60).floatValue(); - float req_28 = ((Number) param59).floatValue(); - float ta_28 = ((Number) param58).floatValue(); - float req_27 = ((Number) param57).floatValue(); - float ta_27 = ((Number) param56).floatValue(); - float req_26 = ((Number) param55).floatValue(); - float ta_26 = ((Number) param54).floatValue(); - float req_25 = ((Number) param53).floatValue(); - float ta_25 = ((Number) param52).floatValue(); - float req_24 = ((Number) param51).floatValue(); - float ta_24 = ((Number) param50).floatValue(); - float req_23 = ((Number) param49).floatValue(); - float ta_23 = ((Number) param48).floatValue(); - float req_22 = ((Number) param47).floatValue(); - float ta_22 = ((Number) param46).floatValue(); - float req_21 = ((Number) param45).floatValue(); - float ta_21 = ((Number) param44).floatValue(); - float req_20 = ((Number) param43).floatValue(); - float ta_20 = ((Number) param42).floatValue(); - float req_19 = ((Number) param41).floatValue(); - float ta_19 = ((Number) param40).floatValue(); - float req_18 = ((Number) param39).floatValue(); - float ta_18 = ((Number) param38).floatValue(); - float req_17 = ((Number) param37).floatValue(); - float ta_17 = ((Number) param36).floatValue(); - float req_16 = ((Number) param35).floatValue(); - float ta_16 = ((Number) param34).floatValue(); - float req_15 = ((Number) param33).floatValue(); - float ta_15 = ((Number) param32).floatValue(); - float req_14 = ((Number) param31).floatValue(); - float ta_14 = ((Number) param30).floatValue(); - float req_13 = ((Number) param29).floatValue(); - float ta_13 = ((Number) param28).floatValue(); - float req_12 = ((Number) param27).floatValue(); - float ta_12 = ((Number) param26).floatValue(); - float req_11 = ((Number) param25).floatValue(); - float ta_11 = ((Number) param24).floatValue(); - float req_10 = ((Number) param23).floatValue(); - float ta_10 = ((Number) param22).floatValue(); - float req_9 = ((Number) param21).floatValue(); - float ta_9 = ((Number) param20).floatValue(); - float req_8 = ((Number) param19).floatValue(); - float ta_8 = ((Number) param18).floatValue(); - float req_7 = ((Number) param17).floatValue(); - float ta_7 = ((Number) param16).floatValue(); - float req_6 = ((Number) param15).floatValue(); - float ta_6 = ((Number) param14).floatValue(); - float req_5 = ((Number) param13).floatValue(); - float ta_5 = ((Number) param12).floatValue(); - float req_4 = ((Number) param11).floatValue(); - float ta_4 = ((Number) param10).floatValue(); - float req_3 = ((Number) param9).floatValue(); - float ta_3 = ((Number) param8).floatValue(); - float req_2 = ((Number) param7).floatValue(); - float ta_2 = ((Number) param6).floatValue(); - float req_1 = ((Number) param5).floatValue(); - float ta_1 = ((Number) param4).floatValue(); - float spill = ((Number) param3).floatValue(); - int contractor = ((Number) param2).intValue(); - int calc = ((Number) param1).intValue(); - - if (DEBUG) { - System.out.println("*************A56_Allocation call**************"); - System.out.println("calc = " + calc); - System.out.println("contractor = " + contractor); - System.out.println("spill = " + spill); - System.out.println("ta_1 = " + ta_1); - System.out.println("req_1 = " + req_1); - System.out.println("ta_2 = " + ta_2); - System.out.println("req_2 = " + req_2); - System.out.println("ta_3 = " + ta_3); - System.out.println("req_3 = " + req_3); - System.out.println("ta_4 = " + ta_4); - System.out.println("req_4 = " + req_4); - System.out.println("ta_5 = " + ta_5); - System.out.println("req_5 = " + req_5); - System.out.println("ta_6 = " + ta_6); - System.out.println("req_6 = " + req_6); - System.out.println("ta_7 = " + ta_7); - System.out.println("req_7 = " + req_7); - System.out.println("ta_8 = " + ta_8); - System.out.println("req_8 = " + req_8); - System.out.println("ta_9 = " + ta_9); - System.out.println("req_9 = " + req_9); - System.out.println("ta_10 = " + ta_10); - System.out.println("req_10 = " + req_10); - System.out.println("ta_11 = " + ta_11); - System.out.println("req_11 = " + req_11); - System.out.println("ta_12 = " + ta_12); - System.out.println("req_12 = " + req_12); - System.out.println("ta_13 = " + ta_13); - System.out.println("req_13 = " + req_13); - System.out.println("ta_14 = " + ta_14); - System.out.println("req_14 = " + req_14); - System.out.println("ta_15 = " + ta_15); - System.out.println("req_15 = " + req_15); - System.out.println("ta_16 = " + ta_16); - System.out.println("req_16 = " + req_16); - System.out.println("ta_17 = " + ta_17); - System.out.println("req_17 = " + req_17); - System.out.println("ta_18 = " + ta_18); - System.out.println("req_18 = " + req_18); - System.out.println("ta_19 = " + ta_19); - System.out.println("req_19 = " + req_19); - System.out.println("ta_20 = " + ta_20); - System.out.println("req_20 = " + req_20); - System.out.println("ta_21 = " + ta_21); - System.out.println("req_21 = " + req_21); - System.out.println("ta_22 = " + ta_22); - System.out.println("req_22 = " + req_22); - System.out.println("ta_23 = " + ta_23); - System.out.println("req_23 = " + req_23); - System.out.println("ta_24 = " + ta_24); - System.out.println("req_24 = " + req_24); - System.out.println("ta_25 = " + ta_25); - System.out.println("req_25 = " + req_25); - System.out.println("ta_26 = " + ta_26); - System.out.println("req_26 = " + req_26); - System.out.println("ta_27 = " + ta_27); - System.out.println("req_27 = " + req_27); - System.out.println("ta_28 = " + ta_28); - System.out.println("req_28 = " + req_28); - System.out.println("ta_29 = " + ta_29); - System.out.println("req_29 = " + req_29); - System.out.println("ta_30 = " + ta_30); - System.out.println("req_30 = " + req_30); - } - - float result = a56_allocation(calc, contractor, spill, ta_1, req_1, ta_2, req_2, ta_3, - req_3, ta_4, req_4, ta_5, req_5, ta_6, req_6, ta_7, req_7, ta_8, req_8, ta_9, req_9, - ta_10, req_10, ta_11, req_11, ta_12, req_12, ta_13, req_13, ta_14, req_14, ta_15, - req_15, ta_16, req_16, ta_17, req_17, ta_18, req_18, ta_19, req_19, ta_20, req_20, - ta_21, req_21, ta_22, req_22, ta_23, req_23, ta_24, req_24, ta_25, req_25, ta_26, - req_26, ta_27, req_27, ta_28, req_28, ta_29, req_29, ta_30, req_30); - - if (DEBUG) { - System.out.println("*************A56_Allocation call**************"); - System.out.println("result = " + result); - } - - // push the result on the Stack - stack.push(new Float(result)); - } - } - - private float a56_allocation(int calc, int contractor) { - return _allocation[contractor]; - } - - /** - * Table A entitlements, spill, and Article 56 requests are necessary only when allocations - * are calculated (calc = 1). Otherwise, those parameters are optional and you can pull the - * previously calculated allocation for a contractor by simply making the following function - * call a56_allocation(0, contractor). - */ - private float a56_allocation(int calc, int contractor, float spill, float ta_1, float req_1, - float ta_2, float req_2, float ta_3, float req_3, float ta_4, float req_4, float ta_5, - float req_5, float ta_6,float req_6, float ta_7, float req_7, float ta_8, float req_8, - float ta_9, float req_9, float ta_10, float req_10, float ta_11, float req_11, - float ta_12, float req_12, float ta_13, float req_13, float ta_14, float req_14, - float ta_15, float req_15, float ta_16, float req_16, float ta_17, float req_17, - float ta_18, float req_18, float ta_19, float req_19, float ta_20, float req_20, - float ta_21, float req_21, float ta_22, float req_22, float ta_23, float req_23, - float ta_24, float req_24, float ta_25, float req_25, float ta_26, float req_26, - float ta_27, float req_27, float ta_28, float req_28, float ta_29, float req_29, - float ta_30, float req_30) { - - - //REAL,DIMENSION(30) :: allocation, shortage, surplus, ta, req, req_alloc - // moved allocation to instance variables - _allocation = new float[ARRAY_SIZE]; - float[] shortage = new float[ARRAY_SIZE]; - float[] surplus = new float[ARRAY_SIZE]; - float[] ta = new float[ARRAY_SIZE]; - float[] req = new float[ARRAY_SIZE]; - float[] req_alloc = new float[ARRAY_SIZE]; - float tot_ta, tot_req, tot_avail, tot_short = 999, tot_surp = 999, adj; - int i, j, stop; - - //The result of the function is the final allocation fraction for the given contractor. - float alloc; - - //If calc == 1, then user wants allocations calculated. - //If calc != 1 (presently setting calc = 0 in wresl calls), bypass if block and pull - // contractor allocation from previous calculation. - if (calc==1) { - //Initialize TableA and Carryover Request Arrays - ta[1] = ta_1; - ta[2] = ta_2; - ta[3] = ta_3; - ta[4] = ta_4; - ta[5] = ta_5; - ta[6] = ta_6; - ta[7] = ta_7; - ta[8] = ta_8; - ta[9] = ta_9; - ta[10] = ta_10; - ta[11] = ta_11; - ta[12] = ta_12; - ta[13] = ta_13; - ta[14] = ta_14; - ta[15] = ta_15; - ta[16] = ta_16; - ta[17] = ta_17; - ta[18] = ta_18; - ta[19] = ta_19; - ta[20] = ta_20; - ta[21] = ta_21; - ta[22] = ta_22; - ta[23] = ta_23; - ta[24] = ta_24; - ta[25] = ta_25; - ta[26] = ta_26; - ta[27] = ta_27; - ta[28] = ta_28; - ta[29] = ta_29; - ta[30] = ta_30; - req[1] = req_1; - req[2] = req_2; - req[3] = req_3; - req[4] = req_4; - req[5] = req_5; - req[6] = req_6; - req[7] = req_7; - req[8] = req_8; - req[9] = req_9; - req[10] = req_10; - req[11] = req_11; - req[12] = req_12; - req[13] = req_13; - req[14] = req_14; - req[15] = req_15; - req[16] = req_16; - req[17] = req_17; - req[18] = req_18; - req[19] = req_19; - req[20] = req_20; - req[21] = req_21; - req[22] = req_22; - req[23] = req_23; - req[24] = req_24; - req[25] = req_25; - req[26] = req_26; - req[27] = req_27; - req[28] = req_28; - req[29] = req_29; - req[30] = req_30; - - //Sum TableA and Carryover Request - tot_ta = 0; - tot_req = 0; - for (i = 1; i <= 30; i++) { - tot_ta += ta[i]; - tot_req += req[i]; - } - - //Calculate available carryover - tot_avail = Math.max(0, tot_req - spill); - - //Initialize allocation and req_alloc - if (tot_avail < 0.005 || tot_ta < 0.005) { - for (i = 1; i <= 30; ++i) - _allocation[i] = 0; - } else { - for (i = 1; i <= 30; ++i) { - req_alloc[i] = req[i]/tot_avail; - _allocation[i] = ta[i]/tot_ta; //CB fraction of Table A - } - - //Allocate carryover and spills. - stop = 0; - j = 0; - - while (tot_surp >= 0.0001 && tot_short >= 0.0001 && j <= 29) { //Check to see if allocation is complete - ++j; //loop index, j should not exceed 29 since only 30 contractors - tot_short = 0; //initialize sum of contractor Article 56 shortages - tot_surp = 0; //initialize sum of contractor Article 56 surplus allocation - tot_ta = 0; //initialize sum of Table A entitlements of shorted contractors - - //With initial allocation calculate shortages and surplus and new Table A denominator for short contractors - for (i = 1; i <= 30; ++i) { - surplus[i] = (float)Math.max(0., _allocation[i] - req_alloc[i]); - shortage[i] = (float)Math.max(0., req_alloc[i] - _allocation[i]); - - tot_surp += surplus[i]; - tot_short += shortage[i]; - - if (shortage[i] > 0.00001) - tot_ta += ta[i]; - } //end for - - //Adjust allocations by allocating available surplus to shorted contractors based on their Table A entitlements - for (i = 1; i <= 30; ++i) { - if (shortage[i] > 0.00001) { - adj = 0; - if (tot_ta > 0.0005) { - adj = tot_surp*ta[i]/tot_ta; - _allocation[i] += adj; - } - }else{ - _allocation[i] = req_alloc[i]; - } - } //end for - } //end while - } - } // end if - return _allocation[contractor]; - } -} +// ! Last change: R 10 May 2007 +// ! Dan Easton 5/10/2007 +// ! This function allocates Article 56 carryover and spills based on Table A entitlement and carryover request. + +package wrimsv2.external; + +import java.util.*; + + +public class Functiona56_allocation extends ExternalFunction { + private final boolean DEBUG = false; + private float[] _allocation; + public final int ARRAY_SIZE = 31; + + public Functiona56_allocation() { + + } + + public void execute(Stack stack) { + int stackSize = stack.size(); + + if (stackSize == 2) { + //values in reverse order: + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast parameters to correct types: + int contractor = ((Number) param2).intValue(); + int calc = ((Number) param1).intValue(); + + float result = a56_allocation(calc, contractor); + + if (DEBUG) { + System.out.println("*************A56_Allocation call**************"); + System.out.println("result = " + result); + } + + // push the result on the Stack + stack.push(new Float(result)); + + } else if (stackSize == 63) { + //values in reverse order: + Object param63 = stack.pop(); + Object param62 = stack.pop(); + Object param61 = stack.pop(); + Object param60 = stack.pop(); + Object param59 = stack.pop(); + Object param58 = stack.pop(); + Object param57 = stack.pop(); + Object param56 = stack.pop(); + Object param55 = stack.pop(); + Object param54 = stack.pop(); + Object param53 = stack.pop(); + Object param52 = stack.pop(); + Object param51 = stack.pop(); + Object param50 = stack.pop(); + Object param49 = stack.pop(); + Object param48 = stack.pop(); + Object param47 = stack.pop(); + Object param46 = stack.pop(); + Object param45 = stack.pop(); + Object param44 = stack.pop(); + Object param43 = stack.pop(); + Object param42 = stack.pop(); + Object param41 = stack.pop(); + Object param40 = stack.pop(); + Object param39 = stack.pop(); + Object param38 = stack.pop(); + Object param37 = stack.pop(); + Object param36 = stack.pop(); + Object param35 = stack.pop(); + Object param34 = stack.pop(); + Object param33 = stack.pop(); + Object param32 = stack.pop(); + Object param31 = stack.pop(); + Object param30 = stack.pop(); + Object param29 = stack.pop(); + Object param28 = stack.pop(); + Object param27 = stack.pop(); + Object param26 = stack.pop(); + Object param25 = stack.pop(); + Object param24 = stack.pop(); + Object param23 = stack.pop(); + Object param22 = stack.pop(); + Object param21 = stack.pop(); + Object param20 = stack.pop(); + Object param19 = stack.pop(); + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast parameters to correct types: + float req_30 = ((Number) param63).floatValue(); + float ta_30 = ((Number) param62).floatValue(); + float req_29 = ((Number) param61).floatValue(); + float ta_29 = ((Number) param60).floatValue(); + float req_28 = ((Number) param59).floatValue(); + float ta_28 = ((Number) param58).floatValue(); + float req_27 = ((Number) param57).floatValue(); + float ta_27 = ((Number) param56).floatValue(); + float req_26 = ((Number) param55).floatValue(); + float ta_26 = ((Number) param54).floatValue(); + float req_25 = ((Number) param53).floatValue(); + float ta_25 = ((Number) param52).floatValue(); + float req_24 = ((Number) param51).floatValue(); + float ta_24 = ((Number) param50).floatValue(); + float req_23 = ((Number) param49).floatValue(); + float ta_23 = ((Number) param48).floatValue(); + float req_22 = ((Number) param47).floatValue(); + float ta_22 = ((Number) param46).floatValue(); + float req_21 = ((Number) param45).floatValue(); + float ta_21 = ((Number) param44).floatValue(); + float req_20 = ((Number) param43).floatValue(); + float ta_20 = ((Number) param42).floatValue(); + float req_19 = ((Number) param41).floatValue(); + float ta_19 = ((Number) param40).floatValue(); + float req_18 = ((Number) param39).floatValue(); + float ta_18 = ((Number) param38).floatValue(); + float req_17 = ((Number) param37).floatValue(); + float ta_17 = ((Number) param36).floatValue(); + float req_16 = ((Number) param35).floatValue(); + float ta_16 = ((Number) param34).floatValue(); + float req_15 = ((Number) param33).floatValue(); + float ta_15 = ((Number) param32).floatValue(); + float req_14 = ((Number) param31).floatValue(); + float ta_14 = ((Number) param30).floatValue(); + float req_13 = ((Number) param29).floatValue(); + float ta_13 = ((Number) param28).floatValue(); + float req_12 = ((Number) param27).floatValue(); + float ta_12 = ((Number) param26).floatValue(); + float req_11 = ((Number) param25).floatValue(); + float ta_11 = ((Number) param24).floatValue(); + float req_10 = ((Number) param23).floatValue(); + float ta_10 = ((Number) param22).floatValue(); + float req_9 = ((Number) param21).floatValue(); + float ta_9 = ((Number) param20).floatValue(); + float req_8 = ((Number) param19).floatValue(); + float ta_8 = ((Number) param18).floatValue(); + float req_7 = ((Number) param17).floatValue(); + float ta_7 = ((Number) param16).floatValue(); + float req_6 = ((Number) param15).floatValue(); + float ta_6 = ((Number) param14).floatValue(); + float req_5 = ((Number) param13).floatValue(); + float ta_5 = ((Number) param12).floatValue(); + float req_4 = ((Number) param11).floatValue(); + float ta_4 = ((Number) param10).floatValue(); + float req_3 = ((Number) param9).floatValue(); + float ta_3 = ((Number) param8).floatValue(); + float req_2 = ((Number) param7).floatValue(); + float ta_2 = ((Number) param6).floatValue(); + float req_1 = ((Number) param5).floatValue(); + float ta_1 = ((Number) param4).floatValue(); + float spill = ((Number) param3).floatValue(); + int contractor = ((Number) param2).intValue(); + int calc = ((Number) param1).intValue(); + + if (DEBUG) { + System.out.println("*************A56_Allocation call**************"); + System.out.println("calc = " + calc); + System.out.println("contractor = " + contractor); + System.out.println("spill = " + spill); + System.out.println("ta_1 = " + ta_1); + System.out.println("req_1 = " + req_1); + System.out.println("ta_2 = " + ta_2); + System.out.println("req_2 = " + req_2); + System.out.println("ta_3 = " + ta_3); + System.out.println("req_3 = " + req_3); + System.out.println("ta_4 = " + ta_4); + System.out.println("req_4 = " + req_4); + System.out.println("ta_5 = " + ta_5); + System.out.println("req_5 = " + req_5); + System.out.println("ta_6 = " + ta_6); + System.out.println("req_6 = " + req_6); + System.out.println("ta_7 = " + ta_7); + System.out.println("req_7 = " + req_7); + System.out.println("ta_8 = " + ta_8); + System.out.println("req_8 = " + req_8); + System.out.println("ta_9 = " + ta_9); + System.out.println("req_9 = " + req_9); + System.out.println("ta_10 = " + ta_10); + System.out.println("req_10 = " + req_10); + System.out.println("ta_11 = " + ta_11); + System.out.println("req_11 = " + req_11); + System.out.println("ta_12 = " + ta_12); + System.out.println("req_12 = " + req_12); + System.out.println("ta_13 = " + ta_13); + System.out.println("req_13 = " + req_13); + System.out.println("ta_14 = " + ta_14); + System.out.println("req_14 = " + req_14); + System.out.println("ta_15 = " + ta_15); + System.out.println("req_15 = " + req_15); + System.out.println("ta_16 = " + ta_16); + System.out.println("req_16 = " + req_16); + System.out.println("ta_17 = " + ta_17); + System.out.println("req_17 = " + req_17); + System.out.println("ta_18 = " + ta_18); + System.out.println("req_18 = " + req_18); + System.out.println("ta_19 = " + ta_19); + System.out.println("req_19 = " + req_19); + System.out.println("ta_20 = " + ta_20); + System.out.println("req_20 = " + req_20); + System.out.println("ta_21 = " + ta_21); + System.out.println("req_21 = " + req_21); + System.out.println("ta_22 = " + ta_22); + System.out.println("req_22 = " + req_22); + System.out.println("ta_23 = " + ta_23); + System.out.println("req_23 = " + req_23); + System.out.println("ta_24 = " + ta_24); + System.out.println("req_24 = " + req_24); + System.out.println("ta_25 = " + ta_25); + System.out.println("req_25 = " + req_25); + System.out.println("ta_26 = " + ta_26); + System.out.println("req_26 = " + req_26); + System.out.println("ta_27 = " + ta_27); + System.out.println("req_27 = " + req_27); + System.out.println("ta_28 = " + ta_28); + System.out.println("req_28 = " + req_28); + System.out.println("ta_29 = " + ta_29); + System.out.println("req_29 = " + req_29); + System.out.println("ta_30 = " + ta_30); + System.out.println("req_30 = " + req_30); + } + + float result = a56_allocation(calc, contractor, spill, ta_1, req_1, ta_2, req_2, ta_3, + req_3, ta_4, req_4, ta_5, req_5, ta_6, req_6, ta_7, req_7, ta_8, req_8, ta_9, req_9, + ta_10, req_10, ta_11, req_11, ta_12, req_12, ta_13, req_13, ta_14, req_14, ta_15, + req_15, ta_16, req_16, ta_17, req_17, ta_18, req_18, ta_19, req_19, ta_20, req_20, + ta_21, req_21, ta_22, req_22, ta_23, req_23, ta_24, req_24, ta_25, req_25, ta_26, + req_26, ta_27, req_27, ta_28, req_28, ta_29, req_29, ta_30, req_30); + + if (DEBUG) { + System.out.println("*************A56_Allocation call**************"); + System.out.println("result = " + result); + } + + // push the result on the Stack + stack.push(new Float(result)); + } + } + + private float a56_allocation(int calc, int contractor) { + return _allocation[contractor]; + } + + /** + * Table A entitlements, spill, and Article 56 requests are necessary only when allocations + * are calculated (calc = 1). Otherwise, those parameters are optional and you can pull the + * previously calculated allocation for a contractor by simply making the following function + * call a56_allocation(0, contractor). + */ + private float a56_allocation(int calc, int contractor, float spill, float ta_1, float req_1, + float ta_2, float req_2, float ta_3, float req_3, float ta_4, float req_4, float ta_5, + float req_5, float ta_6,float req_6, float ta_7, float req_7, float ta_8, float req_8, + float ta_9, float req_9, float ta_10, float req_10, float ta_11, float req_11, + float ta_12, float req_12, float ta_13, float req_13, float ta_14, float req_14, + float ta_15, float req_15, float ta_16, float req_16, float ta_17, float req_17, + float ta_18, float req_18, float ta_19, float req_19, float ta_20, float req_20, + float ta_21, float req_21, float ta_22, float req_22, float ta_23, float req_23, + float ta_24, float req_24, float ta_25, float req_25, float ta_26, float req_26, + float ta_27, float req_27, float ta_28, float req_28, float ta_29, float req_29, + float ta_30, float req_30) { + + + //REAL,DIMENSION(30) :: allocation, shortage, surplus, ta, req, req_alloc + // moved allocation to instance variables + _allocation = new float[ARRAY_SIZE]; + float[] shortage = new float[ARRAY_SIZE]; + float[] surplus = new float[ARRAY_SIZE]; + float[] ta = new float[ARRAY_SIZE]; + float[] req = new float[ARRAY_SIZE]; + float[] req_alloc = new float[ARRAY_SIZE]; + float tot_ta, tot_req, tot_avail, tot_short = 999, tot_surp = 999, adj; + int i, j, stop; + + //The result of the function is the final allocation fraction for the given contractor. + float alloc; + + //If calc == 1, then user wants allocations calculated. + //If calc != 1 (presently setting calc = 0 in wresl calls), bypass if block and pull + // contractor allocation from previous calculation. + if (calc==1) { + //Initialize TableA and Carryover Request Arrays + ta[1] = ta_1; + ta[2] = ta_2; + ta[3] = ta_3; + ta[4] = ta_4; + ta[5] = ta_5; + ta[6] = ta_6; + ta[7] = ta_7; + ta[8] = ta_8; + ta[9] = ta_9; + ta[10] = ta_10; + ta[11] = ta_11; + ta[12] = ta_12; + ta[13] = ta_13; + ta[14] = ta_14; + ta[15] = ta_15; + ta[16] = ta_16; + ta[17] = ta_17; + ta[18] = ta_18; + ta[19] = ta_19; + ta[20] = ta_20; + ta[21] = ta_21; + ta[22] = ta_22; + ta[23] = ta_23; + ta[24] = ta_24; + ta[25] = ta_25; + ta[26] = ta_26; + ta[27] = ta_27; + ta[28] = ta_28; + ta[29] = ta_29; + ta[30] = ta_30; + req[1] = req_1; + req[2] = req_2; + req[3] = req_3; + req[4] = req_4; + req[5] = req_5; + req[6] = req_6; + req[7] = req_7; + req[8] = req_8; + req[9] = req_9; + req[10] = req_10; + req[11] = req_11; + req[12] = req_12; + req[13] = req_13; + req[14] = req_14; + req[15] = req_15; + req[16] = req_16; + req[17] = req_17; + req[18] = req_18; + req[19] = req_19; + req[20] = req_20; + req[21] = req_21; + req[22] = req_22; + req[23] = req_23; + req[24] = req_24; + req[25] = req_25; + req[26] = req_26; + req[27] = req_27; + req[28] = req_28; + req[29] = req_29; + req[30] = req_30; + + //Sum TableA and Carryover Request + tot_ta = 0; + tot_req = 0; + for (i = 1; i <= 30; i++) { + tot_ta += ta[i]; + tot_req += req[i]; + } + + //Calculate available carryover + tot_avail = Math.max(0, tot_req - spill); + + //Initialize allocation and req_alloc + if (tot_avail < 0.005 || tot_ta < 0.005) { + for (i = 1; i <= 30; ++i) + _allocation[i] = 0; + } else { + for (i = 1; i <= 30; ++i) { + req_alloc[i] = req[i]/tot_avail; + _allocation[i] = ta[i]/tot_ta; //CB fraction of Table A + } + + //Allocate carryover and spills. + stop = 0; + j = 0; + + while (tot_surp >= 0.0001 && tot_short >= 0.0001 && j <= 29) { //Check to see if allocation is complete + ++j; //loop index, j should not exceed 29 since only 30 contractors + tot_short = 0; //initialize sum of contractor Article 56 shortages + tot_surp = 0; //initialize sum of contractor Article 56 surplus allocation + tot_ta = 0; //initialize sum of Table A entitlements of shorted contractors + + //With initial allocation calculate shortages and surplus and new Table A denominator for short contractors + for (i = 1; i <= 30; ++i) { + surplus[i] = (float)Math.max(0., _allocation[i] - req_alloc[i]); + shortage[i] = (float)Math.max(0., req_alloc[i] - _allocation[i]); + + tot_surp += surplus[i]; + tot_short += shortage[i]; + + if (shortage[i] > 0.00001) + tot_ta += ta[i]; + } //end for + + //Adjust allocations by allocating available surplus to shorted contractors based on their Table A entitlements + for (i = 1; i <= 30; ++i) { + if (shortage[i] > 0.00001) { + adj = 0; + if (tot_ta > 0.0005) { + adj = tot_surp*ta[i]/tot_ta; + _allocation[i] += adj; + } + }else{ + _allocation[i] = req_alloc[i]; + } + } //end for + } //end while + } + } // end if + return _allocation[contractor]; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionadvancegwstate.java b/wrims-core/src/main/java/wrimsv2/external/Functionadvancegwstate.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionadvancegwstate.java rename to wrims-core/src/main/java/wrimsv2/external/Functionadvancegwstate.java index a0eb67934..04464c2f7 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionadvancegwstate.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functionadvancegwstate.java @@ -1,28 +1,28 @@ -package wrimsv2.external; - -import java.util.*; - -public class Functionadvancegwstate extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functionadvancegwstate(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param1 = stack.pop(); - - //cast params to correct types: - int iDummy = ((Number) param1).intValue(); - - float result = advancegwstate(iDummy); - - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float advancegwstate(int iDummy); -} +package wrimsv2.external; + +import java.util.*; + +public class Functionadvancegwstate extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functionadvancegwstate(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param1 = stack.pop(); + + //cast params to correct types: + int iDummy = ((Number) param1).intValue(); + + float result = advancegwstate(iDummy); + + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float advancegwstate(int iDummy); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionann_x2.java b/wrims-core/src/main/java/wrimsv2/external/Functionann_x2.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionann_x2.java rename to wrims-core/src/main/java/wrimsv2/external/Functionann_x2.java index fccbba34f..eaddc91df 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionann_x2.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functionann_x2.java @@ -1,126 +1,126 @@ -package wrimsv2.external; - -import java.util.*; - -import wrimsv2.components.ControlData; - -public class Functionann_x2 extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functionann_x2(){ - - } - - public void execute(Stack stack) { - - long t1 = Calendar.getInstance().getTimeInMillis(); - - if (stack.size()==20){ - //values in reverse order: - Object param20 = stack.pop(); - Object param19 = stack.pop(); - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int EndDay = ((Number) param20).intValue(); - int BeginDay = ((Number) param19).intValue(); - int currYear = ((Number) param18).intValue(); - int currMonth = ((Number) param17).intValue(); - int ave_type = ((Number) param16).intValue(); - int mon4 = ((Number) param15).intValue(); - int mon3 = ((Number) param14).intValue(); - int mon2 = ((Number) param13).intValue(); - int mon1 = ((Number) param12).intValue(); - int mon0 = ((Number) param11).intValue(); - float DO_prv4 = ((Number) param10).floatValue(); - float DO_prv3 = ((Number) param9).floatValue(); - float DO_prv2 = ((Number) param8).floatValue(); - float DO_prv1 = ((Number) param7).floatValue(); - float DO_prv0 = ((Number) param6).floatValue(); - float X2_prv4 = ((Number) param5).floatValue(); - float X2_prv3 = ((Number) param4).floatValue(); - float X2_prv2 = ((Number) param3).floatValue(); - float X2_prv1 = ((Number) param2).floatValue(); - float X2_prv0 = ((Number) param1).floatValue(); - - float result = ann_x2(X2_prv0, X2_prv1, X2_prv2, X2_prv3, X2_prv4, DO_prv0, DO_prv1, DO_prv2, DO_prv3, DO_prv4, mon0, mon1, mon2, mon3, mon4, ave_type, currMonth, currYear, BeginDay, EndDay); - - // push the result on the Stack - stack.push(new Float(result)); - }else{ - //values in reverse order: - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int EndDay = 28; - int BeginDay = 1; - int currYear = ((Number) param18).intValue(); - int currMonth = ((Number) param17).intValue(); - int ave_type = ((Number) param16).intValue(); - int mon4 = ((Number) param15).intValue(); - int mon3 = ((Number) param14).intValue(); - int mon2 = ((Number) param13).intValue(); - int mon1 = ((Number) param12).intValue(); - int mon0 = ((Number) param11).intValue(); - float DO_prv4 = ((Number) param10).floatValue(); - float DO_prv3 = ((Number) param9).floatValue(); - float DO_prv2 = ((Number) param8).floatValue(); - float DO_prv1 = ((Number) param7).floatValue(); - float DO_prv0 = ((Number) param6).floatValue(); - float X2_prv4 = ((Number) param5).floatValue(); - float X2_prv3 = ((Number) param4).floatValue(); - float X2_prv2 = ((Number) param3).floatValue(); - float X2_prv1 = ((Number) param2).floatValue(); - float X2_prv0 = ((Number) param1).floatValue(); - - float result = ann_x2(X2_prv0, X2_prv1, X2_prv2, X2_prv3, X2_prv4, DO_prv0, DO_prv1, DO_prv2, DO_prv3, DO_prv4, mon0, mon1, mon2, mon3, mon4, ave_type, currMonth, currYear, BeginDay, EndDay); - - // push the result on the Stack - stack.push(new Float(result)); - - } - - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); - ControlData.t_annx2=ControlData.t_annx2+(int) (t2-t1); - ControlData.n_ann=ControlData.n_ann+1; - ControlData.n_annx2=ControlData.n_annx2+1; - } - - public native float ann_x2(float X2_prv0, float X2_prv1, float X2_prv2, float X2_prv3, float X2_prv4, float DO_prv0, float DO_prv1, float DO_prv2, float DO_prv3, float DO_prv4, int mon0, int mon1, int mon2, int mon3, int mon4, int ave_type, int currMonth, int currYear, int BeginDay, int EndDay); -} +package wrimsv2.external; + +import java.util.*; + +import wrimsv2.components.ControlData; + +public class Functionann_x2 extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functionann_x2(){ + + } + + public void execute(Stack stack) { + + long t1 = Calendar.getInstance().getTimeInMillis(); + + if (stack.size()==20){ + //values in reverse order: + Object param20 = stack.pop(); + Object param19 = stack.pop(); + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int EndDay = ((Number) param20).intValue(); + int BeginDay = ((Number) param19).intValue(); + int currYear = ((Number) param18).intValue(); + int currMonth = ((Number) param17).intValue(); + int ave_type = ((Number) param16).intValue(); + int mon4 = ((Number) param15).intValue(); + int mon3 = ((Number) param14).intValue(); + int mon2 = ((Number) param13).intValue(); + int mon1 = ((Number) param12).intValue(); + int mon0 = ((Number) param11).intValue(); + float DO_prv4 = ((Number) param10).floatValue(); + float DO_prv3 = ((Number) param9).floatValue(); + float DO_prv2 = ((Number) param8).floatValue(); + float DO_prv1 = ((Number) param7).floatValue(); + float DO_prv0 = ((Number) param6).floatValue(); + float X2_prv4 = ((Number) param5).floatValue(); + float X2_prv3 = ((Number) param4).floatValue(); + float X2_prv2 = ((Number) param3).floatValue(); + float X2_prv1 = ((Number) param2).floatValue(); + float X2_prv0 = ((Number) param1).floatValue(); + + float result = ann_x2(X2_prv0, X2_prv1, X2_prv2, X2_prv3, X2_prv4, DO_prv0, DO_prv1, DO_prv2, DO_prv3, DO_prv4, mon0, mon1, mon2, mon3, mon4, ave_type, currMonth, currYear, BeginDay, EndDay); + + // push the result on the Stack + stack.push(new Float(result)); + }else{ + //values in reverse order: + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int EndDay = 28; + int BeginDay = 1; + int currYear = ((Number) param18).intValue(); + int currMonth = ((Number) param17).intValue(); + int ave_type = ((Number) param16).intValue(); + int mon4 = ((Number) param15).intValue(); + int mon3 = ((Number) param14).intValue(); + int mon2 = ((Number) param13).intValue(); + int mon1 = ((Number) param12).intValue(); + int mon0 = ((Number) param11).intValue(); + float DO_prv4 = ((Number) param10).floatValue(); + float DO_prv3 = ((Number) param9).floatValue(); + float DO_prv2 = ((Number) param8).floatValue(); + float DO_prv1 = ((Number) param7).floatValue(); + float DO_prv0 = ((Number) param6).floatValue(); + float X2_prv4 = ((Number) param5).floatValue(); + float X2_prv3 = ((Number) param4).floatValue(); + float X2_prv2 = ((Number) param3).floatValue(); + float X2_prv1 = ((Number) param2).floatValue(); + float X2_prv0 = ((Number) param1).floatValue(); + + float result = ann_x2(X2_prv0, X2_prv1, X2_prv2, X2_prv3, X2_prv4, DO_prv0, DO_prv1, DO_prv2, DO_prv3, DO_prv4, mon0, mon1, mon2, mon3, mon4, ave_type, currMonth, currYear, BeginDay, EndDay); + + // push the result on the Stack + stack.push(new Float(result)); + + } + + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); + ControlData.t_annx2=ControlData.t_annx2+(int) (t2-t1); + ControlData.n_ann=ControlData.n_ann+1; + ControlData.n_annx2=ControlData.n_annx2+1; + } + + public native float ann_x2(float X2_prv0, float X2_prv1, float X2_prv2, float X2_prv3, float X2_prv4, float DO_prv0, float DO_prv1, float DO_prv2, float DO_prv3, float DO_prv4, int mon0, int mon1, int mon2, int mon3, int mon4, int ave_type, int currMonth, int currYear, int BeginDay, int EndDay); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionann_x2_daily.java b/wrims-core/src/main/java/wrimsv2/external/Functionann_x2_daily.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionann_x2_daily.java rename to wrims-core/src/main/java/wrimsv2/external/Functionann_x2_daily.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec.java b/wrims-core/src/main/java/wrimsv2/external/Functionannec.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec.java rename to wrims-core/src/main/java/wrimsv2/external/Functionannec.java index 3668aa023..f7b5730ee 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functionannec.java @@ -1,134 +1,134 @@ -package wrimsv2.external; - -import java.util.*; - -import wrimsv2.components.ControlData; - -public class Functionannec extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functionannec(){ - - } - - public void execute(Stack stack) { - - long t1 = Calendar.getInstance().getTimeInMillis(); - - //values in reverse order: - Object param49 = stack.pop(); - Object param48 = stack.pop(); - Object param47 = stack.pop(); - Object param46 = stack.pop(); - Object param45 = stack.pop(); - Object param44 = stack.pop(); - Object param43 = stack.pop(); - Object param42 = stack.pop(); - Object param41 = stack.pop(); - Object param40 = stack.pop(); - Object param39 = stack.pop(); - Object param38 = stack.pop(); - Object param37 = stack.pop(); - Object param36 = stack.pop(); - Object param35 = stack.pop(); - Object param34 = stack.pop(); - Object param33 = stack.pop(); - Object param32 = stack.pop(); - Object param31 = stack.pop(); - Object param30 = stack.pop(); - Object param29 = stack.pop(); - Object param28 = stack.pop(); - Object param27 = stack.pop(); - Object param26 = stack.pop(); - Object param25 = stack.pop(); - Object param24 = stack.pop(); - Object param23 = stack.pop(); - Object param22 = stack.pop(); - Object param21 = stack.pop(); - Object param20 = stack.pop(); - Object param19 = stack.pop(); - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int currYear = ((Number) param49).intValue(); - int currMonth = ((Number) param48).intValue(); - int ave_type = ((Number) param47).intValue(); - int location = ((Number) param46).intValue(); - int mon4 = ((Number) param45).intValue(); - int mon3 = ((Number) param44).intValue(); - int mon2 = ((Number) param43).intValue(); - int mon1 = ((Number) param42).intValue(); - int mon0 = ((Number) param41).intValue(); - float VernEC_prv4 = ((Number) param40).floatValue(); - float VernEC_prv3 = ((Number) param39).floatValue(); - float VernEC_prv2 = ((Number) param38).floatValue(); - float VernEC_prv1 = ((Number) param37).floatValue(); - float VernEC_prv0 = ((Number) param36).floatValue(); - float Qexp_oth_prv4 = ((Number) param35).floatValue(); - float Qexp_oth_prv3 = ((Number) param34).floatValue(); - float Qexp_oth_prv2 = ((Number) param33).floatValue(); - float Qexp_oth_prv1 = ((Number) param32).floatValue(); - float Qexp_oth_prv0 = ((Number) param31).floatValue(); - float Qsac_oth_prv4 = ((Number) param30).floatValue(); - float Qsac_oth_prv3 = ((Number) param29).floatValue(); - float Qsac_oth_prv2 = ((Number) param28).floatValue(); - float Qsac_oth_prv1 = ((Number) param27).floatValue(); - float Qsac_oth_prv0 = ((Number) param26).floatValue(); - float DICU_prv4 = ((Number) param25).floatValue(); - float DICU_prv3 = ((Number) param24).floatValue(); - float DICU_prv2 = ((Number) param23).floatValue(); - float DICU_prv1 = ((Number) param22).floatValue(); - float DICU_prv0 = ((Number) param21).floatValue(); - float DXC_prv4 = ((Number) param20).floatValue(); - float DXC_prv3 = ((Number) param19).floatValue(); - float DXC_prv2 = ((Number) param18).floatValue(); - float DXC_prv1 = ((Number) param17).floatValue(); - float DXC_prv0 = ((Number) param16).floatValue(); - float Qsjr_prv4 = ((Number) param15).floatValue(); - float Qsjr_prv3 = ((Number) param14).floatValue(); - float Qsjr_prv2 = ((Number) param13).floatValue(); - float Qsjr_prv1 = ((Number) param12).floatValue(); - float Qsjr_prv0 = ((Number) param11).floatValue(); - float Qexp_prv4 = ((Number) param10).floatValue(); - float Qexp_prv3 = ((Number) param9).floatValue(); - float Qexp_prv2 = ((Number) param8).floatValue(); - float Qexp_prv1 = ((Number) param7).floatValue(); - float Qexp_prv0 = ((Number) param6).floatValue(); - float Qsac_prv4 = ((Number) param5).floatValue(); - float Qsac_prv3 = ((Number) param4).floatValue(); - float Qsac_prv2 = ((Number) param3).floatValue(); - float Qsac_prv1 = ((Number) param2).floatValue(); - float Qsac_prv0 = ((Number) param1).floatValue(); - - float result = annec(Qsac_prv0, Qsac_prv1, Qsac_prv2, Qsac_prv3, Qsac_prv4, Qexp_prv0, Qexp_prv1, Qexp_prv2, Qexp_prv3, Qexp_prv4, Qsjr_prv0, Qsjr_prv1, Qsjr_prv2, Qsjr_prv3, Qsjr_prv4, DXC_prv0, DXC_prv1, DXC_prv2, DXC_prv3, DXC_prv4, DICU_prv0, DICU_prv1, DICU_prv2, DICU_prv3, DICU_prv4, Qsac_oth_prv0, Qsac_oth_prv1, Qsac_oth_prv2, Qsac_oth_prv3, Qsac_oth_prv4, Qexp_oth_prv0, Qexp_oth_prv1, Qexp_oth_prv2, Qexp_oth_prv3, Qexp_oth_prv4, VernEC_prv0, VernEC_prv1, VernEC_prv2, VernEC_prv3, VernEC_prv4, mon0, mon1, mon2, mon3, mon4, location, ave_type, currMonth, currYear); - - // push the result on the Stack - stack.push(new Float(result)); - - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); - ControlData.t_annec=ControlData.t_annec+(int) (t2-t1); - ControlData.n_ann=ControlData.n_ann+1; - ControlData.n_annec=ControlData.n_annec+1; - } - - public native float annec(float Qsac_prv0, float Qsac_prv1, float Qsac_prv2, float Qsac_prv3, float Qsac_prv4, float Qexp_prv0, float Qexp_prv1, float Qexp_prv2, float Qexp_prv3, float Qexp_prv4, float Qsjr_prv0, float Qsjr_prv1, float Qsjr_prv2, float Qsjr_prv3, float Qsjr_prv4, float DXC_prv0, float DXC_prv1, float DXC_prv2, float DXC_prv3, float DXC_prv4, float DICU_prv0, float DICU_prv1, float DICU_prv2, float DICU_prv3, float DICU_prv4, float Qsac_oth_prv0, float Qsac_oth_prv1, float Qsac_oth_prv2, float Qsac_oth_prv3, float Qsac_oth_prv4, float Qexp_oth_prv0, float Qexp_oth_prv1, float Qexp_oth_prv2, float Qexp_oth_prv3, float Qexp_oth_prv4, float VernEC_prv0, float VernEC_prv1, float VernEC_prv2, float VernEC_prv3, float VernEC_prv4, int mon0, int mon1, int mon2, int mon3, int mon4, int location, int ave_type, int currMonth, int currYear); -} +package wrimsv2.external; + +import java.util.*; + +import wrimsv2.components.ControlData; + +public class Functionannec extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functionannec(){ + + } + + public void execute(Stack stack) { + + long t1 = Calendar.getInstance().getTimeInMillis(); + + //values in reverse order: + Object param49 = stack.pop(); + Object param48 = stack.pop(); + Object param47 = stack.pop(); + Object param46 = stack.pop(); + Object param45 = stack.pop(); + Object param44 = stack.pop(); + Object param43 = stack.pop(); + Object param42 = stack.pop(); + Object param41 = stack.pop(); + Object param40 = stack.pop(); + Object param39 = stack.pop(); + Object param38 = stack.pop(); + Object param37 = stack.pop(); + Object param36 = stack.pop(); + Object param35 = stack.pop(); + Object param34 = stack.pop(); + Object param33 = stack.pop(); + Object param32 = stack.pop(); + Object param31 = stack.pop(); + Object param30 = stack.pop(); + Object param29 = stack.pop(); + Object param28 = stack.pop(); + Object param27 = stack.pop(); + Object param26 = stack.pop(); + Object param25 = stack.pop(); + Object param24 = stack.pop(); + Object param23 = stack.pop(); + Object param22 = stack.pop(); + Object param21 = stack.pop(); + Object param20 = stack.pop(); + Object param19 = stack.pop(); + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int currYear = ((Number) param49).intValue(); + int currMonth = ((Number) param48).intValue(); + int ave_type = ((Number) param47).intValue(); + int location = ((Number) param46).intValue(); + int mon4 = ((Number) param45).intValue(); + int mon3 = ((Number) param44).intValue(); + int mon2 = ((Number) param43).intValue(); + int mon1 = ((Number) param42).intValue(); + int mon0 = ((Number) param41).intValue(); + float VernEC_prv4 = ((Number) param40).floatValue(); + float VernEC_prv3 = ((Number) param39).floatValue(); + float VernEC_prv2 = ((Number) param38).floatValue(); + float VernEC_prv1 = ((Number) param37).floatValue(); + float VernEC_prv0 = ((Number) param36).floatValue(); + float Qexp_oth_prv4 = ((Number) param35).floatValue(); + float Qexp_oth_prv3 = ((Number) param34).floatValue(); + float Qexp_oth_prv2 = ((Number) param33).floatValue(); + float Qexp_oth_prv1 = ((Number) param32).floatValue(); + float Qexp_oth_prv0 = ((Number) param31).floatValue(); + float Qsac_oth_prv4 = ((Number) param30).floatValue(); + float Qsac_oth_prv3 = ((Number) param29).floatValue(); + float Qsac_oth_prv2 = ((Number) param28).floatValue(); + float Qsac_oth_prv1 = ((Number) param27).floatValue(); + float Qsac_oth_prv0 = ((Number) param26).floatValue(); + float DICU_prv4 = ((Number) param25).floatValue(); + float DICU_prv3 = ((Number) param24).floatValue(); + float DICU_prv2 = ((Number) param23).floatValue(); + float DICU_prv1 = ((Number) param22).floatValue(); + float DICU_prv0 = ((Number) param21).floatValue(); + float DXC_prv4 = ((Number) param20).floatValue(); + float DXC_prv3 = ((Number) param19).floatValue(); + float DXC_prv2 = ((Number) param18).floatValue(); + float DXC_prv1 = ((Number) param17).floatValue(); + float DXC_prv0 = ((Number) param16).floatValue(); + float Qsjr_prv4 = ((Number) param15).floatValue(); + float Qsjr_prv3 = ((Number) param14).floatValue(); + float Qsjr_prv2 = ((Number) param13).floatValue(); + float Qsjr_prv1 = ((Number) param12).floatValue(); + float Qsjr_prv0 = ((Number) param11).floatValue(); + float Qexp_prv4 = ((Number) param10).floatValue(); + float Qexp_prv3 = ((Number) param9).floatValue(); + float Qexp_prv2 = ((Number) param8).floatValue(); + float Qexp_prv1 = ((Number) param7).floatValue(); + float Qexp_prv0 = ((Number) param6).floatValue(); + float Qsac_prv4 = ((Number) param5).floatValue(); + float Qsac_prv3 = ((Number) param4).floatValue(); + float Qsac_prv2 = ((Number) param3).floatValue(); + float Qsac_prv1 = ((Number) param2).floatValue(); + float Qsac_prv0 = ((Number) param1).floatValue(); + + float result = annec(Qsac_prv0, Qsac_prv1, Qsac_prv2, Qsac_prv3, Qsac_prv4, Qexp_prv0, Qexp_prv1, Qexp_prv2, Qexp_prv3, Qexp_prv4, Qsjr_prv0, Qsjr_prv1, Qsjr_prv2, Qsjr_prv3, Qsjr_prv4, DXC_prv0, DXC_prv1, DXC_prv2, DXC_prv3, DXC_prv4, DICU_prv0, DICU_prv1, DICU_prv2, DICU_prv3, DICU_prv4, Qsac_oth_prv0, Qsac_oth_prv1, Qsac_oth_prv2, Qsac_oth_prv3, Qsac_oth_prv4, Qexp_oth_prv0, Qexp_oth_prv1, Qexp_oth_prv2, Qexp_oth_prv3, Qexp_oth_prv4, VernEC_prv0, VernEC_prv1, VernEC_prv2, VernEC_prv3, VernEC_prv4, mon0, mon1, mon2, mon3, mon4, location, ave_type, currMonth, currYear); + + // push the result on the Stack + stack.push(new Float(result)); + + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); + ControlData.t_annec=ControlData.t_annec+(int) (t2-t1); + ControlData.n_ann=ControlData.n_ann+1; + ControlData.n_annec=ControlData.n_annec+1; + } + + public native float annec(float Qsac_prv0, float Qsac_prv1, float Qsac_prv2, float Qsac_prv3, float Qsac_prv4, float Qexp_prv0, float Qexp_prv1, float Qexp_prv2, float Qexp_prv3, float Qexp_prv4, float Qsjr_prv0, float Qsjr_prv1, float Qsjr_prv2, float Qsjr_prv3, float Qsjr_prv4, float DXC_prv0, float DXC_prv1, float DXC_prv2, float DXC_prv3, float DXC_prv4, float DICU_prv0, float DICU_prv1, float DICU_prv2, float DICU_prv3, float DICU_prv4, float Qsac_oth_prv0, float Qsac_oth_prv1, float Qsac_oth_prv2, float Qsac_oth_prv3, float Qsac_oth_prv4, float Qexp_oth_prv0, float Qexp_oth_prv1, float Qexp_oth_prv2, float Qexp_oth_prv3, float Qexp_oth_prv4, float VernEC_prv0, float VernEC_prv1, float VernEC_prv2, float VernEC_prv3, float VernEC_prv4, int mon0, int mon1, int mon2, int mon3, int mon4, int location, int ave_type, int currMonth, int currYear); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec_a.java b/wrims-core/src/main/java/wrimsv2/external/Functionannec_a.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec_a.java rename to wrims-core/src/main/java/wrimsv2/external/Functionannec_a.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec_curmoninpsplit_a.java b/wrims-core/src/main/java/wrimsv2/external/Functionannec_curmoninpsplit_a.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec_curmoninpsplit_a.java rename to wrims-core/src/main/java/wrimsv2/external/Functionannec_curmoninpsplit_a.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec_matchdsm2.java b/wrims-core/src/main/java/wrimsv2/external/Functionannec_matchdsm2.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec_matchdsm2.java rename to wrims-core/src/main/java/wrimsv2/external/Functionannec_matchdsm2.java index 87d4cdd85..208eda4b0 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec_matchdsm2.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functionannec_matchdsm2.java @@ -1,273 +1,273 @@ -package wrimsv2.external; - -import java.util.*; - -import wrimsv2.components.ControlData; - -public class Functionannec_matchdsm2 extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functionannec_matchdsm2(){ - - } - - public void execute(Stack stack) { - - long t1 = Calendar.getInstance().getTimeInMillis(); - - if (stack.size()==57){ - //values in reverse order: - Object param57 = stack.pop(); - Object param56 = stack.pop(); - Object param55 = stack.pop(); - Object param54 = stack.pop(); - Object param53 = stack.pop(); - Object param52 = stack.pop(); - Object param51 = stack.pop(); - Object param50 = stack.pop(); - Object param49 = stack.pop(); - Object param48 = stack.pop(); - Object param47 = stack.pop(); - Object param46 = stack.pop(); - Object param45 = stack.pop(); - Object param44 = stack.pop(); - Object param43 = stack.pop(); - Object param42 = stack.pop(); - Object param41 = stack.pop(); - Object param40 = stack.pop(); - Object param39 = stack.pop(); - Object param38 = stack.pop(); - Object param37 = stack.pop(); - Object param36 = stack.pop(); - Object param35 = stack.pop(); - Object param34 = stack.pop(); - Object param33 = stack.pop(); - Object param32 = stack.pop(); - Object param31 = stack.pop(); - Object param30 = stack.pop(); - Object param29 = stack.pop(); - Object param28 = stack.pop(); - Object param27 = stack.pop(); - Object param26 = stack.pop(); - Object param25 = stack.pop(); - Object param24 = stack.pop(); - Object param23 = stack.pop(); - Object param22 = stack.pop(); - Object param21 = stack.pop(); - Object param20 = stack.pop(); - Object param19 = stack.pop(); - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int EndDay = ((Number) param57).intValue(); - int BeginDay = ((Number) param56).intValue(); - int currYear = ((Number) param55).intValue(); - int currMonth = ((Number) param54).intValue(); - int ave_type = ((Number) param53).intValue(); - int location = ((Number) param52).intValue(); - int mon6 = ((Number) param51).intValue(); - int mon5 = ((Number) param50).intValue(); - int mon4 = ((Number) param49).intValue(); - int mon3 = ((Number) param48).intValue(); - int mon2 = ((Number) param47).intValue(); - int mon1 = ((Number) param46).intValue(); - int mon0 = ((Number) param45).intValue(); - float VernEC_prv4 = ((Number) param44).floatValue(); - float VernEC_prv3 = ((Number) param43).floatValue(); - float VernEC_prv2 = ((Number) param42).floatValue(); - float VernEC_prv1 = ((Number) param41).floatValue(); - float VernEC_prv0 = ((Number) param40).floatValue(); - float Qexp_oth_prv4 = ((Number) param39).floatValue(); - float Qexp_oth_prv3 = ((Number) param38).floatValue(); - float Qexp_oth_prv2 = ((Number) param37).floatValue(); - float Qexp_oth_prv1 = ((Number) param36).floatValue(); - float Qexp_oth_prv0 = ((Number) param35).floatValue(); - float Qsac_oth_prv4 = ((Number) param34).floatValue(); - float Qsac_oth_prv3 = ((Number) param33).floatValue(); - float Qsac_oth_prv2 = ((Number) param32).floatValue(); - float Qsac_oth_prv1 = ((Number) param31).floatValue(); - float Qsac_oth_prv0 = ((Number) param30).floatValue(); - float DICU_prv4 = ((Number) param29).floatValue(); - float DICU_prv3 = ((Number) param28).floatValue(); - float DICU_prv2 = ((Number) param27).floatValue(); - float DICU_prv1 = ((Number) param26).floatValue(); - float DICU_prv0 = ((Number) param25).floatValue(); - float DXC_prv4 = ((Number) param24).floatValue(); - float DXC_prv3 = ((Number) param23).floatValue(); - float DXC_prv2 = ((Number) param22).floatValue(); - float DXC_prv1 = ((Number) param21).floatValue(); - float DXC_prv0 = ((Number) param20).floatValue(); - float Qsjr_prv6 = ((Number) param19).floatValue(); - float Qsjr_prv5 = ((Number) param18).floatValue(); - float Qsjr_prv4 = ((Number) param17).floatValue(); - float Qsjr_prv3 = ((Number) param16).floatValue(); - float Qsjr_prv2 = ((Number) param15).floatValue(); - float Qsjr_prv1 = ((Number) param14).floatValue(); - float Qsjr_prv0 = ((Number) param13).floatValue(); - float Qexp_prv4 = ((Number) param12).floatValue(); - float Qexp_prv3 = ((Number) param11).floatValue(); - float Qexp_prv2 = ((Number) param10).floatValue(); - float Qexp_prv1 = ((Number) param9).floatValue(); - float Qexp_prv0 = ((Number) param8).floatValue(); - float Qsac_prv6 = ((Number) param7).floatValue(); - float Qsac_prv5 = ((Number) param6).floatValue(); - float Qsac_prv4 = ((Number) param5).floatValue(); - float Qsac_prv3 = ((Number) param4).floatValue(); - float Qsac_prv2 = ((Number) param3).floatValue(); - float Qsac_prv1 = ((Number) param2).floatValue(); - float Qsac_prv0 = ((Number) param1).floatValue(); - - float result = annec_matchdsm2(Qsac_prv0, Qsac_prv1, Qsac_prv2, Qsac_prv3, Qsac_prv4, Qsac_prv5, Qsac_prv6, Qexp_prv0, Qexp_prv1, Qexp_prv2, Qexp_prv3, Qexp_prv4, Qsjr_prv0, Qsjr_prv1, Qsjr_prv2, Qsjr_prv3, Qsjr_prv4, Qsjr_prv5, Qsjr_prv6, DXC_prv0, DXC_prv1, DXC_prv2, DXC_prv3, DXC_prv4, DICU_prv0, DICU_prv1, DICU_prv2, DICU_prv3, DICU_prv4, Qsac_oth_prv0, Qsac_oth_prv1, Qsac_oth_prv2, Qsac_oth_prv3, Qsac_oth_prv4, Qexp_oth_prv0, Qexp_oth_prv1, Qexp_oth_prv2, Qexp_oth_prv3, Qexp_oth_prv4, VernEC_prv0, VernEC_prv1, VernEC_prv2, VernEC_prv3, VernEC_prv4, mon0, mon1, mon2, mon3, mon4, mon5, mon6, location, ave_type, currMonth, currYear, BeginDay, EndDay); - - // push the result on the Stack - stack.push(new Float(result)); - }else{ - //values in reverse order: - Object param55 = stack.pop(); - Object param54 = stack.pop(); - Object param53 = stack.pop(); - Object param52 = stack.pop(); - Object param51 = stack.pop(); - Object param50 = stack.pop(); - Object param49 = stack.pop(); - Object param48 = stack.pop(); - Object param47 = stack.pop(); - Object param46 = stack.pop(); - Object param45 = stack.pop(); - Object param44 = stack.pop(); - Object param43 = stack.pop(); - Object param42 = stack.pop(); - Object param41 = stack.pop(); - Object param40 = stack.pop(); - Object param39 = stack.pop(); - Object param38 = stack.pop(); - Object param37 = stack.pop(); - Object param36 = stack.pop(); - Object param35 = stack.pop(); - Object param34 = stack.pop(); - Object param33 = stack.pop(); - Object param32 = stack.pop(); - Object param31 = stack.pop(); - Object param30 = stack.pop(); - Object param29 = stack.pop(); - Object param28 = stack.pop(); - Object param27 = stack.pop(); - Object param26 = stack.pop(); - Object param25 = stack.pop(); - Object param24 = stack.pop(); - Object param23 = stack.pop(); - Object param22 = stack.pop(); - Object param21 = stack.pop(); - Object param20 = stack.pop(); - Object param19 = stack.pop(); - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int EndDay = 28; - int BeginDay = 1; - int currYear = ((Number) param55).intValue(); - int currMonth = ((Number) param54).intValue(); - int ave_type = ((Number) param53).intValue(); - int location = ((Number) param52).intValue(); - int mon6 = ((Number) param51).intValue(); - int mon5 = ((Number) param50).intValue(); - int mon4 = ((Number) param49).intValue(); - int mon3 = ((Number) param48).intValue(); - int mon2 = ((Number) param47).intValue(); - int mon1 = ((Number) param46).intValue(); - int mon0 = ((Number) param45).intValue(); - float VernEC_prv4 = ((Number) param44).floatValue(); - float VernEC_prv3 = ((Number) param43).floatValue(); - float VernEC_prv2 = ((Number) param42).floatValue(); - float VernEC_prv1 = ((Number) param41).floatValue(); - float VernEC_prv0 = ((Number) param40).floatValue(); - float Qexp_oth_prv4 = ((Number) param39).floatValue(); - float Qexp_oth_prv3 = ((Number) param38).floatValue(); - float Qexp_oth_prv2 = ((Number) param37).floatValue(); - float Qexp_oth_prv1 = ((Number) param36).floatValue(); - float Qexp_oth_prv0 = ((Number) param35).floatValue(); - float Qsac_oth_prv4 = ((Number) param34).floatValue(); - float Qsac_oth_prv3 = ((Number) param33).floatValue(); - float Qsac_oth_prv2 = ((Number) param32).floatValue(); - float Qsac_oth_prv1 = ((Number) param31).floatValue(); - float Qsac_oth_prv0 = ((Number) param30).floatValue(); - float DICU_prv4 = ((Number) param29).floatValue(); - float DICU_prv3 = ((Number) param28).floatValue(); - float DICU_prv2 = ((Number) param27).floatValue(); - float DICU_prv1 = ((Number) param26).floatValue(); - float DICU_prv0 = ((Number) param25).floatValue(); - float DXC_prv4 = ((Number) param24).floatValue(); - float DXC_prv3 = ((Number) param23).floatValue(); - float DXC_prv2 = ((Number) param22).floatValue(); - float DXC_prv1 = ((Number) param21).floatValue(); - float DXC_prv0 = ((Number) param20).floatValue(); - float Qsjr_prv6 = ((Number) param19).floatValue(); - float Qsjr_prv5 = ((Number) param18).floatValue(); - float Qsjr_prv4 = ((Number) param17).floatValue(); - float Qsjr_prv3 = ((Number) param16).floatValue(); - float Qsjr_prv2 = ((Number) param15).floatValue(); - float Qsjr_prv1 = ((Number) param14).floatValue(); - float Qsjr_prv0 = ((Number) param13).floatValue(); - float Qexp_prv4 = ((Number) param12).floatValue(); - float Qexp_prv3 = ((Number) param11).floatValue(); - float Qexp_prv2 = ((Number) param10).floatValue(); - float Qexp_prv1 = ((Number) param9).floatValue(); - float Qexp_prv0 = ((Number) param8).floatValue(); - float Qsac_prv6 = ((Number) param7).floatValue(); - float Qsac_prv5 = ((Number) param6).floatValue(); - float Qsac_prv4 = ((Number) param5).floatValue(); - float Qsac_prv3 = ((Number) param4).floatValue(); - float Qsac_prv2 = ((Number) param3).floatValue(); - float Qsac_prv1 = ((Number) param2).floatValue(); - float Qsac_prv0 = ((Number) param1).floatValue(); - - float result = annec_matchdsm2(Qsac_prv0, Qsac_prv1, Qsac_prv2, Qsac_prv3, Qsac_prv4, Qsac_prv5, Qsac_prv6, Qexp_prv0, Qexp_prv1, Qexp_prv2, Qexp_prv3, Qexp_prv4, Qsjr_prv0, Qsjr_prv1, Qsjr_prv2, Qsjr_prv3, Qsjr_prv4, Qsjr_prv5, Qsjr_prv6, DXC_prv0, DXC_prv1, DXC_prv2, DXC_prv3, DXC_prv4, DICU_prv0, DICU_prv1, DICU_prv2, DICU_prv3, DICU_prv4, Qsac_oth_prv0, Qsac_oth_prv1, Qsac_oth_prv2, Qsac_oth_prv3, Qsac_oth_prv4, Qexp_oth_prv0, Qexp_oth_prv1, Qexp_oth_prv2, Qexp_oth_prv3, Qexp_oth_prv4, VernEC_prv0, VernEC_prv1, VernEC_prv2, VernEC_prv3, VernEC_prv4, mon0, mon1, mon2, mon3, mon4, mon5, mon6, location, ave_type, currMonth, currYear, BeginDay, EndDay); - - // push the result on the Stack - stack.push(new Float(result)); - } - - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); - ControlData.t_annec_matchdsm2=ControlData.t_annec_matchdsm2+(int) (t2-t1); - ControlData.n_ann=ControlData.n_ann+1; - ControlData.n_annec_matchdsm2=ControlData.n_annec_matchdsm2+1; - } - - public native float annec_matchdsm2(float Qsac_prv0, float Qsac_prv1, float Qsac_prv2, float Qsac_prv3, float Qsac_prv4, float Qsac_prv5, float Qsac_prv6, float Qexp_prv0, float Qexp_prv1, float Qexp_prv2, float Qexp_prv3, float Qexp_prv4, float Qsjr_prv0, float Qsjr_prv1, float Qsjr_prv2, float Qsjr_prv3, float Qsjr_prv4, float Qsjr_prv5, float Qsjr_prv6, float DXC_prv0, float DXC_prv1, float DXC_prv2, float DXC_prv3, float DXC_prv4, float DICU_prv0, float DICU_prv1, float DICU_prv2, float DICU_prv3, float DICU_prv4, float Qsac_oth_prv0, float Qsac_oth_prv1, float Qsac_oth_prv2, float Qsac_oth_prv3, float Qsac_oth_prv4, float Qexp_oth_prv0, float Qexp_oth_prv1, float Qexp_oth_prv2, float Qexp_oth_prv3, float Qexp_oth_prv4, float VernEC_prv0, float VernEC_prv1, float VernEC_prv2, float VernEC_prv3, float VernEC_prv4, int mon0, int mon1, int mon2, int mon3, int mon4, int mon5, int mon6, int location, int ave_type, int currMonth, int currYear, int BeginDay, int EndDay); -} +package wrimsv2.external; + +import java.util.*; + +import wrimsv2.components.ControlData; + +public class Functionannec_matchdsm2 extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functionannec_matchdsm2(){ + + } + + public void execute(Stack stack) { + + long t1 = Calendar.getInstance().getTimeInMillis(); + + if (stack.size()==57){ + //values in reverse order: + Object param57 = stack.pop(); + Object param56 = stack.pop(); + Object param55 = stack.pop(); + Object param54 = stack.pop(); + Object param53 = stack.pop(); + Object param52 = stack.pop(); + Object param51 = stack.pop(); + Object param50 = stack.pop(); + Object param49 = stack.pop(); + Object param48 = stack.pop(); + Object param47 = stack.pop(); + Object param46 = stack.pop(); + Object param45 = stack.pop(); + Object param44 = stack.pop(); + Object param43 = stack.pop(); + Object param42 = stack.pop(); + Object param41 = stack.pop(); + Object param40 = stack.pop(); + Object param39 = stack.pop(); + Object param38 = stack.pop(); + Object param37 = stack.pop(); + Object param36 = stack.pop(); + Object param35 = stack.pop(); + Object param34 = stack.pop(); + Object param33 = stack.pop(); + Object param32 = stack.pop(); + Object param31 = stack.pop(); + Object param30 = stack.pop(); + Object param29 = stack.pop(); + Object param28 = stack.pop(); + Object param27 = stack.pop(); + Object param26 = stack.pop(); + Object param25 = stack.pop(); + Object param24 = stack.pop(); + Object param23 = stack.pop(); + Object param22 = stack.pop(); + Object param21 = stack.pop(); + Object param20 = stack.pop(); + Object param19 = stack.pop(); + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int EndDay = ((Number) param57).intValue(); + int BeginDay = ((Number) param56).intValue(); + int currYear = ((Number) param55).intValue(); + int currMonth = ((Number) param54).intValue(); + int ave_type = ((Number) param53).intValue(); + int location = ((Number) param52).intValue(); + int mon6 = ((Number) param51).intValue(); + int mon5 = ((Number) param50).intValue(); + int mon4 = ((Number) param49).intValue(); + int mon3 = ((Number) param48).intValue(); + int mon2 = ((Number) param47).intValue(); + int mon1 = ((Number) param46).intValue(); + int mon0 = ((Number) param45).intValue(); + float VernEC_prv4 = ((Number) param44).floatValue(); + float VernEC_prv3 = ((Number) param43).floatValue(); + float VernEC_prv2 = ((Number) param42).floatValue(); + float VernEC_prv1 = ((Number) param41).floatValue(); + float VernEC_prv0 = ((Number) param40).floatValue(); + float Qexp_oth_prv4 = ((Number) param39).floatValue(); + float Qexp_oth_prv3 = ((Number) param38).floatValue(); + float Qexp_oth_prv2 = ((Number) param37).floatValue(); + float Qexp_oth_prv1 = ((Number) param36).floatValue(); + float Qexp_oth_prv0 = ((Number) param35).floatValue(); + float Qsac_oth_prv4 = ((Number) param34).floatValue(); + float Qsac_oth_prv3 = ((Number) param33).floatValue(); + float Qsac_oth_prv2 = ((Number) param32).floatValue(); + float Qsac_oth_prv1 = ((Number) param31).floatValue(); + float Qsac_oth_prv0 = ((Number) param30).floatValue(); + float DICU_prv4 = ((Number) param29).floatValue(); + float DICU_prv3 = ((Number) param28).floatValue(); + float DICU_prv2 = ((Number) param27).floatValue(); + float DICU_prv1 = ((Number) param26).floatValue(); + float DICU_prv0 = ((Number) param25).floatValue(); + float DXC_prv4 = ((Number) param24).floatValue(); + float DXC_prv3 = ((Number) param23).floatValue(); + float DXC_prv2 = ((Number) param22).floatValue(); + float DXC_prv1 = ((Number) param21).floatValue(); + float DXC_prv0 = ((Number) param20).floatValue(); + float Qsjr_prv6 = ((Number) param19).floatValue(); + float Qsjr_prv5 = ((Number) param18).floatValue(); + float Qsjr_prv4 = ((Number) param17).floatValue(); + float Qsjr_prv3 = ((Number) param16).floatValue(); + float Qsjr_prv2 = ((Number) param15).floatValue(); + float Qsjr_prv1 = ((Number) param14).floatValue(); + float Qsjr_prv0 = ((Number) param13).floatValue(); + float Qexp_prv4 = ((Number) param12).floatValue(); + float Qexp_prv3 = ((Number) param11).floatValue(); + float Qexp_prv2 = ((Number) param10).floatValue(); + float Qexp_prv1 = ((Number) param9).floatValue(); + float Qexp_prv0 = ((Number) param8).floatValue(); + float Qsac_prv6 = ((Number) param7).floatValue(); + float Qsac_prv5 = ((Number) param6).floatValue(); + float Qsac_prv4 = ((Number) param5).floatValue(); + float Qsac_prv3 = ((Number) param4).floatValue(); + float Qsac_prv2 = ((Number) param3).floatValue(); + float Qsac_prv1 = ((Number) param2).floatValue(); + float Qsac_prv0 = ((Number) param1).floatValue(); + + float result = annec_matchdsm2(Qsac_prv0, Qsac_prv1, Qsac_prv2, Qsac_prv3, Qsac_prv4, Qsac_prv5, Qsac_prv6, Qexp_prv0, Qexp_prv1, Qexp_prv2, Qexp_prv3, Qexp_prv4, Qsjr_prv0, Qsjr_prv1, Qsjr_prv2, Qsjr_prv3, Qsjr_prv4, Qsjr_prv5, Qsjr_prv6, DXC_prv0, DXC_prv1, DXC_prv2, DXC_prv3, DXC_prv4, DICU_prv0, DICU_prv1, DICU_prv2, DICU_prv3, DICU_prv4, Qsac_oth_prv0, Qsac_oth_prv1, Qsac_oth_prv2, Qsac_oth_prv3, Qsac_oth_prv4, Qexp_oth_prv0, Qexp_oth_prv1, Qexp_oth_prv2, Qexp_oth_prv3, Qexp_oth_prv4, VernEC_prv0, VernEC_prv1, VernEC_prv2, VernEC_prv3, VernEC_prv4, mon0, mon1, mon2, mon3, mon4, mon5, mon6, location, ave_type, currMonth, currYear, BeginDay, EndDay); + + // push the result on the Stack + stack.push(new Float(result)); + }else{ + //values in reverse order: + Object param55 = stack.pop(); + Object param54 = stack.pop(); + Object param53 = stack.pop(); + Object param52 = stack.pop(); + Object param51 = stack.pop(); + Object param50 = stack.pop(); + Object param49 = stack.pop(); + Object param48 = stack.pop(); + Object param47 = stack.pop(); + Object param46 = stack.pop(); + Object param45 = stack.pop(); + Object param44 = stack.pop(); + Object param43 = stack.pop(); + Object param42 = stack.pop(); + Object param41 = stack.pop(); + Object param40 = stack.pop(); + Object param39 = stack.pop(); + Object param38 = stack.pop(); + Object param37 = stack.pop(); + Object param36 = stack.pop(); + Object param35 = stack.pop(); + Object param34 = stack.pop(); + Object param33 = stack.pop(); + Object param32 = stack.pop(); + Object param31 = stack.pop(); + Object param30 = stack.pop(); + Object param29 = stack.pop(); + Object param28 = stack.pop(); + Object param27 = stack.pop(); + Object param26 = stack.pop(); + Object param25 = stack.pop(); + Object param24 = stack.pop(); + Object param23 = stack.pop(); + Object param22 = stack.pop(); + Object param21 = stack.pop(); + Object param20 = stack.pop(); + Object param19 = stack.pop(); + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int EndDay = 28; + int BeginDay = 1; + int currYear = ((Number) param55).intValue(); + int currMonth = ((Number) param54).intValue(); + int ave_type = ((Number) param53).intValue(); + int location = ((Number) param52).intValue(); + int mon6 = ((Number) param51).intValue(); + int mon5 = ((Number) param50).intValue(); + int mon4 = ((Number) param49).intValue(); + int mon3 = ((Number) param48).intValue(); + int mon2 = ((Number) param47).intValue(); + int mon1 = ((Number) param46).intValue(); + int mon0 = ((Number) param45).intValue(); + float VernEC_prv4 = ((Number) param44).floatValue(); + float VernEC_prv3 = ((Number) param43).floatValue(); + float VernEC_prv2 = ((Number) param42).floatValue(); + float VernEC_prv1 = ((Number) param41).floatValue(); + float VernEC_prv0 = ((Number) param40).floatValue(); + float Qexp_oth_prv4 = ((Number) param39).floatValue(); + float Qexp_oth_prv3 = ((Number) param38).floatValue(); + float Qexp_oth_prv2 = ((Number) param37).floatValue(); + float Qexp_oth_prv1 = ((Number) param36).floatValue(); + float Qexp_oth_prv0 = ((Number) param35).floatValue(); + float Qsac_oth_prv4 = ((Number) param34).floatValue(); + float Qsac_oth_prv3 = ((Number) param33).floatValue(); + float Qsac_oth_prv2 = ((Number) param32).floatValue(); + float Qsac_oth_prv1 = ((Number) param31).floatValue(); + float Qsac_oth_prv0 = ((Number) param30).floatValue(); + float DICU_prv4 = ((Number) param29).floatValue(); + float DICU_prv3 = ((Number) param28).floatValue(); + float DICU_prv2 = ((Number) param27).floatValue(); + float DICU_prv1 = ((Number) param26).floatValue(); + float DICU_prv0 = ((Number) param25).floatValue(); + float DXC_prv4 = ((Number) param24).floatValue(); + float DXC_prv3 = ((Number) param23).floatValue(); + float DXC_prv2 = ((Number) param22).floatValue(); + float DXC_prv1 = ((Number) param21).floatValue(); + float DXC_prv0 = ((Number) param20).floatValue(); + float Qsjr_prv6 = ((Number) param19).floatValue(); + float Qsjr_prv5 = ((Number) param18).floatValue(); + float Qsjr_prv4 = ((Number) param17).floatValue(); + float Qsjr_prv3 = ((Number) param16).floatValue(); + float Qsjr_prv2 = ((Number) param15).floatValue(); + float Qsjr_prv1 = ((Number) param14).floatValue(); + float Qsjr_prv0 = ((Number) param13).floatValue(); + float Qexp_prv4 = ((Number) param12).floatValue(); + float Qexp_prv3 = ((Number) param11).floatValue(); + float Qexp_prv2 = ((Number) param10).floatValue(); + float Qexp_prv1 = ((Number) param9).floatValue(); + float Qexp_prv0 = ((Number) param8).floatValue(); + float Qsac_prv6 = ((Number) param7).floatValue(); + float Qsac_prv5 = ((Number) param6).floatValue(); + float Qsac_prv4 = ((Number) param5).floatValue(); + float Qsac_prv3 = ((Number) param4).floatValue(); + float Qsac_prv2 = ((Number) param3).floatValue(); + float Qsac_prv1 = ((Number) param2).floatValue(); + float Qsac_prv0 = ((Number) param1).floatValue(); + + float result = annec_matchdsm2(Qsac_prv0, Qsac_prv1, Qsac_prv2, Qsac_prv3, Qsac_prv4, Qsac_prv5, Qsac_prv6, Qexp_prv0, Qexp_prv1, Qexp_prv2, Qexp_prv3, Qexp_prv4, Qsjr_prv0, Qsjr_prv1, Qsjr_prv2, Qsjr_prv3, Qsjr_prv4, Qsjr_prv5, Qsjr_prv6, DXC_prv0, DXC_prv1, DXC_prv2, DXC_prv3, DXC_prv4, DICU_prv0, DICU_prv1, DICU_prv2, DICU_prv3, DICU_prv4, Qsac_oth_prv0, Qsac_oth_prv1, Qsac_oth_prv2, Qsac_oth_prv3, Qsac_oth_prv4, Qexp_oth_prv0, Qexp_oth_prv1, Qexp_oth_prv2, Qexp_oth_prv3, Qexp_oth_prv4, VernEC_prv0, VernEC_prv1, VernEC_prv2, VernEC_prv3, VernEC_prv4, mon0, mon1, mon2, mon3, mon4, mon5, mon6, location, ave_type, currMonth, currYear, BeginDay, EndDay); + + // push the result on the Stack + stack.push(new Float(result)); + } + + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); + ControlData.t_annec_matchdsm2=ControlData.t_annec_matchdsm2+(int) (t2-t1); + ControlData.n_ann=ControlData.n_ann+1; + ControlData.n_annec_matchdsm2=ControlData.n_annec_matchdsm2+1; + } + + public native float annec_matchdsm2(float Qsac_prv0, float Qsac_prv1, float Qsac_prv2, float Qsac_prv3, float Qsac_prv4, float Qsac_prv5, float Qsac_prv6, float Qexp_prv0, float Qexp_prv1, float Qexp_prv2, float Qexp_prv3, float Qexp_prv4, float Qsjr_prv0, float Qsjr_prv1, float Qsjr_prv2, float Qsjr_prv3, float Qsjr_prv4, float Qsjr_prv5, float Qsjr_prv6, float DXC_prv0, float DXC_prv1, float DXC_prv2, float DXC_prv3, float DXC_prv4, float DICU_prv0, float DICU_prv1, float DICU_prv2, float DICU_prv3, float DICU_prv4, float Qsac_oth_prv0, float Qsac_oth_prv1, float Qsac_oth_prv2, float Qsac_oth_prv3, float Qsac_oth_prv4, float Qexp_oth_prv0, float Qexp_oth_prv1, float Qexp_oth_prv2, float Qexp_oth_prv3, float Qexp_oth_prv4, float VernEC_prv0, float VernEC_prv1, float VernEC_prv2, float VernEC_prv3, float VernEC_prv4, int mon0, int mon1, int mon2, int mon3, int mon4, int mon5, int mon6, int location, int ave_type, int currMonth, int currYear, int BeginDay, int EndDay); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec_matchdsm2_a.java b/wrims-core/src/main/java/wrimsv2/external/Functionannec_matchdsm2_a.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionannec_matchdsm2_a.java rename to wrims-core/src/main/java/wrimsv2/external/Functionannec_matchdsm2_a.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionannlinegen.java b/wrims-core/src/main/java/wrimsv2/external/Functionannlinegen.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionannlinegen.java rename to wrims-core/src/main/java/wrimsv2/external/Functionannlinegen.java index 9da95052e..37db205ab 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionannlinegen.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functionannlinegen.java @@ -1,140 +1,140 @@ -package wrimsv2.external; - -import java.util.*; - -import wrimsv2.components.ControlData; - -public class Functionannlinegen extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functionannlinegen(){ - - } - - public void execute(Stack stack) { - - long t1 = Calendar.getInstance().getTimeInMillis(); - - //values in reverse order: - Object param52 = stack.pop(); - Object param51 = stack.pop(); - Object param50 = stack.pop(); - Object param49 = stack.pop(); - Object param48 = stack.pop(); - Object param47 = stack.pop(); - Object param46 = stack.pop(); - Object param45 = stack.pop(); - Object param44 = stack.pop(); - Object param43 = stack.pop(); - Object param42 = stack.pop(); - Object param41 = stack.pop(); - Object param40 = stack.pop(); - Object param39 = stack.pop(); - Object param38 = stack.pop(); - Object param37 = stack.pop(); - Object param36 = stack.pop(); - Object param35 = stack.pop(); - Object param34 = stack.pop(); - Object param33 = stack.pop(); - Object param32 = stack.pop(); - Object param31 = stack.pop(); - Object param30 = stack.pop(); - Object param29 = stack.pop(); - Object param28 = stack.pop(); - Object param27 = stack.pop(); - Object param26 = stack.pop(); - Object param25 = stack.pop(); - Object param24 = stack.pop(); - Object param23 = stack.pop(); - Object param22 = stack.pop(); - Object param21 = stack.pop(); - Object param20 = stack.pop(); - Object param19 = stack.pop(); - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int ForceOption = ((Number) param52).intValue(); - int currYear = ((Number) param51).intValue(); - int currMonth = ((Number) param50).intValue(); - int ave_type = ((Number) param49).intValue(); - int variable = ((Number) param48).intValue(); - int location = ((Number) param47).intValue(); - float linear2 = ((Number) param46).floatValue(); - float linear1 = ((Number) param45).floatValue(); - float ECTARGET = ((Number) param44).floatValue(); - int mon4 = ((Number) param43).intValue(); - int mon3 = ((Number) param42).intValue(); - int mon2 = ((Number) param41).intValue(); - int mon1 = ((Number) param40).intValue(); - int mon0 = ((Number) param39).intValue(); - float VernEC_fut = ((Number) param38).floatValue(); - float VernEC_prv3 = ((Number) param37).floatValue(); - float VernEC_prv2 = ((Number) param36).floatValue(); - float VernEC_prv1 = ((Number) param35).floatValue(); - float VernEC_prv0 = ((Number) param34).floatValue(); - float Qexp_oth_fut = ((Number) param33).floatValue(); - float Qexp_oth_prv3 = ((Number) param32).floatValue(); - float Qexp_oth_prv2 = ((Number) param31).floatValue(); - float Qexp_oth_prv1 = ((Number) param30).floatValue(); - float Qexp_oth_prv0 = ((Number) param29).floatValue(); - float Qsac_oth_fut = ((Number) param28).floatValue(); - float Qsac_oth_prv3 = ((Number) param27).floatValue(); - float Qsac_oth_prv2 = ((Number) param26).floatValue(); - float Qsac_oth_prv1 = ((Number) param25).floatValue(); - float Qsac_oth_prv0 = ((Number) param24).floatValue(); - float DICU_fut = ((Number) param23).floatValue(); - float DICU_prv3 = ((Number) param22).floatValue(); - float DICU_prv2 = ((Number) param21).floatValue(); - float DICU_prv1 = ((Number) param20).floatValue(); - float DICU_prv0 = ((Number) param19).floatValue(); - float DXC_fut = ((Number) param18).floatValue(); - float DXC_prv3 = ((Number) param17).floatValue(); - float DXC_prv2 = ((Number) param16).floatValue(); - float DXC_prv1 = ((Number) param15).floatValue(); - float DXC_prv0 = ((Number) param14).floatValue(); - float Qsjr_fut = ((Number) param13).floatValue(); - float Qsjr_prv3 = ((Number) param12).floatValue(); - float Qsjr_prv2 = ((Number) param11).floatValue(); - float Qsjr_prv1 = ((Number) param10).floatValue(); - float Qsjr_prv0 = ((Number) param9).floatValue(); - float Qexp_prv3 = ((Number) param8).floatValue(); - float Qexp_prv2 = ((Number) param7).floatValue(); - float Qexp_prv1 = ((Number) param6).floatValue(); - float Qexp_prv0 = ((Number) param5).floatValue(); - float Qsac_prv3 = ((Number) param4).floatValue(); - float Qsac_prv2 = ((Number) param3).floatValue(); - float Qsac_prv1 = ((Number) param2).floatValue(); - float Qsac_prv0 = ((Number) param1).floatValue(); - - float result = annlinegen(Qsac_prv0, Qsac_prv1, Qsac_prv2, Qsac_prv3, Qexp_prv0, Qexp_prv1, Qexp_prv2, Qexp_prv3, Qsjr_prv0, Qsjr_prv1, Qsjr_prv2, Qsjr_prv3, Qsjr_fut, DXC_prv0, DXC_prv1, DXC_prv2, DXC_prv3, DXC_fut, DICU_prv0, DICU_prv1, DICU_prv2, DICU_prv3, DICU_fut, Qsac_oth_prv0, Qsac_oth_prv1, Qsac_oth_prv2, Qsac_oth_prv3, Qsac_oth_fut, Qexp_oth_prv0, Qexp_oth_prv1, Qexp_oth_prv2, Qexp_oth_prv3, Qexp_oth_fut, VernEC_prv0, VernEC_prv1, VernEC_prv2, VernEC_prv3, VernEC_fut, mon0, mon1, mon2, mon3, mon4, ECTARGET, linear1, linear2, location, variable, ave_type, currMonth, currYear, ForceOption); - - // push the result on the Stack - stack.push(new Float(result)); - - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); - ControlData.t_annlinegen=ControlData.t_annlinegen+(int) (t2-t1); - ControlData.n_ann=ControlData.n_ann+1; - ControlData.n_annlinegen=ControlData.n_annlinegen+1; - } - - public native float annlinegen(float Qsac_prv0, float Qsac_prv1, float Qsac_prv2, float Qsac_prv3, float Qexp_prv0, float Qexp_prv1, float Qexp_prv2, float Qexp_prv3, float Qsjr_prv0, float Qsjr_prv1, float Qsjr_prv2, float Qsjr_prv3, float Qsjr_fut, float DXC_prv0, float DXC_prv1, float DXC_prv2, float DXC_prv3, float DXC_fut, float DICU_prv0, float DICU_prv1, float DICU_prv2, float DICU_prv3, float DICU_fut, float Qsac_oth_prv0, float Qsac_oth_prv1, float Qsac_oth_prv2, float Qsac_oth_prv3, float Qsac_oth_fut, float Qexp_oth_prv0, float Qexp_oth_prv1, float Qexp_oth_prv2, float Qexp_oth_prv3, float Qexp_oth_fut, float VernEC_prv0, float VernEC_prv1, float VernEC_prv2, float VernEC_prv3, float VernEC_fut, int mon0, int mon1, int mon2, int mon3, int mon4, float ECTARGET, float linear1, float linear2, int location, int variable, int ave_type, int currMonth, int currYear, int ForceOption); -} +package wrimsv2.external; + +import java.util.*; + +import wrimsv2.components.ControlData; + +public class Functionannlinegen extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functionannlinegen(){ + + } + + public void execute(Stack stack) { + + long t1 = Calendar.getInstance().getTimeInMillis(); + + //values in reverse order: + Object param52 = stack.pop(); + Object param51 = stack.pop(); + Object param50 = stack.pop(); + Object param49 = stack.pop(); + Object param48 = stack.pop(); + Object param47 = stack.pop(); + Object param46 = stack.pop(); + Object param45 = stack.pop(); + Object param44 = stack.pop(); + Object param43 = stack.pop(); + Object param42 = stack.pop(); + Object param41 = stack.pop(); + Object param40 = stack.pop(); + Object param39 = stack.pop(); + Object param38 = stack.pop(); + Object param37 = stack.pop(); + Object param36 = stack.pop(); + Object param35 = stack.pop(); + Object param34 = stack.pop(); + Object param33 = stack.pop(); + Object param32 = stack.pop(); + Object param31 = stack.pop(); + Object param30 = stack.pop(); + Object param29 = stack.pop(); + Object param28 = stack.pop(); + Object param27 = stack.pop(); + Object param26 = stack.pop(); + Object param25 = stack.pop(); + Object param24 = stack.pop(); + Object param23 = stack.pop(); + Object param22 = stack.pop(); + Object param21 = stack.pop(); + Object param20 = stack.pop(); + Object param19 = stack.pop(); + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int ForceOption = ((Number) param52).intValue(); + int currYear = ((Number) param51).intValue(); + int currMonth = ((Number) param50).intValue(); + int ave_type = ((Number) param49).intValue(); + int variable = ((Number) param48).intValue(); + int location = ((Number) param47).intValue(); + float linear2 = ((Number) param46).floatValue(); + float linear1 = ((Number) param45).floatValue(); + float ECTARGET = ((Number) param44).floatValue(); + int mon4 = ((Number) param43).intValue(); + int mon3 = ((Number) param42).intValue(); + int mon2 = ((Number) param41).intValue(); + int mon1 = ((Number) param40).intValue(); + int mon0 = ((Number) param39).intValue(); + float VernEC_fut = ((Number) param38).floatValue(); + float VernEC_prv3 = ((Number) param37).floatValue(); + float VernEC_prv2 = ((Number) param36).floatValue(); + float VernEC_prv1 = ((Number) param35).floatValue(); + float VernEC_prv0 = ((Number) param34).floatValue(); + float Qexp_oth_fut = ((Number) param33).floatValue(); + float Qexp_oth_prv3 = ((Number) param32).floatValue(); + float Qexp_oth_prv2 = ((Number) param31).floatValue(); + float Qexp_oth_prv1 = ((Number) param30).floatValue(); + float Qexp_oth_prv0 = ((Number) param29).floatValue(); + float Qsac_oth_fut = ((Number) param28).floatValue(); + float Qsac_oth_prv3 = ((Number) param27).floatValue(); + float Qsac_oth_prv2 = ((Number) param26).floatValue(); + float Qsac_oth_prv1 = ((Number) param25).floatValue(); + float Qsac_oth_prv0 = ((Number) param24).floatValue(); + float DICU_fut = ((Number) param23).floatValue(); + float DICU_prv3 = ((Number) param22).floatValue(); + float DICU_prv2 = ((Number) param21).floatValue(); + float DICU_prv1 = ((Number) param20).floatValue(); + float DICU_prv0 = ((Number) param19).floatValue(); + float DXC_fut = ((Number) param18).floatValue(); + float DXC_prv3 = ((Number) param17).floatValue(); + float DXC_prv2 = ((Number) param16).floatValue(); + float DXC_prv1 = ((Number) param15).floatValue(); + float DXC_prv0 = ((Number) param14).floatValue(); + float Qsjr_fut = ((Number) param13).floatValue(); + float Qsjr_prv3 = ((Number) param12).floatValue(); + float Qsjr_prv2 = ((Number) param11).floatValue(); + float Qsjr_prv1 = ((Number) param10).floatValue(); + float Qsjr_prv0 = ((Number) param9).floatValue(); + float Qexp_prv3 = ((Number) param8).floatValue(); + float Qexp_prv2 = ((Number) param7).floatValue(); + float Qexp_prv1 = ((Number) param6).floatValue(); + float Qexp_prv0 = ((Number) param5).floatValue(); + float Qsac_prv3 = ((Number) param4).floatValue(); + float Qsac_prv2 = ((Number) param3).floatValue(); + float Qsac_prv1 = ((Number) param2).floatValue(); + float Qsac_prv0 = ((Number) param1).floatValue(); + + float result = annlinegen(Qsac_prv0, Qsac_prv1, Qsac_prv2, Qsac_prv3, Qexp_prv0, Qexp_prv1, Qexp_prv2, Qexp_prv3, Qsjr_prv0, Qsjr_prv1, Qsjr_prv2, Qsjr_prv3, Qsjr_fut, DXC_prv0, DXC_prv1, DXC_prv2, DXC_prv3, DXC_fut, DICU_prv0, DICU_prv1, DICU_prv2, DICU_prv3, DICU_fut, Qsac_oth_prv0, Qsac_oth_prv1, Qsac_oth_prv2, Qsac_oth_prv3, Qsac_oth_fut, Qexp_oth_prv0, Qexp_oth_prv1, Qexp_oth_prv2, Qexp_oth_prv3, Qexp_oth_fut, VernEC_prv0, VernEC_prv1, VernEC_prv2, VernEC_prv3, VernEC_fut, mon0, mon1, mon2, mon3, mon4, ECTARGET, linear1, linear2, location, variable, ave_type, currMonth, currYear, ForceOption); + + // push the result on the Stack + stack.push(new Float(result)); + + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); + ControlData.t_annlinegen=ControlData.t_annlinegen+(int) (t2-t1); + ControlData.n_ann=ControlData.n_ann+1; + ControlData.n_annlinegen=ControlData.n_annlinegen+1; + } + + public native float annlinegen(float Qsac_prv0, float Qsac_prv1, float Qsac_prv2, float Qsac_prv3, float Qexp_prv0, float Qexp_prv1, float Qexp_prv2, float Qexp_prv3, float Qsjr_prv0, float Qsjr_prv1, float Qsjr_prv2, float Qsjr_prv3, float Qsjr_fut, float DXC_prv0, float DXC_prv1, float DXC_prv2, float DXC_prv3, float DXC_fut, float DICU_prv0, float DICU_prv1, float DICU_prv2, float DICU_prv3, float DICU_fut, float Qsac_oth_prv0, float Qsac_oth_prv1, float Qsac_oth_prv2, float Qsac_oth_prv3, float Qsac_oth_fut, float Qexp_oth_prv0, float Qexp_oth_prv1, float Qexp_oth_prv2, float Qexp_oth_prv3, float Qexp_oth_fut, float VernEC_prv0, float VernEC_prv1, float VernEC_prv2, float VernEC_prv3, float VernEC_fut, int mon0, int mon1, int mon2, int mon3, int mon4, float ECTARGET, float linear1, float linear2, int location, int variable, int ave_type, int currMonth, int currYear, int ForceOption); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionannlinegen_a.java b/wrims-core/src/main/java/wrimsv2/external/Functionannlinegen_a.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionannlinegen_a.java rename to wrims-core/src/main/java/wrimsv2/external/Functionannlinegen_a.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionannlinegen_daily.java b/wrims-core/src/main/java/wrimsv2/external/Functionannlinegen_daily.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionannlinegen_daily.java rename to wrims-core/src/main/java/wrimsv2/external/Functionannlinegen_daily.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functioncamdll.java b/wrims-core/src/main/java/wrimsv2/external/Functioncamdll.java similarity index 98% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functioncamdll.java rename to wrims-core/src/main/java/wrimsv2/external/Functioncamdll.java index f590d02e7..ca4b8acff 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functioncamdll.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functioncamdll.java @@ -1,449 +1,449 @@ -package wrimsv2.external; - -import java.util.*; - -import wrimsv2.components.ControlData; - -public class Functioncamdll extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functioncamdll(){ - - } - - public void execute(Stack stack) { - - long t1 = Calendar.getInstance().getTimeInMillis(); - - if (stack.size()==2){ - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - int ICODE = ((Number) param2).intValue(); - int ICALC = ((Number) param1).intValue(); - - float result = camdll(ICALC, ICODE, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0); - - // push the result on the Stack - stack.push(new Float(result)); - }else{ - //values in reverse order: - Object param201 = stack.pop(); - Object param200 = stack.pop(); - Object param199 = stack.pop(); - Object param198 = stack.pop(); - Object param197 = stack.pop(); - Object param196 = stack.pop(); - Object param195 = stack.pop(); - Object param194 = stack.pop(); - Object param193 = stack.pop(); - Object param192 = stack.pop(); - Object param191 = stack.pop(); - Object param190 = stack.pop(); - Object param189 = stack.pop(); - Object param188 = stack.pop(); - Object param187 = stack.pop(); - Object param186 = stack.pop(); - Object param185 = stack.pop(); - Object param184 = stack.pop(); - Object param183 = stack.pop(); - Object param182 = stack.pop(); - Object param181 = stack.pop(); - Object param180 = stack.pop(); - Object param179 = stack.pop(); - Object param178 = stack.pop(); - Object param177 = stack.pop(); - Object param176 = stack.pop(); - Object param175 = stack.pop(); - Object param174 = stack.pop(); - Object param173 = stack.pop(); - Object param172 = stack.pop(); - Object param171 = stack.pop(); - Object param170 = stack.pop(); - Object param169 = stack.pop(); - Object param168 = stack.pop(); - Object param167 = stack.pop(); - Object param166 = stack.pop(); - Object param165 = stack.pop(); - Object param164 = stack.pop(); - Object param163 = stack.pop(); - Object param162 = stack.pop(); - Object param161 = stack.pop(); - Object param160 = stack.pop(); - Object param159 = stack.pop(); - Object param158 = stack.pop(); - Object param157 = stack.pop(); - Object param156 = stack.pop(); - Object param155 = stack.pop(); - Object param154 = stack.pop(); - Object param153 = stack.pop(); - Object param152 = stack.pop(); - Object param151 = stack.pop(); - Object param150 = stack.pop(); - Object param149 = stack.pop(); - Object param148 = stack.pop(); - Object param147 = stack.pop(); - Object param146 = stack.pop(); - Object param145 = stack.pop(); - Object param144 = stack.pop(); - Object param143 = stack.pop(); - Object param142 = stack.pop(); - Object param141 = stack.pop(); - Object param140 = stack.pop(); - Object param139 = stack.pop(); - Object param138 = stack.pop(); - Object param137 = stack.pop(); - Object param136 = stack.pop(); - Object param135 = stack.pop(); - Object param134 = stack.pop(); - Object param133 = stack.pop(); - Object param132 = stack.pop(); - Object param131 = stack.pop(); - Object param130 = stack.pop(); - Object param129 = stack.pop(); - Object param128 = stack.pop(); - Object param127 = stack.pop(); - Object param126 = stack.pop(); - Object param125 = stack.pop(); - Object param124 = stack.pop(); - Object param123 = stack.pop(); - Object param122 = stack.pop(); - Object param121 = stack.pop(); - Object param120 = stack.pop(); - Object param119 = stack.pop(); - Object param118 = stack.pop(); - Object param117 = stack.pop(); - Object param116 = stack.pop(); - Object param115 = stack.pop(); - Object param114 = stack.pop(); - Object param113 = stack.pop(); - Object param112 = stack.pop(); - Object param111 = stack.pop(); - Object param110 = stack.pop(); - Object param109 = stack.pop(); - Object param108 = stack.pop(); - Object param107 = stack.pop(); - Object param106 = stack.pop(); - Object param105 = stack.pop(); - Object param104 = stack.pop(); - Object param103 = stack.pop(); - Object param102 = stack.pop(); - Object param101 = stack.pop(); - Object param100 = stack.pop(); - Object param99 = stack.pop(); - Object param98 = stack.pop(); - Object param97 = stack.pop(); - Object param96 = stack.pop(); - Object param95 = stack.pop(); - Object param94 = stack.pop(); - Object param93 = stack.pop(); - Object param92 = stack.pop(); - Object param91 = stack.pop(); - Object param90 = stack.pop(); - Object param89 = stack.pop(); - Object param88 = stack.pop(); - Object param87 = stack.pop(); - Object param86 = stack.pop(); - Object param85 = stack.pop(); - Object param84 = stack.pop(); - Object param83 = stack.pop(); - Object param82 = stack.pop(); - Object param81 = stack.pop(); - Object param80 = stack.pop(); - Object param79 = stack.pop(); - Object param78 = stack.pop(); - Object param77 = stack.pop(); - Object param76 = stack.pop(); - Object param75 = stack.pop(); - Object param74 = stack.pop(); - Object param73 = stack.pop(); - Object param72 = stack.pop(); - Object param71 = stack.pop(); - Object param70 = stack.pop(); - Object param69 = stack.pop(); - Object param68 = stack.pop(); - Object param67 = stack.pop(); - Object param66 = stack.pop(); - Object param65 = stack.pop(); - Object param64 = stack.pop(); - Object param63 = stack.pop(); - Object param62 = stack.pop(); - Object param61 = stack.pop(); - Object param60 = stack.pop(); - Object param59 = stack.pop(); - Object param58 = stack.pop(); - Object param57 = stack.pop(); - Object param56 = stack.pop(); - Object param55 = stack.pop(); - Object param54 = stack.pop(); - Object param53 = stack.pop(); - Object param52 = stack.pop(); - Object param51 = stack.pop(); - Object param50 = stack.pop(); - Object param49 = stack.pop(); - Object param48 = stack.pop(); - Object param47 = stack.pop(); - Object param46 = stack.pop(); - Object param45 = stack.pop(); - Object param44 = stack.pop(); - Object param43 = stack.pop(); - Object param42 = stack.pop(); - Object param41 = stack.pop(); - Object param40 = stack.pop(); - Object param39 = stack.pop(); - Object param38 = stack.pop(); - Object param37 = stack.pop(); - Object param36 = stack.pop(); - Object param35 = stack.pop(); - Object param34 = stack.pop(); - Object param33 = stack.pop(); - Object param32 = stack.pop(); - Object param31 = stack.pop(); - Object param30 = stack.pop(); - Object param29 = stack.pop(); - Object param28 = stack.pop(); - Object param27 = stack.pop(); - Object param26 = stack.pop(); - Object param25 = stack.pop(); - Object param24 = stack.pop(); - Object param23 = stack.pop(); - Object param22 = stack.pop(); - Object param21 = stack.pop(); - Object param20 = stack.pop(); - Object param19 = stack.pop(); - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - float PSH_1_12 = ((Number) param201).floatValue(); - float PSH_1_11 = ((Number) param200).floatValue(); - float PSH_1_10 = ((Number) param199).floatValue(); - float PSH_0_4 = ((Number) param198).floatValue(); - float PSH_0_3 = ((Number) param197).floatValue(); - float PSH_0_2 = ((Number) param196).floatValue(); - float PSH_0_1 = ((Number) param195).floatValue(); - float PYU_1_12 = ((Number) param194).floatValue(); - float PYU_1_11 = ((Number) param193).floatValue(); - float PYU_1_10 = ((Number) param192).floatValue(); - float PYU_0_4 = ((Number) param191).floatValue(); - float PYU_0_3 = ((Number) param190).floatValue(); - float PYU_0_2 = ((Number) param189).floatValue(); - float PYU_0_1 = ((Number) param188).floatValue(); - float PFO_1_12 = ((Number) param187).floatValue(); - float PFO_1_11 = ((Number) param186).floatValue(); - float PFO_1_10 = ((Number) param185).floatValue(); - float PFO_0_4 = ((Number) param184).floatValue(); - float PFO_0_3 = ((Number) param183).floatValue(); - float PFO_0_2 = ((Number) param182).floatValue(); - float PFO_0_1 = ((Number) param181).floatValue(); - float POR_1_12 = ((Number) param180).floatValue(); - float POR_1_11 = ((Number) param179).floatValue(); - float POR_1_10 = ((Number) param178).floatValue(); - float POR_0_4 = ((Number) param177).floatValue(); - float POR_0_3 = ((Number) param176).floatValue(); - float POR_0_2 = ((Number) param175).floatValue(); - float POR_0_1 = ((Number) param174).floatValue(); - float QBD_1_12 = ((Number) param173).floatValue(); - float QBD_1_11 = ((Number) param172).floatValue(); - float QBD_1_10 = ((Number) param171).floatValue(); - float QBD_0_4 = ((Number) param170).floatValue(); - float QBD_0_3 = ((Number) param169).floatValue(); - float QBD_0_2 = ((Number) param168).floatValue(); - float QBD_0_1 = ((Number) param167).floatValue(); - float QSH_1_12 = ((Number) param166).floatValue(); - float QSH_1_11 = ((Number) param165).floatValue(); - float QSH_1_10 = ((Number) param164).floatValue(); - float QSH_0_4 = ((Number) param163).floatValue(); - float QSH_0_3 = ((Number) param162).floatValue(); - float QSH_0_2 = ((Number) param161).floatValue(); - float QSH_0_1 = ((Number) param160).floatValue(); - float QYU_1_12 = ((Number) param159).floatValue(); - float QYU_1_11 = ((Number) param158).floatValue(); - float QYU_1_10 = ((Number) param157).floatValue(); - float QYU_0_4 = ((Number) param156).floatValue(); - float QYU_0_3 = ((Number) param155).floatValue(); - float QYU_0_2 = ((Number) param154).floatValue(); - float QYU_0_1 = ((Number) param153).floatValue(); - float QFO_1_12 = ((Number) param152).floatValue(); - float QFO_1_11 = ((Number) param151).floatValue(); - float QFO_1_10 = ((Number) param150).floatValue(); - float QFO_0_4 = ((Number) param149).floatValue(); - float QFO_0_3 = ((Number) param148).floatValue(); - float QFO_0_2 = ((Number) param147).floatValue(); - float QFO_0_1 = ((Number) param146).floatValue(); - float QOR_2_12 = ((Number) param145).floatValue(); - float QOR_2_11 = ((Number) param144).floatValue(); - float QOR_2_10 = ((Number) param143).floatValue(); - float QOR_1_12 = ((Number) param142).floatValue(); - float QOR_1_11 = ((Number) param141).floatValue(); - float QOR_1_10 = ((Number) param140).floatValue(); - float QOR_1_9 = ((Number) param139).floatValue(); - float QOR_1_8 = ((Number) param138).floatValue(); - float QOR_1_7 = ((Number) param137).floatValue(); - float QOR_1_6 = ((Number) param136).floatValue(); - float QOR_1_5 = ((Number) param135).floatValue(); - float QOR_1_4 = ((Number) param134).floatValue(); - float QOR_1_3 = ((Number) param133).floatValue(); - float QOR_1_2 = ((Number) param132).floatValue(); - float QOR_1_1 = ((Number) param131).floatValue(); - float QOR_0_4 = ((Number) param130).floatValue(); - float QOR_0_3 = ((Number) param129).floatValue(); - float QOR_0_2 = ((Number) param128).floatValue(); - float QOR_0_1 = ((Number) param127).floatValue(); - float SQNB_2_12 = ((Number) param126).floatValue(); - float SQNB_2_11 = ((Number) param125).floatValue(); - float SQNB_2_10 = ((Number) param124).floatValue(); - float SQNB_1_12 = ((Number) param123).floatValue(); - float SQNB_1_11 = ((Number) param122).floatValue(); - float SQNB_1_10 = ((Number) param121).floatValue(); - float SQNB_1_9 = ((Number) param120).floatValue(); - float SQNB_1_8 = ((Number) param119).floatValue(); - float SQNB_1_7 = ((Number) param118).floatValue(); - float SQNB_1_6 = ((Number) param117).floatValue(); - float SQNB_1_5 = ((Number) param116).floatValue(); - float SQNB_1_4 = ((Number) param115).floatValue(); - float SQNB_1_3 = ((Number) param114).floatValue(); - float SQNB_1_2 = ((Number) param113).floatValue(); - float SQNB_1_1 = ((Number) param112).floatValue(); - float SQNB_0_4 = ((Number) param111).floatValue(); - float SQNB_0_3 = ((Number) param110).floatValue(); - float SQNB_0_2 = ((Number) param109).floatValue(); - float SQNB_0_1 = ((Number) param108).floatValue(); - float SQSW_2_12 = ((Number) param107).floatValue(); - float SQSW_2_11 = ((Number) param106).floatValue(); - float SQSW_2_10 = ((Number) param105).floatValue(); - float SQSW_1_12 = ((Number) param104).floatValue(); - float SQSW_1_11 = ((Number) param103).floatValue(); - float SQSW_1_10 = ((Number) param102).floatValue(); - float SQSW_1_9 = ((Number) param101).floatValue(); - float SQSW_1_8 = ((Number) param100).floatValue(); - float SQSW_1_7 = ((Number) param99).floatValue(); - float SQSW_1_6 = ((Number) param98).floatValue(); - float SQSW_1_5 = ((Number) param97).floatValue(); - float SQSW_1_4 = ((Number) param96).floatValue(); - float SQSW_1_3 = ((Number) param95).floatValue(); - float SQSW_1_2 = ((Number) param94).floatValue(); - float SQSW_1_1 = ((Number) param93).floatValue(); - float SQSW_0_4 = ((Number) param92).floatValue(); - float SQSW_0_3 = ((Number) param91).floatValue(); - float SQSW_0_2 = ((Number) param90).floatValue(); - float SQSW_0_1 = ((Number) param89).floatValue(); - float SQFP_2_12 = ((Number) param88).floatValue(); - float SQFP_2_11 = ((Number) param87).floatValue(); - float SQFP_2_10 = ((Number) param86).floatValue(); - float SQFP_1_12 = ((Number) param85).floatValue(); - float SQFP_1_11 = ((Number) param84).floatValue(); - float SQFP_1_10 = ((Number) param83).floatValue(); - float SQFP_1_9 = ((Number) param82).floatValue(); - float SQFP_1_8 = ((Number) param81).floatValue(); - float SQFP_1_7 = ((Number) param80).floatValue(); - float SQFP_1_6 = ((Number) param79).floatValue(); - float SQFP_1_5 = ((Number) param78).floatValue(); - float SQFP_1_4 = ((Number) param77).floatValue(); - float SQFP_1_3 = ((Number) param76).floatValue(); - float SQFP_1_2 = ((Number) param75).floatValue(); - float SQFP_1_1 = ((Number) param74).floatValue(); - float SQFP_0_4 = ((Number) param73).floatValue(); - float SQFP_0_3 = ((Number) param72).floatValue(); - float SQFP_0_2 = ((Number) param71).floatValue(); - float SQFP_0_1 = ((Number) param70).floatValue(); - float SQFW_2_12 = ((Number) param69).floatValue(); - float SQFW_2_11 = ((Number) param68).floatValue(); - float SQFW_2_10 = ((Number) param67).floatValue(); - float SQFW_1_12 = ((Number) param66).floatValue(); - float SQFW_1_11 = ((Number) param65).floatValue(); - float SQFW_1_10 = ((Number) param64).floatValue(); - float SQFW_1_9 = ((Number) param63).floatValue(); - float SQFW_1_8 = ((Number) param62).floatValue(); - float SQFW_1_7 = ((Number) param61).floatValue(); - float SQFW_1_6 = ((Number) param60).floatValue(); - float SQFW_1_5 = ((Number) param59).floatValue(); - float SQFW_1_4 = ((Number) param58).floatValue(); - float SQFW_1_3 = ((Number) param57).floatValue(); - float SQFW_1_2 = ((Number) param56).floatValue(); - float SQFW_1_1 = ((Number) param55).floatValue(); - float SQFW_0_4 = ((Number) param54).floatValue(); - float SQFW_0_3 = ((Number) param53).floatValue(); - float SQFW_0_2 = ((Number) param52).floatValue(); - float SQFW_0_1 = ((Number) param51).floatValue(); - float SQOR_2_12 = ((Number) param50).floatValue(); - float SQOR_2_11 = ((Number) param49).floatValue(); - float SQOR_2_10 = ((Number) param48).floatValue(); - float SQOR_1_12 = ((Number) param47).floatValue(); - float SQOR_1_11 = ((Number) param46).floatValue(); - float SQOR_1_10 = ((Number) param45).floatValue(); - float SQOR_1_9 = ((Number) param44).floatValue(); - float SQOR_1_8 = ((Number) param43).floatValue(); - float SQOR_1_7 = ((Number) param42).floatValue(); - float SQOR_1_6 = ((Number) param41).floatValue(); - float SQOR_1_5 = ((Number) param40).floatValue(); - float SQOR_1_4 = ((Number) param39).floatValue(); - float SQOR_1_3 = ((Number) param38).floatValue(); - float SQOR_1_2 = ((Number) param37).floatValue(); - float SQOR_1_1 = ((Number) param36).floatValue(); - float SQOR_0_4 = ((Number) param35).floatValue(); - float SQOR_0_3 = ((Number) param34).floatValue(); - float SQOR_0_2 = ((Number) param33).floatValue(); - float SQOR_0_1 = ((Number) param32).floatValue(); - float SQKS_2_12 = ((Number) param31).floatValue(); - float SQKS_2_11 = ((Number) param30).floatValue(); - float SQKS_2_10 = ((Number) param29).floatValue(); - float SQKS_1_12 = ((Number) param28).floatValue(); - float SQKS_1_11 = ((Number) param27).floatValue(); - float SQKS_1_10 = ((Number) param26).floatValue(); - float SQKS_1_9 = ((Number) param25).floatValue(); - float SQKS_1_8 = ((Number) param24).floatValue(); - float SQKS_1_7 = ((Number) param23).floatValue(); - float SQKS_1_6 = ((Number) param22).floatValue(); - float SQKS_1_5 = ((Number) param21).floatValue(); - float SQKS_1_4 = ((Number) param20).floatValue(); - float SQKS_1_3 = ((Number) param19).floatValue(); - float SQKS_1_2 = ((Number) param18).floatValue(); - float SQKS_1_1 = ((Number) param17).floatValue(); - float SQKS_0_4 = ((Number) param16).floatValue(); - float SQKS_0_3 = ((Number) param15).floatValue(); - float SQKS_0_2 = ((Number) param14).floatValue(); - float SQKS_0_1 = ((Number) param13).floatValue(); - float IFREQ5X = ((Number) param12).floatValue(); - float IFREQ4X = ((Number) param11).floatValue(); - float IFREQ3X = ((Number) param10).floatValue(); - float IFREQ2X = ((Number) param9).floatValue(); - float IFREQ1X = ((Number) param8).floatValue(); - float IFREQODX = ((Number) param7).floatValue(); - float IMX = ((Number) param6).floatValue(); - float IYEARX = ((Number) param5).floatValue(); - float IMPOSX = ((Number) param4).floatValue(); - float IYPOSX = ((Number) param3).floatValue(); - int ICODE = ((Number) param2).intValue(); - int ICALC = ((Number) param1).intValue(); - - float result = camdll(ICALC, ICODE, IYPOSX, IMPOSX, IYEARX, IMX, IFREQODX, IFREQ1X, IFREQ2X, IFREQ3X, IFREQ4X, IFREQ5X, SQKS_0_1, SQKS_0_2, SQKS_0_3, SQKS_0_4, SQKS_1_1, SQKS_1_2, SQKS_1_3, SQKS_1_4, SQKS_1_5, SQKS_1_6, SQKS_1_7, SQKS_1_8, SQKS_1_9, SQKS_1_10, SQKS_1_11, SQKS_1_12, SQKS_2_10, SQKS_2_11, SQKS_2_12, SQOR_0_1, SQOR_0_2, SQOR_0_3, SQOR_0_4, SQOR_1_1, SQOR_1_2, SQOR_1_3, SQOR_1_4, SQOR_1_5, SQOR_1_6, SQOR_1_7, SQOR_1_8, SQOR_1_9, SQOR_1_10, SQOR_1_11, SQOR_1_12, SQOR_2_10, SQOR_2_11, SQOR_2_12, SQFW_0_1, SQFW_0_2, SQFW_0_3, SQFW_0_4, SQFW_1_1, SQFW_1_2, SQFW_1_3, SQFW_1_4, SQFW_1_5, SQFW_1_6, SQFW_1_7, SQFW_1_8, SQFW_1_9, SQFW_1_10, SQFW_1_11, SQFW_1_12, SQFW_2_10, SQFW_2_11, SQFW_2_12, SQFP_0_1, SQFP_0_2, SQFP_0_3, SQFP_0_4, SQFP_1_1, SQFP_1_2, SQFP_1_3, SQFP_1_4, SQFP_1_5, SQFP_1_6, SQFP_1_7, SQFP_1_8, SQFP_1_9, SQFP_1_10, SQFP_1_11, SQFP_1_12, SQFP_2_10, SQFP_2_11, SQFP_2_12, SQSW_0_1, SQSW_0_2, SQSW_0_3, SQSW_0_4, SQSW_1_1, SQSW_1_2, SQSW_1_3, SQSW_1_4, SQSW_1_5, SQSW_1_6, SQSW_1_7, SQSW_1_8, SQSW_1_9, SQSW_1_10, SQSW_1_11, SQSW_1_12, SQSW_2_10, SQSW_2_11, SQSW_2_12, SQNB_0_1, SQNB_0_2, SQNB_0_3, SQNB_0_4, SQNB_1_1, SQNB_1_2, SQNB_1_3, SQNB_1_4, SQNB_1_5, SQNB_1_6, SQNB_1_7, SQNB_1_8, SQNB_1_9, SQNB_1_10, SQNB_1_11, SQNB_1_12, SQNB_2_10, SQNB_2_11, SQNB_2_12, QOR_0_1, QOR_0_2, QOR_0_3, QOR_0_4, QOR_1_1, QOR_1_2, QOR_1_3, QOR_1_4, QOR_1_5, QOR_1_6, QOR_1_7, QOR_1_8, QOR_1_9, QOR_1_10, QOR_1_11, QOR_1_12, QOR_2_10, QOR_2_11, QOR_2_12, QFO_0_1, QFO_0_2, QFO_0_3, QFO_0_4, QFO_1_10, QFO_1_11, QFO_1_12, QYU_0_1, QYU_0_2, QYU_0_3, QYU_0_4, QYU_1_10, QYU_1_11, QYU_1_12, QSH_0_1, QSH_0_2, QSH_0_3, QSH_0_4, QSH_1_10, QSH_1_11, QSH_1_12, QBD_0_1, QBD_0_2, QBD_0_3, QBD_0_4, QBD_1_10, QBD_1_11, QBD_1_12, POR_0_1, POR_0_2, POR_0_3, POR_0_4, POR_1_10, POR_1_11, POR_1_12, PFO_0_1, PFO_0_2, PFO_0_3, PFO_0_4, PFO_1_10, PFO_1_11, PFO_1_12, PYU_0_1, PYU_0_2, PYU_0_3, PYU_0_4, PYU_1_10, PYU_1_11, PYU_1_12, PSH_0_1, PSH_0_2, PSH_0_3, PSH_0_4, PSH_1_10, PSH_1_11, PSH_1_12); - - // push the result on the Stack - stack.push(new Float(result)); - - } - - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_cam=ControlData.t_cam+(int) (t2-t1); - } - - public native float camdll(int ICALC, int ICODE, float IYPOSX, float IMPOSX, float IYEARX, float IMX, float IFREQODX, float IFREQ1X, float IFREQ2X, float IFREQ3X, float IFREQ4X, float IFREQ5X, float SQKS_0_1, float SQKS_0_2, float SQKS_0_3, float SQKS_0_4, float SQKS_1_1, float SQKS_1_2, float SQKS_1_3, float SQKS_1_4, float SQKS_1_5, float SQKS_1_6, float SQKS_1_7, float SQKS_1_8, float SQKS_1_9, float SQKS_1_10, float SQKS_1_11, float SQKS_1_12, float SQKS_2_10, float SQKS_2_11, float SQKS_2_12, float SQOR_0_1, float SQOR_0_2, float SQOR_0_3, float SQOR_0_4, float SQOR_1_1, float SQOR_1_2, float SQOR_1_3, float SQOR_1_4, float SQOR_1_5, float SQOR_1_6, float SQOR_1_7, float SQOR_1_8, float SQOR_1_9, float SQOR_1_10, float SQOR_1_11, float SQOR_1_12, float SQOR_2_10, float SQOR_2_11, float SQOR_2_12, float SQFW_0_1, float SQFW_0_2, float SQFW_0_3, float SQFW_0_4, float SQFW_1_1, float SQFW_1_2, float SQFW_1_3, float SQFW_1_4, float SQFW_1_5, float SQFW_1_6, float SQFW_1_7, float SQFW_1_8, float SQFW_1_9, float SQFW_1_10, float SQFW_1_11, float SQFW_1_12, float SQFW_2_10, float SQFW_2_11, float SQFW_2_12, float SQFP_0_1, float SQFP_0_2, float SQFP_0_3, float SQFP_0_4, float SQFP_1_1, float SQFP_1_2, float SQFP_1_3, float SQFP_1_4, float SQFP_1_5, float SQFP_1_6, float SQFP_1_7, float SQFP_1_8, float SQFP_1_9, float SQFP_1_10, float SQFP_1_11, float SQFP_1_12, float SQFP_2_10, float SQFP_2_11, float SQFP_2_12, float SQSW_0_1, float SQSW_0_2, float SQSW_0_3, float SQSW_0_4, float SQSW_1_1, float SQSW_1_2, float SQSW_1_3, float SQSW_1_4, float SQSW_1_5, float SQSW_1_6, float SQSW_1_7, float SQSW_1_8, float SQSW_1_9, float SQSW_1_10, float SQSW_1_11, float SQSW_1_12, float SQSW_2_10, float SQSW_2_11, float SQSW_2_12, float SQNB_0_1, float SQNB_0_2, float SQNB_0_3, float SQNB_0_4, float SQNB_1_1, float SQNB_1_2, float SQNB_1_3, float SQNB_1_4, float SQNB_1_5, float SQNB_1_6, float SQNB_1_7, float SQNB_1_8, float SQNB_1_9, float SQNB_1_10, float SQNB_1_11, float SQNB_1_12, float SQNB_2_10, float SQNB_2_11, float SQNB_2_12, float QOR_0_1, float QOR_0_2, float QOR_0_3, float QOR_0_4, float QOR_1_1, float QOR_1_2, float QOR_1_3, float QOR_1_4, float QOR_1_5, float QOR_1_6, float QOR_1_7, float QOR_1_8, float QOR_1_9, float QOR_1_10, float QOR_1_11, float QOR_1_12, float QOR_2_10, float QOR_2_11, float QOR_2_12, float QFO_0_1, float QFO_0_2, float QFO_0_3, float QFO_0_4, float QFO_1_10, float QFO_1_11, float QFO_1_12, float QYU_0_1, float QYU_0_2, float QYU_0_3, float QYU_0_4, float QYU_1_10, float QYU_1_11, float QYU_1_12, float QSH_0_1, float QSH_0_2, float QSH_0_3, float QSH_0_4, float QSH_1_10, float QSH_1_11, float QSH_1_12, float QBD_0_1, float QBD_0_2, float QBD_0_3, float QBD_0_4, float QBD_1_10, float QBD_1_11, float QBD_1_12, float POR_0_1, float POR_0_2, float POR_0_3, float POR_0_4, float POR_1_10, float POR_1_11, float POR_1_12, float PFO_0_1, float PFO_0_2, float PFO_0_3, float PFO_0_4, float PFO_1_10, float PFO_1_11, float PFO_1_12, float PYU_0_1, float PYU_0_2, float PYU_0_3, float PYU_0_4, float PYU_1_10, float PYU_1_11, float PYU_1_12, float PSH_0_1, float PSH_0_2, float PSH_0_3, float PSH_0_4, float PSH_1_10, float PSH_1_11, float PSH_1_12); -} +package wrimsv2.external; + +import java.util.*; + +import wrimsv2.components.ControlData; + +public class Functioncamdll extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functioncamdll(){ + + } + + public void execute(Stack stack) { + + long t1 = Calendar.getInstance().getTimeInMillis(); + + if (stack.size()==2){ + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + int ICODE = ((Number) param2).intValue(); + int ICALC = ((Number) param1).intValue(); + + float result = camdll(ICALC, ICODE, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0); + + // push the result on the Stack + stack.push(new Float(result)); + }else{ + //values in reverse order: + Object param201 = stack.pop(); + Object param200 = stack.pop(); + Object param199 = stack.pop(); + Object param198 = stack.pop(); + Object param197 = stack.pop(); + Object param196 = stack.pop(); + Object param195 = stack.pop(); + Object param194 = stack.pop(); + Object param193 = stack.pop(); + Object param192 = stack.pop(); + Object param191 = stack.pop(); + Object param190 = stack.pop(); + Object param189 = stack.pop(); + Object param188 = stack.pop(); + Object param187 = stack.pop(); + Object param186 = stack.pop(); + Object param185 = stack.pop(); + Object param184 = stack.pop(); + Object param183 = stack.pop(); + Object param182 = stack.pop(); + Object param181 = stack.pop(); + Object param180 = stack.pop(); + Object param179 = stack.pop(); + Object param178 = stack.pop(); + Object param177 = stack.pop(); + Object param176 = stack.pop(); + Object param175 = stack.pop(); + Object param174 = stack.pop(); + Object param173 = stack.pop(); + Object param172 = stack.pop(); + Object param171 = stack.pop(); + Object param170 = stack.pop(); + Object param169 = stack.pop(); + Object param168 = stack.pop(); + Object param167 = stack.pop(); + Object param166 = stack.pop(); + Object param165 = stack.pop(); + Object param164 = stack.pop(); + Object param163 = stack.pop(); + Object param162 = stack.pop(); + Object param161 = stack.pop(); + Object param160 = stack.pop(); + Object param159 = stack.pop(); + Object param158 = stack.pop(); + Object param157 = stack.pop(); + Object param156 = stack.pop(); + Object param155 = stack.pop(); + Object param154 = stack.pop(); + Object param153 = stack.pop(); + Object param152 = stack.pop(); + Object param151 = stack.pop(); + Object param150 = stack.pop(); + Object param149 = stack.pop(); + Object param148 = stack.pop(); + Object param147 = stack.pop(); + Object param146 = stack.pop(); + Object param145 = stack.pop(); + Object param144 = stack.pop(); + Object param143 = stack.pop(); + Object param142 = stack.pop(); + Object param141 = stack.pop(); + Object param140 = stack.pop(); + Object param139 = stack.pop(); + Object param138 = stack.pop(); + Object param137 = stack.pop(); + Object param136 = stack.pop(); + Object param135 = stack.pop(); + Object param134 = stack.pop(); + Object param133 = stack.pop(); + Object param132 = stack.pop(); + Object param131 = stack.pop(); + Object param130 = stack.pop(); + Object param129 = stack.pop(); + Object param128 = stack.pop(); + Object param127 = stack.pop(); + Object param126 = stack.pop(); + Object param125 = stack.pop(); + Object param124 = stack.pop(); + Object param123 = stack.pop(); + Object param122 = stack.pop(); + Object param121 = stack.pop(); + Object param120 = stack.pop(); + Object param119 = stack.pop(); + Object param118 = stack.pop(); + Object param117 = stack.pop(); + Object param116 = stack.pop(); + Object param115 = stack.pop(); + Object param114 = stack.pop(); + Object param113 = stack.pop(); + Object param112 = stack.pop(); + Object param111 = stack.pop(); + Object param110 = stack.pop(); + Object param109 = stack.pop(); + Object param108 = stack.pop(); + Object param107 = stack.pop(); + Object param106 = stack.pop(); + Object param105 = stack.pop(); + Object param104 = stack.pop(); + Object param103 = stack.pop(); + Object param102 = stack.pop(); + Object param101 = stack.pop(); + Object param100 = stack.pop(); + Object param99 = stack.pop(); + Object param98 = stack.pop(); + Object param97 = stack.pop(); + Object param96 = stack.pop(); + Object param95 = stack.pop(); + Object param94 = stack.pop(); + Object param93 = stack.pop(); + Object param92 = stack.pop(); + Object param91 = stack.pop(); + Object param90 = stack.pop(); + Object param89 = stack.pop(); + Object param88 = stack.pop(); + Object param87 = stack.pop(); + Object param86 = stack.pop(); + Object param85 = stack.pop(); + Object param84 = stack.pop(); + Object param83 = stack.pop(); + Object param82 = stack.pop(); + Object param81 = stack.pop(); + Object param80 = stack.pop(); + Object param79 = stack.pop(); + Object param78 = stack.pop(); + Object param77 = stack.pop(); + Object param76 = stack.pop(); + Object param75 = stack.pop(); + Object param74 = stack.pop(); + Object param73 = stack.pop(); + Object param72 = stack.pop(); + Object param71 = stack.pop(); + Object param70 = stack.pop(); + Object param69 = stack.pop(); + Object param68 = stack.pop(); + Object param67 = stack.pop(); + Object param66 = stack.pop(); + Object param65 = stack.pop(); + Object param64 = stack.pop(); + Object param63 = stack.pop(); + Object param62 = stack.pop(); + Object param61 = stack.pop(); + Object param60 = stack.pop(); + Object param59 = stack.pop(); + Object param58 = stack.pop(); + Object param57 = stack.pop(); + Object param56 = stack.pop(); + Object param55 = stack.pop(); + Object param54 = stack.pop(); + Object param53 = stack.pop(); + Object param52 = stack.pop(); + Object param51 = stack.pop(); + Object param50 = stack.pop(); + Object param49 = stack.pop(); + Object param48 = stack.pop(); + Object param47 = stack.pop(); + Object param46 = stack.pop(); + Object param45 = stack.pop(); + Object param44 = stack.pop(); + Object param43 = stack.pop(); + Object param42 = stack.pop(); + Object param41 = stack.pop(); + Object param40 = stack.pop(); + Object param39 = stack.pop(); + Object param38 = stack.pop(); + Object param37 = stack.pop(); + Object param36 = stack.pop(); + Object param35 = stack.pop(); + Object param34 = stack.pop(); + Object param33 = stack.pop(); + Object param32 = stack.pop(); + Object param31 = stack.pop(); + Object param30 = stack.pop(); + Object param29 = stack.pop(); + Object param28 = stack.pop(); + Object param27 = stack.pop(); + Object param26 = stack.pop(); + Object param25 = stack.pop(); + Object param24 = stack.pop(); + Object param23 = stack.pop(); + Object param22 = stack.pop(); + Object param21 = stack.pop(); + Object param20 = stack.pop(); + Object param19 = stack.pop(); + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + float PSH_1_12 = ((Number) param201).floatValue(); + float PSH_1_11 = ((Number) param200).floatValue(); + float PSH_1_10 = ((Number) param199).floatValue(); + float PSH_0_4 = ((Number) param198).floatValue(); + float PSH_0_3 = ((Number) param197).floatValue(); + float PSH_0_2 = ((Number) param196).floatValue(); + float PSH_0_1 = ((Number) param195).floatValue(); + float PYU_1_12 = ((Number) param194).floatValue(); + float PYU_1_11 = ((Number) param193).floatValue(); + float PYU_1_10 = ((Number) param192).floatValue(); + float PYU_0_4 = ((Number) param191).floatValue(); + float PYU_0_3 = ((Number) param190).floatValue(); + float PYU_0_2 = ((Number) param189).floatValue(); + float PYU_0_1 = ((Number) param188).floatValue(); + float PFO_1_12 = ((Number) param187).floatValue(); + float PFO_1_11 = ((Number) param186).floatValue(); + float PFO_1_10 = ((Number) param185).floatValue(); + float PFO_0_4 = ((Number) param184).floatValue(); + float PFO_0_3 = ((Number) param183).floatValue(); + float PFO_0_2 = ((Number) param182).floatValue(); + float PFO_0_1 = ((Number) param181).floatValue(); + float POR_1_12 = ((Number) param180).floatValue(); + float POR_1_11 = ((Number) param179).floatValue(); + float POR_1_10 = ((Number) param178).floatValue(); + float POR_0_4 = ((Number) param177).floatValue(); + float POR_0_3 = ((Number) param176).floatValue(); + float POR_0_2 = ((Number) param175).floatValue(); + float POR_0_1 = ((Number) param174).floatValue(); + float QBD_1_12 = ((Number) param173).floatValue(); + float QBD_1_11 = ((Number) param172).floatValue(); + float QBD_1_10 = ((Number) param171).floatValue(); + float QBD_0_4 = ((Number) param170).floatValue(); + float QBD_0_3 = ((Number) param169).floatValue(); + float QBD_0_2 = ((Number) param168).floatValue(); + float QBD_0_1 = ((Number) param167).floatValue(); + float QSH_1_12 = ((Number) param166).floatValue(); + float QSH_1_11 = ((Number) param165).floatValue(); + float QSH_1_10 = ((Number) param164).floatValue(); + float QSH_0_4 = ((Number) param163).floatValue(); + float QSH_0_3 = ((Number) param162).floatValue(); + float QSH_0_2 = ((Number) param161).floatValue(); + float QSH_0_1 = ((Number) param160).floatValue(); + float QYU_1_12 = ((Number) param159).floatValue(); + float QYU_1_11 = ((Number) param158).floatValue(); + float QYU_1_10 = ((Number) param157).floatValue(); + float QYU_0_4 = ((Number) param156).floatValue(); + float QYU_0_3 = ((Number) param155).floatValue(); + float QYU_0_2 = ((Number) param154).floatValue(); + float QYU_0_1 = ((Number) param153).floatValue(); + float QFO_1_12 = ((Number) param152).floatValue(); + float QFO_1_11 = ((Number) param151).floatValue(); + float QFO_1_10 = ((Number) param150).floatValue(); + float QFO_0_4 = ((Number) param149).floatValue(); + float QFO_0_3 = ((Number) param148).floatValue(); + float QFO_0_2 = ((Number) param147).floatValue(); + float QFO_0_1 = ((Number) param146).floatValue(); + float QOR_2_12 = ((Number) param145).floatValue(); + float QOR_2_11 = ((Number) param144).floatValue(); + float QOR_2_10 = ((Number) param143).floatValue(); + float QOR_1_12 = ((Number) param142).floatValue(); + float QOR_1_11 = ((Number) param141).floatValue(); + float QOR_1_10 = ((Number) param140).floatValue(); + float QOR_1_9 = ((Number) param139).floatValue(); + float QOR_1_8 = ((Number) param138).floatValue(); + float QOR_1_7 = ((Number) param137).floatValue(); + float QOR_1_6 = ((Number) param136).floatValue(); + float QOR_1_5 = ((Number) param135).floatValue(); + float QOR_1_4 = ((Number) param134).floatValue(); + float QOR_1_3 = ((Number) param133).floatValue(); + float QOR_1_2 = ((Number) param132).floatValue(); + float QOR_1_1 = ((Number) param131).floatValue(); + float QOR_0_4 = ((Number) param130).floatValue(); + float QOR_0_3 = ((Number) param129).floatValue(); + float QOR_0_2 = ((Number) param128).floatValue(); + float QOR_0_1 = ((Number) param127).floatValue(); + float SQNB_2_12 = ((Number) param126).floatValue(); + float SQNB_2_11 = ((Number) param125).floatValue(); + float SQNB_2_10 = ((Number) param124).floatValue(); + float SQNB_1_12 = ((Number) param123).floatValue(); + float SQNB_1_11 = ((Number) param122).floatValue(); + float SQNB_1_10 = ((Number) param121).floatValue(); + float SQNB_1_9 = ((Number) param120).floatValue(); + float SQNB_1_8 = ((Number) param119).floatValue(); + float SQNB_1_7 = ((Number) param118).floatValue(); + float SQNB_1_6 = ((Number) param117).floatValue(); + float SQNB_1_5 = ((Number) param116).floatValue(); + float SQNB_1_4 = ((Number) param115).floatValue(); + float SQNB_1_3 = ((Number) param114).floatValue(); + float SQNB_1_2 = ((Number) param113).floatValue(); + float SQNB_1_1 = ((Number) param112).floatValue(); + float SQNB_0_4 = ((Number) param111).floatValue(); + float SQNB_0_3 = ((Number) param110).floatValue(); + float SQNB_0_2 = ((Number) param109).floatValue(); + float SQNB_0_1 = ((Number) param108).floatValue(); + float SQSW_2_12 = ((Number) param107).floatValue(); + float SQSW_2_11 = ((Number) param106).floatValue(); + float SQSW_2_10 = ((Number) param105).floatValue(); + float SQSW_1_12 = ((Number) param104).floatValue(); + float SQSW_1_11 = ((Number) param103).floatValue(); + float SQSW_1_10 = ((Number) param102).floatValue(); + float SQSW_1_9 = ((Number) param101).floatValue(); + float SQSW_1_8 = ((Number) param100).floatValue(); + float SQSW_1_7 = ((Number) param99).floatValue(); + float SQSW_1_6 = ((Number) param98).floatValue(); + float SQSW_1_5 = ((Number) param97).floatValue(); + float SQSW_1_4 = ((Number) param96).floatValue(); + float SQSW_1_3 = ((Number) param95).floatValue(); + float SQSW_1_2 = ((Number) param94).floatValue(); + float SQSW_1_1 = ((Number) param93).floatValue(); + float SQSW_0_4 = ((Number) param92).floatValue(); + float SQSW_0_3 = ((Number) param91).floatValue(); + float SQSW_0_2 = ((Number) param90).floatValue(); + float SQSW_0_1 = ((Number) param89).floatValue(); + float SQFP_2_12 = ((Number) param88).floatValue(); + float SQFP_2_11 = ((Number) param87).floatValue(); + float SQFP_2_10 = ((Number) param86).floatValue(); + float SQFP_1_12 = ((Number) param85).floatValue(); + float SQFP_1_11 = ((Number) param84).floatValue(); + float SQFP_1_10 = ((Number) param83).floatValue(); + float SQFP_1_9 = ((Number) param82).floatValue(); + float SQFP_1_8 = ((Number) param81).floatValue(); + float SQFP_1_7 = ((Number) param80).floatValue(); + float SQFP_1_6 = ((Number) param79).floatValue(); + float SQFP_1_5 = ((Number) param78).floatValue(); + float SQFP_1_4 = ((Number) param77).floatValue(); + float SQFP_1_3 = ((Number) param76).floatValue(); + float SQFP_1_2 = ((Number) param75).floatValue(); + float SQFP_1_1 = ((Number) param74).floatValue(); + float SQFP_0_4 = ((Number) param73).floatValue(); + float SQFP_0_3 = ((Number) param72).floatValue(); + float SQFP_0_2 = ((Number) param71).floatValue(); + float SQFP_0_1 = ((Number) param70).floatValue(); + float SQFW_2_12 = ((Number) param69).floatValue(); + float SQFW_2_11 = ((Number) param68).floatValue(); + float SQFW_2_10 = ((Number) param67).floatValue(); + float SQFW_1_12 = ((Number) param66).floatValue(); + float SQFW_1_11 = ((Number) param65).floatValue(); + float SQFW_1_10 = ((Number) param64).floatValue(); + float SQFW_1_9 = ((Number) param63).floatValue(); + float SQFW_1_8 = ((Number) param62).floatValue(); + float SQFW_1_7 = ((Number) param61).floatValue(); + float SQFW_1_6 = ((Number) param60).floatValue(); + float SQFW_1_5 = ((Number) param59).floatValue(); + float SQFW_1_4 = ((Number) param58).floatValue(); + float SQFW_1_3 = ((Number) param57).floatValue(); + float SQFW_1_2 = ((Number) param56).floatValue(); + float SQFW_1_1 = ((Number) param55).floatValue(); + float SQFW_0_4 = ((Number) param54).floatValue(); + float SQFW_0_3 = ((Number) param53).floatValue(); + float SQFW_0_2 = ((Number) param52).floatValue(); + float SQFW_0_1 = ((Number) param51).floatValue(); + float SQOR_2_12 = ((Number) param50).floatValue(); + float SQOR_2_11 = ((Number) param49).floatValue(); + float SQOR_2_10 = ((Number) param48).floatValue(); + float SQOR_1_12 = ((Number) param47).floatValue(); + float SQOR_1_11 = ((Number) param46).floatValue(); + float SQOR_1_10 = ((Number) param45).floatValue(); + float SQOR_1_9 = ((Number) param44).floatValue(); + float SQOR_1_8 = ((Number) param43).floatValue(); + float SQOR_1_7 = ((Number) param42).floatValue(); + float SQOR_1_6 = ((Number) param41).floatValue(); + float SQOR_1_5 = ((Number) param40).floatValue(); + float SQOR_1_4 = ((Number) param39).floatValue(); + float SQOR_1_3 = ((Number) param38).floatValue(); + float SQOR_1_2 = ((Number) param37).floatValue(); + float SQOR_1_1 = ((Number) param36).floatValue(); + float SQOR_0_4 = ((Number) param35).floatValue(); + float SQOR_0_3 = ((Number) param34).floatValue(); + float SQOR_0_2 = ((Number) param33).floatValue(); + float SQOR_0_1 = ((Number) param32).floatValue(); + float SQKS_2_12 = ((Number) param31).floatValue(); + float SQKS_2_11 = ((Number) param30).floatValue(); + float SQKS_2_10 = ((Number) param29).floatValue(); + float SQKS_1_12 = ((Number) param28).floatValue(); + float SQKS_1_11 = ((Number) param27).floatValue(); + float SQKS_1_10 = ((Number) param26).floatValue(); + float SQKS_1_9 = ((Number) param25).floatValue(); + float SQKS_1_8 = ((Number) param24).floatValue(); + float SQKS_1_7 = ((Number) param23).floatValue(); + float SQKS_1_6 = ((Number) param22).floatValue(); + float SQKS_1_5 = ((Number) param21).floatValue(); + float SQKS_1_4 = ((Number) param20).floatValue(); + float SQKS_1_3 = ((Number) param19).floatValue(); + float SQKS_1_2 = ((Number) param18).floatValue(); + float SQKS_1_1 = ((Number) param17).floatValue(); + float SQKS_0_4 = ((Number) param16).floatValue(); + float SQKS_0_3 = ((Number) param15).floatValue(); + float SQKS_0_2 = ((Number) param14).floatValue(); + float SQKS_0_1 = ((Number) param13).floatValue(); + float IFREQ5X = ((Number) param12).floatValue(); + float IFREQ4X = ((Number) param11).floatValue(); + float IFREQ3X = ((Number) param10).floatValue(); + float IFREQ2X = ((Number) param9).floatValue(); + float IFREQ1X = ((Number) param8).floatValue(); + float IFREQODX = ((Number) param7).floatValue(); + float IMX = ((Number) param6).floatValue(); + float IYEARX = ((Number) param5).floatValue(); + float IMPOSX = ((Number) param4).floatValue(); + float IYPOSX = ((Number) param3).floatValue(); + int ICODE = ((Number) param2).intValue(); + int ICALC = ((Number) param1).intValue(); + + float result = camdll(ICALC, ICODE, IYPOSX, IMPOSX, IYEARX, IMX, IFREQODX, IFREQ1X, IFREQ2X, IFREQ3X, IFREQ4X, IFREQ5X, SQKS_0_1, SQKS_0_2, SQKS_0_3, SQKS_0_4, SQKS_1_1, SQKS_1_2, SQKS_1_3, SQKS_1_4, SQKS_1_5, SQKS_1_6, SQKS_1_7, SQKS_1_8, SQKS_1_9, SQKS_1_10, SQKS_1_11, SQKS_1_12, SQKS_2_10, SQKS_2_11, SQKS_2_12, SQOR_0_1, SQOR_0_2, SQOR_0_3, SQOR_0_4, SQOR_1_1, SQOR_1_2, SQOR_1_3, SQOR_1_4, SQOR_1_5, SQOR_1_6, SQOR_1_7, SQOR_1_8, SQOR_1_9, SQOR_1_10, SQOR_1_11, SQOR_1_12, SQOR_2_10, SQOR_2_11, SQOR_2_12, SQFW_0_1, SQFW_0_2, SQFW_0_3, SQFW_0_4, SQFW_1_1, SQFW_1_2, SQFW_1_3, SQFW_1_4, SQFW_1_5, SQFW_1_6, SQFW_1_7, SQFW_1_8, SQFW_1_9, SQFW_1_10, SQFW_1_11, SQFW_1_12, SQFW_2_10, SQFW_2_11, SQFW_2_12, SQFP_0_1, SQFP_0_2, SQFP_0_3, SQFP_0_4, SQFP_1_1, SQFP_1_2, SQFP_1_3, SQFP_1_4, SQFP_1_5, SQFP_1_6, SQFP_1_7, SQFP_1_8, SQFP_1_9, SQFP_1_10, SQFP_1_11, SQFP_1_12, SQFP_2_10, SQFP_2_11, SQFP_2_12, SQSW_0_1, SQSW_0_2, SQSW_0_3, SQSW_0_4, SQSW_1_1, SQSW_1_2, SQSW_1_3, SQSW_1_4, SQSW_1_5, SQSW_1_6, SQSW_1_7, SQSW_1_8, SQSW_1_9, SQSW_1_10, SQSW_1_11, SQSW_1_12, SQSW_2_10, SQSW_2_11, SQSW_2_12, SQNB_0_1, SQNB_0_2, SQNB_0_3, SQNB_0_4, SQNB_1_1, SQNB_1_2, SQNB_1_3, SQNB_1_4, SQNB_1_5, SQNB_1_6, SQNB_1_7, SQNB_1_8, SQNB_1_9, SQNB_1_10, SQNB_1_11, SQNB_1_12, SQNB_2_10, SQNB_2_11, SQNB_2_12, QOR_0_1, QOR_0_2, QOR_0_3, QOR_0_4, QOR_1_1, QOR_1_2, QOR_1_3, QOR_1_4, QOR_1_5, QOR_1_6, QOR_1_7, QOR_1_8, QOR_1_9, QOR_1_10, QOR_1_11, QOR_1_12, QOR_2_10, QOR_2_11, QOR_2_12, QFO_0_1, QFO_0_2, QFO_0_3, QFO_0_4, QFO_1_10, QFO_1_11, QFO_1_12, QYU_0_1, QYU_0_2, QYU_0_3, QYU_0_4, QYU_1_10, QYU_1_11, QYU_1_12, QSH_0_1, QSH_0_2, QSH_0_3, QSH_0_4, QSH_1_10, QSH_1_11, QSH_1_12, QBD_0_1, QBD_0_2, QBD_0_3, QBD_0_4, QBD_1_10, QBD_1_11, QBD_1_12, POR_0_1, POR_0_2, POR_0_3, POR_0_4, POR_1_10, POR_1_11, POR_1_12, PFO_0_1, PFO_0_2, PFO_0_3, PFO_0_4, PFO_1_10, PFO_1_11, PFO_1_12, PYU_0_1, PYU_0_2, PYU_0_3, PYU_0_4, PYU_1_10, PYU_1_11, PYU_1_12, PSH_0_1, PSH_0_2, PSH_0_3, PSH_0_4, PSH_1_10, PSH_1_11, PSH_1_12); + + // push the result on the Stack + stack.push(new Float(result)); + + } + + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_cam=ControlData.t_cam+(int) (t2-t1); + } + + public native float camdll(int ICALC, int ICODE, float IYPOSX, float IMPOSX, float IYEARX, float IMX, float IFREQODX, float IFREQ1X, float IFREQ2X, float IFREQ3X, float IFREQ4X, float IFREQ5X, float SQKS_0_1, float SQKS_0_2, float SQKS_0_3, float SQKS_0_4, float SQKS_1_1, float SQKS_1_2, float SQKS_1_3, float SQKS_1_4, float SQKS_1_5, float SQKS_1_6, float SQKS_1_7, float SQKS_1_8, float SQKS_1_9, float SQKS_1_10, float SQKS_1_11, float SQKS_1_12, float SQKS_2_10, float SQKS_2_11, float SQKS_2_12, float SQOR_0_1, float SQOR_0_2, float SQOR_0_3, float SQOR_0_4, float SQOR_1_1, float SQOR_1_2, float SQOR_1_3, float SQOR_1_4, float SQOR_1_5, float SQOR_1_6, float SQOR_1_7, float SQOR_1_8, float SQOR_1_9, float SQOR_1_10, float SQOR_1_11, float SQOR_1_12, float SQOR_2_10, float SQOR_2_11, float SQOR_2_12, float SQFW_0_1, float SQFW_0_2, float SQFW_0_3, float SQFW_0_4, float SQFW_1_1, float SQFW_1_2, float SQFW_1_3, float SQFW_1_4, float SQFW_1_5, float SQFW_1_6, float SQFW_1_7, float SQFW_1_8, float SQFW_1_9, float SQFW_1_10, float SQFW_1_11, float SQFW_1_12, float SQFW_2_10, float SQFW_2_11, float SQFW_2_12, float SQFP_0_1, float SQFP_0_2, float SQFP_0_3, float SQFP_0_4, float SQFP_1_1, float SQFP_1_2, float SQFP_1_3, float SQFP_1_4, float SQFP_1_5, float SQFP_1_6, float SQFP_1_7, float SQFP_1_8, float SQFP_1_9, float SQFP_1_10, float SQFP_1_11, float SQFP_1_12, float SQFP_2_10, float SQFP_2_11, float SQFP_2_12, float SQSW_0_1, float SQSW_0_2, float SQSW_0_3, float SQSW_0_4, float SQSW_1_1, float SQSW_1_2, float SQSW_1_3, float SQSW_1_4, float SQSW_1_5, float SQSW_1_6, float SQSW_1_7, float SQSW_1_8, float SQSW_1_9, float SQSW_1_10, float SQSW_1_11, float SQSW_1_12, float SQSW_2_10, float SQSW_2_11, float SQSW_2_12, float SQNB_0_1, float SQNB_0_2, float SQNB_0_3, float SQNB_0_4, float SQNB_1_1, float SQNB_1_2, float SQNB_1_3, float SQNB_1_4, float SQNB_1_5, float SQNB_1_6, float SQNB_1_7, float SQNB_1_8, float SQNB_1_9, float SQNB_1_10, float SQNB_1_11, float SQNB_1_12, float SQNB_2_10, float SQNB_2_11, float SQNB_2_12, float QOR_0_1, float QOR_0_2, float QOR_0_3, float QOR_0_4, float QOR_1_1, float QOR_1_2, float QOR_1_3, float QOR_1_4, float QOR_1_5, float QOR_1_6, float QOR_1_7, float QOR_1_8, float QOR_1_9, float QOR_1_10, float QOR_1_11, float QOR_1_12, float QOR_2_10, float QOR_2_11, float QOR_2_12, float QFO_0_1, float QFO_0_2, float QFO_0_3, float QFO_0_4, float QFO_1_10, float QFO_1_11, float QFO_1_12, float QYU_0_1, float QYU_0_2, float QYU_0_3, float QYU_0_4, float QYU_1_10, float QYU_1_11, float QYU_1_12, float QSH_0_1, float QSH_0_2, float QSH_0_3, float QSH_0_4, float QSH_1_10, float QSH_1_11, float QSH_1_12, float QBD_0_1, float QBD_0_2, float QBD_0_3, float QBD_0_4, float QBD_1_10, float QBD_1_11, float QBD_1_12, float POR_0_1, float POR_0_2, float POR_0_3, float POR_0_4, float POR_1_10, float POR_1_11, float POR_1_12, float PFO_0_1, float PFO_0_2, float PFO_0_3, float PFO_0_4, float PFO_1_10, float PFO_1_11, float PFO_1_12, float PYU_0_1, float PYU_0_2, float PYU_0_3, float PYU_0_4, float PYU_1_10, float PYU_1_11, float PYU_1_12, float PSH_0_1, float PSH_0_2, float PSH_0_3, float PSH_0_4, float PSH_1_10, float PSH_1_11, float PSH_1_12); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functioncamsjrdll.java b/wrims-core/src/main/java/wrimsv2/external/Functioncamsjrdll.java similarity index 98% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functioncamsjrdll.java rename to wrims-core/src/main/java/wrimsv2/external/Functioncamsjrdll.java index 5a2bae437..579fec13a 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functioncamsjrdll.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functioncamsjrdll.java @@ -1,206 +1,206 @@ -package wrimsv2.external; - -import java.util.*; - -import wrimsv2.components.ControlData; - -public class Functioncamsjrdll extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functioncamsjrdll(){ - - } - - public void execute(Stack stack) { - - long t1 = Calendar.getInstance().getTimeInMillis(); - - if (stack.size()==2){ - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - int ICODE = ((Number) param2).intValue(); - int ICALC = ((Number) param1).intValue(); - - float result = camsjrdll(ICALC, ICODE, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0); - - // push the result on the Stack - stack.push(new Float(result)); - }else{ - //values in reverse order: - Object param80 = stack.pop(); - Object param79 = stack.pop(); - Object param78 = stack.pop(); - Object param77 = stack.pop(); - Object param76 = stack.pop(); - Object param75 = stack.pop(); - Object param74 = stack.pop(); - Object param73 = stack.pop(); - Object param72 = stack.pop(); - Object param71 = stack.pop(); - Object param70 = stack.pop(); - Object param69 = stack.pop(); - Object param68 = stack.pop(); - Object param67 = stack.pop(); - Object param66 = stack.pop(); - Object param65 = stack.pop(); - Object param64 = stack.pop(); - Object param63 = stack.pop(); - Object param62 = stack.pop(); - Object param61 = stack.pop(); - Object param60 = stack.pop(); - Object param59 = stack.pop(); - Object param58 = stack.pop(); - Object param57 = stack.pop(); - Object param56 = stack.pop(); - Object param55 = stack.pop(); - Object param54 = stack.pop(); - Object param53 = stack.pop(); - Object param52 = stack.pop(); - Object param51 = stack.pop(); - Object param50 = stack.pop(); - Object param49 = stack.pop(); - Object param48 = stack.pop(); - Object param47 = stack.pop(); - Object param46 = stack.pop(); - Object param45 = stack.pop(); - Object param44 = stack.pop(); - Object param43 = stack.pop(); - Object param42 = stack.pop(); - Object param41 = stack.pop(); - Object param40 = stack.pop(); - Object param39 = stack.pop(); - Object param38 = stack.pop(); - Object param37 = stack.pop(); - Object param36 = stack.pop(); - Object param35 = stack.pop(); - Object param34 = stack.pop(); - Object param33 = stack.pop(); - Object param32 = stack.pop(); - Object param31 = stack.pop(); - Object param30 = stack.pop(); - Object param29 = stack.pop(); - Object param28 = stack.pop(); - Object param27 = stack.pop(); - Object param26 = stack.pop(); - Object param25 = stack.pop(); - Object param24 = stack.pop(); - Object param23 = stack.pop(); - Object param22 = stack.pop(); - Object param21 = stack.pop(); - Object param20 = stack.pop(); - Object param19 = stack.pop(); - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - float PSJ_1_12 = ((Number) param80).floatValue(); - float PSJ_1_11 = ((Number) param79).floatValue(); - float PSJ_1_10 = ((Number) param78).floatValue(); - float PSJ_0_4 = ((Number) param77).floatValue(); - float PSJ_0_3 = ((Number) param76).floatValue(); - float PSJ_0_2 = ((Number) param75).floatValue(); - float PSJ_0_1 = ((Number) param74).floatValue(); - float PME_1_12 = ((Number) param73).floatValue(); - float PME_1_11 = ((Number) param72).floatValue(); - float PME_1_10 = ((Number) param71).floatValue(); - float PME_0_4 = ((Number) param70).floatValue(); - float PME_0_3 = ((Number) param69).floatValue(); - float PME_0_2 = ((Number) param68).floatValue(); - float PME_0_1 = ((Number) param67).floatValue(); - float PTU_1_12 = ((Number) param66).floatValue(); - float PTU_1_11 = ((Number) param65).floatValue(); - float PTU_1_10 = ((Number) param64).floatValue(); - float PTU_0_4 = ((Number) param63).floatValue(); - float PTU_0_3 = ((Number) param62).floatValue(); - float PTU_0_2 = ((Number) param61).floatValue(); - float PTU_0_1 = ((Number) param60).floatValue(); - float PST_1_12 = ((Number) param59).floatValue(); - float PST_1_11 = ((Number) param58).floatValue(); - float PST_1_10 = ((Number) param57).floatValue(); - float PST_0_4 = ((Number) param56).floatValue(); - float PST_0_3 = ((Number) param55).floatValue(); - float PST_0_2 = ((Number) param54).floatValue(); - float PST_0_1 = ((Number) param53).floatValue(); - float QSJ_1_12 = ((Number) param52).floatValue(); - float QSJ_1_11 = ((Number) param51).floatValue(); - float QSJ_1_10 = ((Number) param50).floatValue(); - float QSJ_0_4 = ((Number) param49).floatValue(); - float QSJ_0_3 = ((Number) param48).floatValue(); - float QSJ_0_2 = ((Number) param47).floatValue(); - float QSJ_0_1 = ((Number) param46).floatValue(); - float QME_1_12 = ((Number) param45).floatValue(); - float QME_1_11 = ((Number) param44).floatValue(); - float QME_1_10 = ((Number) param43).floatValue(); - float QME_0_4 = ((Number) param42).floatValue(); - float QME_0_3 = ((Number) param41).floatValue(); - float QME_0_2 = ((Number) param40).floatValue(); - float QME_0_1 = ((Number) param39).floatValue(); - float QTU_1_12 = ((Number) param38).floatValue(); - float QTU_1_11 = ((Number) param37).floatValue(); - float QTU_1_10 = ((Number) param36).floatValue(); - float QTU_0_4 = ((Number) param35).floatValue(); - float QTU_0_3 = ((Number) param34).floatValue(); - float QTU_0_2 = ((Number) param33).floatValue(); - float QTU_0_1 = ((Number) param32).floatValue(); - float QST_2_12 = ((Number) param31).floatValue(); - float QST_2_11 = ((Number) param30).floatValue(); - float QST_2_10 = ((Number) param29).floatValue(); - float QST_1_12 = ((Number) param28).floatValue(); - float QST_1_11 = ((Number) param27).floatValue(); - float QST_1_10 = ((Number) param26).floatValue(); - float QST_1_9 = ((Number) param25).floatValue(); - float QST_1_8 = ((Number) param24).floatValue(); - float QST_1_7 = ((Number) param23).floatValue(); - float QST_1_6 = ((Number) param22).floatValue(); - float QST_1_5 = ((Number) param21).floatValue(); - float QST_1_4 = ((Number) param20).floatValue(); - float QST_1_3 = ((Number) param19).floatValue(); - float QST_1_2 = ((Number) param18).floatValue(); - float QST_1_1 = ((Number) param17).floatValue(); - float QST_0_4 = ((Number) param16).floatValue(); - float QST_0_3 = ((Number) param15).floatValue(); - float QST_0_2 = ((Number) param14).floatValue(); - float QST_0_1 = ((Number) param13).floatValue(); - float IFREQ5X = ((Number) param12).floatValue(); - float IFREQ4X = ((Number) param11).floatValue(); - float IFREQ3X = ((Number) param10).floatValue(); - float IFREQ2X = ((Number) param9).floatValue(); - float IFREQ1X = ((Number) param8).floatValue(); - float IFREQODX = ((Number) param7).floatValue(); - float IMX = ((Number) param6).floatValue(); - float IYEARX = ((Number) param5).floatValue(); - float IMPOSX = ((Number) param4).floatValue(); - float IYPOSX = ((Number) param3).floatValue(); - int ICODE = ((Number) param2).intValue(); - int ICALC = ((Number) param1).intValue(); - - float result = camsjrdll(ICALC, ICODE, IYPOSX, IMPOSX, IYEARX, IMX, IFREQODX, IFREQ1X, IFREQ2X, IFREQ3X, IFREQ4X, IFREQ5X, QST_0_1, QST_0_2, QST_0_3, QST_0_4, QST_1_1, QST_1_2, QST_1_3, QST_1_4, QST_1_5, QST_1_6, QST_1_7, QST_1_8, QST_1_9, QST_1_10, QST_1_11, QST_1_12, QST_2_10, QST_2_11, QST_2_12, QTU_0_1, QTU_0_2, QTU_0_3, QTU_0_4, QTU_1_10, QTU_1_11, QTU_1_12, QME_0_1, QME_0_2, QME_0_3, QME_0_4, QME_1_10, QME_1_11, QME_1_12, QSJ_0_1, QSJ_0_2, QSJ_0_3, QSJ_0_4, QSJ_1_10, QSJ_1_11, QSJ_1_12, PST_0_1, PST_0_2, PST_0_3, PST_0_4, PST_1_10, PST_1_11, PST_1_12, PTU_0_1, PTU_0_2, PTU_0_3, PTU_0_4, PTU_1_10, PTU_1_11, PTU_1_12, PME_0_1, PME_0_2, PME_0_3, PME_0_4, PME_1_10, PME_1_11, PME_1_12, PSJ_0_1, PSJ_0_2, PSJ_0_3, PSJ_0_4, PSJ_1_10, PSJ_1_11, PSJ_1_12); - - // push the result on the Stack - stack.push(new Float(result)); - } - - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_cam=ControlData.t_cam+(int) (t2-t1); - } - - public native float camsjrdll(int ICALC, int ICODE, float IYPOSX, float IMPOSX, float IYEARX, float IMX, float IFREQODX, float IFREQ1X, float IFREQ2X, float IFREQ3X, float IFREQ4X, float IFREQ5X, float QST_0_1, float QST_0_2, float QST_0_3, float QST_0_4, float QST_1_1, float QST_1_2, float QST_1_3, float QST_1_4, float QST_1_5, float QST_1_6, float QST_1_7, float QST_1_8, float QST_1_9, float QST_1_10, float QST_1_11, float QST_1_12, float QST_2_10, float QST_2_11, float QST_2_12, float QTU_0_1, float QTU_0_2, float QTU_0_3, float QTU_0_4, float QTU_1_10, float QTU_1_11, float QTU_1_12, float QME_0_1, float QME_0_2, float QME_0_3, float QME_0_4, float QME_1_10, float QME_1_11, float QME_1_12, float QSJ_0_1, float QSJ_0_2, float QSJ_0_3, float QSJ_0_4, float QSJ_1_10, float QSJ_1_11, float QSJ_1_12, float PST_0_1, float PST_0_2, float PST_0_3, float PST_0_4, float PST_1_10, float PST_1_11, float PST_1_12, float PTU_0_1, float PTU_0_2, float PTU_0_3, float PTU_0_4, float PTU_1_10, float PTU_1_11, float PTU_1_12, float PME_0_1, float PME_0_2, float PME_0_3, float PME_0_4, float PME_1_10, float PME_1_11, float PME_1_12, float PSJ_0_1, float PSJ_0_2, float PSJ_0_3, float PSJ_0_4, float PSJ_1_10, float PSJ_1_11, float PSJ_1_12); -} +package wrimsv2.external; + +import java.util.*; + +import wrimsv2.components.ControlData; + +public class Functioncamsjrdll extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functioncamsjrdll(){ + + } + + public void execute(Stack stack) { + + long t1 = Calendar.getInstance().getTimeInMillis(); + + if (stack.size()==2){ + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + int ICODE = ((Number) param2).intValue(); + int ICALC = ((Number) param1).intValue(); + + float result = camsjrdll(ICALC, ICODE, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0, (float) 0.0); + + // push the result on the Stack + stack.push(new Float(result)); + }else{ + //values in reverse order: + Object param80 = stack.pop(); + Object param79 = stack.pop(); + Object param78 = stack.pop(); + Object param77 = stack.pop(); + Object param76 = stack.pop(); + Object param75 = stack.pop(); + Object param74 = stack.pop(); + Object param73 = stack.pop(); + Object param72 = stack.pop(); + Object param71 = stack.pop(); + Object param70 = stack.pop(); + Object param69 = stack.pop(); + Object param68 = stack.pop(); + Object param67 = stack.pop(); + Object param66 = stack.pop(); + Object param65 = stack.pop(); + Object param64 = stack.pop(); + Object param63 = stack.pop(); + Object param62 = stack.pop(); + Object param61 = stack.pop(); + Object param60 = stack.pop(); + Object param59 = stack.pop(); + Object param58 = stack.pop(); + Object param57 = stack.pop(); + Object param56 = stack.pop(); + Object param55 = stack.pop(); + Object param54 = stack.pop(); + Object param53 = stack.pop(); + Object param52 = stack.pop(); + Object param51 = stack.pop(); + Object param50 = stack.pop(); + Object param49 = stack.pop(); + Object param48 = stack.pop(); + Object param47 = stack.pop(); + Object param46 = stack.pop(); + Object param45 = stack.pop(); + Object param44 = stack.pop(); + Object param43 = stack.pop(); + Object param42 = stack.pop(); + Object param41 = stack.pop(); + Object param40 = stack.pop(); + Object param39 = stack.pop(); + Object param38 = stack.pop(); + Object param37 = stack.pop(); + Object param36 = stack.pop(); + Object param35 = stack.pop(); + Object param34 = stack.pop(); + Object param33 = stack.pop(); + Object param32 = stack.pop(); + Object param31 = stack.pop(); + Object param30 = stack.pop(); + Object param29 = stack.pop(); + Object param28 = stack.pop(); + Object param27 = stack.pop(); + Object param26 = stack.pop(); + Object param25 = stack.pop(); + Object param24 = stack.pop(); + Object param23 = stack.pop(); + Object param22 = stack.pop(); + Object param21 = stack.pop(); + Object param20 = stack.pop(); + Object param19 = stack.pop(); + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + float PSJ_1_12 = ((Number) param80).floatValue(); + float PSJ_1_11 = ((Number) param79).floatValue(); + float PSJ_1_10 = ((Number) param78).floatValue(); + float PSJ_0_4 = ((Number) param77).floatValue(); + float PSJ_0_3 = ((Number) param76).floatValue(); + float PSJ_0_2 = ((Number) param75).floatValue(); + float PSJ_0_1 = ((Number) param74).floatValue(); + float PME_1_12 = ((Number) param73).floatValue(); + float PME_1_11 = ((Number) param72).floatValue(); + float PME_1_10 = ((Number) param71).floatValue(); + float PME_0_4 = ((Number) param70).floatValue(); + float PME_0_3 = ((Number) param69).floatValue(); + float PME_0_2 = ((Number) param68).floatValue(); + float PME_0_1 = ((Number) param67).floatValue(); + float PTU_1_12 = ((Number) param66).floatValue(); + float PTU_1_11 = ((Number) param65).floatValue(); + float PTU_1_10 = ((Number) param64).floatValue(); + float PTU_0_4 = ((Number) param63).floatValue(); + float PTU_0_3 = ((Number) param62).floatValue(); + float PTU_0_2 = ((Number) param61).floatValue(); + float PTU_0_1 = ((Number) param60).floatValue(); + float PST_1_12 = ((Number) param59).floatValue(); + float PST_1_11 = ((Number) param58).floatValue(); + float PST_1_10 = ((Number) param57).floatValue(); + float PST_0_4 = ((Number) param56).floatValue(); + float PST_0_3 = ((Number) param55).floatValue(); + float PST_0_2 = ((Number) param54).floatValue(); + float PST_0_1 = ((Number) param53).floatValue(); + float QSJ_1_12 = ((Number) param52).floatValue(); + float QSJ_1_11 = ((Number) param51).floatValue(); + float QSJ_1_10 = ((Number) param50).floatValue(); + float QSJ_0_4 = ((Number) param49).floatValue(); + float QSJ_0_3 = ((Number) param48).floatValue(); + float QSJ_0_2 = ((Number) param47).floatValue(); + float QSJ_0_1 = ((Number) param46).floatValue(); + float QME_1_12 = ((Number) param45).floatValue(); + float QME_1_11 = ((Number) param44).floatValue(); + float QME_1_10 = ((Number) param43).floatValue(); + float QME_0_4 = ((Number) param42).floatValue(); + float QME_0_3 = ((Number) param41).floatValue(); + float QME_0_2 = ((Number) param40).floatValue(); + float QME_0_1 = ((Number) param39).floatValue(); + float QTU_1_12 = ((Number) param38).floatValue(); + float QTU_1_11 = ((Number) param37).floatValue(); + float QTU_1_10 = ((Number) param36).floatValue(); + float QTU_0_4 = ((Number) param35).floatValue(); + float QTU_0_3 = ((Number) param34).floatValue(); + float QTU_0_2 = ((Number) param33).floatValue(); + float QTU_0_1 = ((Number) param32).floatValue(); + float QST_2_12 = ((Number) param31).floatValue(); + float QST_2_11 = ((Number) param30).floatValue(); + float QST_2_10 = ((Number) param29).floatValue(); + float QST_1_12 = ((Number) param28).floatValue(); + float QST_1_11 = ((Number) param27).floatValue(); + float QST_1_10 = ((Number) param26).floatValue(); + float QST_1_9 = ((Number) param25).floatValue(); + float QST_1_8 = ((Number) param24).floatValue(); + float QST_1_7 = ((Number) param23).floatValue(); + float QST_1_6 = ((Number) param22).floatValue(); + float QST_1_5 = ((Number) param21).floatValue(); + float QST_1_4 = ((Number) param20).floatValue(); + float QST_1_3 = ((Number) param19).floatValue(); + float QST_1_2 = ((Number) param18).floatValue(); + float QST_1_1 = ((Number) param17).floatValue(); + float QST_0_4 = ((Number) param16).floatValue(); + float QST_0_3 = ((Number) param15).floatValue(); + float QST_0_2 = ((Number) param14).floatValue(); + float QST_0_1 = ((Number) param13).floatValue(); + float IFREQ5X = ((Number) param12).floatValue(); + float IFREQ4X = ((Number) param11).floatValue(); + float IFREQ3X = ((Number) param10).floatValue(); + float IFREQ2X = ((Number) param9).floatValue(); + float IFREQ1X = ((Number) param8).floatValue(); + float IFREQODX = ((Number) param7).floatValue(); + float IMX = ((Number) param6).floatValue(); + float IYEARX = ((Number) param5).floatValue(); + float IMPOSX = ((Number) param4).floatValue(); + float IYPOSX = ((Number) param3).floatValue(); + int ICODE = ((Number) param2).intValue(); + int ICALC = ((Number) param1).intValue(); + + float result = camsjrdll(ICALC, ICODE, IYPOSX, IMPOSX, IYEARX, IMX, IFREQODX, IFREQ1X, IFREQ2X, IFREQ3X, IFREQ4X, IFREQ5X, QST_0_1, QST_0_2, QST_0_3, QST_0_4, QST_1_1, QST_1_2, QST_1_3, QST_1_4, QST_1_5, QST_1_6, QST_1_7, QST_1_8, QST_1_9, QST_1_10, QST_1_11, QST_1_12, QST_2_10, QST_2_11, QST_2_12, QTU_0_1, QTU_0_2, QTU_0_3, QTU_0_4, QTU_1_10, QTU_1_11, QTU_1_12, QME_0_1, QME_0_2, QME_0_3, QME_0_4, QME_1_10, QME_1_11, QME_1_12, QSJ_0_1, QSJ_0_2, QSJ_0_3, QSJ_0_4, QSJ_1_10, QSJ_1_11, QSJ_1_12, PST_0_1, PST_0_2, PST_0_3, PST_0_4, PST_1_10, PST_1_11, PST_1_12, PTU_0_1, PTU_0_2, PTU_0_3, PTU_0_4, PTU_1_10, PTU_1_11, PTU_1_12, PME_0_1, PME_0_2, PME_0_3, PME_0_4, PME_1_10, PME_1_11, PME_1_12, PSJ_0_1, PSJ_0_2, PSJ_0_3, PSJ_0_4, PSJ_1_10, PSJ_1_11, PSJ_1_12); + + // push the result on the Stack + stack.push(new Float(result)); + } + + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_cam=ControlData.t_cam+(int) (t2-t1); + } + + public native float camsjrdll(int ICALC, int ICODE, float IYPOSX, float IMPOSX, float IYEARX, float IMX, float IFREQODX, float IFREQ1X, float IFREQ2X, float IFREQ3X, float IFREQ4X, float IFREQ5X, float QST_0_1, float QST_0_2, float QST_0_3, float QST_0_4, float QST_1_1, float QST_1_2, float QST_1_3, float QST_1_4, float QST_1_5, float QST_1_6, float QST_1_7, float QST_1_8, float QST_1_9, float QST_1_10, float QST_1_11, float QST_1_12, float QST_2_10, float QST_2_11, float QST_2_12, float QTU_0_1, float QTU_0_2, float QTU_0_3, float QTU_0_4, float QTU_1_10, float QTU_1_11, float QTU_1_12, float QME_0_1, float QME_0_2, float QME_0_3, float QME_0_4, float QME_1_10, float QME_1_11, float QME_1_12, float QSJ_0_1, float QSJ_0_2, float QSJ_0_3, float QSJ_0_4, float QSJ_1_10, float QSJ_1_11, float QSJ_1_12, float PST_0_1, float PST_0_2, float PST_0_3, float PST_0_4, float PST_1_10, float PST_1_11, float PST_1_12, float PTU_0_1, float PTU_0_2, float PTU_0_3, float PTU_0_4, float PTU_1_10, float PTU_1_11, float PTU_1_12, float PME_0_1, float PME_0_2, float PME_0_3, float PME_0_4, float PME_1_10, float PME_1_11, float PME_1_12, float PSJ_0_1, float PSJ_0_2, float PSJ_0_3, float PSJ_0_4, float PSJ_1_10, float PSJ_1_11, float PSJ_1_12); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongenfrcstrunofftables.java b/wrims-core/src/main/java/wrimsv2/external/Functiongenfrcstrunofftables.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongenfrcstrunofftables.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongenfrcstrunofftables.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionget_req_do.java b/wrims-core/src/main/java/wrimsv2/external/Functionget_req_do.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionget_req_do.java rename to wrims-core/src/main/java/wrimsv2/external/Functionget_req_do.java index 3368925bc..5a7617c1d 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionget_req_do.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functionget_req_do.java @@ -1,101 +1,101 @@ -package wrimsv2.external; - -//import java.io.*; -import java.util.*; - -public class Functionget_req_do extends ExternalFunction{ - - public Functionget_req_do() { - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - float n = ((Number) param7).floatValue(); - float gbeta = ((Number) param6).floatValue(); - float galpha = ((Number) param5).floatValue(); - float Sb = ((Number) param4).floatValue(); - float So = ((Number) param3).floatValue(); - float ECstd = ((Number) param2).floatValue(); - float G_o = ((Number) param1).floatValue(); - - float result = get_Req_DO(G_o, ECstd, So, Sb, galpha, gbeta, n); - stack.push(result); - - } - - private float get_Req_DO(float G_o, float ECstd, float So, float Sb, float galpha, float gbeta, float n) { - - float Qreq, arg2, Gavg,YY,DYDQ,QOLD,QNEW,diff,G99avg; - float gmtol = 1E-08f; - float gmdT = 0.08333f; - int nit; - - // ********************************************************************************** - // Calculate required average G - // check log argument so that it is greater than tolerance, otherwise use tolerance - arg2 = (ECstd - Sb) / (So - Sb); - if (arg2 < gmtol) arg2 = gmtol; -// Gavg = (-LOG(arg2) / galpha)**(1.0 / n); - Gavg = (float)(Math.pow((-Math.log10(arg2) / galpha), (1.0f / n))); - // ********************************************************************************* - // Use Newton-Raphson to calculate required Q given Gavg - // where Gavg = Q + gbeta/gmdT * LN((1 + (Q/G_o-1) * EXP(-Q*gmdT/gbeta))/(Q/G_o)) - // - // Newton-Raphson uses Q new = Q old - Y / (dY/dQ) - // where Y = Q/G_o * EXP(-gmdT*(Q-Gavg)/gbeta) - Q/G_o * EXP(-gmdT*Q/gbeta) - // + EXP(-gmdT*Q/gbeta) - 1.0 - - QOLD = (gbeta * (Gavg - G_o)/(G_o * gmdT)) + 0.5f * (Gavg + G_o); // initial guess - if (QOLD < 500) QOLD = Gavg; // In case initial guess of Q < 0 - - //! Check the value of G99AVE that results from a very low Q of 99 cfs. - //! if Go > Gavg and G99avg > Gavg, - //! then set Qreq = 99, and skip Newton-Raphson step. - - Qreq = 0.0f; - QNEW = 99.0f; // Nominal very low outflow - if (G_o > Gavg) { - G99avg = QNEW + (gbeta / gmdT) * (float)Math.log10((1.0f + (QNEW / G_o - 1.0f) - * (float)Math.exp(-QNEW * gmdT/gbeta)) / (QNEW / G_o)); - if (G99avg >= Gavg) Qreq = 99.0f; - } - if (Qreq < 0.1) { - diff=gmtol + 1; - nit = 0; - while (diff > gmtol) { - nit = nit + 1; - if (nit > 50) { - // System.out.println("Newton-Raphson error - exceeded 50 iterations"); - System.exit(1); - } - YY = (QOLD * (float)Math.exp(-gmdT * (QOLD - Gavg) / gbeta) / G_o - (QOLD / G_o - 1.0f) - * (float)Math.exp(-gmdT * QOLD / gbeta) - 1.0f); - DYDQ = (1.0f / G_o - QOLD * gmdT / (G_o * gbeta)) * (float)Math.exp(-gmdT * (QOLD - Gavg) - / gbeta) - (1.0f / G_o - QOLD * gmdT / (G_o * gbeta) + gmdT / gbeta) - * (float)Math.exp(-gmdT * QOLD/gbeta); - - QNEW = QOLD - YY / DYDQ; - if (QNEW < 0) QNEW = 0; - diff = Math.abs(QNEW - QOLD); - if (QNEW < 0 && QOLD < 0) { - diff = 0; - QNEW = 0; - } - QOLD = QNEW; // Update QOLD value for next iteration - } - Qreq = QOLD; - } - return Qreq; - } -} +package wrimsv2.external; + +//import java.io.*; +import java.util.*; + +public class Functionget_req_do extends ExternalFunction{ + + public Functionget_req_do() { + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + float n = ((Number) param7).floatValue(); + float gbeta = ((Number) param6).floatValue(); + float galpha = ((Number) param5).floatValue(); + float Sb = ((Number) param4).floatValue(); + float So = ((Number) param3).floatValue(); + float ECstd = ((Number) param2).floatValue(); + float G_o = ((Number) param1).floatValue(); + + float result = get_Req_DO(G_o, ECstd, So, Sb, galpha, gbeta, n); + stack.push(result); + + } + + private float get_Req_DO(float G_o, float ECstd, float So, float Sb, float galpha, float gbeta, float n) { + + float Qreq, arg2, Gavg,YY,DYDQ,QOLD,QNEW,diff,G99avg; + float gmtol = 1E-08f; + float gmdT = 0.08333f; + int nit; + + // ********************************************************************************** + // Calculate required average G + // check log argument so that it is greater than tolerance, otherwise use tolerance + arg2 = (ECstd - Sb) / (So - Sb); + if (arg2 < gmtol) arg2 = gmtol; +// Gavg = (-LOG(arg2) / galpha)**(1.0 / n); + Gavg = (float)(Math.pow((-Math.log10(arg2) / galpha), (1.0f / n))); + // ********************************************************************************* + // Use Newton-Raphson to calculate required Q given Gavg + // where Gavg = Q + gbeta/gmdT * LN((1 + (Q/G_o-1) * EXP(-Q*gmdT/gbeta))/(Q/G_o)) + // + // Newton-Raphson uses Q new = Q old - Y / (dY/dQ) + // where Y = Q/G_o * EXP(-gmdT*(Q-Gavg)/gbeta) - Q/G_o * EXP(-gmdT*Q/gbeta) + // + EXP(-gmdT*Q/gbeta) - 1.0 + + QOLD = (gbeta * (Gavg - G_o)/(G_o * gmdT)) + 0.5f * (Gavg + G_o); // initial guess + if (QOLD < 500) QOLD = Gavg; // In case initial guess of Q < 0 + + //! Check the value of G99AVE that results from a very low Q of 99 cfs. + //! if Go > Gavg and G99avg > Gavg, + //! then set Qreq = 99, and skip Newton-Raphson step. + + Qreq = 0.0f; + QNEW = 99.0f; // Nominal very low outflow + if (G_o > Gavg) { + G99avg = QNEW + (gbeta / gmdT) * (float)Math.log10((1.0f + (QNEW / G_o - 1.0f) + * (float)Math.exp(-QNEW * gmdT/gbeta)) / (QNEW / G_o)); + if (G99avg >= Gavg) Qreq = 99.0f; + } + if (Qreq < 0.1) { + diff=gmtol + 1; + nit = 0; + while (diff > gmtol) { + nit = nit + 1; + if (nit > 50) { + // System.out.println("Newton-Raphson error - exceeded 50 iterations"); + System.exit(1); + } + YY = (QOLD * (float)Math.exp(-gmdT * (QOLD - Gavg) / gbeta) / G_o - (QOLD / G_o - 1.0f) + * (float)Math.exp(-gmdT * QOLD / gbeta) - 1.0f); + DYDQ = (1.0f / G_o - QOLD * gmdT / (G_o * gbeta)) * (float)Math.exp(-gmdT * (QOLD - Gavg) + / gbeta) - (1.0f / G_o - QOLD * gmdT / (G_o * gbeta) + gmdT / gbeta) + * (float)Math.exp(-gmdT * QOLD/gbeta); + + QNEW = QOLD - YY / DYDQ; + if (QNEW < 0) QNEW = 0; + diff = Math.abs(QNEW - QOLD); + if (QNEW < 0 && QOLD < 0) { + diff = 0; + QNEW = 0; + } + QOLD = QNEW; // Update QOLD value for next iteration + } + Qreq = QOLD; + } + return Qreq; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetfinalmrdo.java b/wrims-core/src/main/java/wrimsv2/external/Functiongetfinalmrdo.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetfinalmrdo.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongetfinalmrdo.java index 8ce547d7b..9891df33a 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetfinalmrdo.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functiongetfinalmrdo.java @@ -1,257 +1,257 @@ -package wrimsv2.external; - -import java.io.*; -import java.util.*; - -/** - * Custom JEP class for calculating Final Mrdo. - * @author Clay Booher - */ -public class Functiongetfinalmrdo extends ExternalFunction{ - private int _lastmonth; - - // TO DO: pass in absolute path of dll file from study directory structure; USE load instead of loadLibrary - public Functiongetfinalmrdo() { - - } - - public void execute(Stack stack) { - - Object param39 = stack.pop(); - Object param38 = stack.pop(); - Object param37 = stack.pop(); - Object param36 = stack.pop(); - Object param35 = stack.pop(); - Object param34 = stack.pop(); - Object param33 = stack.pop(); - Object param32 = stack.pop(); - Object param31 = stack.pop(); - Object param30 = stack.pop(); - Object param29 = stack.pop(); - Object param28 = stack.pop(); - Object param27 = stack.pop(); - Object param26 = stack.pop(); - Object param25 = stack.pop(); - Object param24 = stack.pop(); - Object param23 = stack.pop(); - Object param22 = stack.pop(); - Object param21 = stack.pop(); - Object param20 = stack.pop(); - Object param19 = stack.pop(); - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int daysin = ((Number) param39).intValue(); - int month = ((Number) param38).intValue(); - int wyear = ((Number) param37).intValue(); - int eday_flw = ((Number) param36).intValue(); - int bday_flw = ((Number) param35).intValue(); - float Qflw = ((Number) param34).floatValue(); - int eday_rsl2 = ((Number) param33).intValue(); - int bday_rsl2 = ((Number) param32).intValue(); - float Qrsl2 = ((Number) param31).floatValue(); - int eday_rsl1 = ((Number) param30).intValue(); - int bday_rsl1 = ((Number) param29).intValue(); - float Qrsl1 = ((Number) param28).floatValue(); - int eday_col2 = ((Number) param27).intValue(); - int bday_col2 = ((Number) param26).intValue(); - float Qcol2 = ((Number) param25).floatValue(); - int eday_col1 = ((Number) param24).intValue(); - int bday_col1 = ((Number) param23).intValue(); - float Qcol1 = ((Number) param22).floatValue(); - int eday_jpt2 = ((Number) param21).intValue(); - int bday_jpt2 = ((Number) param20).intValue(); - float Qjpt2 = ((Number) param19).floatValue(); - int eday_jpt1 = ((Number) param18).intValue(); - int bday_jpt1 = ((Number) param17).intValue(); - float Qjpt1 = ((Number) param16).floatValue(); - int eday_emt2 = ((Number) param15).intValue(); - int bday_emt2 = ((Number) param14).intValue(); - float Qemt2 = ((Number) param13).floatValue(); - int eday_emt1 = ((Number) param12).intValue(); - int bday_emt1 = ((Number) param11).intValue(); - float Qemt1 = ((Number) param10).floatValue(); - int eday_cnf = ((Number) param9).intValue(); - int bday_cnf = ((Number) param8).intValue(); - float Qcnf = ((Number) param7).floatValue(); - int eday_chs = ((Number) param6).intValue(); - int bday_chs = ((Number) param5).intValue(); - float Qchs = ((Number) param4).floatValue(); - int eday_roe = ((Number) param3).intValue(); - int bday_roe = ((Number) param2).intValue(); - float Qroe = ((Number) param1).floatValue(); - - stack.push(new Float(getFinalMrdo(Qroe, bday_roe, eday_roe, Qchs, bday_chs, eday_chs, Qcnf, - bday_cnf, eday_cnf, Qemt1, bday_emt1, eday_emt1, Qemt2, bday_emt2, eday_emt2, Qjpt1, - bday_jpt1, eday_jpt1, Qjpt2, bday_jpt2, eday_jpt2, Qcol1, bday_col1, eday_col1, Qcol2, - bday_col2, eday_col2, Qrsl1, bday_rsl1, eday_rsl1, Qrsl2, bday_rsl2, eday_rsl2, Qflw, - bday_flw, eday_flw, wyear, month, daysin))); - - //System.gc(); - - } - - private float getFinalMrdo(float Qroe, int bday_roe, int eday_roe, float Qchs, int bday_chs, //CB tried synchronized to prevent java.io.FileNotFoundException but it still happened - int eday_chs, float Qcnf, int bday_cnf, int eday_cnf, float Qemt1, int bday_emt1, - int eday_emt1, float Qemt2, int bday_emt2, int eday_emt2, float Qjpt1, int bday_jpt1, - int eday_jpt1, float Qjpt2, int bday_jpt2, int eday_jpt2, float Qcol1, int bday_col1, - int eday_col1, float Qcol2, int bday_col2, int eday_col2, float Qrsl1, int bday_rsl1, - int eday_rsl1, float Qrsl2, int bday_rsl2, int eday_rsl2, float Qflw, int bday_flw, - int eday_flw, int wyear, int month, int daysin) { - - float[] Qout = new float[daysin + 1]; //CB +1 for Java (vs. Fortran) - float mrdo; - - //CHARACTER(LEN=20),DIMENSION(daysin):: control - String[] control = new String[daysin + 1]; //CB +1 for Java (vs. Fortran) - // CHARACTER(LEN=20):: Gcontrol - String Gcontrol; - int em, jp, co, rs; - - //if (wyear==1922 && month==1) OPEN(17,FILE='delta-control.out',STATUS='new') - //if (wyear==1922 && month==1) OPEN(18,FILE='g-control.out',STATUS='new') -/* File deltaControlOut = new File("delta-control.out"); - if (deltaControlOut.exists()) - deltaControlOut.delete(); - File gControlOut = new File("g-control.out"); - if (gControlOut.exists()) - gControlOut.delete(); - PrintStream deltaOutPS = null; - PrintStream gOutPS = null; - try { - FileOutputStream deltaFOS = new FileOutputStream(deltaControlOut); // creates new one if not existing - FileOutputStream gFOS = new FileOutputStream(gControlOut); // creates new one if not existing - deltaOutPS = new PrintStream(deltaFOS); - gOutPS = new PrintStream(gFOS); - } catch (FileNotFoundException fnfe) { - fnfe.printStackTrace(); - } finally { - //CB TODO may need something here if System.gc() above does not eliminate the "The requested operation cannot be performed on a file with a user-mapped section open" - } */ - //WRITE(17,100) 'YEAR = ',wyear, 'MONTH = ',month - //100 FORMAT(1x,a,i4,1x,a,i2) - //System.out.println(" YEAR = " + wyear + " MONTH = " + month); - -// DO i=1,daysin // automatically done in Java -// Qout(i) = 0.0 -// END DO - - for(int i = 1; i <= daysin; ++i) { - if (i >= bday_roe && i <= eday_roe && Qroe > Qout[i]) { - Qout[i] = Qroe; - control[i] = "X2 Roe"; - } - if (i >= bday_chs && i <= eday_chs && Qchs > Qout[i]) { - Qout[i] = Qchs; - control[i] = "X2 Chipps"; - } - if (i >= bday_cnf && i <= eday_cnf && Qcnf > Qout[i]) { - Qout[i] = Qcnf; - control[i] = "X2 Confluence"; - } - if (i >= bday_emt1 && i <= eday_emt1 && Qemt1 > Qout[i]) { - Qout[i] = Qemt1; - control[i] = "Emmaton"; - } - if (i >= bday_emt2 && i <= eday_emt2 && Qemt2 > Qout[i]) { - Qout[i] = Qemt2; - control[i] = "Emmaton"; - } - if (i >= bday_jpt1 && i <= eday_jpt1 && Qjpt1 > Qout[i]) { - Qout[i] = Qjpt1; - control[i] = "Jersey Point"; - } - if (i >= bday_jpt2 && i <= eday_jpt2 && Qjpt2 > Qout[i]) { - Qout[i] = Qjpt2; - control[i] = "Jersey Point"; - } - if (i >= bday_col1 && i <= eday_col1 && Qcol1 > Qout[i]) { - Qout[i] = Qcol1; - control[i] = "Collinsville"; - } - if (i >= bday_col2 && i <= eday_col2 && Qcol2 > Qout[i]) { - Qout[i] = Qcol2; - control[i] = "Collinsville"; - } - if (i >= bday_rsl1 && i <= eday_rsl1 && Qrsl1 > Qout[i]) { - Qout[i] = Qrsl1; - control[i] = "Rock Slough"; - } - if (i >= bday_rsl2 && i <= eday_rsl2 && Qrsl2 > Qout[i]) { - Qout[i] = Qrsl2; - control[i] = "Rock Slough"; - } - if (i >= bday_flw && i <= eday_flw && Qflw > Qout[i]) { - Qout[i] = Qflw; - control[i] = "Flow"; - } - - //WRITE(17,110) 'DAY = ',i,Qout(i),' control = ',control(i) - //110 FORMAT(1x,a,i2,2x,f16.2,2x,a,a) - //System.out.println(" DAY = " + i + " " + Qout[i] + " control = " + control[i]); // TO DO: 16.2 format - } - - //determine what G-model is controling for each month - if (wyear==1922 && month==1) _lastmonth = 12; - em = 0; - jp = 0; - co = 0; - rs = 0; - for(int i = 1; i <= daysin; ++i) { - if (control[i] == "Emmaton") em = em + 1; - if (control[i] == "Jersey Point") jp = jp + 1; - if (control[i] == "Collinsville") co = co + 1; - if (control[i] == "Rock Slough") rs = rs + 1; - } - Gcontrol = "none"; - if(em >= 5) Gcontrol = "Emmaton"; - if(jp >= 5) Gcontrol = "Jersey_Point"; - if(co >= 5) Gcontrol = "Collinsville"; - if(rs >= 5) Gcontrol = "Rock_Slough"; -// if(month /= lastmonth) WRITE(18,111) wyear,month,Gcontrol - //111 FORMAT(i4,x,i2,x,a) - //if(month != _lastmonth) System.out.println(wyear + " " + month + " " + Gcontrol); - _lastmonth = month; - mrdo = sum(Qout)/daysin; - -// if (wyear==1994 && month==12) CLOSE(17) -// if (wyear==1994 && month==12) CLOSE(18) -/* if (wyear==1994 && month==12) { - AppUtils.deltaOutPS.close(); - AppUtils.gOutPS.close(); - AppUtils.deltaOutPS = null; - AppUtils.gOutPS = null; - System.gc(); - } */ - return mrdo; - } - - private float sum(float[] array) { //CB this works even tough the array is one element (#0) longer than it should be; #0 = 0.0. - if(array != null) { - float sum = 0.0f; - for(int i = 0; i < array.length; ++i) { - sum += array[i]; - } - return sum; - } else { - throw new NullPointerException("Method SUM argument cannot be null"); - } - } -} +package wrimsv2.external; + +import java.io.*; +import java.util.*; + +/** + * Custom JEP class for calculating Final Mrdo. + * @author Clay Booher + */ +public class Functiongetfinalmrdo extends ExternalFunction{ + private int _lastmonth; + + // TO DO: pass in absolute path of dll file from study directory structure; USE load instead of loadLibrary + public Functiongetfinalmrdo() { + + } + + public void execute(Stack stack) { + + Object param39 = stack.pop(); + Object param38 = stack.pop(); + Object param37 = stack.pop(); + Object param36 = stack.pop(); + Object param35 = stack.pop(); + Object param34 = stack.pop(); + Object param33 = stack.pop(); + Object param32 = stack.pop(); + Object param31 = stack.pop(); + Object param30 = stack.pop(); + Object param29 = stack.pop(); + Object param28 = stack.pop(); + Object param27 = stack.pop(); + Object param26 = stack.pop(); + Object param25 = stack.pop(); + Object param24 = stack.pop(); + Object param23 = stack.pop(); + Object param22 = stack.pop(); + Object param21 = stack.pop(); + Object param20 = stack.pop(); + Object param19 = stack.pop(); + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int daysin = ((Number) param39).intValue(); + int month = ((Number) param38).intValue(); + int wyear = ((Number) param37).intValue(); + int eday_flw = ((Number) param36).intValue(); + int bday_flw = ((Number) param35).intValue(); + float Qflw = ((Number) param34).floatValue(); + int eday_rsl2 = ((Number) param33).intValue(); + int bday_rsl2 = ((Number) param32).intValue(); + float Qrsl2 = ((Number) param31).floatValue(); + int eday_rsl1 = ((Number) param30).intValue(); + int bday_rsl1 = ((Number) param29).intValue(); + float Qrsl1 = ((Number) param28).floatValue(); + int eday_col2 = ((Number) param27).intValue(); + int bday_col2 = ((Number) param26).intValue(); + float Qcol2 = ((Number) param25).floatValue(); + int eday_col1 = ((Number) param24).intValue(); + int bday_col1 = ((Number) param23).intValue(); + float Qcol1 = ((Number) param22).floatValue(); + int eday_jpt2 = ((Number) param21).intValue(); + int bday_jpt2 = ((Number) param20).intValue(); + float Qjpt2 = ((Number) param19).floatValue(); + int eday_jpt1 = ((Number) param18).intValue(); + int bday_jpt1 = ((Number) param17).intValue(); + float Qjpt1 = ((Number) param16).floatValue(); + int eday_emt2 = ((Number) param15).intValue(); + int bday_emt2 = ((Number) param14).intValue(); + float Qemt2 = ((Number) param13).floatValue(); + int eday_emt1 = ((Number) param12).intValue(); + int bday_emt1 = ((Number) param11).intValue(); + float Qemt1 = ((Number) param10).floatValue(); + int eday_cnf = ((Number) param9).intValue(); + int bday_cnf = ((Number) param8).intValue(); + float Qcnf = ((Number) param7).floatValue(); + int eday_chs = ((Number) param6).intValue(); + int bday_chs = ((Number) param5).intValue(); + float Qchs = ((Number) param4).floatValue(); + int eday_roe = ((Number) param3).intValue(); + int bday_roe = ((Number) param2).intValue(); + float Qroe = ((Number) param1).floatValue(); + + stack.push(new Float(getFinalMrdo(Qroe, bday_roe, eday_roe, Qchs, bday_chs, eday_chs, Qcnf, + bday_cnf, eday_cnf, Qemt1, bday_emt1, eday_emt1, Qemt2, bday_emt2, eday_emt2, Qjpt1, + bday_jpt1, eday_jpt1, Qjpt2, bday_jpt2, eday_jpt2, Qcol1, bday_col1, eday_col1, Qcol2, + bday_col2, eday_col2, Qrsl1, bday_rsl1, eday_rsl1, Qrsl2, bday_rsl2, eday_rsl2, Qflw, + bday_flw, eday_flw, wyear, month, daysin))); + + //System.gc(); + + } + + private float getFinalMrdo(float Qroe, int bday_roe, int eday_roe, float Qchs, int bday_chs, //CB tried synchronized to prevent java.io.FileNotFoundException but it still happened + int eday_chs, float Qcnf, int bday_cnf, int eday_cnf, float Qemt1, int bday_emt1, + int eday_emt1, float Qemt2, int bday_emt2, int eday_emt2, float Qjpt1, int bday_jpt1, + int eday_jpt1, float Qjpt2, int bday_jpt2, int eday_jpt2, float Qcol1, int bday_col1, + int eday_col1, float Qcol2, int bday_col2, int eday_col2, float Qrsl1, int bday_rsl1, + int eday_rsl1, float Qrsl2, int bday_rsl2, int eday_rsl2, float Qflw, int bday_flw, + int eday_flw, int wyear, int month, int daysin) { + + float[] Qout = new float[daysin + 1]; //CB +1 for Java (vs. Fortran) + float mrdo; + + //CHARACTER(LEN=20),DIMENSION(daysin):: control + String[] control = new String[daysin + 1]; //CB +1 for Java (vs. Fortran) + // CHARACTER(LEN=20):: Gcontrol + String Gcontrol; + int em, jp, co, rs; + + //if (wyear==1922 && month==1) OPEN(17,FILE='delta-control.out',STATUS='new') + //if (wyear==1922 && month==1) OPEN(18,FILE='g-control.out',STATUS='new') +/* File deltaControlOut = new File("delta-control.out"); + if (deltaControlOut.exists()) + deltaControlOut.delete(); + File gControlOut = new File("g-control.out"); + if (gControlOut.exists()) + gControlOut.delete(); + PrintStream deltaOutPS = null; + PrintStream gOutPS = null; + try { + FileOutputStream deltaFOS = new FileOutputStream(deltaControlOut); // creates new one if not existing + FileOutputStream gFOS = new FileOutputStream(gControlOut); // creates new one if not existing + deltaOutPS = new PrintStream(deltaFOS); + gOutPS = new PrintStream(gFOS); + } catch (FileNotFoundException fnfe) { + fnfe.printStackTrace(); + } finally { + //CB TODO may need something here if System.gc() above does not eliminate the "The requested operation cannot be performed on a file with a user-mapped section open" + } */ + //WRITE(17,100) 'YEAR = ',wyear, 'MONTH = ',month + //100 FORMAT(1x,a,i4,1x,a,i2) + //System.out.println(" YEAR = " + wyear + " MONTH = " + month); + +// DO i=1,daysin // automatically done in Java +// Qout(i) = 0.0 +// END DO + + for(int i = 1; i <= daysin; ++i) { + if (i >= bday_roe && i <= eday_roe && Qroe > Qout[i]) { + Qout[i] = Qroe; + control[i] = "X2 Roe"; + } + if (i >= bday_chs && i <= eday_chs && Qchs > Qout[i]) { + Qout[i] = Qchs; + control[i] = "X2 Chipps"; + } + if (i >= bday_cnf && i <= eday_cnf && Qcnf > Qout[i]) { + Qout[i] = Qcnf; + control[i] = "X2 Confluence"; + } + if (i >= bday_emt1 && i <= eday_emt1 && Qemt1 > Qout[i]) { + Qout[i] = Qemt1; + control[i] = "Emmaton"; + } + if (i >= bday_emt2 && i <= eday_emt2 && Qemt2 > Qout[i]) { + Qout[i] = Qemt2; + control[i] = "Emmaton"; + } + if (i >= bday_jpt1 && i <= eday_jpt1 && Qjpt1 > Qout[i]) { + Qout[i] = Qjpt1; + control[i] = "Jersey Point"; + } + if (i >= bday_jpt2 && i <= eday_jpt2 && Qjpt2 > Qout[i]) { + Qout[i] = Qjpt2; + control[i] = "Jersey Point"; + } + if (i >= bday_col1 && i <= eday_col1 && Qcol1 > Qout[i]) { + Qout[i] = Qcol1; + control[i] = "Collinsville"; + } + if (i >= bday_col2 && i <= eday_col2 && Qcol2 > Qout[i]) { + Qout[i] = Qcol2; + control[i] = "Collinsville"; + } + if (i >= bday_rsl1 && i <= eday_rsl1 && Qrsl1 > Qout[i]) { + Qout[i] = Qrsl1; + control[i] = "Rock Slough"; + } + if (i >= bday_rsl2 && i <= eday_rsl2 && Qrsl2 > Qout[i]) { + Qout[i] = Qrsl2; + control[i] = "Rock Slough"; + } + if (i >= bday_flw && i <= eday_flw && Qflw > Qout[i]) { + Qout[i] = Qflw; + control[i] = "Flow"; + } + + //WRITE(17,110) 'DAY = ',i,Qout(i),' control = ',control(i) + //110 FORMAT(1x,a,i2,2x,f16.2,2x,a,a) + //System.out.println(" DAY = " + i + " " + Qout[i] + " control = " + control[i]); // TO DO: 16.2 format + } + + //determine what G-model is controling for each month + if (wyear==1922 && month==1) _lastmonth = 12; + em = 0; + jp = 0; + co = 0; + rs = 0; + for(int i = 1; i <= daysin; ++i) { + if (control[i] == "Emmaton") em = em + 1; + if (control[i] == "Jersey Point") jp = jp + 1; + if (control[i] == "Collinsville") co = co + 1; + if (control[i] == "Rock Slough") rs = rs + 1; + } + Gcontrol = "none"; + if(em >= 5) Gcontrol = "Emmaton"; + if(jp >= 5) Gcontrol = "Jersey_Point"; + if(co >= 5) Gcontrol = "Collinsville"; + if(rs >= 5) Gcontrol = "Rock_Slough"; +// if(month /= lastmonth) WRITE(18,111) wyear,month,Gcontrol + //111 FORMAT(i4,x,i2,x,a) + //if(month != _lastmonth) System.out.println(wyear + " " + month + " " + Gcontrol); + _lastmonth = month; + mrdo = sum(Qout)/daysin; + +// if (wyear==1994 && month==12) CLOSE(17) +// if (wyear==1994 && month==12) CLOSE(18) +/* if (wyear==1994 && month==12) { + AppUtils.deltaOutPS.close(); + AppUtils.gOutPS.close(); + AppUtils.deltaOutPS = null; + AppUtils.gOutPS = null; + System.gc(); + } */ + return mrdo; + } + + private float sum(float[] array) { //CB this works even tough the array is one element (#0) longer than it should be; #0 = 0.0. + if(array != null) { + float sum = 0.0f; + for(int i = 0; i < array.length; ++i) { + sum += array[i]; + } + return sum; + } else { + throw new NullPointerException("Method SUM argument cannot be null"); + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetghbflow.java b/wrims-core/src/main/java/wrimsv2/external/Functiongetghbflow.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetghbflow.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongetghbflow.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetgw_h.java b/wrims-core/src/main/java/wrimsv2/external/Functiongetgw_h.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetgw_h.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongetgw_h.java index 9b14d0906..b7ca3b00c 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetgw_h.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functiongetgw_h.java @@ -1,30 +1,30 @@ -package wrimsv2.external; - -import java.util.*; - -public class Functiongetgw_h extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functiongetgw_h(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int Layer = ((Number) param2).intValue(); - int indxGW = ((Number) param1).intValue(); - - float result = getgw_h(indxGW, Layer); - - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float getgw_h(int indxGW, int Layer); -} +package wrimsv2.external; + +import java.util.*; + +public class Functiongetgw_h extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functiongetgw_h(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int Layer = ((Number) param2).intValue(); + int indxGW = ((Number) param1).intValue(); + + float result = getgw_h(indxGW, Layer); + + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float getgw_h(int indxGW, int Layer); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetndo_x2.java b/wrims-core/src/main/java/wrimsv2/external/Functiongetndo_x2.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetndo_x2.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongetndo_x2.java index caad0eab0..04d689bd9 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetndo_x2.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functiongetndo_x2.java @@ -1,76 +1,76 @@ -package wrimsv2.external; - -import java.util.*; - -import wrimsv2.components.ControlData; - -public class Functiongetndo_x2 extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functiongetndo_x2(){ - - } - - public void execute(Stack stack) { - - long t1 = Calendar.getInstance().getTimeInMillis(); - - //values in reverse order: - Object param20 = stack.pop(); - Object param19 = stack.pop(); - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int EndDay = ((Number) param20).intValue(); - int BeginDay = ((Number) param19).intValue(); - int currYear = ((Number) param18).intValue(); - int currMonth = ((Number) param17).intValue(); - int ave_type = ((Number) param16).intValue(); - int mon4 = ((Number) param15).intValue(); - int mon3 = ((Number) param14).intValue(); - int mon2 = ((Number) param13).intValue(); - int mon1 = ((Number) param12).intValue(); - int mon0 = ((Number) param11).intValue(); - float DO_prv3 = ((Number) param10).floatValue(); - float DO_prv2 = ((Number) param9).floatValue(); - float DO_prv1 = ((Number) param8).floatValue(); - float DO_prv0 = ((Number) param7).floatValue(); - float X2_prv4 = ((Number) param6).floatValue(); - float X2_prv3 = ((Number) param5).floatValue(); - float X2_prv2 = ((Number) param4).floatValue(); - float X2_prv1 = ((Number) param3).floatValue(); - float X2_prv0 = ((Number) param2).floatValue(); - float X2 = ((Number) param1).floatValue(); - - float result = getndo_x2(X2, X2_prv0, X2_prv1, X2_prv2, X2_prv3, X2_prv4, DO_prv0, DO_prv1, DO_prv2, DO_prv3, mon0, mon1, mon2, mon3, mon4, ave_type, currMonth, currYear, BeginDay, EndDay); - - // push the result on the Stack - stack.push(new Float(result)); - - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); - ControlData.t_anngetndo_x2=ControlData.t_anngetndo_x2+(int) (t2-t1); - ControlData.n_ann=ControlData.n_ann+1; - ControlData.n_anngetndo_x2=ControlData.n_anngetndo_x2+1; - } - - public native float getndo_x2(float X2, float X2_prv0, float X2_prv1, float X2_prv2, float X2_prv3, float X2_prv4, float DO_prv0, float DO_prv1, float DO_prv2, float DO_prv3, int mon0, int mon1, int mon2, int mon3, int mon4, int ave_type, int currMonth, int currYear, int BeginDay, int EndDay); -} +package wrimsv2.external; + +import java.util.*; + +import wrimsv2.components.ControlData; + +public class Functiongetndo_x2 extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functiongetndo_x2(){ + + } + + public void execute(Stack stack) { + + long t1 = Calendar.getInstance().getTimeInMillis(); + + //values in reverse order: + Object param20 = stack.pop(); + Object param19 = stack.pop(); + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int EndDay = ((Number) param20).intValue(); + int BeginDay = ((Number) param19).intValue(); + int currYear = ((Number) param18).intValue(); + int currMonth = ((Number) param17).intValue(); + int ave_type = ((Number) param16).intValue(); + int mon4 = ((Number) param15).intValue(); + int mon3 = ((Number) param14).intValue(); + int mon2 = ((Number) param13).intValue(); + int mon1 = ((Number) param12).intValue(); + int mon0 = ((Number) param11).intValue(); + float DO_prv3 = ((Number) param10).floatValue(); + float DO_prv2 = ((Number) param9).floatValue(); + float DO_prv1 = ((Number) param8).floatValue(); + float DO_prv0 = ((Number) param7).floatValue(); + float X2_prv4 = ((Number) param6).floatValue(); + float X2_prv3 = ((Number) param5).floatValue(); + float X2_prv2 = ((Number) param4).floatValue(); + float X2_prv1 = ((Number) param3).floatValue(); + float X2_prv0 = ((Number) param2).floatValue(); + float X2 = ((Number) param1).floatValue(); + + float result = getndo_x2(X2, X2_prv0, X2_prv1, X2_prv2, X2_prv3, X2_prv4, DO_prv0, DO_prv1, DO_prv2, DO_prv3, mon0, mon1, mon2, mon3, mon4, ave_type, currMonth, currYear, BeginDay, EndDay); + + // push the result on the Stack + stack.push(new Float(result)); + + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); + ControlData.t_anngetndo_x2=ControlData.t_anngetndo_x2+(int) (t2-t1); + ControlData.n_ann=ControlData.n_ann+1; + ControlData.n_anngetndo_x2=ControlData.n_anngetndo_x2+1; + } + + public native float getndo_x2(float X2, float X2_prv0, float X2_prv1, float X2_prv2, float X2_prv3, float X2_prv4, float DO_prv0, float DO_prv1, float DO_prv2, float DO_prv3, int mon0, int mon1, int mon2, int mon3, int mon4, int ave_type, int currMonth, int currYear, int BeginDay, int EndDay); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetndo_x2_curmonndosplit.java b/wrims-core/src/main/java/wrimsv2/external/Functiongetndo_x2_curmonndosplit.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetndo_x2_curmonndosplit.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongetndo_x2_curmonndosplit.java index f28717c0f..088b2e5fd 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetndo_x2_curmonndosplit.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functiongetndo_x2_curmonndosplit.java @@ -1,84 +1,84 @@ -package wrimsv2.external; - -import java.util.*; - -import wrimsv2.components.ControlData; - -public class Functiongetndo_x2_curmonndosplit extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functiongetndo_x2_curmonndosplit(){ - - } - - public void execute(Stack stack) { - - long t1 = Calendar.getInstance().getTimeInMillis(); - - //values in reverse order: - Object param24 = stack.pop(); - Object param23 = stack.pop(); - Object param22 = stack.pop(); - Object param21 = stack.pop(); - Object param20 = stack.pop(); - Object param19 = stack.pop(); - Object param18 = stack.pop(); - Object param17 = stack.pop(); - Object param16 = stack.pop(); - Object param15 = stack.pop(); - Object param14 = stack.pop(); - Object param13 = stack.pop(); - Object param12 = stack.pop(); - Object param11 = stack.pop(); - Object param10 = stack.pop(); - Object param9 = stack.pop(); - Object param8 = stack.pop(); - Object param7 = stack.pop(); - Object param6 = stack.pop(); - Object param5 = stack.pop(); - Object param4 = stack.pop(); - Object param3 = stack.pop(); - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int EndDay = ((Number) param24).intValue(); - int BeginDay = ((Number) param23).intValue(); - int currYear = ((Number) param22).intValue(); - int currMonth = ((Number) param21).intValue(); - int ave_type = ((Number) param20).intValue(); - int mon4_2 = ((Number) param19).intValue(); - int mon4_1 = ((Number) param18).intValue(); - int mon4 = ((Number) param17).intValue(); - int mon3 = ((Number) param16).intValue(); - int mon2 = ((Number) param15).intValue(); - int mon1 = ((Number) param14).intValue(); - int mon0 = ((Number) param13).intValue(); - float DO_prv4_2 = ((Number) param12).floatValue(); - float DO_prv4_1 = ((Number) param11).floatValue(); - float DO_prv3 = ((Number) param10).floatValue(); - float DO_prv2 = ((Number) param9).floatValue(); - float DO_prv1 = ((Number) param8).floatValue(); - float DO_prv0 = ((Number) param7).floatValue(); - float X2_prv4 = ((Number) param6).floatValue(); - float X2_prv3 = ((Number) param5).floatValue(); - float X2_prv2 = ((Number) param4).floatValue(); - float X2_prv1 = ((Number) param3).floatValue(); - float X2_prv0 = ((Number) param2).floatValue(); - float X2 = ((Number) param1).floatValue(); - - float result = getndo_x2_curmonndosplit(X2, X2_prv0, X2_prv1, X2_prv2, X2_prv3, X2_prv4, DO_prv0, DO_prv1, DO_prv2, DO_prv3, DO_prv4_1, DO_prv4_2, mon0, mon1, mon2, mon3, mon4, mon4_1, mon4_2, ave_type, currMonth, currYear, BeginDay, EndDay); - - // push the result on the Stack - stack.push(new Float(result)); - - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); - ControlData.t_anngetndo_x2_curmonndosplit=ControlData.t_anngetndo_x2_curmonndosplit+(int) (t2-t1); - ControlData.n_ann=ControlData.n_ann+1; - ControlData.n_anngetndo_x2_curmonndosplit=ControlData.n_anngetndo_x2_curmonndosplit+1; - } - - public native float getndo_x2_curmonndosplit(float X2, float X2_prv0, float X2_prv1, float X2_prv2, float X2_prv3, float X2_prv4, float DO_prv0, float DO_prv1, float DO_prv2, float DO_prv3, float DO_prv4_1, float DO_prv4_2, int mon0, int mon1, int mon2, int mon3, int mon4, int mon4_1, int mon4_2, int ave_type, int currMonth, int currYear, int BeginDay, int EndDay); -} +package wrimsv2.external; + +import java.util.*; + +import wrimsv2.components.ControlData; + +public class Functiongetndo_x2_curmonndosplit extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functiongetndo_x2_curmonndosplit(){ + + } + + public void execute(Stack stack) { + + long t1 = Calendar.getInstance().getTimeInMillis(); + + //values in reverse order: + Object param24 = stack.pop(); + Object param23 = stack.pop(); + Object param22 = stack.pop(); + Object param21 = stack.pop(); + Object param20 = stack.pop(); + Object param19 = stack.pop(); + Object param18 = stack.pop(); + Object param17 = stack.pop(); + Object param16 = stack.pop(); + Object param15 = stack.pop(); + Object param14 = stack.pop(); + Object param13 = stack.pop(); + Object param12 = stack.pop(); + Object param11 = stack.pop(); + Object param10 = stack.pop(); + Object param9 = stack.pop(); + Object param8 = stack.pop(); + Object param7 = stack.pop(); + Object param6 = stack.pop(); + Object param5 = stack.pop(); + Object param4 = stack.pop(); + Object param3 = stack.pop(); + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int EndDay = ((Number) param24).intValue(); + int BeginDay = ((Number) param23).intValue(); + int currYear = ((Number) param22).intValue(); + int currMonth = ((Number) param21).intValue(); + int ave_type = ((Number) param20).intValue(); + int mon4_2 = ((Number) param19).intValue(); + int mon4_1 = ((Number) param18).intValue(); + int mon4 = ((Number) param17).intValue(); + int mon3 = ((Number) param16).intValue(); + int mon2 = ((Number) param15).intValue(); + int mon1 = ((Number) param14).intValue(); + int mon0 = ((Number) param13).intValue(); + float DO_prv4_2 = ((Number) param12).floatValue(); + float DO_prv4_1 = ((Number) param11).floatValue(); + float DO_prv3 = ((Number) param10).floatValue(); + float DO_prv2 = ((Number) param9).floatValue(); + float DO_prv1 = ((Number) param8).floatValue(); + float DO_prv0 = ((Number) param7).floatValue(); + float X2_prv4 = ((Number) param6).floatValue(); + float X2_prv3 = ((Number) param5).floatValue(); + float X2_prv2 = ((Number) param4).floatValue(); + float X2_prv1 = ((Number) param3).floatValue(); + float X2_prv0 = ((Number) param2).floatValue(); + float X2 = ((Number) param1).floatValue(); + + float result = getndo_x2_curmonndosplit(X2, X2_prv0, X2_prv1, X2_prv2, X2_prv3, X2_prv4, DO_prv0, DO_prv1, DO_prv2, DO_prv3, DO_prv4_1, DO_prv4_2, mon0, mon1, mon2, mon3, mon4, mon4_1, mon4_2, ave_type, currMonth, currYear, BeginDay, EndDay); + + // push the result on the Stack + stack.push(new Float(result)); + + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_ann=ControlData.t_ann+(int) (t2-t1); + ControlData.t_anngetndo_x2_curmonndosplit=ControlData.t_anngetndo_x2_curmonndosplit+(int) (t2-t1); + ControlData.n_ann=ControlData.n_ann+1; + ControlData.n_anngetndo_x2_curmonndosplit=ControlData.n_anngetndo_x2_curmonndosplit+1; + } + + public native float getndo_x2_curmonndosplit(float X2, float X2_prv0, float X2_prv1, float X2_prv2, float X2_prv3, float X2_prv4, float DO_prv0, float DO_prv1, float DO_prv2, float DO_prv3, float DO_prv4_1, float DO_prv4_2, int mon0, int mon1, int mon2, int mon3, int mon4, int mon4_1, int mon4_2, int ave_type, int currMonth, int currYear, int BeginDay, int EndDay); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetndo_x2_daily.java b/wrims-core/src/main/java/wrimsv2/external/Functiongetndo_x2_daily.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetndo_x2_daily.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongetndo_x2_daily.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetpercentpumpshort.java b/wrims-core/src/main/java/wrimsv2/external/Functiongetpercentpumpshort.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetpercentpumpshort.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongetpercentpumpshort.java index cf0d1f7dd..475a46632 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetpercentpumpshort.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functiongetpercentpumpshort.java @@ -1,28 +1,28 @@ -package wrimsv2.external; - -import java.util.*; - -public class Functiongetpercentpumpshort extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functiongetpercentpumpshort(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param1 = stack.pop(); - - //cast params to correct types: - int iDummy = ((Number) param1).intValue(); - - float result = getpercentpumpshort(iDummy); - - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float getpercentpumpshort(int iDummy); -} +package wrimsv2.external; + +import java.util.*; + +public class Functiongetpercentpumpshort extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functiongetpercentpumpshort(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param1 = stack.pop(); + + //cast params to correct types: + int iDummy = ((Number) param1).intValue(); + + float result = getpercentpumpshort(iDummy); + + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float getpercentpumpshort(int iDummy); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetpumpshort.java b/wrims-core/src/main/java/wrimsv2/external/Functiongetpumpshort.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetpumpshort.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongetpumpshort.java index 5f03ad5d0..f8b8fafba 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetpumpshort.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functiongetpumpshort.java @@ -1,28 +1,28 @@ -package wrimsv2.external; - -import java.util.*; - -public class Functiongetpumpshort extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functiongetpumpshort(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param1 = stack.pop(); - - //cast params to correct types: - int iDummy = ((Number) param1).intValue(); - - float result = getpumpshort(iDummy); - - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float getpumpshort(int iDummy); -} +package wrimsv2.external; + +import java.util.*; + +public class Functiongetpumpshort extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functiongetpumpshort(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param1 = stack.pop(); + + //cast params to correct types: + int iDummy = ((Number) param1).intValue(); + + float result = getpumpshort(iDummy); + + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float getpumpshort(int iDummy); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetseep.java b/wrims-core/src/main/java/wrimsv2/external/Functiongetseep.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetseep.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongetseep.java index 8f0bcbbc4..1917da6d5 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetseep.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functiongetseep.java @@ -1,28 +1,28 @@ -package wrimsv2.external; - -import java.util.*; - -public class Functiongetseep extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functiongetseep(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param1 = stack.pop(); - - //cast params to correct types: - int indxStrm = ((Number) param1).intValue(); - - float result = getseep(indxStrm); - - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float getseep(int indxStrm); -} +package wrimsv2.external; + +import java.util.*; + +public class Functiongetseep extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functiongetseep(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param1 = stack.pop(); + + //cast params to correct types: + int indxStrm = ((Number) param1).intValue(); + + float result = getseep(indxStrm); + + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float getseep(int indxStrm); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetseep_givenstrmflow.java b/wrims-core/src/main/java/wrimsv2/external/Functiongetseep_givenstrmflow.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetseep_givenstrmflow.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongetseep_givenstrmflow.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetstrm_h.java b/wrims-core/src/main/java/wrimsv2/external/Functiongetstrm_h.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetstrm_h.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongetstrm_h.java index 40058ab73..1d4ef98b2 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongetstrm_h.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functiongetstrm_h.java @@ -1,28 +1,28 @@ -package wrimsv2.external; - -import java.util.*; - -public class Functiongetstrm_h extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functiongetstrm_h(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param1 = stack.pop(); - - //cast params to correct types: - int indxStrm = ((Number) param1).intValue(); - - float result = getstrm_h(indxStrm); - - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float getstrm_h(int indxStrm); -} +package wrimsv2.external; + +import java.util.*; + +public class Functiongetstrm_h extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functiongetstrm_h(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param1 = stack.pop(); + + //cast params to correct types: + int indxStrm = ((Number) param1).intValue(); + + float result = getstrm_h(indxStrm); + + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float getstrm_h(int indxStrm); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functiongettdrainintostream.java b/wrims-core/src/main/java/wrimsv2/external/Functiongettdrainintostream.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functiongettdrainintostream.java rename to wrims-core/src/main/java/wrimsv2/external/Functiongettdrainintostream.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionhydroforecast.java b/wrims-core/src/main/java/wrimsv2/external/Functionhydroforecast.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionhydroforecast.java rename to wrims-core/src/main/java/wrimsv2/external/Functionhydroforecast.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functioninitgwsystem.java b/wrims-core/src/main/java/wrimsv2/external/Functioninitgwsystem.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functioninitgwsystem.java rename to wrims-core/src/main/java/wrimsv2/external/Functioninitgwsystem.java index c28b9bec2..79293b3c3 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functioninitgwsystem.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functioninitgwsystem.java @@ -1,67 +1,67 @@ -package wrimsv2.external; - -import java.io.File; -import java.util.*; - -import wrimsv2.components.ControlData; -import wrimsv2.components.DebugInterface; -import wrimsv2.components.FilePaths; -import wrimsv2.components.VariableTimeStep; -import wrimsv2.ilp.ILP; - -public class Functioninitgwsystem extends ExternalFunction{ - private final boolean DEBUG = false; - - public Functioninitgwsystem(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param1 = stack.pop(); - - String cGWPath = FilePaths.groundwaterDir; - int iLenGWPath = cGWPath.length(); - String cOutPath = FilePaths.dvarDssDirectory; - int iLenOutPath = cOutPath.length(); - String cTimeStep = ControlData.defaultTimeStep; - int iNTimeSteps = VariableTimeStep.getTotalTimeStep(ControlData.defaultTimeStep); - int iSimBeginMonth; - int iSimBeginYear; - int iResimulate; - if (ControlData.resimGroundwater){ - ControlData.resimGroundwater=false; - iSimBeginMonth = ControlData.resimMonth; - iSimBeginYear = ControlData.resimYear; - iResimulate=1; - }else{ - iSimBeginMonth = ControlData.startMonth; - iSimBeginYear = ControlData.startYear; - iResimulate=0; - } - int iSimMode=0; - - if (ILP.logging){ - iSimMode = 1; - } - - int iNRestartFiles=12; - if (ControlData.allRestartFiles){ - iNRestartFiles=-1; - }else{ - iNRestartFiles=ControlData.numberRestartFiles; - } - - int iPrintFuncCalls=0; - if (ControlData.printGWFuncCalls){ - iPrintFuncCalls=1; - } - - float result = initgwsystem(cGWPath,iLenGWPath,cOutPath,iLenOutPath,cTimeStep,iNTimeSteps,iSimBeginMonth,iSimBeginYear,iSimMode,iNRestartFiles,iResimulate, iPrintFuncCalls); - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float initgwsystem(String cGWPath, int iLenGWPath,String cOutPath, int iLenOutPath, String cTimeStep, int iNTimeSteps, int iSimBeginMonth, int iSimBeginYear, int iSimMode, int iNRestartFiles, int iResimulate, int iPrintFuncCalls); -} +package wrimsv2.external; + +import java.io.File; +import java.util.*; + +import wrimsv2.components.ControlData; +import wrimsv2.components.DebugInterface; +import wrimsv2.components.FilePaths; +import wrimsv2.components.VariableTimeStep; +import wrimsv2.ilp.ILP; + +public class Functioninitgwsystem extends ExternalFunction{ + private final boolean DEBUG = false; + + public Functioninitgwsystem(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param1 = stack.pop(); + + String cGWPath = FilePaths.groundwaterDir; + int iLenGWPath = cGWPath.length(); + String cOutPath = FilePaths.dvarDssDirectory; + int iLenOutPath = cOutPath.length(); + String cTimeStep = ControlData.defaultTimeStep; + int iNTimeSteps = VariableTimeStep.getTotalTimeStep(ControlData.defaultTimeStep); + int iSimBeginMonth; + int iSimBeginYear; + int iResimulate; + if (ControlData.resimGroundwater){ + ControlData.resimGroundwater=false; + iSimBeginMonth = ControlData.resimMonth; + iSimBeginYear = ControlData.resimYear; + iResimulate=1; + }else{ + iSimBeginMonth = ControlData.startMonth; + iSimBeginYear = ControlData.startYear; + iResimulate=0; + } + int iSimMode=0; + + if (ILP.logging){ + iSimMode = 1; + } + + int iNRestartFiles=12; + if (ControlData.allRestartFiles){ + iNRestartFiles=-1; + }else{ + iNRestartFiles=ControlData.numberRestartFiles; + } + + int iPrintFuncCalls=0; + if (ControlData.printGWFuncCalls){ + iPrintFuncCalls=1; + } + + float result = initgwsystem(cGWPath,iLenGWPath,cOutPath,iLenOutPath,cTimeStep,iNTimeSteps,iSimBeginMonth,iSimBeginYear,iSimMode,iNRestartFiles,iResimulate, iPrintFuncCalls); + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float initgwsystem(String cGWPath, int iLenGWPath,String cOutPath, int iLenOutPath, String cTimeStep, int iNTimeSteps, int iSimBeginMonth, int iSimBeginYear, int iSimMode, int iNRestartFiles, int iResimulate, int iPrintFuncCalls); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionprintgwresults.java b/wrims-core/src/main/java/wrimsv2/external/Functionprintgwresults.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionprintgwresults.java rename to wrims-core/src/main/java/wrimsv2/external/Functionprintgwresults.java index f5dec6eac..211e89633 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionprintgwresults.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functionprintgwresults.java @@ -1,30 +1,30 @@ -package wrimsv2.external; - -import java.util.*; - -public class Functionprintgwresults extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functionprintgwresults(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int Month = ((Number) param2).intValue(); - int WaterYear = ((Number) param1).intValue(); - - float result = printgwresults(WaterYear, Month); - - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float printgwresults(int WaterYear, int Month); -} +package wrimsv2.external; + +import java.util.*; + +public class Functionprintgwresults extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functionprintgwresults(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int Month = ((Number) param2).intValue(); + int WaterYear = ((Number) param1).intValue(); + + float result = printgwresults(WaterYear, Month); + + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float printgwresults(int WaterYear, int Month); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetdp.java b/wrims-core/src/main/java/wrimsv2/external/Functionsetdp.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetdp.java rename to wrims-core/src/main/java/wrimsv2/external/Functionsetdp.java index 583256849..ff1258631 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetdp.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functionsetdp.java @@ -1,30 +1,30 @@ -package wrimsv2.external; - -import java.util.*; - -public class Functionsetdp extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functionsetdp(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int WBAIndex = ((Number) param2).intValue(); - float Value = ((Number) param1).floatValue(); - - float result = setdp(Value, WBAIndex); - - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float setdp(float Value, int WBAIndex); -} +package wrimsv2.external; + +import java.util.*; + +public class Functionsetdp extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functionsetdp(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int WBAIndex = ((Number) param2).intValue(); + float Value = ((Number) param1).floatValue(); + + float result = setdp(Value, WBAIndex); + + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float setdp(float Value, int WBAIndex); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetgeneralheadbc.java b/wrims-core/src/main/java/wrimsv2/external/Functionsetgeneralheadbc.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetgeneralheadbc.java rename to wrims-core/src/main/java/wrimsv2/external/Functionsetgeneralheadbc.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetgp.java b/wrims-core/src/main/java/wrimsv2/external/Functionsetgp.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetgp.java rename to wrims-core/src/main/java/wrimsv2/external/Functionsetgp.java index f5906975d..b9589e5f9 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetgp.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functionsetgp.java @@ -1,30 +1,30 @@ -package wrimsv2.external; - -import java.util.*; - -public class Functionsetgp extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functionsetgp(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int WBAIndex = ((Number) param2).intValue(); - float Value = ((Number) param1).floatValue(); - - float result = setgp(Value, WBAIndex); - - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float setgp(float Value, int WBAIndex); -} +package wrimsv2.external; + +import java.util.*; + +public class Functionsetgp extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functionsetgp(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int WBAIndex = ((Number) param2).intValue(); + float Value = ((Number) param1).floatValue(); + + float result = setgp(Value, WBAIndex); + + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float setgp(float Value, int WBAIndex); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetspecifiedflowbc.java b/wrims-core/src/main/java/wrimsv2/external/Functionsetspecifiedflowbc.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetspecifiedflowbc.java rename to wrims-core/src/main/java/wrimsv2/external/Functionsetspecifiedflowbc.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetspecifiedheadbc.java b/wrims-core/src/main/java/wrimsv2/external/Functionsetspecifiedheadbc.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetspecifiedheadbc.java rename to wrims-core/src/main/java/wrimsv2/external/Functionsetspecifiedheadbc.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetstrmflow.java b/wrims-core/src/main/java/wrimsv2/external/Functionsetstrmflow.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetstrmflow.java rename to wrims-core/src/main/java/wrimsv2/external/Functionsetstrmflow.java index d3024e411..11c0496b8 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsetstrmflow.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functionsetstrmflow.java @@ -1,30 +1,30 @@ -package wrimsv2.external; - -import java.util.*; - -public class Functionsetstrmflow extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functionsetstrmflow(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int StrmNodeIndex = ((Number) param2).intValue(); - float Value = ((Number) param1).floatValue(); - - float result = setstrmflow(Value, StrmNodeIndex); - - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float setstrmflow(float Value, int StrmNodeIndex); -} +package wrimsv2.external; + +import java.util.*; + +public class Functionsetstrmflow extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functionsetstrmflow(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int StrmNodeIndex = ((Number) param2).intValue(); + float Value = ((Number) param1).floatValue(); + + float result = setstrmflow(Value, StrmNodeIndex); + + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float setstrmflow(float Value, int StrmNodeIndex); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsimgw.java b/wrims-core/src/main/java/wrimsv2/external/Functionsimgw.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionsimgw.java rename to wrims-core/src/main/java/wrimsv2/external/Functionsimgw.java index ccd23d4b2..b602bc575 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsimgw.java +++ b/wrims-core/src/main/java/wrimsv2/external/Functionsimgw.java @@ -1,30 +1,30 @@ -package wrimsv2.external; - -import java.util.*; - -public class Functionsimgw extends ExternalFunction{ - private final boolean DEBUG = false; - - - public Functionsimgw(){ - - } - - public void execute(Stack stack) { - - //values in reverse order: - Object param2 = stack.pop(); - Object param1 = stack.pop(); - - //cast params to correct types: - int Month = ((Number) param2).intValue(); - int WaterYear = ((Number) param1).intValue(); - - float result = simgw(WaterYear, Month); - - // push the result on the Stack - stack.push(new Float(result)); - } - - public native float simgw(int WaterYear, int Month); -} +package wrimsv2.external; + +import java.util.*; + +public class Functionsimgw extends ExternalFunction{ + private final boolean DEBUG = false; + + + public Functionsimgw(){ + + } + + public void execute(Stack stack) { + + //values in reverse order: + Object param2 = stack.pop(); + Object param1 = stack.pop(); + + //cast params to correct types: + int Month = ((Number) param2).intValue(); + int WaterYear = ((Number) param1).intValue(); + + float result = simgw(WaterYear, Month); + + // push the result on the Stack + stack.push(new Float(result)); + } + + public native float simgw(int WaterYear, int Month); +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/Functionsuitablehabitat.java b/wrims-core/src/main/java/wrimsv2/external/Functionsuitablehabitat.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/external/Functionsuitablehabitat.java rename to wrims-core/src/main/java/wrimsv2/external/Functionsuitablehabitat.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/GenerateCompileFiles.java b/wrims-core/src/main/java/wrimsv2/external/GenerateCompileFiles.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/external/GenerateCompileFiles.java rename to wrims-core/src/main/java/wrimsv2/external/GenerateCompileFiles.java index 4a81ba3e5..945057c2f 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/GenerateCompileFiles.java +++ b/wrims-core/src/main/java/wrimsv2/external/GenerateCompileFiles.java @@ -1,779 +1,779 @@ -package wrimsv2.external; - -import java.io.BufferedReader; -import java.io.DataInputStream; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.io.File; -import java.util.HashMap; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Stack; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class GenerateCompileFiles { - public static HashMap dllFunctions=new HashMap(); - public static HashMap dllDlls = new HashMap(); - public static HashMap functionTypes=new HashMap(); - public static HashMap functionVariableNames = new HashMap (); - public static HashMap functionVariableTypes = new HashMap (); - private static ArrayList functionArray=new ArrayList(); - public static ArrayList error=new ArrayList(); - public static String workingDir; - public static boolean setPath=false; - private static String currentDirectory; - - public static void generateBatchFile(){ - String batchFileFullPath=workingDir+"processDll.bat"; - - Iterator fvni=functionVariableNames.keySet().iterator(); - Iterator dfi=dllFunctions.keySet().iterator(); - - try{ - FileWriter batchFile = new FileWriter(batchFileFullPath, false); - PrintWriter out = new PrintWriter(batchFile); - if (setPath){ - out.println("set path="+currentDirectory+"/../jdk/bin;"+currentDirectory+"/../mingw/bin;"); - } - - while (fvni.hasNext()){ - String functionName=(String)fvni.next(); - if (setPath){ - out.println("javac -cp "+currentDirectory+"/../lib/wrimsv2.jar "+"wrimsv2\\external\\Function"+functionName+".java"); - }else{ - out.println("javac -cp . wrimsv2\\external\\Function"+functionName+".java"); - } - out.println("javah -jni wrimsv2.external.Function"+functionName); - out.println("gcc -c -Wall -D_JNI_IMPLEMENTATION_ -Wl,--kill-at -I\""+currentDirectory+"/../jdk/include\" -I\""+currentDirectory+"/../jdk/include/win32\" wrimsv2_external_Function"+functionName+".c"); - } - String compileString="gcc -Wall -D_JNI_IMPLEMENTATION_ -Wl,--kill-at -shared "; - while (dfi.hasNext()){ - String dllName=(String)dfi.next(); - String fortranDllName=dllDlls.get(dllName); - String[] functions=dllFunctions.get(dllName); - for (int i=0; i0; i--){ - out.println(" Object param"+i+" = stack.pop();"); - } - out.println(); - out.println(" //cast params to correct types:"); - for (int i=variableNames.length; i>0; i--){ - if (variableTypes[i-1].equals("String")){ - out.println(" "+variableTypes[i-1] +" "+ variableNames[i-1]+" = param"+i+".toString();"); - }else if (variableTypes[i-1].equals("int[]")){ - String size="size_"+variableNames[i-1]; - String variableArrName=variableNames[i-1]+"_Arr"; - out.println(" Number[] "+variableArrName+" = (Number[])param"+i+";"); - out.println(" int "+size+"="+variableArrName+".length;"); - out.println(" int[] "+variableNames[i-1]+"=new int["+size+"];"); - out.println(" for (int i=0; i<"+size+"; i++){"); - out.println(" "+variableNames[i-1]+"[i]="+variableArrName+"[i].intValue();"); - out.println(" }"); - }else if (variableTypes[i-1].equals("int[][]")){ - String size1="size1_"+variableNames[i-1]; - String size2="size2_"+variableNames[i-1]; - String variableArrName=variableNames[i-1]+"_Arr"; - out.println(" Number[][] "+variableArrName+" = (Number[][])param"+i+";"); - out.println(" int "+size1+"="+variableArrName+".length;"); - out.println(" int "+size2+"="+variableArrName+"[0].length;"); - out.println(" int[][] "+variableNames[i-1]+"=new int["+size1+"]["+size2+"];"); - out.println(" for (int i=0; i<"+size1+"; i++){"); - out.println(" for (int j=0; j<"+size2+"; j++){"); - out.println(" "+variableNames[i-1]+"[i][j]="+variableArrName+"[i][j].intValue();"); - out.println(" }"); - out.println(" }"); - }else if (variableTypes[i-1].equals("int*")){ - out.println(" "+variableNames[i-1]+" = ((Number) param"+i+").intValue();"); - }else if (variableTypes[i-1].equals("float[]")){ - String size="size_"+variableNames[i-1]; - String variableArrName=variableNames[i-1]+"_Arr"; - out.println(" Number[] "+variableArrName+" = (Number[])param"+i+";"); - out.println(" int "+size+"="+variableArrName+".length;"); - out.println(" float[] "+variableNames[i-1]+"=new float["+size+"];"); - out.println(" for (int i=0; i<"+size+"; i++){"); - out.println(" "+variableNames[i-1]+"[i]="+variableArrName+"[i].floatValue();"); - out.println(" }"); - }else if (variableTypes[i-1].equals("float[][]")){ - String size1="size1_"+variableNames[i-1]; - String size2="size2_"+variableNames[i-1]; - String variableArrName=variableNames[i-1]+"_Arr"; - out.println(" Number[][] "+variableArrName+" = (Number[][])param"+i+";"); - out.println(" int "+size1+"="+variableArrName+".length;"); - out.println(" int "+size2+"="+variableArrName+"[0].length;"); - out.println(" float[][] "+variableNames[i-1]+"=new float["+size1+"]["+size2+"];"); - out.println(" for (int i=0; i<"+size1+"; i++){"); - out.println(" for (int j=0; j<"+size2+"; j++){"); - out.println(" "+variableNames[i-1]+"[i][j]="+variableArrName+"[i][j].floatValue();"); - out.println(" }"); - out.println(" }"); - }else if (variableTypes[i-1].equals("float*")){ - out.println(" "+variableNames[i-1]+" = ((Number) param"+i+").floatValue();"); - }else if (variableTypes[i-1].equals("double[]")){ - String size="size_"+variableNames[i-1]; - String variableArrName=variableNames[i-1]+"_Arr"; - out.println(" Number[] "+variableArrName+" = (Number[])param"+i+";"); - out.println(" int "+size+"="+variableArrName+".length;"); - out.println(" double[] "+variableNames[i-1]+"=new double["+size+"];"); - out.println(" for (int i=0; i<"+size+"; i++){"); - out.println(" "+variableNames[i-1]+"[i]="+variableArrName+"[i].doubleValue();"); - out.println(" }"); - }else if (variableTypes[i-1].equals("double[][]")){ - String size1="size1_"+variableNames[i-1]; - String size2="size2_"+variableNames[i-1]; - String variableArrName=variableNames[i-1]+"_Arr"; - out.println(" Number[][] "+variableArrName+" = (Number[][])param"+i+";"); - out.println(" int "+size1+"="+variableArrName+".length;"); - out.println(" int "+size2+"="+variableArrName+"[0].length;"); - out.println(" double[][] "+variableNames[i-1]+"=new double["+size1+"]["+size2+"];"); - out.println(" for (int i=0; i<"+size1+"; i++){"); - out.println(" for (int j=0; j<"+size2+"; j++){"); - out.println(" "+variableNames[i-1]+"[i][j]="+variableArrName+"[i][j].doubleValue();"); - out.println(" }"); - out.println(" }"); - }else if (variableTypes[i-1].equals("double*")){ - out.println(" "+variableNames[i-1]+" = ((Number) param"+i+").doubleValue();"); - }else{ - out.println(" "+variableTypes[i-1] +" "+ variableNames[i-1]+" = ((Number) param"+i+")."+variableTypes[i-1]+"Value();"); - } - } - out.println(); - String resultString=""; - if (functionType.equals("void")){ - resultString=" "+functionName+"("; - }else{ - resultString=" "+functionType+" result = "+functionName+"("; - } - for (int i=0; i"); - out.println("#include \"wrimsv2_external_Function"+functionName+".h\""); - out.println(); - String externalString="extern "+functionType+" "+functionName.toUpperCase()+"("; - String variableType; - for (int i=0; iGetStringUTFChars(env, "+variableNames[i]+", 0);"); - }else if (variableTypes[i].equals("int[]")){ - out.println(" jint* "+variableNames[i]+"_arr = (*env)->GetIntArrayElements(env, "+variableNames[i]+", 0);"); - }else if (variableTypes[i].equals("float[]")){ - out.println(" jfloat* "+variableNames[i]+"_arr = (*env)->GetFloatArrayElements(env, "+variableNames[i]+", 0);"); - }else if (variableTypes[i].equals("double[]")){ - out.println(" jdouble* "+variableNames[i]+"_arr = (*env)->GetDoubleArrayElements(env, "+variableNames[i]+", 0);"); - }else if (variableTypes[i].equals("int[][]")){ - preCall_2DArray(out, "int", variableNames[i]); - }else if (variableTypes[i].equals("float[][]")){ - preCall_2DArray(out, "float", variableNames[i]); - }else if (variableTypes[i].equals("double[][]")){ - preCall_2DArray(out, "double", variableNames[i]); - }else if (variableTypes[i].equals("double[]")){ - out.println(" jdouble* "+variableNames[i]+"_arr = (*env)->GetDoubleArrayElements(env, "+variableNames[i]+", 0);"); - } - } - String resultString=""; - if (functionType.startsWith("int[]")){ - resultString=" jint* result = "+functionName.toUpperCase()+"("; - }else if (functionType.startsWith("float[]")){ - resultString=" jfloat* result = "+functionName.toUpperCase()+"("; - }else if (functionType.startsWith("double[]")){ - resultString=" jdouble* result = "+functionName.toUpperCase()+"("; - }else if (functionType.equals("void")){ - resultString=" "+functionName.toUpperCase()+"("; - }else{ - resultString=" j"+functionType.toLowerCase()+" result = "+functionName.toUpperCase()+"("; - } - - for (int i=0; iGetObjectClass(env, obj);"); - out.println(); - - for (int i=0; iReleaseStringUTFChars(env, "+variableNames[i]+", "+variableNames[i]+"Chars);"); - }else if (variableTypes[i].equals("int[]")){ - out.println(" (*env)->ReleaseIntArrayElements(env, "+variableNames[i]+", "+variableNames[i]+"_arr, 0);"); - }else if (variableTypes[i].equals("float[]")){ - out.println(" (*env)->ReleaseFloatArrayElements(env, "+variableNames[i]+", "+variableNames[i]+"_arr, 0);"); - }else if (variableTypes[i].equals("double[]")){ - out.println(" (*env)->ReleaseDoubleArrayElements(env, "+variableNames[i]+", "+variableNames[i]+"_arr, 0);"); - }else if (variableTypes[i].equals("int[][]")){ - afterCall_2DArray(out, "int", variableNames[i]); - }else if (variableTypes[i].equals("float[][]")){ - afterCall_2DArray(out, "float", variableNames[i]); - }else if (variableTypes[i].equals("double[][]")){ - afterCall_2DArray(out, "double", variableNames[i]); - }else if (variableTypes[i].equals("int*")){ - afterCallScalar(out, "int", variableNames[i]); - }else if (variableTypes[i].equals("float*")){ - afterCallScalar(out, "float", variableNames[i]); - }else if (variableTypes[i].equals("double*")){ - afterCallScalar(out, "double", variableNames[i]); - } - } - String returnString; - if (functionType.equals("void")){ - returnString =" return;"; - }else{ - returnString =" return result;"; - } - out.println(returnString); - out.println("}"); - out.close(); - } catch (IOException e){ - error.add(e.getMessage()); - } - } - - public static boolean setDllFunction(String fileName) { - FileInputStream fstream; - try { - fstream = new FileInputStream(fileName); - DataInputStream in = new DataInputStream(fstream); - BufferedReader br = new BufferedReader(new InputStreamReader(in)); - String nDllFileString; - int line=0; - - int nDllFiles; - nDllFileString=br.readLine(); - line=line+1; - if (nDllFileString ==null){ - error.add("Line "+line+": Number of interface dll files is not defined." ); - return false; - } - nDllFiles=Integer.parseInt(nDllFileString); - - for (int i=0; iGetArrayLength(env, "+vn+");"); - out.println(" int "+ir1+";"); - out.println(); - out.println(" "+jvtArray+" "+oneDim1+"["+r1+"];"); - out.println(" "+jvt+" *"+elements1+"["+r1+"];"); - out.println(); - out.println(" "+jvtArray+" "+oneDim1_0+" = ("+jvtArray+") (*env)->GetObjectArrayElement(env, "+vn+", 0);"); - out.println(); - out.println(" int "+c1+"=(*env)->GetArrayLength(env, "+oneDim1_0+");"); - out.println(); - out.println(" "+arrt+" "+vn_arr+"["+c1+"]["+r1+"];"); - out.println(); - out.println(" for ("+ir1+"=0; "+ir1+"<"+r1+"; "+ir1+"++){"); - out.println(" "+oneDim1+"["+ir1+"] = ("+jvtArray+") (*env)->GetObjectArrayElement(env, "+vn+", "+ir1+");"); - out.println(" "+elements1+"["+ir1+"] = (*env)->"+getVtArrayElements+"(env, "+oneDim1+"["+ir1+"], 0);"); - out.println(); - out.println(" int j;"); - out.println(" for (j=0; j<"+c1+"; j++){"); - out.println(" "+vn_arr+"[j]["+ir1+"]="+elements1+"["+ir1+"][j];"); - out.println(" }"); - out.println(" }"); - } - - public static void afterCall_2DArray(PrintWriter out, String vt, String vn){ - String r1="r_"+vn; - String ir1="ir_"+vn; - String c1="c_"+vn; - String oneDim1="oneDim_"+vn; - String oneDim1_0=oneDim1+"_0"; - String elements1="elements_"+vn; - String jvtArray="j"+vt+"Array"; - String jvt="j"+vt; - String arrt=vt; - String vn_arr=vn+"_arr"; - String releaseVtArrayElements; - if (vt.equals("int")){ - releaseVtArrayElements="ReleaseIntArrayElements"; - }else if (vt.equals("float")){ - releaseVtArrayElements="ReleaseFloatArrayElements"; - }else{ - releaseVtArrayElements="ReleaseDoubleArrayElements"; - } - - out.println("for ("+ir1+"=0; "+ir1+"<"+r1+"; "+ir1+"++){"); - out.println(" int j;"); - out.println(" for (j=0; j<+"+c1+"; j++){"); - out.println(" "+elements1+"["+ir1+"][j]="+vn_arr+"[j]["+ir1+"];"); - out.println(" }"); - out.println(); - out.println(" (*env)->"+releaseVtArrayElements+"(env, "+oneDim1+"["+ir1+"], "+elements1+"["+ir1+"], 0);"); - out.println(" (*env)->DeleteLocalRef(env, "+oneDim1+"["+ir1+"]);"); - out.println("}"); - } - - /* - public static void preCallScalar(PrintWriter out, String vt, String vn){ - String jvt="j"+vt; - String vn0=vn+"_0"; - String vnArr=vn+"_arr"; - String pvt=vt; - if (vt.equals("int")) pvt="long"; - String getVtArrayElements; - if (vt.equals("int")){ - getVtArrayElements="GetIntArrayElements"; - }else if (vt.equals("float")){ - getVtArrayElements="GetFloatArrayElements"; - }else{ - getVtArrayElements="GetDoubleArrayElements"; - } - - out.println(" "+jvt+"* "+vn+"_arr = (*env)->"+getVtArrayElements+"(env, "+vn+", 0);"); - out.println(" "+pvt+" "+vn0+"="+vnArr+"[0];"); - } - */ - - public static void afterCallScalar(PrintWriter out, String vt, String vn){ - String vnField=vn+"Field"; - String type="I"; - String setVtField="SetIntField"; - if (vt.equals("int")){ - type="I"; - setVtField="SetIntField"; - }else if (vt.equals("float")){ - type="F"; - setVtField="SetFloatField"; - }else if (vt.equals("double")){ - type="D"; - setVtField="SetDoubleField"; - } - out.println(" jfieldID "+vnField+" = (*env)->GetFieldID(env, clazz, \""+vn+"\", \""+type+"\");"); - out.println(" (*env)->"+setVtField+"(env, obj, "+vnField+", "+vn+");"); - } - - public static void setWorkingDirectory(String fileFullPath){ - int index=fileFullPath.lastIndexOf(File.separator); - workingDir= fileFullPath.substring(0,index+1); - } - - public static void main(String args[]){ - setWorkingDirectory(args[0]); - if (args.length>1) { - setPath=true; - currentDirectory=args[1]; - } - if (setDllFunction(args[0])) generateFiles(); - reportErrors(); - } -} +package wrimsv2.external; + +import java.io.BufferedReader; +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.io.File; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Stack; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class GenerateCompileFiles { + public static HashMap dllFunctions=new HashMap(); + public static HashMap dllDlls = new HashMap(); + public static HashMap functionTypes=new HashMap(); + public static HashMap functionVariableNames = new HashMap (); + public static HashMap functionVariableTypes = new HashMap (); + private static ArrayList functionArray=new ArrayList(); + public static ArrayList error=new ArrayList(); + public static String workingDir; + public static boolean setPath=false; + private static String currentDirectory; + + public static void generateBatchFile(){ + String batchFileFullPath=workingDir+"processDll.bat"; + + Iterator fvni=functionVariableNames.keySet().iterator(); + Iterator dfi=dllFunctions.keySet().iterator(); + + try{ + FileWriter batchFile = new FileWriter(batchFileFullPath, false); + PrintWriter out = new PrintWriter(batchFile); + if (setPath){ + out.println("set path="+currentDirectory+"/../jdk/bin;"+currentDirectory+"/../mingw/bin;"); + } + + while (fvni.hasNext()){ + String functionName=(String)fvni.next(); + if (setPath){ + out.println("javac -cp "+currentDirectory+"/../lib/wrimsv2.jar "+"wrimsv2\\external\\Function"+functionName+".java"); + }else{ + out.println("javac -cp . wrimsv2\\external\\Function"+functionName+".java"); + } + out.println("javah -jni wrimsv2.external.Function"+functionName); + out.println("gcc -c -Wall -D_JNI_IMPLEMENTATION_ -Wl,--kill-at -I\""+currentDirectory+"/../jdk/include\" -I\""+currentDirectory+"/../jdk/include/win32\" wrimsv2_external_Function"+functionName+".c"); + } + String compileString="gcc -Wall -D_JNI_IMPLEMENTATION_ -Wl,--kill-at -shared "; + while (dfi.hasNext()){ + String dllName=(String)dfi.next(); + String fortranDllName=dllDlls.get(dllName); + String[] functions=dllFunctions.get(dllName); + for (int i=0; i0; i--){ + out.println(" Object param"+i+" = stack.pop();"); + } + out.println(); + out.println(" //cast params to correct types:"); + for (int i=variableNames.length; i>0; i--){ + if (variableTypes[i-1].equals("String")){ + out.println(" "+variableTypes[i-1] +" "+ variableNames[i-1]+" = param"+i+".toString();"); + }else if (variableTypes[i-1].equals("int[]")){ + String size="size_"+variableNames[i-1]; + String variableArrName=variableNames[i-1]+"_Arr"; + out.println(" Number[] "+variableArrName+" = (Number[])param"+i+";"); + out.println(" int "+size+"="+variableArrName+".length;"); + out.println(" int[] "+variableNames[i-1]+"=new int["+size+"];"); + out.println(" for (int i=0; i<"+size+"; i++){"); + out.println(" "+variableNames[i-1]+"[i]="+variableArrName+"[i].intValue();"); + out.println(" }"); + }else if (variableTypes[i-1].equals("int[][]")){ + String size1="size1_"+variableNames[i-1]; + String size2="size2_"+variableNames[i-1]; + String variableArrName=variableNames[i-1]+"_Arr"; + out.println(" Number[][] "+variableArrName+" = (Number[][])param"+i+";"); + out.println(" int "+size1+"="+variableArrName+".length;"); + out.println(" int "+size2+"="+variableArrName+"[0].length;"); + out.println(" int[][] "+variableNames[i-1]+"=new int["+size1+"]["+size2+"];"); + out.println(" for (int i=0; i<"+size1+"; i++){"); + out.println(" for (int j=0; j<"+size2+"; j++){"); + out.println(" "+variableNames[i-1]+"[i][j]="+variableArrName+"[i][j].intValue();"); + out.println(" }"); + out.println(" }"); + }else if (variableTypes[i-1].equals("int*")){ + out.println(" "+variableNames[i-1]+" = ((Number) param"+i+").intValue();"); + }else if (variableTypes[i-1].equals("float[]")){ + String size="size_"+variableNames[i-1]; + String variableArrName=variableNames[i-1]+"_Arr"; + out.println(" Number[] "+variableArrName+" = (Number[])param"+i+";"); + out.println(" int "+size+"="+variableArrName+".length;"); + out.println(" float[] "+variableNames[i-1]+"=new float["+size+"];"); + out.println(" for (int i=0; i<"+size+"; i++){"); + out.println(" "+variableNames[i-1]+"[i]="+variableArrName+"[i].floatValue();"); + out.println(" }"); + }else if (variableTypes[i-1].equals("float[][]")){ + String size1="size1_"+variableNames[i-1]; + String size2="size2_"+variableNames[i-1]; + String variableArrName=variableNames[i-1]+"_Arr"; + out.println(" Number[][] "+variableArrName+" = (Number[][])param"+i+";"); + out.println(" int "+size1+"="+variableArrName+".length;"); + out.println(" int "+size2+"="+variableArrName+"[0].length;"); + out.println(" float[][] "+variableNames[i-1]+"=new float["+size1+"]["+size2+"];"); + out.println(" for (int i=0; i<"+size1+"; i++){"); + out.println(" for (int j=0; j<"+size2+"; j++){"); + out.println(" "+variableNames[i-1]+"[i][j]="+variableArrName+"[i][j].floatValue();"); + out.println(" }"); + out.println(" }"); + }else if (variableTypes[i-1].equals("float*")){ + out.println(" "+variableNames[i-1]+" = ((Number) param"+i+").floatValue();"); + }else if (variableTypes[i-1].equals("double[]")){ + String size="size_"+variableNames[i-1]; + String variableArrName=variableNames[i-1]+"_Arr"; + out.println(" Number[] "+variableArrName+" = (Number[])param"+i+";"); + out.println(" int "+size+"="+variableArrName+".length;"); + out.println(" double[] "+variableNames[i-1]+"=new double["+size+"];"); + out.println(" for (int i=0; i<"+size+"; i++){"); + out.println(" "+variableNames[i-1]+"[i]="+variableArrName+"[i].doubleValue();"); + out.println(" }"); + }else if (variableTypes[i-1].equals("double[][]")){ + String size1="size1_"+variableNames[i-1]; + String size2="size2_"+variableNames[i-1]; + String variableArrName=variableNames[i-1]+"_Arr"; + out.println(" Number[][] "+variableArrName+" = (Number[][])param"+i+";"); + out.println(" int "+size1+"="+variableArrName+".length;"); + out.println(" int "+size2+"="+variableArrName+"[0].length;"); + out.println(" double[][] "+variableNames[i-1]+"=new double["+size1+"]["+size2+"];"); + out.println(" for (int i=0; i<"+size1+"; i++){"); + out.println(" for (int j=0; j<"+size2+"; j++){"); + out.println(" "+variableNames[i-1]+"[i][j]="+variableArrName+"[i][j].doubleValue();"); + out.println(" }"); + out.println(" }"); + }else if (variableTypes[i-1].equals("double*")){ + out.println(" "+variableNames[i-1]+" = ((Number) param"+i+").doubleValue();"); + }else{ + out.println(" "+variableTypes[i-1] +" "+ variableNames[i-1]+" = ((Number) param"+i+")."+variableTypes[i-1]+"Value();"); + } + } + out.println(); + String resultString=""; + if (functionType.equals("void")){ + resultString=" "+functionName+"("; + }else{ + resultString=" "+functionType+" result = "+functionName+"("; + } + for (int i=0; i"); + out.println("#include \"wrimsv2_external_Function"+functionName+".h\""); + out.println(); + String externalString="extern "+functionType+" "+functionName.toUpperCase()+"("; + String variableType; + for (int i=0; iGetStringUTFChars(env, "+variableNames[i]+", 0);"); + }else if (variableTypes[i].equals("int[]")){ + out.println(" jint* "+variableNames[i]+"_arr = (*env)->GetIntArrayElements(env, "+variableNames[i]+", 0);"); + }else if (variableTypes[i].equals("float[]")){ + out.println(" jfloat* "+variableNames[i]+"_arr = (*env)->GetFloatArrayElements(env, "+variableNames[i]+", 0);"); + }else if (variableTypes[i].equals("double[]")){ + out.println(" jdouble* "+variableNames[i]+"_arr = (*env)->GetDoubleArrayElements(env, "+variableNames[i]+", 0);"); + }else if (variableTypes[i].equals("int[][]")){ + preCall_2DArray(out, "int", variableNames[i]); + }else if (variableTypes[i].equals("float[][]")){ + preCall_2DArray(out, "float", variableNames[i]); + }else if (variableTypes[i].equals("double[][]")){ + preCall_2DArray(out, "double", variableNames[i]); + }else if (variableTypes[i].equals("double[]")){ + out.println(" jdouble* "+variableNames[i]+"_arr = (*env)->GetDoubleArrayElements(env, "+variableNames[i]+", 0);"); + } + } + String resultString=""; + if (functionType.startsWith("int[]")){ + resultString=" jint* result = "+functionName.toUpperCase()+"("; + }else if (functionType.startsWith("float[]")){ + resultString=" jfloat* result = "+functionName.toUpperCase()+"("; + }else if (functionType.startsWith("double[]")){ + resultString=" jdouble* result = "+functionName.toUpperCase()+"("; + }else if (functionType.equals("void")){ + resultString=" "+functionName.toUpperCase()+"("; + }else{ + resultString=" j"+functionType.toLowerCase()+" result = "+functionName.toUpperCase()+"("; + } + + for (int i=0; iGetObjectClass(env, obj);"); + out.println(); + + for (int i=0; iReleaseStringUTFChars(env, "+variableNames[i]+", "+variableNames[i]+"Chars);"); + }else if (variableTypes[i].equals("int[]")){ + out.println(" (*env)->ReleaseIntArrayElements(env, "+variableNames[i]+", "+variableNames[i]+"_arr, 0);"); + }else if (variableTypes[i].equals("float[]")){ + out.println(" (*env)->ReleaseFloatArrayElements(env, "+variableNames[i]+", "+variableNames[i]+"_arr, 0);"); + }else if (variableTypes[i].equals("double[]")){ + out.println(" (*env)->ReleaseDoubleArrayElements(env, "+variableNames[i]+", "+variableNames[i]+"_arr, 0);"); + }else if (variableTypes[i].equals("int[][]")){ + afterCall_2DArray(out, "int", variableNames[i]); + }else if (variableTypes[i].equals("float[][]")){ + afterCall_2DArray(out, "float", variableNames[i]); + }else if (variableTypes[i].equals("double[][]")){ + afterCall_2DArray(out, "double", variableNames[i]); + }else if (variableTypes[i].equals("int*")){ + afterCallScalar(out, "int", variableNames[i]); + }else if (variableTypes[i].equals("float*")){ + afterCallScalar(out, "float", variableNames[i]); + }else if (variableTypes[i].equals("double*")){ + afterCallScalar(out, "double", variableNames[i]); + } + } + String returnString; + if (functionType.equals("void")){ + returnString =" return;"; + }else{ + returnString =" return result;"; + } + out.println(returnString); + out.println("}"); + out.close(); + } catch (IOException e){ + error.add(e.getMessage()); + } + } + + public static boolean setDllFunction(String fileName) { + FileInputStream fstream; + try { + fstream = new FileInputStream(fileName); + DataInputStream in = new DataInputStream(fstream); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + String nDllFileString; + int line=0; + + int nDllFiles; + nDllFileString=br.readLine(); + line=line+1; + if (nDllFileString ==null){ + error.add("Line "+line+": Number of interface dll files is not defined." ); + return false; + } + nDllFiles=Integer.parseInt(nDllFileString); + + for (int i=0; iGetArrayLength(env, "+vn+");"); + out.println(" int "+ir1+";"); + out.println(); + out.println(" "+jvtArray+" "+oneDim1+"["+r1+"];"); + out.println(" "+jvt+" *"+elements1+"["+r1+"];"); + out.println(); + out.println(" "+jvtArray+" "+oneDim1_0+" = ("+jvtArray+") (*env)->GetObjectArrayElement(env, "+vn+", 0);"); + out.println(); + out.println(" int "+c1+"=(*env)->GetArrayLength(env, "+oneDim1_0+");"); + out.println(); + out.println(" "+arrt+" "+vn_arr+"["+c1+"]["+r1+"];"); + out.println(); + out.println(" for ("+ir1+"=0; "+ir1+"<"+r1+"; "+ir1+"++){"); + out.println(" "+oneDim1+"["+ir1+"] = ("+jvtArray+") (*env)->GetObjectArrayElement(env, "+vn+", "+ir1+");"); + out.println(" "+elements1+"["+ir1+"] = (*env)->"+getVtArrayElements+"(env, "+oneDim1+"["+ir1+"], 0);"); + out.println(); + out.println(" int j;"); + out.println(" for (j=0; j<"+c1+"; j++){"); + out.println(" "+vn_arr+"[j]["+ir1+"]="+elements1+"["+ir1+"][j];"); + out.println(" }"); + out.println(" }"); + } + + public static void afterCall_2DArray(PrintWriter out, String vt, String vn){ + String r1="r_"+vn; + String ir1="ir_"+vn; + String c1="c_"+vn; + String oneDim1="oneDim_"+vn; + String oneDim1_0=oneDim1+"_0"; + String elements1="elements_"+vn; + String jvtArray="j"+vt+"Array"; + String jvt="j"+vt; + String arrt=vt; + String vn_arr=vn+"_arr"; + String releaseVtArrayElements; + if (vt.equals("int")){ + releaseVtArrayElements="ReleaseIntArrayElements"; + }else if (vt.equals("float")){ + releaseVtArrayElements="ReleaseFloatArrayElements"; + }else{ + releaseVtArrayElements="ReleaseDoubleArrayElements"; + } + + out.println("for ("+ir1+"=0; "+ir1+"<"+r1+"; "+ir1+"++){"); + out.println(" int j;"); + out.println(" for (j=0; j<+"+c1+"; j++){"); + out.println(" "+elements1+"["+ir1+"][j]="+vn_arr+"[j]["+ir1+"];"); + out.println(" }"); + out.println(); + out.println(" (*env)->"+releaseVtArrayElements+"(env, "+oneDim1+"["+ir1+"], "+elements1+"["+ir1+"], 0);"); + out.println(" (*env)->DeleteLocalRef(env, "+oneDim1+"["+ir1+"]);"); + out.println("}"); + } + + /* + public static void preCallScalar(PrintWriter out, String vt, String vn){ + String jvt="j"+vt; + String vn0=vn+"_0"; + String vnArr=vn+"_arr"; + String pvt=vt; + if (vt.equals("int")) pvt="long"; + String getVtArrayElements; + if (vt.equals("int")){ + getVtArrayElements="GetIntArrayElements"; + }else if (vt.equals("float")){ + getVtArrayElements="GetFloatArrayElements"; + }else{ + getVtArrayElements="GetDoubleArrayElements"; + } + + out.println(" "+jvt+"* "+vn+"_arr = (*env)->"+getVtArrayElements+"(env, "+vn+", 0);"); + out.println(" "+pvt+" "+vn0+"="+vnArr+"[0];"); + } + */ + + public static void afterCallScalar(PrintWriter out, String vt, String vn){ + String vnField=vn+"Field"; + String type="I"; + String setVtField="SetIntField"; + if (vt.equals("int")){ + type="I"; + setVtField="SetIntField"; + }else if (vt.equals("float")){ + type="F"; + setVtField="SetFloatField"; + }else if (vt.equals("double")){ + type="D"; + setVtField="SetDoubleField"; + } + out.println(" jfieldID "+vnField+" = (*env)->GetFieldID(env, clazz, \""+vn+"\", \""+type+"\");"); + out.println(" (*env)->"+setVtField+"(env, obj, "+vnField+", "+vn+");"); + } + + public static void setWorkingDirectory(String fileFullPath){ + int index=fileFullPath.lastIndexOf(File.separator); + workingDir= fileFullPath.substring(0,index+1); + } + + public static void main(String args[]){ + setWorkingDirectory(args[0]); + if (args.length>1) { + setPath=true; + currentDirectory=args[1]; + } + if (setDllFunction(args[0])) generateFiles(); + reportErrors(); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/external/LoadAllDll.java b/wrims-core/src/main/java/wrimsv2/external/LoadAllDll.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/external/LoadAllDll.java rename to wrims-core/src/main/java/wrimsv2/external/LoadAllDll.java index db2866e47..ded8e4915 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/external/LoadAllDll.java +++ b/wrims-core/src/main/java/wrimsv2/external/LoadAllDll.java @@ -1,20 +1,20 @@ -package wrimsv2.external; - -import java.util.ArrayList; - -import jep.Jep; -import jep.JepException; -import wrimsv2.components.Error; - - -public class LoadAllDll { - public LoadAllDll(){ - new LoadDll("interfacetoann.dll"); - } - - public LoadAllDll(ArrayList allDll){ - for (int i=0; i allDll){ + for (int i=0; i output() { -// -// Set usedDvar = new HashSet(); -// -// writeInfo(); -// Set usedDvarInWeight = writeObj(); -// _ilpFile.print("\n"); -// Set usedDvarInConstraint = writeConstraint(); -// _ilpFile.print("\n"); -// usedDvar.addAll(usedDvarInWeight); -// usedDvar.addAll(usedDvarInConstraint); -// writeDvar(usedDvar); -// _ilpFile.flush(); -// -// // write to _svarFile -// writeSvarValue(); -// return usedDvar; -// } - - protected static void writeDvarValue(PrintWriter dvarFile, Set dvar_effective) { - - Map dvMap = SolverData.getDvarMap(); - Map wtMap = SolverData.getWeightMap(); - //Map wtSlackSurplusMap = SolverData.getWeightSlackSurplusMap(); - - ArrayList dvar_weighted = new ArrayList(wtMap.keySet()); - dvar_weighted.addAll(ControlData.currModelDataSet.usedWtSlackSurplusList); - - ArrayList dvar_unweighted = new ArrayList(dvMap.keySet()); - dvar_unweighted.removeAll(wtMap.keySet()); - dvar_unweighted.removeAll(ControlData.currModelDataSet.usedWtSlackSurplusList); - - dvar_unweighted.retainAll(dvar_effective); - Collections.sort(dvar_weighted); - Collections.sort(dvar_unweighted); - - - dvarFile.println("/* Weighted Dvar */"); - for (String s : dvar_weighted){ - String dvName = String.format("%-35s", s); - dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); - } - dvarFile.println(); - dvarFile.println("/* Unweighted Dvar */"); - for (String s : dvar_unweighted){ - String dvName = String.format("%-35s", s); - dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); - } - } - - protected static void writeSvarValue(PrintWriter svarFile) { - - Map svMap = ControlData.currSvMap; - - ArrayList sortedTerm = new ArrayList(svMap.keySet()); - Collections.sort(sortedTerm); - - for (String s : sortedTerm){ - String svName = String.format("%-35s", s); - svarFile.print(svName + ": " + svMap.get(s).getData().getData() +"\n" ); - - } - } - - public static void writeComment(PrintWriter outFile, String msg) { - - - outFile.println("// " + msg ); - - } - - public static void writeObjValue() { - - - } - - - protected static void writeObj(PrintWriter outFile, Map activeWeightMap) { - - - String ObjString = ""; - - ObjString = "# objective function \n"; - ObjString = ObjString + "maximize Obj: \n"; - - - String toPrint = ""; - - ArrayList sortedTerm = new ArrayList(SolverData.getWeightMap().keySet()); - sortedTerm.addAll(ControlData.currModelDataSet.usedWtSlackSurplusList); - Collections.sort(sortedTerm); - - for (String dvar : sortedTerm) { - - double weight = activeWeightMap.get(dvar).getValue(); - - if (weight > 0) { - - toPrint = toPrint + "+ " + weight + " * " + dvar.toUpperCase() + " "; - ObjString = ObjString + "+ " + weight + " * " + dvar.toUpperCase() + "\n"; - //_amplFile.println("+ " + weight + " * " + dvar.toUpperCase()); - - } - else if (weight < 0) { - toPrint = toPrint + weight + " * " + dvar.toUpperCase() + " "; - ObjString = ObjString + weight + " * " + dvar.toUpperCase() + "\n"; - //_amplFile.println(weight + " * " + dvar.toUpperCase()); - } - - } - - // _ilpFile.println(toPrint); - ObjString = ObjString + ";"; - - outFile.print(ObjString); - - } - - protected static void writeConstraint(PrintWriter outFile) { - - //outFile.println("/* constraint */"); - - String constraintString = ""; - - constraintString = "# constraint \n"; - - Map constraintMap = SolverData.getConstraintDataMap(); - - ArrayList sortedConstraint = new ArrayList(constraintMap.keySet()); - Collections.sort(sortedConstraint); - - for (String constraintName : sortedConstraint) { - - String lhs = ""; - - if (!constraintMap.get(constraintName).getEvalExpression().isNumeric()) { - - ArrayList sortedTerm = new ArrayList(constraintMap.get(constraintName) - .getEvalExpression().getMultiplier().keySet()); - Collections.sort(sortedTerm); - - for (String var : sortedTerm) { - - Number coef = constraintMap.get(constraintName).getEvalExpression().getMultiplier().get(var) - .getData(); - double coefDouble = coef.doubleValue(); - String coefStr = coef.toString(); - String term; - - if (coefDouble == 1.0) { - term = " + " + var.toUpperCase(); - } - else if (coefDouble == -1.0) { - term = " - " + var.toUpperCase(); - } - else if (coefDouble < 0) { - term = " " + coefStr + " * " + var.toUpperCase(); - } - else { // coefDouble >= 0 - term = " + " + coefStr + " * " + var.toUpperCase(); - } - lhs = lhs + term; - } - - } - else { - - lhs = "0"; - } - - // TODO: improve this - String sign = constraintMap.get(constraintName).getSign()+"="; - sign= sign.replace("==", "="); - double val = constraintMap.get(constraintName).getEvalExpression().getValue().getData().doubleValue(); - - if (val == 0) { - lhs = constraintName.toUpperCase() + ": " + lhs + " " + sign + " " + "0"; - } - else { - lhs = constraintName.toUpperCase() + ": " + lhs + " " + sign + " " + val * -1; - } - - //_amplFile.println("subject to "+lhs + " ;"); - constraintString = constraintString + "subject to "+lhs + " ;\n"; - - } - - outFile.print(constraintString); - - } - - protected static void writeDvar(PrintWriter outFile, Set dvar_weighted, Set dvar_unWeighted) { - - - Map dvarMap = SolverData.getDvarMap(); - - ArrayList sortedDvar_weighted = new ArrayList(dvarMap.keySet()); - sortedDvar_weighted.retainAll(dvar_weighted); - Collections.sort(sortedDvar_weighted); - - ArrayList sortedDvar_unWeighted = new ArrayList(dvarMap.keySet()); - sortedDvar_unWeighted.retainAll(dvar_unWeighted); - Collections.sort(sortedDvar_unWeighted); - - // TODO: separate integer list in the parsing stage for efficiency - ArrayList intList = new ArrayList(); - ArrayList freeList = new ArrayList(); - - - /////// weighted - outFile.println("/* dvar weighted */"); - - for (String key : sortedDvar_weighted) { - double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); - double upper = dvarMap.get(key).upperBoundValue.doubleValue(); - String lowerStr = dvarMap.get(key).lowerBound; - String upperStr = dvarMap.get(key).upperBound; - - if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); - - if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - freeList.add(key); //TODO: test what happen if it's a free integer ??? - continue; - } - else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { - outFile.print(key + " < " + upper + " ;\n"); - } - else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - // TODO: be careful, by default LpSolve treat this as standard so we don't write to ilp file - if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); - } - else { - if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); - outFile.print(key + " < " + upper + " ;\n"); - } - } - - /////// unweighted - outFile.println("/* dvar unweighted in constraint*/"); - - for (String key : sortedDvar_unWeighted) { - double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); - double upper = dvarMap.get(key).upperBoundValue.doubleValue(); - String lowerStr = dvarMap.get(key).lowerBound; - String upperStr = dvarMap.get(key).upperBound; - - if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); - - if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - freeList.add(key); //TODO: test what happen if it's a free integer ??? - continue; - } - else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { - outFile.print(key + " < " + upper + " ;\n"); - } - else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - // TODO: be careful, by default LpSolve treat this as standard so we don't write to ilp file - if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); - } - else { - if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); - outFile.print(key + " < " + upper + " ;\n"); - } - } - - - - - if (intList.size() > 0) { - outFile.print("int "); - - for (int i = 0; i < intList.size(); i++) { - String term = intList.get(i); - - if (i == 0) { - outFile.print(term); - } - else { - outFile.print(", " + term); - } - } - - outFile.print(" ;\n"); - } - - if (freeList.size() > 0) { - outFile.print("free "); - - for (int i = 0; i < freeList.size(); i++) { - String term = freeList.get(i); - - if (i == 0) { - outFile.print(term); - } - else { - outFile.print(", " + term); - } - } - - outFile.print(" ;\n"); - } - } - - protected static void writeDvar(PrintWriter outFile, Set dvar_effective) { - - outFile.println("# dvar "); - - Map dvarMap = SolverData.getDvarMap(); - ArrayList sortedDvar = new ArrayList(dvarMap.keySet()); - sortedDvar.retainAll(dvar_effective); - Collections.sort(sortedDvar); - -// ArrayList intList = new ArrayList(); -// ArrayList freeList = new ArrayList(); - - for (String key : sortedDvar) { - - double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); - double upper = dvarMap.get(key).upperBoundValue.doubleValue(); - String lowerStr = dvarMap.get(key).lowerBound; - String upperStr = dvarMap.get(key).upperBound; - String toPrint = null; - String freeTag = ""; - - if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - // free - outFile.print("var "+key.toUpperCase()); - freeTag = " # free"; - } - else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { - toPrint = key.toUpperCase() + " <= " + upper; - outFile.print("var "+toPrint ); - } - else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - - outFile.print("var "+key.toUpperCase() + " >= " + lower ); - } - else { - - outFile.print("var "+key.toUpperCase() + " >= " + lower + " <= " + upper ); - } - - - if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) { - //intList.add(key); - outFile.print(" integer "); - } - - outFile.print(" ; "+freeTag+"\n"); - - } - - outFile.println("# dynamic slack and surplus "); - - // for dynamic slack surplus vars - for (String ss :ControlData.currModelDataSet.usedWtSlackSurplusList) { - - //System.out.println("ss:"+ss); - outFile.print("var "+ss.toUpperCase() + " >= 0 ; \n"); - - } - - } - -} +package wrimsv2.ilp; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.components.ControlData; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.evaluator.EvalConstraint; + +// for LpSolve select 1.Rows 2.Cols 3.Elimeq2 in Presolve + +public class AmplWriter { + + private AmplWriter() { + + } + +// public static Set output() { +// +// Set usedDvar = new HashSet(); +// +// writeInfo(); +// Set usedDvarInWeight = writeObj(); +// _ilpFile.print("\n"); +// Set usedDvarInConstraint = writeConstraint(); +// _ilpFile.print("\n"); +// usedDvar.addAll(usedDvarInWeight); +// usedDvar.addAll(usedDvarInConstraint); +// writeDvar(usedDvar); +// _ilpFile.flush(); +// +// // write to _svarFile +// writeSvarValue(); +// return usedDvar; +// } + + protected static void writeDvarValue(PrintWriter dvarFile, Set dvar_effective) { + + Map dvMap = SolverData.getDvarMap(); + Map wtMap = SolverData.getWeightMap(); + //Map wtSlackSurplusMap = SolverData.getWeightSlackSurplusMap(); + + ArrayList dvar_weighted = new ArrayList(wtMap.keySet()); + dvar_weighted.addAll(ControlData.currModelDataSet.usedWtSlackSurplusList); + + ArrayList dvar_unweighted = new ArrayList(dvMap.keySet()); + dvar_unweighted.removeAll(wtMap.keySet()); + dvar_unweighted.removeAll(ControlData.currModelDataSet.usedWtSlackSurplusList); + + dvar_unweighted.retainAll(dvar_effective); + Collections.sort(dvar_weighted); + Collections.sort(dvar_unweighted); + + + dvarFile.println("/* Weighted Dvar */"); + for (String s : dvar_weighted){ + String dvName = String.format("%-35s", s); + dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); + } + dvarFile.println(); + dvarFile.println("/* Unweighted Dvar */"); + for (String s : dvar_unweighted){ + String dvName = String.format("%-35s", s); + dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); + } + } + + protected static void writeSvarValue(PrintWriter svarFile) { + + Map svMap = ControlData.currSvMap; + + ArrayList sortedTerm = new ArrayList(svMap.keySet()); + Collections.sort(sortedTerm); + + for (String s : sortedTerm){ + String svName = String.format("%-35s", s); + svarFile.print(svName + ": " + svMap.get(s).getData().getData() +"\n" ); + + } + } + + public static void writeComment(PrintWriter outFile, String msg) { + + + outFile.println("// " + msg ); + + } + + public static void writeObjValue() { + + + } + + + protected static void writeObj(PrintWriter outFile, Map activeWeightMap) { + + + String ObjString = ""; + + ObjString = "# objective function \n"; + ObjString = ObjString + "maximize Obj: \n"; + + + String toPrint = ""; + + ArrayList sortedTerm = new ArrayList(SolverData.getWeightMap().keySet()); + sortedTerm.addAll(ControlData.currModelDataSet.usedWtSlackSurplusList); + Collections.sort(sortedTerm); + + for (String dvar : sortedTerm) { + + double weight = activeWeightMap.get(dvar).getValue(); + + if (weight > 0) { + + toPrint = toPrint + "+ " + weight + " * " + dvar.toUpperCase() + " "; + ObjString = ObjString + "+ " + weight + " * " + dvar.toUpperCase() + "\n"; + //_amplFile.println("+ " + weight + " * " + dvar.toUpperCase()); + + } + else if (weight < 0) { + toPrint = toPrint + weight + " * " + dvar.toUpperCase() + " "; + ObjString = ObjString + weight + " * " + dvar.toUpperCase() + "\n"; + //_amplFile.println(weight + " * " + dvar.toUpperCase()); + } + + } + + // _ilpFile.println(toPrint); + ObjString = ObjString + ";"; + + outFile.print(ObjString); + + } + + protected static void writeConstraint(PrintWriter outFile) { + + //outFile.println("/* constraint */"); + + String constraintString = ""; + + constraintString = "# constraint \n"; + + Map constraintMap = SolverData.getConstraintDataMap(); + + ArrayList sortedConstraint = new ArrayList(constraintMap.keySet()); + Collections.sort(sortedConstraint); + + for (String constraintName : sortedConstraint) { + + String lhs = ""; + + if (!constraintMap.get(constraintName).getEvalExpression().isNumeric()) { + + ArrayList sortedTerm = new ArrayList(constraintMap.get(constraintName) + .getEvalExpression().getMultiplier().keySet()); + Collections.sort(sortedTerm); + + for (String var : sortedTerm) { + + Number coef = constraintMap.get(constraintName).getEvalExpression().getMultiplier().get(var) + .getData(); + double coefDouble = coef.doubleValue(); + String coefStr = coef.toString(); + String term; + + if (coefDouble == 1.0) { + term = " + " + var.toUpperCase(); + } + else if (coefDouble == -1.0) { + term = " - " + var.toUpperCase(); + } + else if (coefDouble < 0) { + term = " " + coefStr + " * " + var.toUpperCase(); + } + else { // coefDouble >= 0 + term = " + " + coefStr + " * " + var.toUpperCase(); + } + lhs = lhs + term; + } + + } + else { + + lhs = "0"; + } + + // TODO: improve this + String sign = constraintMap.get(constraintName).getSign()+"="; + sign= sign.replace("==", "="); + double val = constraintMap.get(constraintName).getEvalExpression().getValue().getData().doubleValue(); + + if (val == 0) { + lhs = constraintName.toUpperCase() + ": " + lhs + " " + sign + " " + "0"; + } + else { + lhs = constraintName.toUpperCase() + ": " + lhs + " " + sign + " " + val * -1; + } + + //_amplFile.println("subject to "+lhs + " ;"); + constraintString = constraintString + "subject to "+lhs + " ;\n"; + + } + + outFile.print(constraintString); + + } + + protected static void writeDvar(PrintWriter outFile, Set dvar_weighted, Set dvar_unWeighted) { + + + Map dvarMap = SolverData.getDvarMap(); + + ArrayList sortedDvar_weighted = new ArrayList(dvarMap.keySet()); + sortedDvar_weighted.retainAll(dvar_weighted); + Collections.sort(sortedDvar_weighted); + + ArrayList sortedDvar_unWeighted = new ArrayList(dvarMap.keySet()); + sortedDvar_unWeighted.retainAll(dvar_unWeighted); + Collections.sort(sortedDvar_unWeighted); + + // TODO: separate integer list in the parsing stage for efficiency + ArrayList intList = new ArrayList(); + ArrayList freeList = new ArrayList(); + + + /////// weighted + outFile.println("/* dvar weighted */"); + + for (String key : sortedDvar_weighted) { + double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); + double upper = dvarMap.get(key).upperBoundValue.doubleValue(); + String lowerStr = dvarMap.get(key).lowerBound; + String upperStr = dvarMap.get(key).upperBound; + + if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); + + if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + freeList.add(key); //TODO: test what happen if it's a free integer ??? + continue; + } + else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { + outFile.print(key + " < " + upper + " ;\n"); + } + else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + // TODO: be careful, by default LpSolve treat this as standard so we don't write to ilp file + if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); + } + else { + if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); + outFile.print(key + " < " + upper + " ;\n"); + } + } + + /////// unweighted + outFile.println("/* dvar unweighted in constraint*/"); + + for (String key : sortedDvar_unWeighted) { + double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); + double upper = dvarMap.get(key).upperBoundValue.doubleValue(); + String lowerStr = dvarMap.get(key).lowerBound; + String upperStr = dvarMap.get(key).upperBound; + + if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); + + if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + freeList.add(key); //TODO: test what happen if it's a free integer ??? + continue; + } + else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { + outFile.print(key + " < " + upper + " ;\n"); + } + else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + // TODO: be careful, by default LpSolve treat this as standard so we don't write to ilp file + if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); + } + else { + if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); + outFile.print(key + " < " + upper + " ;\n"); + } + } + + + + + if (intList.size() > 0) { + outFile.print("int "); + + for (int i = 0; i < intList.size(); i++) { + String term = intList.get(i); + + if (i == 0) { + outFile.print(term); + } + else { + outFile.print(", " + term); + } + } + + outFile.print(" ;\n"); + } + + if (freeList.size() > 0) { + outFile.print("free "); + + for (int i = 0; i < freeList.size(); i++) { + String term = freeList.get(i); + + if (i == 0) { + outFile.print(term); + } + else { + outFile.print(", " + term); + } + } + + outFile.print(" ;\n"); + } + } + + protected static void writeDvar(PrintWriter outFile, Set dvar_effective) { + + outFile.println("# dvar "); + + Map dvarMap = SolverData.getDvarMap(); + ArrayList sortedDvar = new ArrayList(dvarMap.keySet()); + sortedDvar.retainAll(dvar_effective); + Collections.sort(sortedDvar); + +// ArrayList intList = new ArrayList(); +// ArrayList freeList = new ArrayList(); + + for (String key : sortedDvar) { + + double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); + double upper = dvarMap.get(key).upperBoundValue.doubleValue(); + String lowerStr = dvarMap.get(key).lowerBound; + String upperStr = dvarMap.get(key).upperBound; + String toPrint = null; + String freeTag = ""; + + if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + // free + outFile.print("var "+key.toUpperCase()); + freeTag = " # free"; + } + else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { + toPrint = key.toUpperCase() + " <= " + upper; + outFile.print("var "+toPrint ); + } + else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + + outFile.print("var "+key.toUpperCase() + " >= " + lower ); + } + else { + + outFile.print("var "+key.toUpperCase() + " >= " + lower + " <= " + upper ); + } + + + if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) { + //intList.add(key); + outFile.print(" integer "); + } + + outFile.print(" ; "+freeTag+"\n"); + + } + + outFile.println("# dynamic slack and surplus "); + + // for dynamic slack surplus vars + for (String ss :ControlData.currModelDataSet.usedWtSlackSurplusList) { + + //System.out.println("ss:"+ss); + outFile.print("var "+ss.toUpperCase() + " >= 0 ; \n"); + + } + + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/ilp/CplexLpWriter.java b/wrims-core/src/main/java/wrimsv2/ilp/CplexLpWriter.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/ilp/CplexLpWriter.java rename to wrims-core/src/main/java/wrimsv2/ilp/CplexLpWriter.java index 775964a77..173439c7d 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/ilp/CplexLpWriter.java +++ b/wrims-core/src/main/java/wrimsv2/ilp/CplexLpWriter.java @@ -1,223 +1,223 @@ -package wrimsv2.ilp; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.evaluator.EvalConstraint; - - - -public class CplexLpWriter { - - private CplexLpWriter() { - - } - - public static void writeComment(PrintWriter outFile, String msg) { - - - outFile.println("\\ " + msg ); - - } - - public static void writeObjValue() { - - - } - - - protected static void writeObj(PrintWriter outFile, Map activeWeightMap) { - - outFile.println("\\ objective function "); - outFile.println("Maximize"); - - - String toPrint = ""; - - ArrayList sortedTerm = new ArrayList(activeWeightMap.keySet()); - - Collections.sort(sortedTerm); - - for (String dvar : sortedTerm) { - - double weight = activeWeightMap.get(dvar).getValue(); - - if (weight > 0) { - - toPrint = toPrint + "+ " + weight + " " + dvar + " "; - outFile.println("+ " + weight + " " + dvar); - - } - else if (weight < 0) { - toPrint = toPrint + weight + " " + dvar + " "; - outFile.println(weight + " " + dvar); - } - - } - - //outFile.println(";"); - - } - - protected static void writeConstraint(PrintWriter outFile) { - - outFile.println(""); - outFile.println("\\ constraint"); - outFile.println("Subject To"); - - Map constraintMap = SolverData.getConstraintDataMap(); - - ArrayList sortedConstraint = new ArrayList(constraintMap.keySet()); - Collections.sort(sortedConstraint); - - for (String constraintName : sortedConstraint) { - - String lhs = ""; - - if (!constraintMap.get(constraintName).getEvalExpression().isNumeric()) { - - ArrayList sortedTerm = new ArrayList(constraintMap.get(constraintName) - .getEvalExpression().getMultiplier().keySet()); - Collections.sort(sortedTerm); - - for (String var : sortedTerm) { - - Number coef = constraintMap.get(constraintName).getEvalExpression().getMultiplier().get(var) - .getData(); - double coefDouble = coef.doubleValue(); - String coefStr = coef.toString(); - String term; - - if (coefDouble == 1.0) { - term = " + " + var; - } - else if (coefDouble == -1.0) { - term = " - " + var; - } - else if (coefDouble < 0) { - term = " " + coefStr + " " + var; - } - else { // coefDouble >= 0 - term = " + " + coefStr + " " + var; - } - lhs = lhs + term; - } - - } - else { - - continue; // skip trivial constraint - //lhs = "0"; - } - - String sign = constraintMap.get(constraintName).getSign(); - double val = constraintMap.get(constraintName).getEvalExpression().getValue().getData().doubleValue(); - - if (sign.equals(">")) sign = ">="; - if (sign.equals("<")) sign = "<="; - - if (val == 0) { - lhs = constraintName + ": " + lhs + " " + sign + " " + "0"; - } - else { - lhs = constraintName + ": " + lhs + " " + sign + " " + val * -1; - } - - outFile.println(lhs); - - } - - } - - protected static void writeDvar(PrintWriter outFile, Set dvar_effective) { - - - Map dvarMap = SolverData.getDvarMap(); - - ArrayList sortedDvar_effective = new ArrayList(dvarMap.keySet()); - sortedDvar_effective.retainAll(dvar_effective); - Collections.sort(sortedDvar_effective); - - - // TODO: separate integer list in the parsing stage for efficiency - ILP.intList = new ArrayList(); - ArrayList freeList = new ArrayList(); - - outFile.println(""); - outFile.println("\\ dvar"); - outFile.println("Bounds"); - - for (String key : sortedDvar_effective) { - double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); - double upper = dvarMap.get(key).upperBoundValue.doubleValue(); - String lowerStr = dvarMap.get(key).lowerBound; - String upperStr = dvarMap.get(key).upperBound; - - if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) ILP.intList.add(key); - - if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - freeList.add(key); //TODO: test what happen if it's a free integer ??? - continue; - } - if (lowerParam.upper_unbounded_double) { - freeList.add(key); //TODO: test what happen if it's a free integer ??? - continue; - } - else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) || lowerParam.upper_unbounded_double){ - - if (lower != 0) outFile.print(key + " >= " + lower + " \n"); - } - else { - if (lower != 0) { - outFile.print(lower + " <= " + key + " <= " + upper + " \n"); - } else { - outFile.print(key + " <= " + upper + " \n"); - } - } - } - - if (freeList.size() > 0) { - //outFile.print("free "); - - for (int i = 0; i < freeList.size(); i++) { - String term = freeList.get(i); - - outFile.print(" -inf <= " + term + " \n"); - - } - - } - - if (ILP.intList.size() > 0) { - outFile.println(""); - outFile.println("\\ Integer"); - outFile.println("Generals"); - - for (int i = 0; i < ILP.intList.size(); i++) { - String term = ILP.intList.get(i); - - //if (i == 0) { - outFile.println(term); - //} - //else { - // outFile.print(", " + term); - //} - } - - //outFile.print(" ;\n"); - } - - - } - -} +package wrimsv2.ilp; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.evaluator.EvalConstraint; + + + +public class CplexLpWriter { + + private CplexLpWriter() { + + } + + public static void writeComment(PrintWriter outFile, String msg) { + + + outFile.println("\\ " + msg ); + + } + + public static void writeObjValue() { + + + } + + + protected static void writeObj(PrintWriter outFile, Map activeWeightMap) { + + outFile.println("\\ objective function "); + outFile.println("Maximize"); + + + String toPrint = ""; + + ArrayList sortedTerm = new ArrayList(activeWeightMap.keySet()); + + Collections.sort(sortedTerm); + + for (String dvar : sortedTerm) { + + double weight = activeWeightMap.get(dvar).getValue(); + + if (weight > 0) { + + toPrint = toPrint + "+ " + weight + " " + dvar + " "; + outFile.println("+ " + weight + " " + dvar); + + } + else if (weight < 0) { + toPrint = toPrint + weight + " " + dvar + " "; + outFile.println(weight + " " + dvar); + } + + } + + //outFile.println(";"); + + } + + protected static void writeConstraint(PrintWriter outFile) { + + outFile.println(""); + outFile.println("\\ constraint"); + outFile.println("Subject To"); + + Map constraintMap = SolverData.getConstraintDataMap(); + + ArrayList sortedConstraint = new ArrayList(constraintMap.keySet()); + Collections.sort(sortedConstraint); + + for (String constraintName : sortedConstraint) { + + String lhs = ""; + + if (!constraintMap.get(constraintName).getEvalExpression().isNumeric()) { + + ArrayList sortedTerm = new ArrayList(constraintMap.get(constraintName) + .getEvalExpression().getMultiplier().keySet()); + Collections.sort(sortedTerm); + + for (String var : sortedTerm) { + + Number coef = constraintMap.get(constraintName).getEvalExpression().getMultiplier().get(var) + .getData(); + double coefDouble = coef.doubleValue(); + String coefStr = coef.toString(); + String term; + + if (coefDouble == 1.0) { + term = " + " + var; + } + else if (coefDouble == -1.0) { + term = " - " + var; + } + else if (coefDouble < 0) { + term = " " + coefStr + " " + var; + } + else { // coefDouble >= 0 + term = " + " + coefStr + " " + var; + } + lhs = lhs + term; + } + + } + else { + + continue; // skip trivial constraint + //lhs = "0"; + } + + String sign = constraintMap.get(constraintName).getSign(); + double val = constraintMap.get(constraintName).getEvalExpression().getValue().getData().doubleValue(); + + if (sign.equals(">")) sign = ">="; + if (sign.equals("<")) sign = "<="; + + if (val == 0) { + lhs = constraintName + ": " + lhs + " " + sign + " " + "0"; + } + else { + lhs = constraintName + ": " + lhs + " " + sign + " " + val * -1; + } + + outFile.println(lhs); + + } + + } + + protected static void writeDvar(PrintWriter outFile, Set dvar_effective) { + + + Map dvarMap = SolverData.getDvarMap(); + + ArrayList sortedDvar_effective = new ArrayList(dvarMap.keySet()); + sortedDvar_effective.retainAll(dvar_effective); + Collections.sort(sortedDvar_effective); + + + // TODO: separate integer list in the parsing stage for efficiency + ILP.intList = new ArrayList(); + ArrayList freeList = new ArrayList(); + + outFile.println(""); + outFile.println("\\ dvar"); + outFile.println("Bounds"); + + for (String key : sortedDvar_effective) { + double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); + double upper = dvarMap.get(key).upperBoundValue.doubleValue(); + String lowerStr = dvarMap.get(key).lowerBound; + String upperStr = dvarMap.get(key).upperBound; + + if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) ILP.intList.add(key); + + if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + freeList.add(key); //TODO: test what happen if it's a free integer ??? + continue; + } + if (lowerParam.upper_unbounded_double) { + freeList.add(key); //TODO: test what happen if it's a free integer ??? + continue; + } + else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) || lowerParam.upper_unbounded_double){ + + if (lower != 0) outFile.print(key + " >= " + lower + " \n"); + } + else { + if (lower != 0) { + outFile.print(lower + " <= " + key + " <= " + upper + " \n"); + } else { + outFile.print(key + " <= " + upper + " \n"); + } + } + } + + if (freeList.size() > 0) { + //outFile.print("free "); + + for (int i = 0; i < freeList.size(); i++) { + String term = freeList.get(i); + + outFile.print(" -inf <= " + term + " \n"); + + } + + } + + if (ILP.intList.size() > 0) { + outFile.println(""); + outFile.println("\\ Integer"); + outFile.println("Generals"); + + for (int i = 0; i < ILP.intList.size(); i++) { + String term = ILP.intList.get(i); + + //if (i == 0) { + outFile.println(term); + //} + //else { + // outFile.print(", " + term); + //} + } + + //outFile.print(" ;\n"); + } + + + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/ilp/ILP.java b/wrims-core/src/main/java/wrimsv2/ilp/ILP.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/ilp/ILP.java rename to wrims-core/src/main/java/wrimsv2/ilp/ILP.java index b476898f2..8ee5b5992 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/ilp/ILP.java +++ b/wrims-core/src/main/java/wrimsv2/ilp/ILP.java @@ -1,1148 +1,1148 @@ -package wrimsv2.ilp; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.ObjectOutputStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.text.DecimalFormat; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.components.BuildProps; -import wrimsv2.components.ControlData; -import wrimsv2.components.Error; -import wrimsv2.components.FilePaths; -import wrimsv2.evaluator.EvalConstraint; -import wrimsv2.solver.CbcSolver; -import wrimsv2.solver.Clp0Solver; -import wrimsv2.solver.LPSolveSolver; -import wrimsv2.solver.Gurobi.GurobiSolver; -import wrimsv2.solver.mpmodel.MPModel; -import wrimsv2.wreslparser.elements.StudyUtils; -import wrimsv2.wreslparser.elements.Tools; - -// for LpSolve select 1.Rows 2.Cols 3.Elimeq2 in Presolve - -public class ILP { - - private static String _mpModelDir; - private static String _lpSolveDir; - private static String _cplexLpDir; - private static String _amplDir; - public static String mpModelFilePath; - public static String lpSolveFilePath; - public static String cplexLpFilePath; - public static String amplFilePath; - private static ObjectOutputStream _mpModelFile; - private static PrintWriter _lpSolveFile; - private static PrintWriter _cplexLpFile; - private static StringWriter _cplexLpString; - private static String cplexLpFileName; - private static PrintWriter _amplFile; - private static PrintWriter _svarFile; - private static PrintWriter _dvarFile; - private static PrintWriter _objValueFile; - public static PrintWriter _noteFile; - public static PrintWriter _noteFile_xa_obj; - public static PrintWriter _noteFile_xa_int; - public static PrintWriter _noteFile_cbc_obj; - public static PrintWriter _noteFile_cbc_time; - public static PrintWriter _noteFile_cbc_int; - public static PrintWriter _noteFile_cbc_int_log; - public static PrintWriter _noteFile_memory; - public static PrintWriter _watchFile_xa; - public static PrintWriter _watchFile_cbc; - private static Set dvar_effective; - private static final String lpSolve_comment_Symbol = "//"; - private static final String ampl_comment_Symbol = "#"; - private static final String cplexLp_comment_Symbol = "\\"; - private static DecimalFormat df; - public static int maximumFractionDigits = 16; - public static boolean loggingVariableValue = false; - public static boolean loggingVariableValueRound = false; - public static boolean loggingVariableValueRound10 = false; - public static boolean loggingAllCycles = true; - public static boolean logging = false; - public static boolean loggingAmpl = false; - public static boolean loggingCplexLp = false; // special LP problem file format designed by Cplex - public static boolean loggingLpSolve = false; // special LP problem file format designed by LpSolve - public static boolean loggingMPModel = false; // special LP problem binary file format designed for OR-Tools - public static boolean loggingUsageMemeory = false; - - private static File _ilpRootDir; - private static File _ilpDir; - private static File _svarDir; - private static File _dvarDir; - - public static ArrayList intList = null; - - private ILP() { - - } - - public static File getIlpDir() { - _ilpRootDir = new File(FilePaths.mainDirectory, "=ILP="); - _ilpDir = new File(_ilpRootDir.getAbsolutePath(), StudyUtils.configFileName); - return _ilpDir; - } - - public static void createNoteFile() { - try { - _noteFile = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_"+ControlData.dateTimeAppend+".log"); - writeNoteLn("wrims2 revision:", new BuildProps().getVN()); - writeNoteLn("jCbc dll name:", CbcSolver.cbcLibName); - if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) { - _noteFile_xa_obj = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_xa_obj.log"); - _noteFile_cbc_obj = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_obj.log"); - _noteFile_cbc_time = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_time.log"); - _noteFile_xa_int = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_xa_int.log"); - _noteFile_cbc_int = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_int.log"); - - if (ControlData.currStudyDataSet.cycIntDvMap!=null) { - ILP.writeNote("cyc ", _noteFile_cbc_int); - ILP.writeNote("cyc ", _noteFile_xa_int); - for (String s:ControlData.currStudyDataSet.allIntDv ){ - ILP.writeNote( s+" ", _noteFile_cbc_int); - ILP.writeNote( s+" ", _noteFile_xa_int); - } - ILP.writeNote("\r\n", _noteFile_cbc_int); - ILP.writeNote("\r\n", _noteFile_xa_int); - } - - if (ControlData.watchList!=null) { - _watchFile_xa = Tools.openFile(_ilpDir.getAbsolutePath(), "Watch_XA.log"); - _watchFile_cbc = Tools.openFile(_ilpDir.getAbsolutePath(), "Watch_CBC.log"); - ILP.writeNote( "time ", _watchFile_xa); - ILP.writeNote( "time ", _watchFile_cbc); - for (String s:ControlData.watchList) { - ILP.writeNote( s+" ", _watchFile_xa); - ILP.writeNote( s+" ", _watchFile_cbc); - } - ILP.writeNote("\r\n", _watchFile_xa); - ILP.writeNote("\r\n", _watchFile_cbc); - } - - } else if (CbcSolver.logObj && ControlData.solverName.equalsIgnoreCase("Cbc")){ - _noteFile_cbc_obj = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_obj.log"); - _noteFile_cbc_time = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_time.log"); - _watchFile_cbc = Tools.openFile(_ilpDir.getAbsolutePath(), "Watch_CBC.log"); - ILP.writeNote( "time ", _watchFile_cbc); - for (String s:ControlData.watchList) { - ILP.writeNote( s+" ", _watchFile_cbc); - } - ILP.writeNote("\r\n", _watchFile_cbc); - } - - if (CbcSolver.intLog && ControlData.solverName.equalsIgnoreCase("Cbc")){ - - _noteFile_cbc_int_log = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_int_check_"+ControlData.dateTimeAppend+".csv"); - if (ControlData.currStudyDataSet.cycIntDvMap!=null) { - ILP.writeNote("cyc,int_violation,solver,", _noteFile_cbc_int_log); - //ILP.writeNote("cyc ", _noteFile_xa_int); - for (String s:ControlData.currStudyDataSet.allIntDv ){ - ILP.writeNote( s+",", _noteFile_cbc_int_log); - //ILP.writeNote( s+" ", _noteFile_xa_int); - } - ILP.writeNote("\r\n", _noteFile_cbc_int_log); - //ILP.writeNote("\r\n", _noteFile_xa_int); - } - } - - //new File(_ilpDir.getAbsolutePath()+"\\Note_memory.log").createNewFile(); - _noteFile_memory = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_memory.log"); - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public static void initializeIlp() { - - _ilpRootDir = new File(FilePaths.mainDirectory, "=ILP="); - _ilpDir = new File(_ilpRootDir.getAbsolutePath(), StudyUtils.configFileName); - - if (ILP.loggingMPModel) _mpModelDir = new File(_ilpDir, "mpmodel").getAbsolutePath(); - if (ILP.loggingLpSolve) _lpSolveDir = new File(_ilpDir, "lpsolve").getAbsolutePath(); - if (ILP.loggingCplexLp) _cplexLpDir = new File(_ilpDir, "cplexlp").getAbsolutePath(); - if (ILP.loggingAmpl) _amplDir = new File(_ilpDir, "ampl").getAbsolutePath(); - // TODO: write ampl command file "option presolve_eps 1e-13;" - - if (ILP.loggingVariableValue) setVarDir(); - setMaximumFractionDigits(); - createNoteFile(); - try { - _objValueFile = Tools.openFile(_ilpDir.getAbsolutePath(), "ObjValues.log"); - } - catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public static void setMaximumFractionDigits() { - - df = new DecimalFormat(); - //df.setMinimumFractionDigits(2); - df.setMaximumFractionDigits(maximumFractionDigits); - } - - public static void setIlpFile() { - - if (ILP.loggingMPModel) setMPModelFile(); - if (ILP.loggingLpSolve) setLpSolveFile(); - if (ILP.loggingCplexLp) { - if (ControlData.useCplexLpString && ControlData.solverType != Param.SOLVER_CBC0.intValue() - && ControlData.solverType != Param.SOLVER_CBC1.intValue()){ - setCplexLpString(); - } else { - setCplexLpFile(); - } - } - if (ILP.loggingAmpl) setAmplFile(); - } - - public static void writeIlp() { - -// Set dvar_inConstraint = findDvarInConstraint(); -// Set dvar_weighted = findWeightedDvar(); -// //Set dvar_unWeighted = findUnWeightedDvarInConstraint(dvar_inConstraint, dvar_weighted); -// -// dvar_effective = new HashSet(); -// dvar_effective.addAll(dvar_weighted); -// dvar_effective.addAll(dvar_inConstraint); - - findDvarEffective(); - //if (ILP.loggingMPModel) writeMPModelFile(); - if (ILP.loggingLpSolve) writeLpSolveFile(); - if (ILP.loggingCplexLp) writeCplexLpFile(); - if (ILP.loggingAmpl) writeAmplFile(); - - } - - public static void findDvarEffective(){ - - Set dvar_inConstraint = findDvarInConstraint(); - Set dvar_weighted = findWeightedDvar(); - //Set dvar_unWeighted = findUnWeightedDvarInConstraint(dvar_inConstraint, dvar_weighted); - - dvar_effective = new HashSet(); - dvar_effective.addAll(dvar_weighted); - dvar_effective.addAll(dvar_inConstraint); - - } - - public static void writeObjValue_XA() { - - double objValue = ControlData.xasolver.getObjective(); - String objValueStr = Double.toString(objValue); - - if (ILP.loggingLpSolve) writeObjValue(objValueStr, _lpSolveFile, lpSolve_comment_Symbol); - if (ILP.loggingCplexLp) writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); - if (ILP.loggingAmpl) writeObjValue(objValueStr, _amplFile, ampl_comment_Symbol); - - writeObjValueLog(getYearMonthCycle(), objValueStr, _objValueFile); - - } - - public static void writeObjValue_LPSOLVE() { - - double objValue = ControlData.lpsolve_objective; - String objValueStr = Double.toString(objValue); - - writeObjValue(objValueStr, _lpSolveFile, lpSolve_comment_Symbol); - if (ILP.loggingCplexLp) writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); - if (ILP.loggingAmpl) writeObjValue(objValueStr, _amplFile, ampl_comment_Symbol); - - writeObjValueLog(getYearMonthCycle(), objValueStr, _objValueFile); - - } - - public static void writeObjValue_Clp0_Cbc0() { - - double objValue = ControlData.clp_cbc_objective; - String objValueStr = Double.toString(objValue); - - writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); - //if (ILP.loggingCplexLp) writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); - //if (ILP.loggingAmpl) writeObjValue(objValueStr, _amplFile, ampl_comment_Symbol); - - writeObjValueLog(getYearMonthCycle(), objValueStr, _objValueFile); - if (!ControlData.clp_cbc_note.isEmpty()) writeNoteLn(getYearMonthCycle(), ControlData.clp_cbc_note, _noteFile); - - } - - public static void writeObjValue_Gurobi() { - - double objValue = ControlData.gurobi_objective; - String objValueStr = Double.toString(objValue); - - writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); - if (ILP.loggingLpSolve) writeObjValue(objValueStr, _lpSolveFile, lpSolve_comment_Symbol); - if (ILP.loggingAmpl) writeObjValue(objValueStr, _amplFile, ampl_comment_Symbol); - - writeObjValueLog(getYearMonthCycle(), objValueStr, _objValueFile); - - } - - public static void writeObjValue_OrTools() { - - double objValue = ControlData.otsolver.solver.objectiveValue(); - String objValueStr = Double.toString(objValue); - - if (ILP.loggingCplexLp) writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); - if (ILP.loggingLpSolve) writeObjValue(objValueStr, _lpSolveFile, lpSolve_comment_Symbol); - if (ILP.loggingAmpl) writeObjValue(objValueStr, _amplFile, ampl_comment_Symbol); - - writeObjValueLog(getYearMonthCycle(), objValueStr, _objValueFile); - - } - - public static void writeMPModelFile(MPModel m) { - - try { - _mpModelFile.writeObject(m); - _mpModelFile.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - private static void writeLpSolveFile() { - - _lpSolveFile.print(findHeaderStr(lpSolve_comment_Symbol)); - - Map activeWeightMap = findActiveWeightMap(); - - LpSolveWriter.writeObj(_lpSolveFile, activeWeightMap); - LpSolveWriter.writeConstraint(_lpSolveFile); - -// Set dvar_inConstraint = findDvarInConstraint(); -// Set dvar_weighted = findWeightedDvar(); -// //Set dvar_unWeighted = findUnWeightedDvarInConstraint(dvar_inConstraint, dvar_weighted); -// -// dvar_effective = new HashSet(); -// dvar_effective.addAll(dvar_weighted); -// dvar_effective.addAll(dvar_inConstraint); - - //LpSolveWriter.writeDvar(_lpSolveFile, dvar_weighted, dvar_unWeighted); - LpSolveWriter.writeDvar(_lpSolveFile, dvar_effective); - _lpSolveFile.flush(); - } - private static void writeCplexLpFile() { - - _cplexLpFile.print(findHeaderStr(cplexLp_comment_Symbol)); - - Map activeWeightMap = findActiveWeightMap(); - - CplexLpWriter.writeObj(_cplexLpFile, activeWeightMap); - CplexLpWriter.writeConstraint(_cplexLpFile); - -// Set dvar_inConstraint = findDvarInConstraint(); -// Set dvar_weighted = findWeightedDvar(); -// //Set dvar_unWeighted = findUnWeightedDvarInConstraint(dvar_inConstraint, dvar_weighted); -// -// dvar_effective = new HashSet(); -// dvar_effective.addAll(dvar_weighted); -// dvar_effective.addAll(dvar_inConstraint); - - CplexLpWriter.writeDvar(_cplexLpFile, dvar_effective); - _cplexLpFile.println("\nEnd"); - _cplexLpFile.flush(); - - } - private static void writeAmplFile() { - - _amplFile.print(findHeaderStr(ampl_comment_Symbol)); - - Map activeWeightMap = findActiveWeightMap(); - -// Set dvar_inConstraint = findDvarInConstraint(); -// Set dvar_weighted = findWeightedDvar(); -// //Set dvar_unWeighted = findUnWeightedDvarInConstraint(dvar_inConstraint, dvar_weighted); -// -// dvar_effective = new HashSet(); -// dvar_effective.addAll(dvar_weighted); -// dvar_effective.addAll(dvar_inConstraint); - - AmplWriter.writeDvar(_amplFile, dvar_effective); - AmplWriter.writeConstraint(_amplFile); - AmplWriter.writeObj(_amplFile, activeWeightMap); - _amplFile.flush(); - } - - public static void writeDvarValue_XA() { - - writeDvarValue_XA(_dvarFile, dvar_effective); - _dvarFile.flush(); - - } - public static void writeDvarValue_LPSOLVE() { - - writeDvarValue_LPSOLVE(_dvarFile, dvar_effective); - _dvarFile.flush(); - - } - public static void writeDvarValue_Clp0_Cbc0(Map varDoubleMap) { - - writeDvarValue_Clp0_Cbc0(_dvarFile, dvar_effective, varDoubleMap); - _dvarFile.flush(); - - } - public static void writeDvarValue_Gurobi() { - - writeDvarValue_Gurobi(_dvarFile, dvar_effective); - _dvarFile.flush(); - - } - public static void writeDvarValue_OrTools() { - - writeDvarValue_OrTools(_dvarFile, dvar_effective); - _dvarFile.flush(); - - } - public static void writeSvarValue() { - - writeSvarValue(_svarFile); - _svarFile.flush(); - } - - public static void closeIlpFile() { - - try { - if (ILP.loggingMPModel) _mpModelFile.close(); - if (ILP.loggingLpSolve) _lpSolveFile.close(); - if (ILP.loggingCplexLp) _cplexLpFile.close(); - if (ILP.loggingAmpl) _amplFile.close(); - if (ILP.loggingVariableValue) { - _svarFile.close(); - _dvarFile.close(); - } - } catch (Exception e) { - - // ignore - } - } - - private static void setMPModelFile() { - - String mpModelFileName; - String twoDigitMonth = String.format("%02d", ControlData.currMonth); - String twoDigitCycle = String.format("%02d", ControlData.currCycleIndex+1); - - mpModelFileName = ControlData.currYear + "_" + twoDigitMonth + "_c" + twoDigitCycle + ".mpm"; - - try { - - File dir = new File(_mpModelDir); - dir.mkdirs(); - mpModelFilePath = new File(_mpModelDir, mpModelFileName).getAbsolutePath(); // for public access - _mpModelFile = new ObjectOutputStream(new FileOutputStream(mpModelFilePath)); - - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - } - - private static void setLpSolveFile() { - - String lpSolveFileName; - String twoDigitMonth = String.format("%02d", ControlData.currMonth); - String twoDigitCycle = String.format("%02d", ControlData.currCycleIndex+1); - - lpSolveFileName = ControlData.currYear + "_" + twoDigitMonth + "_c" + twoDigitCycle + ".lps"; - - try { - - _lpSolveFile = Tools.openFile(_lpSolveDir, lpSolveFileName); - lpSolveFilePath = new File(_lpSolveDir, lpSolveFileName).getAbsolutePath(); // for public access - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - } - - public static void setVarDir(){ - - _svarDir = new File(_ilpDir, "svar"); - _dvarDir = new File(_ilpDir, "dvar"); - - } - - public static String getYearMonthCycle(){ - - String twoDigitMonth = String.format("%02d", ControlData.currMonth); - String twoDigitCycle = String.format("%02d", ControlData.currCycleIndex+1); - String ret = ControlData.currYear + "_" + twoDigitMonth + "_c" + twoDigitCycle; - - return ret; - - } - - public static void setObjValueFile(){ - - - try { - - _objValueFile = Tools.openFile(_ilpDir.getAbsolutePath(), "objectiveValues.log"); - - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - public static void setVarFile(){ - - String svarFileName = getYearMonthCycle()+ ".svar"; - String dvarFileName = getYearMonthCycle()+ ".dvar"; - - - try { - - _svarFile = Tools.openFile(_svarDir.getAbsolutePath(), svarFileName); - _dvarFile = Tools.openFile(_dvarDir.getAbsolutePath(), dvarFileName); - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - public static void setSvarFile(){ - - String svarFileName = getYearMonthCycle()+ ".svar"; - - try { - //_svarDir = new File(_ilpDir, "svar"); - _svarFile = Tools.openFile(_svarDir.getAbsolutePath(), svarFileName); - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - public static void setDvarFile(String append){ - - String dvarFileName = getYearMonthCycle()+ ".dvar_"+append; - - try { - - _dvarFile = Tools.openFile(_dvarDir.getAbsolutePath(), dvarFileName); - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - - private static void setCplexLpFile() { - - cplexLpFileName = getYearMonthCycle()+".lp"; - - try { - - _cplexLpFile = Tools.openFile(_cplexLpDir, cplexLpFileName); - cplexLpFilePath = new File(_cplexLpDir, cplexLpFileName).getAbsolutePath(); // for public access - - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - } - - private static void setCplexLpString() { - - - - //_cplexLpFile = Tools.openFile(_cplexLpDir, cplexLpFileName); - _cplexLpString = new StringWriter(); - _cplexLpFile = new PrintWriter(new BufferedWriter(_cplexLpString)); - //cplexLpFilePath = new File(_cplexLpDir, cplexLpFileName).getAbsolutePath(); // for public access - - } - - public static void saveCplexLpStringToFile() { - - - cplexLpFileName = getYearMonthCycle()+".lp"; - - try { - - _cplexLpFile = Tools.openFile(_cplexLpDir, cplexLpFileName); - _cplexLpFile.print(_cplexLpString); - _cplexLpFile.close(); - cplexLpFilePath = new File(_cplexLpDir, cplexLpFileName).getAbsolutePath(); // for public access - - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - } - - public static void closeCplexLpFile() { - - try { - - _cplexLpFile.close(); - - } - catch (Exception e) { - // TODO Auto-generated catch block - //ignore - } - - } - - public static void reOpenCplexLpFile(boolean isAppend) { - - try { - - _cplexLpFile = Tools.openFile(_cplexLpDir, cplexLpFileName, isAppend); - - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - } - - private static void setAmplFile() { - - String amplFileName = getYearMonthCycle()+ ".mod"; - - try { - - _amplFile = Tools.openFile(_amplDir, amplFileName); - amplFilePath = new File(_amplDir, amplFileName).getAbsolutePath(); // for public access - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - } - - - private static String findHeaderStr(String commentSymbol) { - - String headerStr = ""; - - String twoDigitMonth = String.format("%02d", ControlData.currMonth); - String twoDigitCycle = String.format("%02d", ControlData.currCycleIndex+1); - - String CurrDate = Integer.toString(ControlData.currYear)+"." - + twoDigitMonth; - - headerStr = headerStr + commentSymbol + " Date: "+CurrDate + "\n"; - headerStr = headerStr + commentSymbol + " Cycle: "+twoDigitCycle + "\n";; - headerStr = headerStr + commentSymbol + " Solver: "+ControlData.solverName + "\n\n"; - - return headerStr; - } - - private static Set findWeightedDvar() { - - Set dvar_weighted = new HashSet(); - - dvar_weighted.addAll(ControlData.currModelDataSet.usedWtSlackSurplusList); - dvar_weighted.addAll(SolverData.getWeightMap().keySet()); - - return dvar_weighted; - } - - private static Set findDvarInConstraint() { - - Set dvar_inConstraint = new HashSet(); - - Map constraintMap = SolverData.getConstraintDataMap(); - - for (String constraintName : constraintMap.keySet()) { - - if (!constraintMap.get(constraintName).getEvalExpression().isNumeric()) { - - dvar_inConstraint.addAll(constraintMap.get(constraintName).getEvalExpression().getMultiplier().keySet()); - } - } - return dvar_inConstraint; - } - - private static Set findUnWeightedDvarInConstraint( Set dvar_inConstraint, Set dvar_weighted ) { - - Set dvar_unWeighted = new HashSet(); - - dvar_unWeighted.addAll(dvar_inConstraint); - - dvar_unWeighted.removeAll(dvar_weighted); - - return dvar_unWeighted; - } - - private static Map findActiveWeightMap() { - - Map activeWeightMap = new HashMap(); - - for (String usedSlackSurplus: ControlData.currModelDataSet.usedWtSlackSurplusList){ - - activeWeightMap.put(usedSlackSurplus, SolverData.getWeightSlackSurplusMap().get(usedSlackSurplus)); - - } - - activeWeightMap.putAll(SolverData.getWeightMap()); - - return activeWeightMap; - } - - private static String findSvarValueStr() { - - String svarValueStr = ""; - - Map svMap = ControlData.currSvMap; - - ArrayList sortedTerm = new ArrayList(svMap.keySet()); - Collections.sort(sortedTerm); - - for (String s : sortedTerm){ - String svName = String.format("%-35s", s); - svarValueStr = svarValueStr + ( svName + ": " + svMap.get(s).getData().getData() +"\n" ); - } - - return svarValueStr; - } - - private static String findDvarValueStr_XA(Set dvar) { - - ArrayList dvar_sorted = new ArrayList(dvar); - - Collections.sort(dvar_sorted); - - String dvarValueStr = ""; - - for (String s : dvar_sorted){ - String dvName = String.format("%-35s", s); - dvarValueStr = dvarValueStr + (dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); - } - - return dvarValueStr; - } - - public static void writeObjValueLog(String msg, String objValueStr, PrintWriter outFile) { - - if (Error.getTotalError()==0) { - outFile.println(msg+": "+objValueStr); - } else { - outFile.println(msg+": "+"Error! "); - } - outFile.flush(); - } - - public static void writeNoteLn(String msg, boolean printToScreen, boolean isErr) { - - writeNoteLn(msg, _noteFile); - if (printToScreen) { - if (isErr) { System.err.println(msg);} - else {System.out.println(msg);}; - } - } - - public static void writeNoteLn(String msg) { - - writeNoteLn(msg, false, false); - } - - public static void writeNoteLn(String msg, String noteStr) { - - writeNoteLn(msg, noteStr, _noteFile); - } - - public static void writeNoteLn(String msg, String noteStr, PrintWriter outFile) { - -// if (Error.getTotalError()==0) { - outFile.println(msg+": "+noteStr); -// } else { -// outFile.println(msg+": "+"Error! "); -// } - outFile.flush(); - } - - public static void writeNoteLn(String msg, PrintWriter outFile) { - - outFile.println(msg); - outFile.flush(); - } - - public static void writeNote(String msg, PrintWriter outFile) { - - outFile.print(msg); - outFile.flush(); - } - - private static void writeObjValue(String objValueStr, PrintWriter outFile, String commentSym) { - - //double objValue = ControlData.xasolver.getObjective(); - - outFile.print("\n\n\n\n"); - if (Error.getTotalError()==0) { - outFile.println(commentSym+" objective value: "+objValueStr); - } else { - outFile.println(commentSym+" objective value: Error! "); - } - outFile.flush(); - } - - // returns - private static ArrayList> prepareDvarToWrite(Set dvar_effective){ - - ArrayList> ret = new ArrayList>(); - - Map dvMap = SolverData.getDvarMap(); - Map wtMap = SolverData.getWeightMap(); - //Map wtSlackSurplusMap = SolverData.getWeightSlackSurplusMap(); - - ArrayList dvar_weighted = new ArrayList(wtMap.keySet()); - dvar_weighted.addAll(ControlData.currModelDataSet.usedWtSlackSurplusList); - - //TODO: remove weight of 0 from dvar_weighted. - - - ArrayList dvar_unweighted = new ArrayList(dvMap.keySet()); - //dvar_unweighted.removeAll(wtMap.keySet()); - //dvar_unweighted.removeAll(ControlData.currModelDataSet.usedWtSlackSurplusList); - dvar_unweighted.removeAll(dvar_weighted); - - dvar_unweighted.retainAll(dvar_effective); - Collections.sort(dvar_weighted); - Collections.sort(dvar_unweighted); - - ret.add(dvar_weighted); - ret.add(dvar_unweighted); - - return ret; - - } - private static void writeDvarValue_XA(PrintWriter dvarFile, Set dvar_effective) { - - ArrayList> sortedDvar = prepareDvarToWrite(dvar_effective); - ArrayList dvar_weighted = sortedDvar.get(0); - ArrayList dvar_unweighted = sortedDvar.get(1); - - dvarFile.println("/* Weighted Dvar */"); - for (String s : dvar_weighted){ - String dvName = String.format("%-35s", s); - double v = ControlData.xasolver.getColumnActivity(s); - if (loggingVariableValueRound) v = Math.round(v); - if (loggingVariableValueRound10 && !intList.contains(s)) { - v = Math.round(v/10)*10; - } - try{ - if (v!=0){ - dvarFile.print(dvName + ": " + String.format("%23s", df.format(v)) +"\n" ); - } else { - dvarFile.print(dvName + ": " + String.format("%23s", "0") +"\n" ); - } - } catch (Exception e) { - dvarFile.print(dvName + ": " + String.format("%23s", v) +"\n" ); - } - } - dvarFile.println(); - dvarFile.println("/* Unweighted Dvar */"); - for (String s : dvar_unweighted){ - String dvName = String.format("%-35s", s); - double v = ControlData.xasolver.getColumnActivity(s); - if (loggingVariableValueRound) v = Math.round(v); - if (loggingVariableValueRound10 && !intList.contains(s)) { - v = Math.round(v/10)*10; - } - try{ - if (v!=0){ - dvarFile.print(dvName + ": " + String.format("%23s", df.format(v)) +"\n" ); - } else { - dvarFile.print(dvName + ": " + String.format("%23s", "0") +"\n" ); - } - } catch (Exception e) { - dvarFile.print(dvName + ": " + String.format("%23s", v) +"\n" ); - } - } - } - - private static void writeDvarValue_LPSOLVE(PrintWriter dvarFile, Set dvar_effective) { - - ArrayList> sortedDvar = prepareDvarToWrite(dvar_effective); - ArrayList dvar_weighted = sortedDvar.get(0); - ArrayList dvar_unweighted = sortedDvar.get(1); - - dvarFile.println("/* Weighted Dvar */"); - for (String s : dvar_weighted){ - String dvName = String.format("%-35s", s); - //dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); - try{ - double v = LPSolveSolver.varDoubleMap.get(s); - // TODO: improve speed - if (!df.format(v).equals("-0")) { - dvarFile.print(dvName + ": " + df.format(v) +"\n" ); - } else { - dvarFile.print(dvName + ": 0" +"\n" ); - } - - } catch (Exception e) { - dvarFile.print(dvName + ": " + LPSolveSolver.varDoubleMap.get(s) +"\n" ); - } - } - dvarFile.println(); - dvarFile.println("/* Unweighted Dvar */"); - for (String s : dvar_unweighted){ - String dvName = String.format("%-35s", s); - try{ - double v = LPSolveSolver.varDoubleMap.get(s); - // TODO: improve speed - if (!df.format(v).equals("-0")) { - dvarFile.print(dvName + ": " + df.format(v) +"\n" ); - } else { - dvarFile.print(dvName + ": 0" +"\n" ); - } - - } catch (Exception e) { - dvarFile.print(dvName + ": " + LPSolveSolver.varDoubleMap.get(s) +"\n" ); - } - } - } - - private static void writeDvarValue_Clp0_Cbc0(PrintWriter dvarFile, Set dvar_effective, Map varDoubleMap) { - - ArrayList> sortedDvar = prepareDvarToWrite(dvar_effective); - ArrayList dvar_weighted = sortedDvar.get(0); - ArrayList dvar_unweighted = sortedDvar.get(1); - - dvarFile.println("/* Weighted Dvar */"); - for (String s : dvar_weighted){ - String dvName = String.format("%-35s", s); - //dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); - try{ - double v = varDoubleMap.get(s); - if (loggingVariableValueRound) v = Math.round(v); - if (loggingVariableValueRound10 && !intList.contains(s)) { - v = Math.round(v/10)*10; - } - // TODO: improve speed - if (v!=0) { - dvarFile.print(dvName + ": " + String.format("%23s", df.format(v)) +"\n" ); - } else { - dvarFile.print(dvName + ": " + String.format("%23s", "0") +"\n" ); - } - - } catch (Exception e) { - dvarFile.print(dvName + ": " + varDoubleMap.get(s) +"\n" ); - } - } - dvarFile.println(); - dvarFile.println("/* Unweighted Dvar */"); - for (String s : dvar_unweighted){ - String dvName = String.format("%-35s", s); - try{ - double v = varDoubleMap.get(s); - if (loggingVariableValueRound) v = Math.round(v); - if (loggingVariableValueRound10 && !intList.contains(s)) { - v = Math.round(v/10)*10; - } - // TODO: improve speed - if (v!=0) { - dvarFile.print(dvName + ": " + String.format("%23s", df.format(v)) +"\n" ); - } else { - dvarFile.print(dvName + ": " + String.format("%23s", "0") +"\n" ); - } - - } catch (Exception e) { - dvarFile.print(dvName + ": " + varDoubleMap.get(s) +"\n" ); - } - } - } - - private static void writeDvarValue_Gurobi(PrintWriter dvarFile, Set dvar_effective) { - - - ArrayList> sortedDvar = prepareDvarToWrite(dvar_effective); - ArrayList dvar_weighted = sortedDvar.get(0); - ArrayList dvar_unweighted = sortedDvar.get(1); - - dvarFile.println("/* Weighted Dvar */"); - for (String s : dvar_weighted){ - String dvName = String.format("%-35s", s); - //dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); - try{ - double v = GurobiSolver.varDoubleMap.get(s); - // TODO: improve speed - if (!df.format(v).equals("-0")) { - dvarFile.print(dvName + ": " + df.format(v) +"\n" ); - } else { - dvarFile.print(dvName + ": 0" +"\n" ); - } - - } catch (Exception e) { - dvarFile.print(dvName + ": " + GurobiSolver.varDoubleMap.get(s) +"\n" ); - } - } - dvarFile.println(); - dvarFile.println("/* Unweighted Dvar */"); - for (String s : dvar_unweighted){ - String dvName = String.format("%-35s", s); - try{ - double v = GurobiSolver.varDoubleMap.get(s); - // TODO: improve speed - if (!df.format(v).equals("-0")) { - dvarFile.print(dvName + ": " + df.format(v) +"\n" ); - } else { - dvarFile.print(dvName + ": 0" +"\n" ); - } - - } catch (Exception e) { - dvarFile.print(dvName + ": " + GurobiSolver.varDoubleMap.get(s) +"\n" ); - } - } - } - - private static void writeDvarValue_OrTools(PrintWriter dvarFile, Set dvar_effective) { - - - ArrayList> sortedDvar = prepareDvarToWrite(dvar_effective); - ArrayList dvar_weighted = sortedDvar.get(0); - ArrayList dvar_unweighted = sortedDvar.get(1); - - dvarFile.println("/* Weighted Dvar */"); - for (String s : dvar_weighted){ - String dvName = String.format("%-35s", s); - //dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); - try{ - double v = ControlData.otsolver.solution.get(s); - // TODO: improve speed - if (!df.format(v).equals("-0")) { - dvarFile.print(dvName + ": " + df.format(v) +"\n" ); - } else { - dvarFile.print(dvName + ": 0" +"\n" ); - } - - } catch (Exception e) { - dvarFile.print(dvName + ": " + ControlData.otsolver.solution.get(s) +"\n" ); - } - } - dvarFile.println(); - dvarFile.println("/* Unweighted Dvar */"); - for (String s : dvar_unweighted){ - String dvName = String.format("%-35s", s); - try{ - double v = ControlData.otsolver.solution.get(s); - // TODO: improve speed - if (!df.format(v).equals("-0")) { - dvarFile.print(dvName + ": " + df.format(v) +"\n" ); - } else { - dvarFile.print(dvName + ": 0" +"\n" ); - } - - } catch (Exception e) { - dvarFile.print(dvName + ": " + ControlData.otsolver.solution.get(s) +"\n" ); - } - } - } - - private static void writeSvarValue(PrintWriter svarFile) { - - Map svMap = ControlData.currSvMap; - - ArrayList sortedTerm = new ArrayList(svMap.keySet()); - Collections.sort(sortedTerm); - - - - - for (String s : sortedTerm){ - String svName = String.format("%-35s", s); - double v =svMap.get(s).getData().getData().doubleValue(); - if (loggingVariableValueRound) v = Math.round(v); - if (loggingVariableValueRound10) {v = Math.round(v/10)*10;} - // TODO: improve speed -// System.out.println("svarFile:"+svarFile.toString()); -// System.out.println("svName:"+svName); -// System.out.println("v:"+v); -// System.out.println("df:"+df.toString()); - if (v!=0) { - svarFile.print(svName + ": " + String.format("%23s", df.format(v)) +"\n" ); - } else { - svarFile.print(svName + ": " + String.format("%23s", "0") +"\n" ); - } - - -// svarFile.print(svName + ": "); -// svarFile.print(df.format(svMap.get(s).getData().getData())); -// svarFile.print("\n" ); - - } - - } - - public static void setLPSolveDir(String dir){ - _lpSolveDir=dir; - } - - public static void setCplxLpDir(String dir){ - _cplexLpDir=dir; - } - - public static void logUsageMemory(int year, int month, int day, int cycleIndex){ - Thread thread = new Thread(){ - public void run(){ - try { - //System.out.println("tasklist.exe /fi \"PID eq "+ControlData.pid+"\" > \""+ _ilpDir.getAbsolutePath()+"\\Note_memory.log\""); - ProcessBuilder builder = new ProcessBuilder("tasklist.exe", "/nh", "/fi", "\"PID", "eq", ControlData.pid+"\""); - Process process = builder.start(); - InputStream stdout = process.getInputStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(stdout)); - BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); - - String line = null; - while ((line = br.readLine()) != null) { - if (!line.equals("")){ - String twoDigitMonth = String.format("%02d", month); - String twoDigitCycle = String.format("%02d", cycleIndex+1); - String ret = year + "_" + twoDigitMonth + "_c" + twoDigitCycle; - ILP.writeNoteLn(ret, line, ILP._noteFile_memory); - } - } - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }; - - thread.start(); - } -} +package wrimsv2.ilp; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.ObjectOutputStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.text.DecimalFormat; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.components.BuildProps; +import wrimsv2.components.ControlData; +import wrimsv2.components.Error; +import wrimsv2.components.FilePaths; +import wrimsv2.evaluator.EvalConstraint; +import wrimsv2.solver.CbcSolver; +import wrimsv2.solver.Clp0Solver; +import wrimsv2.solver.LPSolveSolver; +import wrimsv2.solver.Gurobi.GurobiSolver; +import wrimsv2.solver.mpmodel.MPModel; +import wrimsv2.wreslparser.elements.StudyUtils; +import wrimsv2.wreslparser.elements.Tools; + +// for LpSolve select 1.Rows 2.Cols 3.Elimeq2 in Presolve + +public class ILP { + + private static String _mpModelDir; + private static String _lpSolveDir; + private static String _cplexLpDir; + private static String _amplDir; + public static String mpModelFilePath; + public static String lpSolveFilePath; + public static String cplexLpFilePath; + public static String amplFilePath; + private static ObjectOutputStream _mpModelFile; + private static PrintWriter _lpSolveFile; + private static PrintWriter _cplexLpFile; + private static StringWriter _cplexLpString; + private static String cplexLpFileName; + private static PrintWriter _amplFile; + private static PrintWriter _svarFile; + private static PrintWriter _dvarFile; + private static PrintWriter _objValueFile; + public static PrintWriter _noteFile; + public static PrintWriter _noteFile_xa_obj; + public static PrintWriter _noteFile_xa_int; + public static PrintWriter _noteFile_cbc_obj; + public static PrintWriter _noteFile_cbc_time; + public static PrintWriter _noteFile_cbc_int; + public static PrintWriter _noteFile_cbc_int_log; + public static PrintWriter _noteFile_memory; + public static PrintWriter _watchFile_xa; + public static PrintWriter _watchFile_cbc; + private static Set dvar_effective; + private static final String lpSolve_comment_Symbol = "//"; + private static final String ampl_comment_Symbol = "#"; + private static final String cplexLp_comment_Symbol = "\\"; + private static DecimalFormat df; + public static int maximumFractionDigits = 16; + public static boolean loggingVariableValue = false; + public static boolean loggingVariableValueRound = false; + public static boolean loggingVariableValueRound10 = false; + public static boolean loggingAllCycles = true; + public static boolean logging = false; + public static boolean loggingAmpl = false; + public static boolean loggingCplexLp = false; // special LP problem file format designed by Cplex + public static boolean loggingLpSolve = false; // special LP problem file format designed by LpSolve + public static boolean loggingMPModel = false; // special LP problem binary file format designed for OR-Tools + public static boolean loggingUsageMemeory = false; + + private static File _ilpRootDir; + private static File _ilpDir; + private static File _svarDir; + private static File _dvarDir; + + public static ArrayList intList = null; + + private ILP() { + + } + + public static File getIlpDir() { + _ilpRootDir = new File(FilePaths.mainDirectory, "=ILP="); + _ilpDir = new File(_ilpRootDir.getAbsolutePath(), StudyUtils.configFileName); + return _ilpDir; + } + + public static void createNoteFile() { + try { + _noteFile = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_"+ControlData.dateTimeAppend+".log"); + writeNoteLn("wrims2 revision:", new BuildProps().getVN()); + writeNoteLn("jCbc dll name:", CbcSolver.cbcLibName); + if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) { + _noteFile_xa_obj = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_xa_obj.log"); + _noteFile_cbc_obj = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_obj.log"); + _noteFile_cbc_time = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_time.log"); + _noteFile_xa_int = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_xa_int.log"); + _noteFile_cbc_int = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_int.log"); + + if (ControlData.currStudyDataSet.cycIntDvMap!=null) { + ILP.writeNote("cyc ", _noteFile_cbc_int); + ILP.writeNote("cyc ", _noteFile_xa_int); + for (String s:ControlData.currStudyDataSet.allIntDv ){ + ILP.writeNote( s+" ", _noteFile_cbc_int); + ILP.writeNote( s+" ", _noteFile_xa_int); + } + ILP.writeNote("\r\n", _noteFile_cbc_int); + ILP.writeNote("\r\n", _noteFile_xa_int); + } + + if (ControlData.watchList!=null) { + _watchFile_xa = Tools.openFile(_ilpDir.getAbsolutePath(), "Watch_XA.log"); + _watchFile_cbc = Tools.openFile(_ilpDir.getAbsolutePath(), "Watch_CBC.log"); + ILP.writeNote( "time ", _watchFile_xa); + ILP.writeNote( "time ", _watchFile_cbc); + for (String s:ControlData.watchList) { + ILP.writeNote( s+" ", _watchFile_xa); + ILP.writeNote( s+" ", _watchFile_cbc); + } + ILP.writeNote("\r\n", _watchFile_xa); + ILP.writeNote("\r\n", _watchFile_cbc); + } + + } else if (CbcSolver.logObj && ControlData.solverName.equalsIgnoreCase("Cbc")){ + _noteFile_cbc_obj = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_obj.log"); + _noteFile_cbc_time = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_time.log"); + _watchFile_cbc = Tools.openFile(_ilpDir.getAbsolutePath(), "Watch_CBC.log"); + ILP.writeNote( "time ", _watchFile_cbc); + for (String s:ControlData.watchList) { + ILP.writeNote( s+" ", _watchFile_cbc); + } + ILP.writeNote("\r\n", _watchFile_cbc); + } + + if (CbcSolver.intLog && ControlData.solverName.equalsIgnoreCase("Cbc")){ + + _noteFile_cbc_int_log = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_cbc_int_check_"+ControlData.dateTimeAppend+".csv"); + if (ControlData.currStudyDataSet.cycIntDvMap!=null) { + ILP.writeNote("cyc,int_violation,solver,", _noteFile_cbc_int_log); + //ILP.writeNote("cyc ", _noteFile_xa_int); + for (String s:ControlData.currStudyDataSet.allIntDv ){ + ILP.writeNote( s+",", _noteFile_cbc_int_log); + //ILP.writeNote( s+" ", _noteFile_xa_int); + } + ILP.writeNote("\r\n", _noteFile_cbc_int_log); + //ILP.writeNote("\r\n", _noteFile_xa_int); + } + } + + //new File(_ilpDir.getAbsolutePath()+"\\Note_memory.log").createNewFile(); + _noteFile_memory = Tools.openFile(_ilpDir.getAbsolutePath(), "Note_memory.log"); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public static void initializeIlp() { + + _ilpRootDir = new File(FilePaths.mainDirectory, "=ILP="); + _ilpDir = new File(_ilpRootDir.getAbsolutePath(), StudyUtils.configFileName); + + if (ILP.loggingMPModel) _mpModelDir = new File(_ilpDir, "mpmodel").getAbsolutePath(); + if (ILP.loggingLpSolve) _lpSolveDir = new File(_ilpDir, "lpsolve").getAbsolutePath(); + if (ILP.loggingCplexLp) _cplexLpDir = new File(_ilpDir, "cplexlp").getAbsolutePath(); + if (ILP.loggingAmpl) _amplDir = new File(_ilpDir, "ampl").getAbsolutePath(); + // TODO: write ampl command file "option presolve_eps 1e-13;" + + if (ILP.loggingVariableValue) setVarDir(); + setMaximumFractionDigits(); + createNoteFile(); + try { + _objValueFile = Tools.openFile(_ilpDir.getAbsolutePath(), "ObjValues.log"); + } + catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public static void setMaximumFractionDigits() { + + df = new DecimalFormat(); + //df.setMinimumFractionDigits(2); + df.setMaximumFractionDigits(maximumFractionDigits); + } + + public static void setIlpFile() { + + if (ILP.loggingMPModel) setMPModelFile(); + if (ILP.loggingLpSolve) setLpSolveFile(); + if (ILP.loggingCplexLp) { + if (ControlData.useCplexLpString && ControlData.solverType != Param.SOLVER_CBC0.intValue() + && ControlData.solverType != Param.SOLVER_CBC1.intValue()){ + setCplexLpString(); + } else { + setCplexLpFile(); + } + } + if (ILP.loggingAmpl) setAmplFile(); + } + + public static void writeIlp() { + +// Set dvar_inConstraint = findDvarInConstraint(); +// Set dvar_weighted = findWeightedDvar(); +// //Set dvar_unWeighted = findUnWeightedDvarInConstraint(dvar_inConstraint, dvar_weighted); +// +// dvar_effective = new HashSet(); +// dvar_effective.addAll(dvar_weighted); +// dvar_effective.addAll(dvar_inConstraint); + + findDvarEffective(); + //if (ILP.loggingMPModel) writeMPModelFile(); + if (ILP.loggingLpSolve) writeLpSolveFile(); + if (ILP.loggingCplexLp) writeCplexLpFile(); + if (ILP.loggingAmpl) writeAmplFile(); + + } + + public static void findDvarEffective(){ + + Set dvar_inConstraint = findDvarInConstraint(); + Set dvar_weighted = findWeightedDvar(); + //Set dvar_unWeighted = findUnWeightedDvarInConstraint(dvar_inConstraint, dvar_weighted); + + dvar_effective = new HashSet(); + dvar_effective.addAll(dvar_weighted); + dvar_effective.addAll(dvar_inConstraint); + + } + + public static void writeObjValue_XA() { + + double objValue = ControlData.xasolver.getObjective(); + String objValueStr = Double.toString(objValue); + + if (ILP.loggingLpSolve) writeObjValue(objValueStr, _lpSolveFile, lpSolve_comment_Symbol); + if (ILP.loggingCplexLp) writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); + if (ILP.loggingAmpl) writeObjValue(objValueStr, _amplFile, ampl_comment_Symbol); + + writeObjValueLog(getYearMonthCycle(), objValueStr, _objValueFile); + + } + + public static void writeObjValue_LPSOLVE() { + + double objValue = ControlData.lpsolve_objective; + String objValueStr = Double.toString(objValue); + + writeObjValue(objValueStr, _lpSolveFile, lpSolve_comment_Symbol); + if (ILP.loggingCplexLp) writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); + if (ILP.loggingAmpl) writeObjValue(objValueStr, _amplFile, ampl_comment_Symbol); + + writeObjValueLog(getYearMonthCycle(), objValueStr, _objValueFile); + + } + + public static void writeObjValue_Clp0_Cbc0() { + + double objValue = ControlData.clp_cbc_objective; + String objValueStr = Double.toString(objValue); + + writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); + //if (ILP.loggingCplexLp) writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); + //if (ILP.loggingAmpl) writeObjValue(objValueStr, _amplFile, ampl_comment_Symbol); + + writeObjValueLog(getYearMonthCycle(), objValueStr, _objValueFile); + if (!ControlData.clp_cbc_note.isEmpty()) writeNoteLn(getYearMonthCycle(), ControlData.clp_cbc_note, _noteFile); + + } + + public static void writeObjValue_Gurobi() { + + double objValue = ControlData.gurobi_objective; + String objValueStr = Double.toString(objValue); + + writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); + if (ILP.loggingLpSolve) writeObjValue(objValueStr, _lpSolveFile, lpSolve_comment_Symbol); + if (ILP.loggingAmpl) writeObjValue(objValueStr, _amplFile, ampl_comment_Symbol); + + writeObjValueLog(getYearMonthCycle(), objValueStr, _objValueFile); + + } + + public static void writeObjValue_OrTools() { + + double objValue = ControlData.otsolver.solver.objectiveValue(); + String objValueStr = Double.toString(objValue); + + if (ILP.loggingCplexLp) writeObjValue(objValueStr, _cplexLpFile, cplexLp_comment_Symbol); + if (ILP.loggingLpSolve) writeObjValue(objValueStr, _lpSolveFile, lpSolve_comment_Symbol); + if (ILP.loggingAmpl) writeObjValue(objValueStr, _amplFile, ampl_comment_Symbol); + + writeObjValueLog(getYearMonthCycle(), objValueStr, _objValueFile); + + } + + public static void writeMPModelFile(MPModel m) { + + try { + _mpModelFile.writeObject(m); + _mpModelFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + private static void writeLpSolveFile() { + + _lpSolveFile.print(findHeaderStr(lpSolve_comment_Symbol)); + + Map activeWeightMap = findActiveWeightMap(); + + LpSolveWriter.writeObj(_lpSolveFile, activeWeightMap); + LpSolveWriter.writeConstraint(_lpSolveFile); + +// Set dvar_inConstraint = findDvarInConstraint(); +// Set dvar_weighted = findWeightedDvar(); +// //Set dvar_unWeighted = findUnWeightedDvarInConstraint(dvar_inConstraint, dvar_weighted); +// +// dvar_effective = new HashSet(); +// dvar_effective.addAll(dvar_weighted); +// dvar_effective.addAll(dvar_inConstraint); + + //LpSolveWriter.writeDvar(_lpSolveFile, dvar_weighted, dvar_unWeighted); + LpSolveWriter.writeDvar(_lpSolveFile, dvar_effective); + _lpSolveFile.flush(); + } + private static void writeCplexLpFile() { + + _cplexLpFile.print(findHeaderStr(cplexLp_comment_Symbol)); + + Map activeWeightMap = findActiveWeightMap(); + + CplexLpWriter.writeObj(_cplexLpFile, activeWeightMap); + CplexLpWriter.writeConstraint(_cplexLpFile); + +// Set dvar_inConstraint = findDvarInConstraint(); +// Set dvar_weighted = findWeightedDvar(); +// //Set dvar_unWeighted = findUnWeightedDvarInConstraint(dvar_inConstraint, dvar_weighted); +// +// dvar_effective = new HashSet(); +// dvar_effective.addAll(dvar_weighted); +// dvar_effective.addAll(dvar_inConstraint); + + CplexLpWriter.writeDvar(_cplexLpFile, dvar_effective); + _cplexLpFile.println("\nEnd"); + _cplexLpFile.flush(); + + } + private static void writeAmplFile() { + + _amplFile.print(findHeaderStr(ampl_comment_Symbol)); + + Map activeWeightMap = findActiveWeightMap(); + +// Set dvar_inConstraint = findDvarInConstraint(); +// Set dvar_weighted = findWeightedDvar(); +// //Set dvar_unWeighted = findUnWeightedDvarInConstraint(dvar_inConstraint, dvar_weighted); +// +// dvar_effective = new HashSet(); +// dvar_effective.addAll(dvar_weighted); +// dvar_effective.addAll(dvar_inConstraint); + + AmplWriter.writeDvar(_amplFile, dvar_effective); + AmplWriter.writeConstraint(_amplFile); + AmplWriter.writeObj(_amplFile, activeWeightMap); + _amplFile.flush(); + } + + public static void writeDvarValue_XA() { + + writeDvarValue_XA(_dvarFile, dvar_effective); + _dvarFile.flush(); + + } + public static void writeDvarValue_LPSOLVE() { + + writeDvarValue_LPSOLVE(_dvarFile, dvar_effective); + _dvarFile.flush(); + + } + public static void writeDvarValue_Clp0_Cbc0(Map varDoubleMap) { + + writeDvarValue_Clp0_Cbc0(_dvarFile, dvar_effective, varDoubleMap); + _dvarFile.flush(); + + } + public static void writeDvarValue_Gurobi() { + + writeDvarValue_Gurobi(_dvarFile, dvar_effective); + _dvarFile.flush(); + + } + public static void writeDvarValue_OrTools() { + + writeDvarValue_OrTools(_dvarFile, dvar_effective); + _dvarFile.flush(); + + } + public static void writeSvarValue() { + + writeSvarValue(_svarFile); + _svarFile.flush(); + } + + public static void closeIlpFile() { + + try { + if (ILP.loggingMPModel) _mpModelFile.close(); + if (ILP.loggingLpSolve) _lpSolveFile.close(); + if (ILP.loggingCplexLp) _cplexLpFile.close(); + if (ILP.loggingAmpl) _amplFile.close(); + if (ILP.loggingVariableValue) { + _svarFile.close(); + _dvarFile.close(); + } + } catch (Exception e) { + + // ignore + } + } + + private static void setMPModelFile() { + + String mpModelFileName; + String twoDigitMonth = String.format("%02d", ControlData.currMonth); + String twoDigitCycle = String.format("%02d", ControlData.currCycleIndex+1); + + mpModelFileName = ControlData.currYear + "_" + twoDigitMonth + "_c" + twoDigitCycle + ".mpm"; + + try { + + File dir = new File(_mpModelDir); + dir.mkdirs(); + mpModelFilePath = new File(_mpModelDir, mpModelFileName).getAbsolutePath(); // for public access + _mpModelFile = new ObjectOutputStream(new FileOutputStream(mpModelFilePath)); + + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + } + + private static void setLpSolveFile() { + + String lpSolveFileName; + String twoDigitMonth = String.format("%02d", ControlData.currMonth); + String twoDigitCycle = String.format("%02d", ControlData.currCycleIndex+1); + + lpSolveFileName = ControlData.currYear + "_" + twoDigitMonth + "_c" + twoDigitCycle + ".lps"; + + try { + + _lpSolveFile = Tools.openFile(_lpSolveDir, lpSolveFileName); + lpSolveFilePath = new File(_lpSolveDir, lpSolveFileName).getAbsolutePath(); // for public access + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + } + + public static void setVarDir(){ + + _svarDir = new File(_ilpDir, "svar"); + _dvarDir = new File(_ilpDir, "dvar"); + + } + + public static String getYearMonthCycle(){ + + String twoDigitMonth = String.format("%02d", ControlData.currMonth); + String twoDigitCycle = String.format("%02d", ControlData.currCycleIndex+1); + String ret = ControlData.currYear + "_" + twoDigitMonth + "_c" + twoDigitCycle; + + return ret; + + } + + public static void setObjValueFile(){ + + + try { + + _objValueFile = Tools.openFile(_ilpDir.getAbsolutePath(), "objectiveValues.log"); + + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + public static void setVarFile(){ + + String svarFileName = getYearMonthCycle()+ ".svar"; + String dvarFileName = getYearMonthCycle()+ ".dvar"; + + + try { + + _svarFile = Tools.openFile(_svarDir.getAbsolutePath(), svarFileName); + _dvarFile = Tools.openFile(_dvarDir.getAbsolutePath(), dvarFileName); + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + public static void setSvarFile(){ + + String svarFileName = getYearMonthCycle()+ ".svar"; + + try { + //_svarDir = new File(_ilpDir, "svar"); + _svarFile = Tools.openFile(_svarDir.getAbsolutePath(), svarFileName); + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + public static void setDvarFile(String append){ + + String dvarFileName = getYearMonthCycle()+ ".dvar_"+append; + + try { + + _dvarFile = Tools.openFile(_dvarDir.getAbsolutePath(), dvarFileName); + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + private static void setCplexLpFile() { + + cplexLpFileName = getYearMonthCycle()+".lp"; + + try { + + _cplexLpFile = Tools.openFile(_cplexLpDir, cplexLpFileName); + cplexLpFilePath = new File(_cplexLpDir, cplexLpFileName).getAbsolutePath(); // for public access + + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + } + + private static void setCplexLpString() { + + + + //_cplexLpFile = Tools.openFile(_cplexLpDir, cplexLpFileName); + _cplexLpString = new StringWriter(); + _cplexLpFile = new PrintWriter(new BufferedWriter(_cplexLpString)); + //cplexLpFilePath = new File(_cplexLpDir, cplexLpFileName).getAbsolutePath(); // for public access + + } + + public static void saveCplexLpStringToFile() { + + + cplexLpFileName = getYearMonthCycle()+".lp"; + + try { + + _cplexLpFile = Tools.openFile(_cplexLpDir, cplexLpFileName); + _cplexLpFile.print(_cplexLpString); + _cplexLpFile.close(); + cplexLpFilePath = new File(_cplexLpDir, cplexLpFileName).getAbsolutePath(); // for public access + + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + } + + public static void closeCplexLpFile() { + + try { + + _cplexLpFile.close(); + + } + catch (Exception e) { + // TODO Auto-generated catch block + //ignore + } + + } + + public static void reOpenCplexLpFile(boolean isAppend) { + + try { + + _cplexLpFile = Tools.openFile(_cplexLpDir, cplexLpFileName, isAppend); + + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + } + + private static void setAmplFile() { + + String amplFileName = getYearMonthCycle()+ ".mod"; + + try { + + _amplFile = Tools.openFile(_amplDir, amplFileName); + amplFilePath = new File(_amplDir, amplFileName).getAbsolutePath(); // for public access + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + } + + + private static String findHeaderStr(String commentSymbol) { + + String headerStr = ""; + + String twoDigitMonth = String.format("%02d", ControlData.currMonth); + String twoDigitCycle = String.format("%02d", ControlData.currCycleIndex+1); + + String CurrDate = Integer.toString(ControlData.currYear)+"." + + twoDigitMonth; + + headerStr = headerStr + commentSymbol + " Date: "+CurrDate + "\n"; + headerStr = headerStr + commentSymbol + " Cycle: "+twoDigitCycle + "\n";; + headerStr = headerStr + commentSymbol + " Solver: "+ControlData.solverName + "\n\n"; + + return headerStr; + } + + private static Set findWeightedDvar() { + + Set dvar_weighted = new HashSet(); + + dvar_weighted.addAll(ControlData.currModelDataSet.usedWtSlackSurplusList); + dvar_weighted.addAll(SolverData.getWeightMap().keySet()); + + return dvar_weighted; + } + + private static Set findDvarInConstraint() { + + Set dvar_inConstraint = new HashSet(); + + Map constraintMap = SolverData.getConstraintDataMap(); + + for (String constraintName : constraintMap.keySet()) { + + if (!constraintMap.get(constraintName).getEvalExpression().isNumeric()) { + + dvar_inConstraint.addAll(constraintMap.get(constraintName).getEvalExpression().getMultiplier().keySet()); + } + } + return dvar_inConstraint; + } + + private static Set findUnWeightedDvarInConstraint( Set dvar_inConstraint, Set dvar_weighted ) { + + Set dvar_unWeighted = new HashSet(); + + dvar_unWeighted.addAll(dvar_inConstraint); + + dvar_unWeighted.removeAll(dvar_weighted); + + return dvar_unWeighted; + } + + private static Map findActiveWeightMap() { + + Map activeWeightMap = new HashMap(); + + for (String usedSlackSurplus: ControlData.currModelDataSet.usedWtSlackSurplusList){ + + activeWeightMap.put(usedSlackSurplus, SolverData.getWeightSlackSurplusMap().get(usedSlackSurplus)); + + } + + activeWeightMap.putAll(SolverData.getWeightMap()); + + return activeWeightMap; + } + + private static String findSvarValueStr() { + + String svarValueStr = ""; + + Map svMap = ControlData.currSvMap; + + ArrayList sortedTerm = new ArrayList(svMap.keySet()); + Collections.sort(sortedTerm); + + for (String s : sortedTerm){ + String svName = String.format("%-35s", s); + svarValueStr = svarValueStr + ( svName + ": " + svMap.get(s).getData().getData() +"\n" ); + } + + return svarValueStr; + } + + private static String findDvarValueStr_XA(Set dvar) { + + ArrayList dvar_sorted = new ArrayList(dvar); + + Collections.sort(dvar_sorted); + + String dvarValueStr = ""; + + for (String s : dvar_sorted){ + String dvName = String.format("%-35s", s); + dvarValueStr = dvarValueStr + (dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); + } + + return dvarValueStr; + } + + public static void writeObjValueLog(String msg, String objValueStr, PrintWriter outFile) { + + if (Error.getTotalError()==0) { + outFile.println(msg+": "+objValueStr); + } else { + outFile.println(msg+": "+"Error! "); + } + outFile.flush(); + } + + public static void writeNoteLn(String msg, boolean printToScreen, boolean isErr) { + + writeNoteLn(msg, _noteFile); + if (printToScreen) { + if (isErr) { System.err.println(msg);} + else {System.out.println(msg);}; + } + } + + public static void writeNoteLn(String msg) { + + writeNoteLn(msg, false, false); + } + + public static void writeNoteLn(String msg, String noteStr) { + + writeNoteLn(msg, noteStr, _noteFile); + } + + public static void writeNoteLn(String msg, String noteStr, PrintWriter outFile) { + +// if (Error.getTotalError()==0) { + outFile.println(msg+": "+noteStr); +// } else { +// outFile.println(msg+": "+"Error! "); +// } + outFile.flush(); + } + + public static void writeNoteLn(String msg, PrintWriter outFile) { + + outFile.println(msg); + outFile.flush(); + } + + public static void writeNote(String msg, PrintWriter outFile) { + + outFile.print(msg); + outFile.flush(); + } + + private static void writeObjValue(String objValueStr, PrintWriter outFile, String commentSym) { + + //double objValue = ControlData.xasolver.getObjective(); + + outFile.print("\n\n\n\n"); + if (Error.getTotalError()==0) { + outFile.println(commentSym+" objective value: "+objValueStr); + } else { + outFile.println(commentSym+" objective value: Error! "); + } + outFile.flush(); + } + + // returns + private static ArrayList> prepareDvarToWrite(Set dvar_effective){ + + ArrayList> ret = new ArrayList>(); + + Map dvMap = SolverData.getDvarMap(); + Map wtMap = SolverData.getWeightMap(); + //Map wtSlackSurplusMap = SolverData.getWeightSlackSurplusMap(); + + ArrayList dvar_weighted = new ArrayList(wtMap.keySet()); + dvar_weighted.addAll(ControlData.currModelDataSet.usedWtSlackSurplusList); + + //TODO: remove weight of 0 from dvar_weighted. + + + ArrayList dvar_unweighted = new ArrayList(dvMap.keySet()); + //dvar_unweighted.removeAll(wtMap.keySet()); + //dvar_unweighted.removeAll(ControlData.currModelDataSet.usedWtSlackSurplusList); + dvar_unweighted.removeAll(dvar_weighted); + + dvar_unweighted.retainAll(dvar_effective); + Collections.sort(dvar_weighted); + Collections.sort(dvar_unweighted); + + ret.add(dvar_weighted); + ret.add(dvar_unweighted); + + return ret; + + } + private static void writeDvarValue_XA(PrintWriter dvarFile, Set dvar_effective) { + + ArrayList> sortedDvar = prepareDvarToWrite(dvar_effective); + ArrayList dvar_weighted = sortedDvar.get(0); + ArrayList dvar_unweighted = sortedDvar.get(1); + + dvarFile.println("/* Weighted Dvar */"); + for (String s : dvar_weighted){ + String dvName = String.format("%-35s", s); + double v = ControlData.xasolver.getColumnActivity(s); + if (loggingVariableValueRound) v = Math.round(v); + if (loggingVariableValueRound10 && !intList.contains(s)) { + v = Math.round(v/10)*10; + } + try{ + if (v!=0){ + dvarFile.print(dvName + ": " + String.format("%23s", df.format(v)) +"\n" ); + } else { + dvarFile.print(dvName + ": " + String.format("%23s", "0") +"\n" ); + } + } catch (Exception e) { + dvarFile.print(dvName + ": " + String.format("%23s", v) +"\n" ); + } + } + dvarFile.println(); + dvarFile.println("/* Unweighted Dvar */"); + for (String s : dvar_unweighted){ + String dvName = String.format("%-35s", s); + double v = ControlData.xasolver.getColumnActivity(s); + if (loggingVariableValueRound) v = Math.round(v); + if (loggingVariableValueRound10 && !intList.contains(s)) { + v = Math.round(v/10)*10; + } + try{ + if (v!=0){ + dvarFile.print(dvName + ": " + String.format("%23s", df.format(v)) +"\n" ); + } else { + dvarFile.print(dvName + ": " + String.format("%23s", "0") +"\n" ); + } + } catch (Exception e) { + dvarFile.print(dvName + ": " + String.format("%23s", v) +"\n" ); + } + } + } + + private static void writeDvarValue_LPSOLVE(PrintWriter dvarFile, Set dvar_effective) { + + ArrayList> sortedDvar = prepareDvarToWrite(dvar_effective); + ArrayList dvar_weighted = sortedDvar.get(0); + ArrayList dvar_unweighted = sortedDvar.get(1); + + dvarFile.println("/* Weighted Dvar */"); + for (String s : dvar_weighted){ + String dvName = String.format("%-35s", s); + //dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); + try{ + double v = LPSolveSolver.varDoubleMap.get(s); + // TODO: improve speed + if (!df.format(v).equals("-0")) { + dvarFile.print(dvName + ": " + df.format(v) +"\n" ); + } else { + dvarFile.print(dvName + ": 0" +"\n" ); + } + + } catch (Exception e) { + dvarFile.print(dvName + ": " + LPSolveSolver.varDoubleMap.get(s) +"\n" ); + } + } + dvarFile.println(); + dvarFile.println("/* Unweighted Dvar */"); + for (String s : dvar_unweighted){ + String dvName = String.format("%-35s", s); + try{ + double v = LPSolveSolver.varDoubleMap.get(s); + // TODO: improve speed + if (!df.format(v).equals("-0")) { + dvarFile.print(dvName + ": " + df.format(v) +"\n" ); + } else { + dvarFile.print(dvName + ": 0" +"\n" ); + } + + } catch (Exception e) { + dvarFile.print(dvName + ": " + LPSolveSolver.varDoubleMap.get(s) +"\n" ); + } + } + } + + private static void writeDvarValue_Clp0_Cbc0(PrintWriter dvarFile, Set dvar_effective, Map varDoubleMap) { + + ArrayList> sortedDvar = prepareDvarToWrite(dvar_effective); + ArrayList dvar_weighted = sortedDvar.get(0); + ArrayList dvar_unweighted = sortedDvar.get(1); + + dvarFile.println("/* Weighted Dvar */"); + for (String s : dvar_weighted){ + String dvName = String.format("%-35s", s); + //dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); + try{ + double v = varDoubleMap.get(s); + if (loggingVariableValueRound) v = Math.round(v); + if (loggingVariableValueRound10 && !intList.contains(s)) { + v = Math.round(v/10)*10; + } + // TODO: improve speed + if (v!=0) { + dvarFile.print(dvName + ": " + String.format("%23s", df.format(v)) +"\n" ); + } else { + dvarFile.print(dvName + ": " + String.format("%23s", "0") +"\n" ); + } + + } catch (Exception e) { + dvarFile.print(dvName + ": " + varDoubleMap.get(s) +"\n" ); + } + } + dvarFile.println(); + dvarFile.println("/* Unweighted Dvar */"); + for (String s : dvar_unweighted){ + String dvName = String.format("%-35s", s); + try{ + double v = varDoubleMap.get(s); + if (loggingVariableValueRound) v = Math.round(v); + if (loggingVariableValueRound10 && !intList.contains(s)) { + v = Math.round(v/10)*10; + } + // TODO: improve speed + if (v!=0) { + dvarFile.print(dvName + ": " + String.format("%23s", df.format(v)) +"\n" ); + } else { + dvarFile.print(dvName + ": " + String.format("%23s", "0") +"\n" ); + } + + } catch (Exception e) { + dvarFile.print(dvName + ": " + varDoubleMap.get(s) +"\n" ); + } + } + } + + private static void writeDvarValue_Gurobi(PrintWriter dvarFile, Set dvar_effective) { + + + ArrayList> sortedDvar = prepareDvarToWrite(dvar_effective); + ArrayList dvar_weighted = sortedDvar.get(0); + ArrayList dvar_unweighted = sortedDvar.get(1); + + dvarFile.println("/* Weighted Dvar */"); + for (String s : dvar_weighted){ + String dvName = String.format("%-35s", s); + //dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); + try{ + double v = GurobiSolver.varDoubleMap.get(s); + // TODO: improve speed + if (!df.format(v).equals("-0")) { + dvarFile.print(dvName + ": " + df.format(v) +"\n" ); + } else { + dvarFile.print(dvName + ": 0" +"\n" ); + } + + } catch (Exception e) { + dvarFile.print(dvName + ": " + GurobiSolver.varDoubleMap.get(s) +"\n" ); + } + } + dvarFile.println(); + dvarFile.println("/* Unweighted Dvar */"); + for (String s : dvar_unweighted){ + String dvName = String.format("%-35s", s); + try{ + double v = GurobiSolver.varDoubleMap.get(s); + // TODO: improve speed + if (!df.format(v).equals("-0")) { + dvarFile.print(dvName + ": " + df.format(v) +"\n" ); + } else { + dvarFile.print(dvName + ": 0" +"\n" ); + } + + } catch (Exception e) { + dvarFile.print(dvName + ": " + GurobiSolver.varDoubleMap.get(s) +"\n" ); + } + } + } + + private static void writeDvarValue_OrTools(PrintWriter dvarFile, Set dvar_effective) { + + + ArrayList> sortedDvar = prepareDvarToWrite(dvar_effective); + ArrayList dvar_weighted = sortedDvar.get(0); + ArrayList dvar_unweighted = sortedDvar.get(1); + + dvarFile.println("/* Weighted Dvar */"); + for (String s : dvar_weighted){ + String dvName = String.format("%-35s", s); + //dvarFile.print(dvName + ": " + ControlData.xasolver.getColumnActivity(s) +"\n" ); + try{ + double v = ControlData.otsolver.solution.get(s); + // TODO: improve speed + if (!df.format(v).equals("-0")) { + dvarFile.print(dvName + ": " + df.format(v) +"\n" ); + } else { + dvarFile.print(dvName + ": 0" +"\n" ); + } + + } catch (Exception e) { + dvarFile.print(dvName + ": " + ControlData.otsolver.solution.get(s) +"\n" ); + } + } + dvarFile.println(); + dvarFile.println("/* Unweighted Dvar */"); + for (String s : dvar_unweighted){ + String dvName = String.format("%-35s", s); + try{ + double v = ControlData.otsolver.solution.get(s); + // TODO: improve speed + if (!df.format(v).equals("-0")) { + dvarFile.print(dvName + ": " + df.format(v) +"\n" ); + } else { + dvarFile.print(dvName + ": 0" +"\n" ); + } + + } catch (Exception e) { + dvarFile.print(dvName + ": " + ControlData.otsolver.solution.get(s) +"\n" ); + } + } + } + + private static void writeSvarValue(PrintWriter svarFile) { + + Map svMap = ControlData.currSvMap; + + ArrayList sortedTerm = new ArrayList(svMap.keySet()); + Collections.sort(sortedTerm); + + + + + for (String s : sortedTerm){ + String svName = String.format("%-35s", s); + double v =svMap.get(s).getData().getData().doubleValue(); + if (loggingVariableValueRound) v = Math.round(v); + if (loggingVariableValueRound10) {v = Math.round(v/10)*10;} + // TODO: improve speed +// System.out.println("svarFile:"+svarFile.toString()); +// System.out.println("svName:"+svName); +// System.out.println("v:"+v); +// System.out.println("df:"+df.toString()); + if (v!=0) { + svarFile.print(svName + ": " + String.format("%23s", df.format(v)) +"\n" ); + } else { + svarFile.print(svName + ": " + String.format("%23s", "0") +"\n" ); + } + + +// svarFile.print(svName + ": "); +// svarFile.print(df.format(svMap.get(s).getData().getData())); +// svarFile.print("\n" ); + + } + + } + + public static void setLPSolveDir(String dir){ + _lpSolveDir=dir; + } + + public static void setCplxLpDir(String dir){ + _cplexLpDir=dir; + } + + public static void logUsageMemory(int year, int month, int day, int cycleIndex){ + Thread thread = new Thread(){ + public void run(){ + try { + //System.out.println("tasklist.exe /fi \"PID eq "+ControlData.pid+"\" > \""+ _ilpDir.getAbsolutePath()+"\\Note_memory.log\""); + ProcessBuilder builder = new ProcessBuilder("tasklist.exe", "/nh", "/fi", "\"PID", "eq", ControlData.pid+"\""); + Process process = builder.start(); + InputStream stdout = process.getInputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(stdout)); + BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); + + String line = null; + while ((line = br.readLine()) != null) { + if (!line.equals("")){ + String twoDigitMonth = String.format("%02d", month); + String twoDigitCycle = String.format("%02d", cycleIndex+1); + String ret = year + "_" + twoDigitMonth + "_c" + twoDigitCycle; + ILP.writeNoteLn(ret, line, ILP._noteFile_memory); + } + } + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + }; + + thread.start(); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/ilp/LpSolveWriter.java b/wrims-core/src/main/java/wrimsv2/ilp/LpSolveWriter.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/ilp/LpSolveWriter.java rename to wrims-core/src/main/java/wrimsv2/ilp/LpSolveWriter.java index 3dc1ff749..0f2b877ef 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/ilp/LpSolveWriter.java +++ b/wrims-core/src/main/java/wrimsv2/ilp/LpSolveWriter.java @@ -1,343 +1,343 @@ -package wrimsv2.ilp; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.evaluator.EvalConstraint; - -// for LpSolve select 1.Rows 2.Cols 3.Elimeq2 in Presolve - -public class LpSolveWriter { - - private LpSolveWriter() { - - } - -// public static Set output() { -// -// Set usedDvar = new HashSet(); -// -// writeInfo(); -// Set usedDvarInWeight = writeObj(); -// _ilpFile.print("\n"); -// Set usedDvarInConstraint = writeConstraint(); -// _ilpFile.print("\n"); -// usedDvar.addAll(usedDvarInWeight); -// usedDvar.addAll(usedDvarInConstraint); -// writeDvar(usedDvar); -// _ilpFile.flush(); -// -// // write to _svarFile -// writeSvarValue(); -// return usedDvar; -// } - - public static void writeComment(PrintWriter outFile, String msg) { - - - outFile.println("// " + msg ); - - } - - public static void writeObjValue() { - - - } - - - protected static void writeObj(PrintWriter outFile, Map activeWeightMap) { - - outFile.println("// objective function "); - outFile.println("max: "); - - - String toPrint = ""; - - ArrayList sortedTerm = new ArrayList(activeWeightMap.keySet()); - - Collections.sort(sortedTerm); - - for (String dvar : sortedTerm) { - - double weight = activeWeightMap.get(dvar).getValue(); - - if (weight > 0) { - - toPrint = toPrint + "+ " + weight + " " + dvar + " "; - outFile.println("+ " + weight + " " + dvar); - - } - else if (weight < 0) { - toPrint = toPrint + weight + " " + dvar + " "; - outFile.println(weight + " " + dvar); - } - - } - - // _ilpFile.println(toPrint); - outFile.println(";"); - - } - - protected static void writeConstraint(PrintWriter outFile) { - - outFile.println("/* constraint */"); - - Map constraintMap = SolverData.getConstraintDataMap(); - - ArrayList sortedConstraint = new ArrayList(constraintMap.keySet()); - Collections.sort(sortedConstraint); - - for (String constraintName : sortedConstraint) { - - String lhs = ""; - - if (!constraintMap.get(constraintName).getEvalExpression().isNumeric()) { - - ArrayList sortedTerm = new ArrayList(constraintMap.get(constraintName) - .getEvalExpression().getMultiplier().keySet()); - Collections.sort(sortedTerm); - - for (String var : sortedTerm) { - - Number coef = constraintMap.get(constraintName).getEvalExpression().getMultiplier().get(var) - .getData(); - double coefDouble = coef.doubleValue(); - String coefStr = coef.toString(); - String term; - - if (coefDouble == 1.0) { - term = " + " + var; - } - else if (coefDouble == -1.0) { - term = " - " + var; - } - else if (coefDouble < 0) { - term = " " + coefStr + " " + var; - } - else { // coefDouble >= 0 - term = " + " + coefStr + " " + var; - } - lhs = lhs + term; - } - - } - else { - - lhs = "0"; - } - - String sign = constraintMap.get(constraintName).getSign(); - double val = constraintMap.get(constraintName).getEvalExpression().getValue().getData().doubleValue(); - - if (val == 0) { - lhs = constraintName + ": " + lhs + " " + sign + " " + "0"; - } - else { - lhs = constraintName + ": " + lhs + " " + sign + " " + val * -1; - } - - outFile.println(lhs + " ;"); - - } - - } - - protected static void writeDvar(PrintWriter outFile, Set dvar_weighted, Set dvar_unWeighted) { - - - Map dvarMap = SolverData.getDvarMap(); - - ArrayList sortedDvar_weighted = new ArrayList(dvarMap.keySet()); - sortedDvar_weighted.retainAll(dvar_weighted); - Collections.sort(sortedDvar_weighted); - - ArrayList sortedDvar_unWeighted = new ArrayList(dvarMap.keySet()); - sortedDvar_unWeighted.retainAll(dvar_unWeighted); - Collections.sort(sortedDvar_unWeighted); - - // TODO: separate integer list in the parsing stage for efficiency - ArrayList intList = new ArrayList(); - ArrayList freeList = new ArrayList(); - - - /////// weighted - outFile.println("/* dvar weighted */"); - - for (String key : sortedDvar_weighted) { - double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); - double upper = dvarMap.get(key).upperBoundValue.doubleValue(); - String lowerStr = dvarMap.get(key).lowerBound; - String upperStr = dvarMap.get(key).upperBound; - - if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); - - if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - freeList.add(key); //TODO: test what happen if it's a free integer ??? - continue; - } - else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { - outFile.print(key + " < " + upper + " ;\n"); - } - else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - // TODO: be careful, by default LpSolve treat this as standard so we don't write to ilp file - if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); - } - else { - if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); - outFile.print(key + " < " + upper + " ;\n"); - } - } - - /////// unweighted - outFile.println("/* dvar unweighted in constraint*/"); - - for (String key : sortedDvar_unWeighted) { - double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); - double upper = dvarMap.get(key).upperBoundValue.doubleValue(); - String lowerStr = dvarMap.get(key).lowerBound; - String upperStr = dvarMap.get(key).upperBound; - - if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); - - if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - freeList.add(key); //TODO: test what happen if it's a free integer ??? - continue; - } - else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { - outFile.print(key + " < " + upper + " ;\n"); - } - else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - // TODO: be careful, by default LpSolve treat this as standard so we don't write to ilp file - if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); - } - else { - if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); - outFile.print(key + " < " + upper + " ;\n"); - } - } - - - - - if (intList.size() > 0) { - outFile.print("int "); - - for (int i = 0; i < intList.size(); i++) { - String term = intList.get(i); - - if (i == 0) { - outFile.print(term); - } - else { - outFile.print(", " + term); - } - } - - outFile.print(" ;\n"); - } - - if (freeList.size() > 0) { - outFile.print("free "); - - for (int i = 0; i < freeList.size(); i++) { - String term = freeList.get(i); - - if (i == 0) { - outFile.print(term); - } - else { - outFile.print(", " + term); - } - } - - outFile.print(" ;\n"); - } - } - - protected static void writeDvar(PrintWriter outFile, Set dvar_effective) { - - - Map dvarMap = SolverData.getDvarMap(); - - ArrayList sortedDvar_effective = new ArrayList(dvarMap.keySet()); - sortedDvar_effective.retainAll(dvar_effective); - Collections.sort(sortedDvar_effective); - - - // TODO: separate integer list in the parsing stage for efficiency - ArrayList intList = new ArrayList(); - ArrayList freeList = new ArrayList(); - - - outFile.println("/* dvar */"); - - for (String key : sortedDvar_effective) { - double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); - double upper = dvarMap.get(key).upperBoundValue.doubleValue(); - String lowerStr = dvarMap.get(key).lowerBound; - String upperStr = dvarMap.get(key).upperBound; - - if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); - - if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - freeList.add(key); //TODO: test what happen if it's a free integer ??? - continue; - } - else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { - outFile.print(key + " < " + upper + " ;\n"); - } - else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - // TODO: be careful, by default LpSolve treat this as standard so we don't write to ilp file - if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); - } - else { - if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); - outFile.print(key + " < " + upper + " ;\n"); - } - } - - - if (intList.size() > 0) { - outFile.print("int "); - - for (int i = 0; i < intList.size(); i++) { - String term = intList.get(i); - - if (i == 0) { - outFile.print(term); - } - else { - outFile.print(", \n" + term); - } - } - - outFile.print(" ;\n"); - } - - if (freeList.size() > 0) { - outFile.print("free "); - - for (int i = 0; i < freeList.size(); i++) { - String term = freeList.get(i); - - if (i == 0) { - outFile.print(term); - } - else { - outFile.print(", \n" + term); - } - } - - outFile.print(" ;\n"); - } - } - -} +package wrimsv2.ilp; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.evaluator.EvalConstraint; + +// for LpSolve select 1.Rows 2.Cols 3.Elimeq2 in Presolve + +public class LpSolveWriter { + + private LpSolveWriter() { + + } + +// public static Set output() { +// +// Set usedDvar = new HashSet(); +// +// writeInfo(); +// Set usedDvarInWeight = writeObj(); +// _ilpFile.print("\n"); +// Set usedDvarInConstraint = writeConstraint(); +// _ilpFile.print("\n"); +// usedDvar.addAll(usedDvarInWeight); +// usedDvar.addAll(usedDvarInConstraint); +// writeDvar(usedDvar); +// _ilpFile.flush(); +// +// // write to _svarFile +// writeSvarValue(); +// return usedDvar; +// } + + public static void writeComment(PrintWriter outFile, String msg) { + + + outFile.println("// " + msg ); + + } + + public static void writeObjValue() { + + + } + + + protected static void writeObj(PrintWriter outFile, Map activeWeightMap) { + + outFile.println("// objective function "); + outFile.println("max: "); + + + String toPrint = ""; + + ArrayList sortedTerm = new ArrayList(activeWeightMap.keySet()); + + Collections.sort(sortedTerm); + + for (String dvar : sortedTerm) { + + double weight = activeWeightMap.get(dvar).getValue(); + + if (weight > 0) { + + toPrint = toPrint + "+ " + weight + " " + dvar + " "; + outFile.println("+ " + weight + " " + dvar); + + } + else if (weight < 0) { + toPrint = toPrint + weight + " " + dvar + " "; + outFile.println(weight + " " + dvar); + } + + } + + // _ilpFile.println(toPrint); + outFile.println(";"); + + } + + protected static void writeConstraint(PrintWriter outFile) { + + outFile.println("/* constraint */"); + + Map constraintMap = SolverData.getConstraintDataMap(); + + ArrayList sortedConstraint = new ArrayList(constraintMap.keySet()); + Collections.sort(sortedConstraint); + + for (String constraintName : sortedConstraint) { + + String lhs = ""; + + if (!constraintMap.get(constraintName).getEvalExpression().isNumeric()) { + + ArrayList sortedTerm = new ArrayList(constraintMap.get(constraintName) + .getEvalExpression().getMultiplier().keySet()); + Collections.sort(sortedTerm); + + for (String var : sortedTerm) { + + Number coef = constraintMap.get(constraintName).getEvalExpression().getMultiplier().get(var) + .getData(); + double coefDouble = coef.doubleValue(); + String coefStr = coef.toString(); + String term; + + if (coefDouble == 1.0) { + term = " + " + var; + } + else if (coefDouble == -1.0) { + term = " - " + var; + } + else if (coefDouble < 0) { + term = " " + coefStr + " " + var; + } + else { // coefDouble >= 0 + term = " + " + coefStr + " " + var; + } + lhs = lhs + term; + } + + } + else { + + lhs = "0"; + } + + String sign = constraintMap.get(constraintName).getSign(); + double val = constraintMap.get(constraintName).getEvalExpression().getValue().getData().doubleValue(); + + if (val == 0) { + lhs = constraintName + ": " + lhs + " " + sign + " " + "0"; + } + else { + lhs = constraintName + ": " + lhs + " " + sign + " " + val * -1; + } + + outFile.println(lhs + " ;"); + + } + + } + + protected static void writeDvar(PrintWriter outFile, Set dvar_weighted, Set dvar_unWeighted) { + + + Map dvarMap = SolverData.getDvarMap(); + + ArrayList sortedDvar_weighted = new ArrayList(dvarMap.keySet()); + sortedDvar_weighted.retainAll(dvar_weighted); + Collections.sort(sortedDvar_weighted); + + ArrayList sortedDvar_unWeighted = new ArrayList(dvarMap.keySet()); + sortedDvar_unWeighted.retainAll(dvar_unWeighted); + Collections.sort(sortedDvar_unWeighted); + + // TODO: separate integer list in the parsing stage for efficiency + ArrayList intList = new ArrayList(); + ArrayList freeList = new ArrayList(); + + + /////// weighted + outFile.println("/* dvar weighted */"); + + for (String key : sortedDvar_weighted) { + double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); + double upper = dvarMap.get(key).upperBoundValue.doubleValue(); + String lowerStr = dvarMap.get(key).lowerBound; + String upperStr = dvarMap.get(key).upperBound; + + if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); + + if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + freeList.add(key); //TODO: test what happen if it's a free integer ??? + continue; + } + else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { + outFile.print(key + " < " + upper + " ;\n"); + } + else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + // TODO: be careful, by default LpSolve treat this as standard so we don't write to ilp file + if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); + } + else { + if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); + outFile.print(key + " < " + upper + " ;\n"); + } + } + + /////// unweighted + outFile.println("/* dvar unweighted in constraint*/"); + + for (String key : sortedDvar_unWeighted) { + double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); + double upper = dvarMap.get(key).upperBoundValue.doubleValue(); + String lowerStr = dvarMap.get(key).lowerBound; + String upperStr = dvarMap.get(key).upperBound; + + if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); + + if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + freeList.add(key); //TODO: test what happen if it's a free integer ??? + continue; + } + else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { + outFile.print(key + " < " + upper + " ;\n"); + } + else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + // TODO: be careful, by default LpSolve treat this as standard so we don't write to ilp file + if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); + } + else { + if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); + outFile.print(key + " < " + upper + " ;\n"); + } + } + + + + + if (intList.size() > 0) { + outFile.print("int "); + + for (int i = 0; i < intList.size(); i++) { + String term = intList.get(i); + + if (i == 0) { + outFile.print(term); + } + else { + outFile.print(", " + term); + } + } + + outFile.print(" ;\n"); + } + + if (freeList.size() > 0) { + outFile.print("free "); + + for (int i = 0; i < freeList.size(); i++) { + String term = freeList.get(i); + + if (i == 0) { + outFile.print(term); + } + else { + outFile.print(", " + term); + } + } + + outFile.print(" ;\n"); + } + } + + protected static void writeDvar(PrintWriter outFile, Set dvar_effective) { + + + Map dvarMap = SolverData.getDvarMap(); + + ArrayList sortedDvar_effective = new ArrayList(dvarMap.keySet()); + sortedDvar_effective.retainAll(dvar_effective); + Collections.sort(sortedDvar_effective); + + + // TODO: separate integer list in the parsing stage for efficiency + ArrayList intList = new ArrayList(); + ArrayList freeList = new ArrayList(); + + + outFile.println("/* dvar */"); + + for (String key : sortedDvar_effective) { + double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); + double upper = dvarMap.get(key).upperBoundValue.doubleValue(); + String lowerStr = dvarMap.get(key).lowerBound; + String upperStr = dvarMap.get(key).upperBound; + + if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); + + if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + freeList.add(key); //TODO: test what happen if it's a free integer ??? + continue; + } + else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded)) { + outFile.print(key + " < " + upper + " ;\n"); + } + else if (upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + // TODO: be careful, by default LpSolve treat this as standard so we don't write to ilp file + if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); + } + else { + if (lower != 0) outFile.print(key + " > " + lower + " ;\n"); + outFile.print(key + " < " + upper + " ;\n"); + } + } + + + if (intList.size() > 0) { + outFile.print("int "); + + for (int i = 0; i < intList.size(); i++) { + String term = intList.get(i); + + if (i == 0) { + outFile.print(term); + } + else { + outFile.print(", \n" + term); + } + } + + outFile.print(" ;\n"); + } + + if (freeList.size() > 0) { + outFile.print("free "); + + for (int i = 0; i < freeList.size(); i++) { + String term = freeList.get(i); + + if (i == 0) { + outFile.print(term); + } + else { + outFile.print(", \n" + term); + } + } + + outFile.print(" ;\n"); + } + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/launch/LaunchConfiguration.java b/wrims-core/src/main/java/wrimsv2/launch/LaunchConfiguration.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/launch/LaunchConfiguration.java rename to wrims-core/src/main/java/wrimsv2/launch/LaunchConfiguration.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/launch/SettingPref.java b/wrims-core/src/main/java/wrimsv2/launch/SettingPref.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/launch/SettingPref.java rename to wrims-core/src/main/java/wrimsv2/launch/SettingPref.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/parallel/ParallelVars.java b/wrims-core/src/main/java/wrimsv2/parallel/ParallelVars.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/parallel/ParallelVars.java rename to wrims-core/src/main/java/wrimsv2/parallel/ParallelVars.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessConstraint.java b/wrims-core/src/main/java/wrimsv2/parallel/ProcessConstraint.java similarity index 98% rename from wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessConstraint.java rename to wrims-core/src/main/java/wrimsv2/parallel/ProcessConstraint.java index 66e447173..a1b60d533 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessConstraint.java +++ b/wrims-core/src/main/java/wrimsv2/parallel/ProcessConstraint.java @@ -12,8 +12,8 @@ import org.antlr.runtime.RecognitionException; -import com.sun.java.util.collections.Collection; -import com.sun.java.util.collections.Collections; +// import com.sun.java.util.collections.Collection; +// import com.sun.java.util.collections.Collections; import wrimsv2.commondata.solverdata.SolverData; import wrimsv2.commondata.wresldata.Dvar; diff --git a/wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessDvar.java b/wrims-core/src/main/java/wrimsv2/parallel/ProcessDvar.java similarity index 98% rename from wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessDvar.java rename to wrims-core/src/main/java/wrimsv2/parallel/ProcessDvar.java index 6a30025ab..ae5c75d22 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessDvar.java +++ b/wrims-core/src/main/java/wrimsv2/parallel/ProcessDvar.java @@ -11,9 +11,6 @@ import org.antlr.runtime.RecognitionException; -import com.sun.java.util.collections.Collection; -import com.sun.java.util.collections.Collections; - import wrimsv2.commondata.solverdata.SolverData; import wrimsv2.commondata.wresldata.Dvar; import wrimsv2.commondata.wresldata.ModelDataSet; diff --git a/wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessTimeseries.java b/wrims-core/src/main/java/wrimsv2/parallel/ProcessTimeseries.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessTimeseries.java rename to wrims-core/src/main/java/wrimsv2/parallel/ProcessTimeseries.java index 6990fd20f..e728a657c 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessTimeseries.java +++ b/wrims-core/src/main/java/wrimsv2/parallel/ProcessTimeseries.java @@ -11,9 +11,6 @@ import org.antlr.runtime.RecognitionException; -import com.sun.java.util.collections.Collection; -import com.sun.java.util.collections.Collections; - import wrimsv2.commondata.solverdata.SolverData; import wrimsv2.commondata.wresldata.Dvar; import wrimsv2.commondata.wresldata.ModelDataSet; diff --git a/wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessWeight.java b/wrims-core/src/main/java/wrimsv2/parallel/ProcessWeight.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessWeight.java rename to wrims-core/src/main/java/wrimsv2/parallel/ProcessWeight.java index f0c741417..882817e58 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessWeight.java +++ b/wrims-core/src/main/java/wrimsv2/parallel/ProcessWeight.java @@ -11,9 +11,6 @@ import org.antlr.runtime.RecognitionException; -import com.sun.java.util.collections.Collection; -import com.sun.java.util.collections.Collections; - import wrimsv2.commondata.solverdata.SolverData; import wrimsv2.commondata.wresldata.Dvar; import wrimsv2.commondata.wresldata.ModelDataSet; diff --git a/wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessWeightSurplusSlack.java b/wrims-core/src/main/java/wrimsv2/parallel/ProcessWeightSurplusSlack.java similarity index 98% rename from wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessWeightSurplusSlack.java rename to wrims-core/src/main/java/wrimsv2/parallel/ProcessWeightSurplusSlack.java index 1453e3d8b..4d53994a0 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/parallel/ProcessWeightSurplusSlack.java +++ b/wrims-core/src/main/java/wrimsv2/parallel/ProcessWeightSurplusSlack.java @@ -11,9 +11,6 @@ import org.antlr.runtime.RecognitionException; -import com.sun.java.util.collections.Collection; -import com.sun.java.util.collections.Collections; - import wrimsv2.commondata.solverdata.SolverData; import wrimsv2.commondata.wresldata.Dvar; import wrimsv2.commondata.wresldata.ModelDataSet; diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/Cbc0Solver.java b/wrims-core/src/main/java/wrimsv2/solver/Cbc0Solver.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/Cbc0Solver.java rename to wrims-core/src/main/java/wrimsv2/solver/Cbc0Solver.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/CbcSolver.java b/wrims-core/src/main/java/wrimsv2/solver/CbcSolver.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/CbcSolver.java rename to wrims-core/src/main/java/wrimsv2/solver/CbcSolver.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/CloseCurrentSolver.java b/wrims-core/src/main/java/wrimsv2/solver/CloseCurrentSolver.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/CloseCurrentSolver.java rename to wrims-core/src/main/java/wrimsv2/solver/CloseCurrentSolver.java index ce115c2e2..acc19fbc6 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/CloseCurrentSolver.java +++ b/wrims-core/src/main/java/wrimsv2/solver/CloseCurrentSolver.java @@ -1,17 +1,17 @@ -package wrimsv2.solver; - -import wrimsv2.components.ControlData; -import wrimsv2.solver.Gurobi.GurobiSolver; - -public class CloseCurrentSolver { - public CloseCurrentSolver(String currentSolver){ - if (currentSolver.equalsIgnoreCase("XA") || currentSolver.equalsIgnoreCase("XALOG")) { - ControlData.xasolver.close(); - }else if (currentSolver.equalsIgnoreCase("Gurobi")){ - GurobiSolver.dispose(); - }else if (currentSolver.equalsIgnoreCase("Cbc")){ - CbcSolver.close(); - if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) {ControlData.xasolver.close();} - } - } -} +package wrimsv2.solver; + +import wrimsv2.components.ControlData; +import wrimsv2.solver.Gurobi.GurobiSolver; + +public class CloseCurrentSolver { + public CloseCurrentSolver(String currentSolver){ + if (currentSolver.equalsIgnoreCase("XA") || currentSolver.equalsIgnoreCase("XALOG")) { + ControlData.xasolver.close(); + }else if (currentSolver.equalsIgnoreCase("Gurobi")){ + GurobiSolver.dispose(); + }else if (currentSolver.equalsIgnoreCase("Cbc")){ + CbcSolver.close(); + if (ControlData.cbc_debug_routeXA || ControlData.cbc_debug_routeCbc) {ControlData.xasolver.close();} + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/Clp0Solver.java b/wrims-core/src/main/java/wrimsv2/solver/Clp0Solver.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/Clp0Solver.java rename to wrims-core/src/main/java/wrimsv2/solver/Clp0Solver.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/ClpSolver.java b/wrims-core/src/main/java/wrimsv2/solver/ClpSolver.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/ClpSolver.java rename to wrims-core/src/main/java/wrimsv2/solver/ClpSolver.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/Gurobi/GurobiSolver.java b/wrims-core/src/main/java/wrimsv2/solver/Gurobi/GurobiSolver.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/Gurobi/GurobiSolver.java rename to wrims-core/src/main/java/wrimsv2/solver/Gurobi/GurobiSolver.java index bdcad538d..3682ee7a5 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/Gurobi/GurobiSolver.java +++ b/wrims-core/src/main/java/wrimsv2/solver/Gurobi/GurobiSolver.java @@ -1,422 +1,422 @@ -package wrimsv2.solver.Gurobi; - -import gurobi.*; - -import gurobi.GRB; -import gurobi.GRBConstr; -import gurobi.GRBEnv; -import gurobi.GRBException; -import gurobi.GRBLinExpr; -import gurobi.GRBModel; -import gurobi.GRBVar; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; -import java.util.Iterator; -import java.util.Set; - -import lpsolve.LpSolveException; - -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; - -import com.sunsetsoft.xa.Optimizer; -import com.sunsetsoft.xa.XAException; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.commondata.solverdata.*; -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; -import wrimsv2.components.IntDouble; -import wrimsv2.components.Error; -import wrimsv2.evaluator.DataTimeSeries; -import wrimsv2.evaluator.DssDataSetFixLength; -import wrimsv2.evaluator.DssOperation; -import wrimsv2.evaluator.EvalConstraint; -import wrimsv2.evaluator.EvaluatorLexer; -import wrimsv2.evaluator.EvaluatorParser; -import gurobi.*; - -public class GurobiSolver { - - int modelStatus; - static GRBEnv env; - static GRBModel model; - public static Map varDoubleMap; - - Map varMap = new HashMap (); - - public static void initialize(){ - - try { - //env = new GRBEnv("TestGurobi.log"); - env = new GRBEnv(); - env.set(GRB.IntParam.LogToConsole, 0); - //env.set(GRB.IntParam.Presolve, 0); - } - catch (GRBException e) { - e.printStackTrace(); - } - - } - - public static void setLp(String CplexLpFilePath) { - - try { - //env = new GRBEnv("TestGurobi.log"); - //env = new GRBEnv(); - //env.set(GRB.IntParam.LogToConsole, 0); - model = new GRBModel(env, CplexLpFilePath); - } - catch (GRBException e) { - Error.addSolvingError("File not found: "+CplexLpFilePath); - //e.printStackTrace(); - } - - } - - public static void dispose(){ - - try { - model.dispose(); - //env.release(); // release license - env.dispose(); - } - catch (GRBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - public GurobiSolver() throws GRBException{ - - setDVars(); - setConstraints(); - model.optimize(); - assignDvar(); - Output(); - - } - - public static void solve() { - - LpResult result = new LpResult(); - - try { - - model.optimize(); - - int optimstatus = model.get(GRB.IntAttr.Status); - result.status = model.get(GRB.IntAttr.Status); - - if (optimstatus == GRB.Status.INF_OR_UNBD) { - model.getEnv().set(GRB.IntParam.Presolve, 0); - //model.getEnv().set(GRB.FloatParam.FeasibilityTol, 0.001); - model.optimize(); - optimstatus = model.get(GRB.IntAttr.Status); - result.status = model.get(GRB.IntAttr.Status); - //reset env - env = new GRBEnv(); - env.set(GRB.IntParam.LogToConsole, 0); - } - - if (optimstatus == GRB.Status.OPTIMAL) { - - double objval = model.get(GRB.DoubleAttr.ObjVal); - //System.out.println("Optimal objective: " + objval); - - - GRBVar[] allVars = model.getVars(); - // String[] allVarNames = model.get(GRB.StringAttr.VarName,allVars); - // double[] allValues = model.get(GRB.DoubleAttr.X,allVars); - - result.varNames = model.get(GRB.StringAttr.VarName,allVars); - result.varValues = model.get(GRB.DoubleAttr.X,allVars); - - ControlData.gurobi_objective = objval; - collectDvar(result); - assignDvar(); - - } else if (optimstatus == GRB.Status.INFEASIBLE) { - - Error.addSolvingError("Model is infeasible"); - //System.out.println("Model is infeasible"); - - // Compute and write out IIS - String IISFilePath = new File(FilePaths.mainDirectory, "Gurobi_infeasible.ilp").getAbsolutePath(); - model.computeIIS(); - model.write(IISFilePath); - } else if (optimstatus == GRB.Status.UNBOUNDED) { - Error.addSolvingError("Model is unbounded"); - //System.out.println("Model is unbounded"); - } else { - Error.addSolvingError("Optimization was stopped with status = " - + optimstatus); - } - - // Dispose of model - model.dispose(); - - } catch (GRBException e) { - - Error.addSolvingError("Error code: " + e.getErrorCode() + ". " + - e.getMessage()); - } - //return result; - } - - public void setDVars() throws GRBException{ - Map DvarMap = SolverData.getDvarMap(); - Set DvarCollection = DvarMap.keySet(); - Iterator dvarIterator=DvarCollection.iterator(); - - while(dvarIterator.hasNext()){ - String dvarName=(String)dvarIterator.next(); - Dvar dvar=DvarMap.get(dvarName); - double testWeight=0; - - Map weightMap = SolverData.getWeightMap(); - Set weightCollection = weightMap.keySet(); - Iterator weightIterator = weightCollection.iterator(); - String weightName=(String)weightIterator.next(); - - double lb = dvar.lowerBoundValue.doubleValue(); - double ub = dvar.upperBoundValue.doubleValue(); - - if (weightMap.containsKey(dvarName)) { - double weight=-weightMap.get(dvarName).getValue(); - GRBVar gv = model.addVar(lb, ub, weight, GRB.CONTINUOUS, dvarName); - varMap.put(dvarName, gv); - - testWeight = weight; - }else{ - GRBVar VarName = model.addVar(lb, ub, 0, GRB.CONTINUOUS, dvarName); - varMap.put(dvarName, VarName); - } - model.update(); - } - } - - private void setConstraints() throws GRBException { - Map constraintMap = SolverData.getConstraintDataMap(); - Set constraintCollection = constraintMap.keySet(); - Iterator constraintIterator = constraintCollection.iterator(); - - while(constraintIterator.hasNext()){ - String constraintName=(String)constraintIterator.next(); - EvalConstraint ec=constraintMap.get(constraintName); - HashMap multMap = ec.getEvalExpression().getMultiplier(); - Set multCollection = multMap.keySet(); - Iterator multIterator = multCollection.iterator(); - GRBLinExpr expr = new GRBLinExpr(); - double [] jack = new double[multCollection.size()+1]; - int counter = 1; - - while(multIterator.hasNext()){ - String multName=(String)multIterator.next(); - double coef=multMap.get(multName).getData().doubleValue(); - GRBVar var=varMap.get(multName); - expr.addTerm(coef, var); - jack[counter] = coef; - counter++; - } - if (ec.getSign().equals("=")) { - model.addConstr(expr, GRB.EQUAL, -ec.getEvalExpression().getValue().getData().doubleValue(), constraintName); } - else if (ec.getSign().equals("<") || ec.getSign().equals("<=")){ - model.addConstr(expr, GRB.LESS_EQUAL, -ec.getEvalExpression().getValue().getData().doubleValue(), constraintName); - } - else if (ec.getSign().equals(">") || ec.getSign().equals(">=")){ - model.addConstr(expr, GRB.GREATER_EQUAL, -ec.getEvalExpression().getValue().getData().doubleValue(), constraintName); - } - } - } - - public static void assignDvar() { - Map> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); - Map> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); - Set dvarUsedByLaterCycle = ControlData.currModelDataSet.dvarUsedByLaterCycle; - Set dvarTimeArrayUsedByLaterCycle = ControlData.currModelDataSet.dvarTimeArrayUsedByLaterCycle; - ArrayList timeArrayDvList = ControlData.currModelDataSet.timeArrayDvList; - String model=ControlData.currCycleName; - - StudyDataSet sds = ControlData.currStudyDataSet; - ArrayList varCycleIndexList = sds.getVarCycleIndexList(); - ArrayList dvarTimeArrayCycleIndexList = sds.getDvarTimeArrayCycleIndexList(); - Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); - - Map dvarMap = SolverData.getDvarMap(); - Set dvarCollection = dvarMap.keySet(); - Iterator dvarIterator = dvarCollection.iterator(); - - while(dvarIterator.hasNext()){ - String dvName=(String)dvarIterator.next(); - Dvar dvar=dvarMap.get(dvName); - - double value = -77777777; - try { - value=varDoubleMap.get(dvName); - } catch (Exception e) { - //value = 0; // TODO: warning!! needs work here!! - - //System.out.println(" This dvName not found: "+ dvName); - //continue; - try { - value = (Double) dvar.getData().getData(); // use whatever is in the container. - } catch (Exception e2) { - value=-77777777; // TODO: if this value is used, then this is probably an error in the wresl code. need to give warning. - } - } - IntDouble id=new IntDouble(value,false); - dvar.setData(id); - if(dvarUsedByLaterCycle.contains(dvName)){ - varCycleValueMap.get(dvName).put(model, id); - }else if (dvarTimeArrayUsedByLaterCycle.contains(dvName)){ - if (varTimeArrayCycleValueMap.containsKey(dvName)){ - varTimeArrayCycleValueMap.get(dvName).put(model, dvar.data); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, dvar.data); - varTimeArrayCycleValueMap.put(dvName, cycleValue); - } - } - if (varCycleIndexList.contains(dvName) || dvarTimeArrayCycleIndexList.contains(dvName)){ - if (varCycleIndexValueMap.containsKey(dvName)){ - varCycleIndexValueMap.get(dvName).put(model, dvar.data); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, dvar.data); - varCycleIndexValueMap.put(dvName, cycleValue); - } - } - String entryNameTS=DssOperation.entryNameTS(dvName, ControlData.timeStep); - DataTimeSeries.saveDataToTimeSeries(dvName, entryNameTS, value, dvar); - if (timeArrayDvList.contains(dvName)){ - entryNameTS=DssOperation.entryNameTS(dvName+"__fut__0", ControlData.timeStep); - DataTimeSeries.saveDataToTimeSeries(entryNameTS, value, dvar, 0); - } - } - - if (ControlData.showRunTimeMessage) { - System.out.println("Objective Value: "+ControlData.lpsolve_objective); - System.out.println("Assign Dvar Done."); - } - } - - private static void collectDvar(LpResult lpResult){ - - //Map dvarMap=SolverData.getDvarMap(); - varDoubleMap = new HashMap(); - - for (int i = 0; i < lpResult.varValues.length; i++) { - - //System.out.println(lpResult.varNames[i]+":"+lpResult.varValues[i]); - varDoubleMap.put(lpResult.varNames[i], lpResult.varValues[i]); - - // TODO: add the following line before sending the problem to the solver using direct link. - // it's too late here. need to assign value. - //if (!dvarMap.containsKey(lpResult.varNames[i])) addConditionalSlackSurplusToDvarMap(dvarMap, lpResult.varNames[i]); - - } - - } - - private void checkStatus() throws GRBException { - int status = model.get(GRB.IntAttr.Status); - if (status == GRB.Status.UNBOUNDED) { - System.out.println("The model cannot be solved " - + "because it is unbounded"); - return; - } - if (status == GRB.Status.OPTIMAL) { - System.out.println("The optimal objective is " + - model.get(GRB.DoubleAttr.ObjVal)); - return; - } - if (status != GRB.Status.INF_OR_UNBD && - status != GRB.Status.INFEASIBLE ) { - System.out.println("Optimization was stopped with status " + status); - return; - } - - // do IIS - System.out.println("The model is infeasible; computing IIS"); - LinkedList removed = new LinkedList(); - - // Loop until we reduce to a model that can be solved - while (true) { - model.computeIIS(); - System.out.println("\nThe following constraint cannot be satisfied:"); - for (GRBConstr c : model.getConstrs()) { - if (c.get(GRB.IntAttr.IISConstr) == 1) { - System.out.println(c.get(GRB.StringAttr.ConstrName)); - // Remove a single constraint from the model - removed.add(c.get(GRB.StringAttr.ConstrName)); - model.remove(c); - break; - } - } - - System.out.println(); - model.optimize(); - status = model.get(GRB.IntAttr.Status); - - if (status == GRB.Status.UNBOUNDED) { - System.out.println("The model cannot be solved " - + "because it is unbounded"); - return; - } - if (status == GRB.Status.OPTIMAL) { - break; - } - if (status != GRB.Status.INF_OR_UNBD && - status != GRB.Status.INFEASIBLE ) { - System.out.println("Optimization was stopped with status " + - status); - return; - } - } - - System.out.println("\nThe following constraints were removed " - + "to get a feasible LP:"); - for (String s : removed) { - System.out.print(s + " "); - } - System.out.println(); - } - - private void Output() throws GRBException { - Map dvarMap = ControlData.currDvMap; - Set dvarCollection = dvarMap.keySet(); - Iterator dvarIterator = dvarCollection.iterator(); - - while(dvarIterator.hasNext()){ - String dvName=(String)dvarIterator.next(); - Dvar dvar=dvarMap.get(dvName); - System.out.print(dvName + ": " + dvar.getData().getData() +"\n"); - } - - System.out.println("Obj: " + model.get(GRB.DoubleAttr.ObjVal)); - } - public static void addConditionalSlackSurplusToDvarMap(Map dvarMap, String multName){ - Dvar dvar=new Dvar(); - dvar.upperBoundValue=1.0e23; - dvar.lowerBoundValue=0.0; - dvarMap.put(multName, dvar); - } -} +package wrimsv2.solver.Gurobi; + +import gurobi.*; + +import gurobi.GRB; +import gurobi.GRBConstr; +import gurobi.GRBEnv; +import gurobi.GRBException; +import gurobi.GRBLinExpr; +import gurobi.GRBModel; +import gurobi.GRBVar; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import java.util.Iterator; +import java.util.Set; + +import lpsolve.LpSolveException; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.TokenStream; + +import com.sunsetsoft.xa.Optimizer; +import com.sunsetsoft.xa.XAException; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.commondata.solverdata.*; +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; +import wrimsv2.components.IntDouble; +import wrimsv2.components.Error; +import wrimsv2.evaluator.DataTimeSeries; +import wrimsv2.evaluator.DssDataSetFixLength; +import wrimsv2.evaluator.DssOperation; +import wrimsv2.evaluator.EvalConstraint; +import wrimsv2.evaluator.EvaluatorLexer; +import wrimsv2.evaluator.EvaluatorParser; +import gurobi.*; + +public class GurobiSolver { + + int modelStatus; + static GRBEnv env; + static GRBModel model; + public static Map varDoubleMap; + + Map varMap = new HashMap (); + + public static void initialize(){ + + try { + //env = new GRBEnv("TestGurobi.log"); + env = new GRBEnv(); + env.set(GRB.IntParam.LogToConsole, 0); + //env.set(GRB.IntParam.Presolve, 0); + } + catch (GRBException e) { + e.printStackTrace(); + } + + } + + public static void setLp(String CplexLpFilePath) { + + try { + //env = new GRBEnv("TestGurobi.log"); + //env = new GRBEnv(); + //env.set(GRB.IntParam.LogToConsole, 0); + model = new GRBModel(env, CplexLpFilePath); + } + catch (GRBException e) { + Error.addSolvingError("File not found: "+CplexLpFilePath); + //e.printStackTrace(); + } + + } + + public static void dispose(){ + + try { + model.dispose(); + //env.release(); // release license + env.dispose(); + } + catch (GRBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + public GurobiSolver() throws GRBException{ + + setDVars(); + setConstraints(); + model.optimize(); + assignDvar(); + Output(); + + } + + public static void solve() { + + LpResult result = new LpResult(); + + try { + + model.optimize(); + + int optimstatus = model.get(GRB.IntAttr.Status); + result.status = model.get(GRB.IntAttr.Status); + + if (optimstatus == GRB.Status.INF_OR_UNBD) { + model.getEnv().set(GRB.IntParam.Presolve, 0); + //model.getEnv().set(GRB.FloatParam.FeasibilityTol, 0.001); + model.optimize(); + optimstatus = model.get(GRB.IntAttr.Status); + result.status = model.get(GRB.IntAttr.Status); + //reset env + env = new GRBEnv(); + env.set(GRB.IntParam.LogToConsole, 0); + } + + if (optimstatus == GRB.Status.OPTIMAL) { + + double objval = model.get(GRB.DoubleAttr.ObjVal); + //System.out.println("Optimal objective: " + objval); + + + GRBVar[] allVars = model.getVars(); + // String[] allVarNames = model.get(GRB.StringAttr.VarName,allVars); + // double[] allValues = model.get(GRB.DoubleAttr.X,allVars); + + result.varNames = model.get(GRB.StringAttr.VarName,allVars); + result.varValues = model.get(GRB.DoubleAttr.X,allVars); + + ControlData.gurobi_objective = objval; + collectDvar(result); + assignDvar(); + + } else if (optimstatus == GRB.Status.INFEASIBLE) { + + Error.addSolvingError("Model is infeasible"); + //System.out.println("Model is infeasible"); + + // Compute and write out IIS + String IISFilePath = new File(FilePaths.mainDirectory, "Gurobi_infeasible.ilp").getAbsolutePath(); + model.computeIIS(); + model.write(IISFilePath); + } else if (optimstatus == GRB.Status.UNBOUNDED) { + Error.addSolvingError("Model is unbounded"); + //System.out.println("Model is unbounded"); + } else { + Error.addSolvingError("Optimization was stopped with status = " + + optimstatus); + } + + // Dispose of model + model.dispose(); + + } catch (GRBException e) { + + Error.addSolvingError("Error code: " + e.getErrorCode() + ". " + + e.getMessage()); + } + //return result; + } + + public void setDVars() throws GRBException{ + Map DvarMap = SolverData.getDvarMap(); + Set DvarCollection = DvarMap.keySet(); + Iterator dvarIterator=DvarCollection.iterator(); + + while(dvarIterator.hasNext()){ + String dvarName=(String)dvarIterator.next(); + Dvar dvar=DvarMap.get(dvarName); + double testWeight=0; + + Map weightMap = SolverData.getWeightMap(); + Set weightCollection = weightMap.keySet(); + Iterator weightIterator = weightCollection.iterator(); + String weightName=(String)weightIterator.next(); + + double lb = dvar.lowerBoundValue.doubleValue(); + double ub = dvar.upperBoundValue.doubleValue(); + + if (weightMap.containsKey(dvarName)) { + double weight=-weightMap.get(dvarName).getValue(); + GRBVar gv = model.addVar(lb, ub, weight, GRB.CONTINUOUS, dvarName); + varMap.put(dvarName, gv); + + testWeight = weight; + }else{ + GRBVar VarName = model.addVar(lb, ub, 0, GRB.CONTINUOUS, dvarName); + varMap.put(dvarName, VarName); + } + model.update(); + } + } + + private void setConstraints() throws GRBException { + Map constraintMap = SolverData.getConstraintDataMap(); + Set constraintCollection = constraintMap.keySet(); + Iterator constraintIterator = constraintCollection.iterator(); + + while(constraintIterator.hasNext()){ + String constraintName=(String)constraintIterator.next(); + EvalConstraint ec=constraintMap.get(constraintName); + HashMap multMap = ec.getEvalExpression().getMultiplier(); + Set multCollection = multMap.keySet(); + Iterator multIterator = multCollection.iterator(); + GRBLinExpr expr = new GRBLinExpr(); + double [] jack = new double[multCollection.size()+1]; + int counter = 1; + + while(multIterator.hasNext()){ + String multName=(String)multIterator.next(); + double coef=multMap.get(multName).getData().doubleValue(); + GRBVar var=varMap.get(multName); + expr.addTerm(coef, var); + jack[counter] = coef; + counter++; + } + if (ec.getSign().equals("=")) { + model.addConstr(expr, GRB.EQUAL, -ec.getEvalExpression().getValue().getData().doubleValue(), constraintName); } + else if (ec.getSign().equals("<") || ec.getSign().equals("<=")){ + model.addConstr(expr, GRB.LESS_EQUAL, -ec.getEvalExpression().getValue().getData().doubleValue(), constraintName); + } + else if (ec.getSign().equals(">") || ec.getSign().equals(">=")){ + model.addConstr(expr, GRB.GREATER_EQUAL, -ec.getEvalExpression().getValue().getData().doubleValue(), constraintName); + } + } + } + + public static void assignDvar() { + Map> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); + Map> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); + Set dvarUsedByLaterCycle = ControlData.currModelDataSet.dvarUsedByLaterCycle; + Set dvarTimeArrayUsedByLaterCycle = ControlData.currModelDataSet.dvarTimeArrayUsedByLaterCycle; + ArrayList timeArrayDvList = ControlData.currModelDataSet.timeArrayDvList; + String model=ControlData.currCycleName; + + StudyDataSet sds = ControlData.currStudyDataSet; + ArrayList varCycleIndexList = sds.getVarCycleIndexList(); + ArrayList dvarTimeArrayCycleIndexList = sds.getDvarTimeArrayCycleIndexList(); + Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); + + Map dvarMap = SolverData.getDvarMap(); + Set dvarCollection = dvarMap.keySet(); + Iterator dvarIterator = dvarCollection.iterator(); + + while(dvarIterator.hasNext()){ + String dvName=(String)dvarIterator.next(); + Dvar dvar=dvarMap.get(dvName); + + double value = -77777777; + try { + value=varDoubleMap.get(dvName); + } catch (Exception e) { + //value = 0; // TODO: warning!! needs work here!! + + //System.out.println(" This dvName not found: "+ dvName); + //continue; + try { + value = (Double) dvar.getData().getData(); // use whatever is in the container. + } catch (Exception e2) { + value=-77777777; // TODO: if this value is used, then this is probably an error in the wresl code. need to give warning. + } + } + IntDouble id=new IntDouble(value,false); + dvar.setData(id); + if(dvarUsedByLaterCycle.contains(dvName)){ + varCycleValueMap.get(dvName).put(model, id); + }else if (dvarTimeArrayUsedByLaterCycle.contains(dvName)){ + if (varTimeArrayCycleValueMap.containsKey(dvName)){ + varTimeArrayCycleValueMap.get(dvName).put(model, dvar.data); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, dvar.data); + varTimeArrayCycleValueMap.put(dvName, cycleValue); + } + } + if (varCycleIndexList.contains(dvName) || dvarTimeArrayCycleIndexList.contains(dvName)){ + if (varCycleIndexValueMap.containsKey(dvName)){ + varCycleIndexValueMap.get(dvName).put(model, dvar.data); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, dvar.data); + varCycleIndexValueMap.put(dvName, cycleValue); + } + } + String entryNameTS=DssOperation.entryNameTS(dvName, ControlData.timeStep); + DataTimeSeries.saveDataToTimeSeries(dvName, entryNameTS, value, dvar); + if (timeArrayDvList.contains(dvName)){ + entryNameTS=DssOperation.entryNameTS(dvName+"__fut__0", ControlData.timeStep); + DataTimeSeries.saveDataToTimeSeries(entryNameTS, value, dvar, 0); + } + } + + if (ControlData.showRunTimeMessage) { + System.out.println("Objective Value: "+ControlData.lpsolve_objective); + System.out.println("Assign Dvar Done."); + } + } + + private static void collectDvar(LpResult lpResult){ + + //Map dvarMap=SolverData.getDvarMap(); + varDoubleMap = new HashMap(); + + for (int i = 0; i < lpResult.varValues.length; i++) { + + //System.out.println(lpResult.varNames[i]+":"+lpResult.varValues[i]); + varDoubleMap.put(lpResult.varNames[i], lpResult.varValues[i]); + + // TODO: add the following line before sending the problem to the solver using direct link. + // it's too late here. need to assign value. + //if (!dvarMap.containsKey(lpResult.varNames[i])) addConditionalSlackSurplusToDvarMap(dvarMap, lpResult.varNames[i]); + + } + + } + + private void checkStatus() throws GRBException { + int status = model.get(GRB.IntAttr.Status); + if (status == GRB.Status.UNBOUNDED) { + System.out.println("The model cannot be solved " + + "because it is unbounded"); + return; + } + if (status == GRB.Status.OPTIMAL) { + System.out.println("The optimal objective is " + + model.get(GRB.DoubleAttr.ObjVal)); + return; + } + if (status != GRB.Status.INF_OR_UNBD && + status != GRB.Status.INFEASIBLE ) { + System.out.println("Optimization was stopped with status " + status); + return; + } + + // do IIS + System.out.println("The model is infeasible; computing IIS"); + LinkedList removed = new LinkedList(); + + // Loop until we reduce to a model that can be solved + while (true) { + model.computeIIS(); + System.out.println("\nThe following constraint cannot be satisfied:"); + for (GRBConstr c : model.getConstrs()) { + if (c.get(GRB.IntAttr.IISConstr) == 1) { + System.out.println(c.get(GRB.StringAttr.ConstrName)); + // Remove a single constraint from the model + removed.add(c.get(GRB.StringAttr.ConstrName)); + model.remove(c); + break; + } + } + + System.out.println(); + model.optimize(); + status = model.get(GRB.IntAttr.Status); + + if (status == GRB.Status.UNBOUNDED) { + System.out.println("The model cannot be solved " + + "because it is unbounded"); + return; + } + if (status == GRB.Status.OPTIMAL) { + break; + } + if (status != GRB.Status.INF_OR_UNBD && + status != GRB.Status.INFEASIBLE ) { + System.out.println("Optimization was stopped with status " + + status); + return; + } + } + + System.out.println("\nThe following constraints were removed " + + "to get a feasible LP:"); + for (String s : removed) { + System.out.print(s + " "); + } + System.out.println(); + } + + private void Output() throws GRBException { + Map dvarMap = ControlData.currDvMap; + Set dvarCollection = dvarMap.keySet(); + Iterator dvarIterator = dvarCollection.iterator(); + + while(dvarIterator.hasNext()){ + String dvName=(String)dvarIterator.next(); + Dvar dvar=dvarMap.get(dvName); + System.out.print(dvName + ": " + dvar.getData().getData() +"\n"); + } + + System.out.println("Obj: " + model.get(GRB.DoubleAttr.ObjVal)); + } + public static void addConditionalSlackSurplusToDvarMap(Map dvarMap, String multName){ + Dvar dvar=new Dvar(); + dvar.upperBoundValue=1.0e23; + dvar.lowerBoundValue=0.0; + dvarMap.put(multName, dvar); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/Gurobi/InitialGurobiSolver.java b/wrims-core/src/main/java/wrimsv2/solver/Gurobi/InitialGurobiSolver.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/Gurobi/InitialGurobiSolver.java rename to wrims-core/src/main/java/wrimsv2/solver/Gurobi/InitialGurobiSolver.java index 974a2e81c..71d819e2b 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/Gurobi/InitialGurobiSolver.java +++ b/wrims-core/src/main/java/wrimsv2/solver/Gurobi/InitialGurobiSolver.java @@ -1,12 +1,12 @@ -package wrimsv2.solver.Gurobi; - -public class InitialGurobiSolver { - - public InitialGurobiSolver(){ -// ControlData.xasolver=new Optimizer(25000); -// ControlData.xasolver.setActivationCodes( 234416483 , 19834525 ) ; -// ControlData.xasolver.openConnection(); -// ControlData.xasolver.setModelSize(100, 100); -// ControlData.xasolver.setCommand("MAXIMIZE Yes MUTE yes FORCE No wait no matlist v set visible no"); - } -} +package wrimsv2.solver.Gurobi; + +public class InitialGurobiSolver { + + public InitialGurobiSolver(){ +// ControlData.xasolver=new Optimizer(25000); +// ControlData.xasolver.setActivationCodes( 234416483 , 19834525 ) ; +// ControlData.xasolver.openConnection(); +// ControlData.xasolver.setModelSize(100, 100); +// ControlData.xasolver.setCommand("MAXIMIZE Yes MUTE yes FORCE No wait no matlist v set visible no"); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/Gurobi/LpResult.java b/wrims-core/src/main/java/wrimsv2/solver/Gurobi/LpResult.java similarity index 93% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/Gurobi/LpResult.java rename to wrims-core/src/main/java/wrimsv2/solver/Gurobi/LpResult.java index f4a19c255..e5a87f7b9 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/Gurobi/LpResult.java +++ b/wrims-core/src/main/java/wrimsv2/solver/Gurobi/LpResult.java @@ -1,18 +1,18 @@ -package wrimsv2.solver.Gurobi; - -public class LpResult { - - public int status = 0; - - public String[] varNames = null; - public double[] varValues = null; - - public LpResult(){ - - this.status = 0; - this.varNames = null; - this.varValues = null; - - } - -} +package wrimsv2.solver.Gurobi; + +public class LpResult { + + public int status = 0; + + public String[] varNames = null; + public double[] varValues = null; + + public LpResult(){ + + this.status = 0; + this.varNames = null; + this.varValues = null; + + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/InitialClpSolver.java b/wrims-core/src/main/java/wrimsv2/solver/InitialClpSolver.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/InitialClpSolver.java rename to wrims-core/src/main/java/wrimsv2/solver/InitialClpSolver.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/InitialXASolver.java b/wrims-core/src/main/java/wrimsv2/solver/InitialXASolver.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/InitialXASolver.java rename to wrims-core/src/main/java/wrimsv2/solver/InitialXASolver.java index f728bc486..01729e817 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/InitialXASolver.java +++ b/wrims-core/src/main/java/wrimsv2/solver/InitialXASolver.java @@ -1,34 +1,34 @@ -package wrimsv2.solver; - -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; - -import com.sunsetsoft.xa.Optimizer; -import com.sunsetsoft.xa.XAException; - -import wrimsv2.components.Error; - -public class InitialXASolver { - public InitialXASolver(){ - ControlData.xasolver=new Optimizer(25000); - ControlData.xasolver.setActivationCodes( 234416483 , 19834525 ) ; - ControlData.xasolver.setXAMessageWindowOff(); - try{ - ControlData.xasolver.openConnection(); - } - catch (XAException e) - { - Error.addEngineError("Missing XA Dongle or supporting license files."); - return; - } - ControlData.xasolver.setModelSize(100, 100); - ControlData.xasolver.setCommand("MAXIMIZE Yes MUTE yes FORCE No wait no matlist v set visible no"); - System.out.println("Initialize XA solver done"); - //ControlData.xasolver.setCommand("Basis "+FilePaths.mainDirectory+"\\xabasis.tmp"); - //ControlData.xasolver.setCommand("set sortName Yes FileName d:\\temp Output v2%d.log MatList V MPSX Yes ToRcc Yes"); //rcc code - //ControlData.xasolver.setCommand( "FileName "+FilePaths.mainDirectory+" Output "+FilePaths.mainDirectory+"\\xa.log set sortName Yes MatList V MPSX Yes ToRcc Yes set debug Yes ListInput Yes") //xa debug ; - //if (ControlData.solverName.equalsIgnoreCase("XALOG") ) ControlData.xasolver.setCommand( "FileName "+FilePaths.mainDirectory+" Output "+FilePaths.mainDirectory+"\\xa.log set sortName YES MPSX Yes ToRcc Yes") ; - //ControlData.xasolver.setCommand("MultiSolver 4"); - //ControlData.xasolver.setCommand("LimitSearch (1%)); - } -} +package wrimsv2.solver; + +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; + +import com.sunsetsoft.xa.Optimizer; +import com.sunsetsoft.xa.XAException; + +import wrimsv2.components.Error; + +public class InitialXASolver { + public InitialXASolver(){ + ControlData.xasolver=new Optimizer(25000); + ControlData.xasolver.setActivationCodes( 234416483 , 19834525 ) ; + ControlData.xasolver.setXAMessageWindowOff(); + try{ + ControlData.xasolver.openConnection(); + } + catch (XAException e) + { + Error.addEngineError("Missing XA Dongle or supporting license files."); + return; + } + ControlData.xasolver.setModelSize(100, 100); + ControlData.xasolver.setCommand("MAXIMIZE Yes MUTE yes FORCE No wait no matlist v set visible no"); + System.out.println("Initialize XA solver done"); + //ControlData.xasolver.setCommand("Basis "+FilePaths.mainDirectory+"\\xabasis.tmp"); + //ControlData.xasolver.setCommand("set sortName Yes FileName d:\\temp Output v2%d.log MatList V MPSX Yes ToRcc Yes"); //rcc code + //ControlData.xasolver.setCommand( "FileName "+FilePaths.mainDirectory+" Output "+FilePaths.mainDirectory+"\\xa.log set sortName Yes MatList V MPSX Yes ToRcc Yes set debug Yes ListInput Yes") //xa debug ; + //if (ControlData.solverName.equalsIgnoreCase("XALOG") ) ControlData.xasolver.setCommand( "FileName "+FilePaths.mainDirectory+" Output "+FilePaths.mainDirectory+"\\xa.log set sortName YES MPSX Yes ToRcc Yes") ; + //ControlData.xasolver.setCommand("MultiSolver 4"); + //ControlData.xasolver.setCommand("LimitSearch (1%)); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/LPSolveSolver.java b/wrims-core/src/main/java/wrimsv2/solver/LPSolveSolver.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/LPSolveSolver.java rename to wrims-core/src/main/java/wrimsv2/solver/LPSolveSolver.java index 903a57aaf..578f2d25e 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/LPSolveSolver.java +++ b/wrims-core/src/main/java/wrimsv2/solver/LPSolveSolver.java @@ -1,251 +1,251 @@ -package wrimsv2.solver; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Iterator; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.solverdata.*; -import wrimsv2.components.ControlData; -import wrimsv2.components.Error; -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.DataTimeSeries; -import wrimsv2.evaluator.DssDataSetFixLength; -import wrimsv2.evaluator.DssOperation; -import wrimsv2.evaluator.EvalConstraint; -import wrimsv2.wreslparser.elements.Tools; -import lpsolve.*; - -public class LPSolveSolver { - - public static Map varDoubleMap; - private static LpSolve solver; - private static String lpFilePath; - private static ArrayList origcolName; - //public static ArrayList paramFiles; - public static String configFile = null; - //public static ArrayList paramHeader; - public static int numberOfRetries = 0; // default is zero - //public static boolean overwriteDefaultSetting = false; // default is false - - public static void setLP(String filePath){ - - try { - // TODO: remove this test - //filePath = "D:\\cvwrsm\\trunk\\callite\\CalLite\\run\\=ILP=\\=LpSolve=\\demo.config\\lpsolve\\1933_06_c01.lps"; - - solver = LpSolve.readLp(filePath, LpSolve.CRITICAL, "test_prob"); - - - try { - solver.readParams(configFile, "-h Default"); - - } catch (Exception e) { - Error.addSolvingError("Header \"Default\" not found in LpSolve config file"); - } - - - lpFilePath = filePath; - - - origcolName = new ArrayList(); - for (int i = 1; i <= solver.getNorigColumns(); i++) { - - //System.out.println(i + ":"+solver.getOrigcolName(i)); - //varDoubleMap.put(solver.getOrigcolName(i), solver.getVarPrimalresult(i+rn)); - - origcolName.add(solver.getOrigcolName(i)); - //System.out.println(solver.getOrigcolName(i)+" : "+solver.getVarPrimalresult(i+rn)); - } - - } - catch (LpSolveException e) { - e.printStackTrace(); - } - - - - } - - public static void solve(){ - - int i = 1; - int modelStatus = -777; - - try { - - modelStatus = solver.solve(); - - while ( (modelStatus!=LpSolve.OPTIMAL) && (i<=numberOfRetries) ) { - - //System.out.println("LpSolve Error: "+solver.getStatustext(modelStatus)); - - - //for (int i=1;i<=numberOfRetries; i++) { - - solver.deleteLp(); - solver = LpSolve.readLp(lpFilePath, LpSolve.CRITICAL, "test_prob"); - - try { - System.out.println("! Retry with LpSolve config named: Retry"+ i); - solver.readParams(configFile, "-h Retry"+i); - modelStatus = solver.solve(); - i++; - } catch (Exception e) { - Error.addSolvingError("Header \"Retry" + i + "\" not found in LpSolve config file"); - break; - } - - } - - if (modelStatus!= LpSolve.OPTIMAL) { - getSolverInformation(modelStatus); - } - - if (Error.error_solving.size()==0) { - ControlData.lpsolve_objective = solver.getObjective(); // for other processes - collectDvar(); - assignDvar(); - } - - // delete the problem and free memory - solver.deleteLp(); - - } - catch (LpSolveException e) { - Error.addSolvingError("LpSolveSolver error."); - e.printStackTrace(); - } - - } - - public static void setDefaultOption() { - - solver.setSimplextype(LpSolve.SIMPLEX_DUAL_PRIMAL); - solver.setImprove(LpSolve.IMPROVE_DUALFEAS | LpSolve.IMPROVE_THETAGAP ); - solver.setAntiDegen(LpSolve.ANTIDEGEN_FIXEDVARS | LpSolve.ANTIDEGEN_STALLING); - solver.setPivoting(LpSolve.PRICER_DEVEX | LpSolve.PRICE_ADAPTIVE); - solver.setScaling(LpSolve.SCALE_GEOMETRIC | LpSolve.SCALE_EQUILIBRATE | LpSolve.SCALE_INTEGERS); - solver.setBbFloorfirst(LpSolve.BRANCH_AUTOMATIC); - solver.setBbRule(LpSolve.NODE_GREEDYMODE | LpSolve.NODE_DYNAMICMODE | LpSolve.NODE_RCOSTFIXING | LpSolve.NODE_PSEUDONONINTSELECT); - solver.setTimeout(5); - solver.setEpsint(2E-7); - solver.setEpsel(1E-11); - - //solver.setVerbose(LpSolve.IMPORTANT); - //solver.setPresolve(LpSolve.PRESOLVE_ROWS , 200); - //solver.setPresolve(LpSolve.PRESOLVE_ROWS|LpSolve.PRESOLVE_COLS|LpSolve.PRESOLVE_PROBEFIX|LpSolve.PRESOLVE_PROBEREDUCE , solver.getPresolveloops()); - solver.setPresolve(LpSolve.PRESOLVE_ROWS|LpSolve.PRESOLVE_COLS , solver.getPresolveloops()); - } - - public static void getSolverInformation(int modelStatus){ - - Error.addSolvingError(solver.getStatustext(modelStatus)); - Error.addSolvingError(lpFilePath); - } - - private static void collectDvar() throws LpSolveException{ - //Map dvarMap=SolverData.getDvarMap(); - - varDoubleMap = new HashMap(); - - int rn = solver.getNorigRows(); - int cn = solver.getNorigColumns(); - - //System.out.println("solver.getNorigColumns():" + cn); - //System.out.println("solver.getNorigRows():" + rn); - - for (int i = 1; i <= cn; i++) { - - //System.out.println(i + ":"+solver.getOrigcolName(i)); - //varDoubleMap.put(solver.getOrigcolName(i), solver.getVarPrimalresult(i+rn)); - varDoubleMap.put(origcolName.get(i-1), solver.getVarPrimalresult(i+rn)); - //System.out.println(solver.getOrigcolName(i)+" : "+solver.getVarPrimalresult(i+rn)); - - // TODO: add the following line before sending the problem to the solver using direct link. - // it's too late here. need to assign value. - // if (!dvarMap.containsKey(origcolName.get(i-1))) addConditionalSlackSurplusToDvarMap(dvarMap, origcolName.get(i-1)); - } - - } - - private static void assignDvar() throws LpSolveException{ - Map> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); - Map> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); - Set dvarUsedByLaterCycle = ControlData.currModelDataSet.dvarUsedByLaterCycle; - Set dvarTimeArrayUsedByLaterCycle = ControlData.currModelDataSet.dvarTimeArrayUsedByLaterCycle; - ArrayList timeArrayDvList = ControlData.currModelDataSet.timeArrayDvList; - String model=ControlData.currCycleName; - - StudyDataSet sds = ControlData.currStudyDataSet; - ArrayList varCycleIndexList = sds.getVarCycleIndexList(); - ArrayList dvarTimeArrayCycleIndexList = sds.getDvarTimeArrayCycleIndexList(); - Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); - - Map dvarMap = SolverData.getDvarMap(); - Set dvarCollection = dvarMap.keySet(); - Iterator dvarIterator = dvarCollection.iterator(); - - while(dvarIterator.hasNext()){ - String dvName=(String)dvarIterator.next(); - Dvar dvar=dvarMap.get(dvName); - - double value = -77777777; - try { - value=varDoubleMap.get(dvName); - } catch (Exception e) { - //value = 0; // TODO: warning!! needs work here!! - - //System.out.println(" This dvName not found: "+ dvName); - //continue; - try { - value = (Double) dvar.getData().getData(); // use whatever is in the container. - } catch (Exception e2) { - value=-77777777; // TODO: if this value is used, then this is probably an error in the wresl code. need to give warning. - } - } - IntDouble id=new IntDouble(value,false); - dvar.setData(id); - if(dvarUsedByLaterCycle.contains(dvName)){ - varCycleValueMap.get(dvName).put(model, id); - }else if (dvarTimeArrayUsedByLaterCycle.contains(dvName)){ - if (varTimeArrayCycleValueMap.containsKey(dvName)){ - varTimeArrayCycleValueMap.get(dvName).put(model, dvar.data); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, dvar.data); - varTimeArrayCycleValueMap.put(dvName, cycleValue); - } - } - if (varCycleIndexList.contains(dvName) || dvarTimeArrayCycleIndexList.contains(dvName)){ - if (varCycleIndexValueMap.containsKey(dvName)){ - varCycleIndexValueMap.get(dvName).put(model, dvar.data); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, dvar.data); - varCycleIndexValueMap.put(dvName, cycleValue); - } - } - String entryNameTS=DssOperation.entryNameTS(dvName, ControlData.timeStep); - DataTimeSeries.saveDataToTimeSeries(dvName, entryNameTS, value, dvar); - if (timeArrayDvList.contains(dvName)){ - entryNameTS=DssOperation.entryNameTS(dvName+"__fut__0", ControlData.timeStep); - DataTimeSeries.saveDataToTimeSeries(entryNameTS, value, dvar, 0); - } - } - - if (ControlData.showRunTimeMessage) { - System.out.println("Objective Value: "+ControlData.lpsolve_objective); - System.out.println("Assign Dvar Done."); - } - } - public static void addConditionalSlackSurplusToDvarMap(Map dvarMap, String multName){ - Dvar dvar=new Dvar(); - dvar.upperBoundValue=1.0e23; - dvar.lowerBoundValue=0.0; - dvarMap.put(multName, dvar); - } -} +package wrimsv2.solver; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Iterator; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.solverdata.*; +import wrimsv2.components.ControlData; +import wrimsv2.components.Error; +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.DataTimeSeries; +import wrimsv2.evaluator.DssDataSetFixLength; +import wrimsv2.evaluator.DssOperation; +import wrimsv2.evaluator.EvalConstraint; +import wrimsv2.wreslparser.elements.Tools; +import lpsolve.*; + +public class LPSolveSolver { + + public static Map varDoubleMap; + private static LpSolve solver; + private static String lpFilePath; + private static ArrayList origcolName; + //public static ArrayList paramFiles; + public static String configFile = null; + //public static ArrayList paramHeader; + public static int numberOfRetries = 0; // default is zero + //public static boolean overwriteDefaultSetting = false; // default is false + + public static void setLP(String filePath){ + + try { + // TODO: remove this test + //filePath = "D:\\cvwrsm\\trunk\\callite\\CalLite\\run\\=ILP=\\=LpSolve=\\demo.config\\lpsolve\\1933_06_c01.lps"; + + solver = LpSolve.readLp(filePath, LpSolve.CRITICAL, "test_prob"); + + + try { + solver.readParams(configFile, "-h Default"); + + } catch (Exception e) { + Error.addSolvingError("Header \"Default\" not found in LpSolve config file"); + } + + + lpFilePath = filePath; + + + origcolName = new ArrayList(); + for (int i = 1; i <= solver.getNorigColumns(); i++) { + + //System.out.println(i + ":"+solver.getOrigcolName(i)); + //varDoubleMap.put(solver.getOrigcolName(i), solver.getVarPrimalresult(i+rn)); + + origcolName.add(solver.getOrigcolName(i)); + //System.out.println(solver.getOrigcolName(i)+" : "+solver.getVarPrimalresult(i+rn)); + } + + } + catch (LpSolveException e) { + e.printStackTrace(); + } + + + + } + + public static void solve(){ + + int i = 1; + int modelStatus = -777; + + try { + + modelStatus = solver.solve(); + + while ( (modelStatus!=LpSolve.OPTIMAL) && (i<=numberOfRetries) ) { + + //System.out.println("LpSolve Error: "+solver.getStatustext(modelStatus)); + + + //for (int i=1;i<=numberOfRetries; i++) { + + solver.deleteLp(); + solver = LpSolve.readLp(lpFilePath, LpSolve.CRITICAL, "test_prob"); + + try { + System.out.println("! Retry with LpSolve config named: Retry"+ i); + solver.readParams(configFile, "-h Retry"+i); + modelStatus = solver.solve(); + i++; + } catch (Exception e) { + Error.addSolvingError("Header \"Retry" + i + "\" not found in LpSolve config file"); + break; + } + + } + + if (modelStatus!= LpSolve.OPTIMAL) { + getSolverInformation(modelStatus); + } + + if (Error.error_solving.size()==0) { + ControlData.lpsolve_objective = solver.getObjective(); // for other processes + collectDvar(); + assignDvar(); + } + + // delete the problem and free memory + solver.deleteLp(); + + } + catch (LpSolveException e) { + Error.addSolvingError("LpSolveSolver error."); + e.printStackTrace(); + } + + } + + public static void setDefaultOption() { + + solver.setSimplextype(LpSolve.SIMPLEX_DUAL_PRIMAL); + solver.setImprove(LpSolve.IMPROVE_DUALFEAS | LpSolve.IMPROVE_THETAGAP ); + solver.setAntiDegen(LpSolve.ANTIDEGEN_FIXEDVARS | LpSolve.ANTIDEGEN_STALLING); + solver.setPivoting(LpSolve.PRICER_DEVEX | LpSolve.PRICE_ADAPTIVE); + solver.setScaling(LpSolve.SCALE_GEOMETRIC | LpSolve.SCALE_EQUILIBRATE | LpSolve.SCALE_INTEGERS); + solver.setBbFloorfirst(LpSolve.BRANCH_AUTOMATIC); + solver.setBbRule(LpSolve.NODE_GREEDYMODE | LpSolve.NODE_DYNAMICMODE | LpSolve.NODE_RCOSTFIXING | LpSolve.NODE_PSEUDONONINTSELECT); + solver.setTimeout(5); + solver.setEpsint(2E-7); + solver.setEpsel(1E-11); + + //solver.setVerbose(LpSolve.IMPORTANT); + //solver.setPresolve(LpSolve.PRESOLVE_ROWS , 200); + //solver.setPresolve(LpSolve.PRESOLVE_ROWS|LpSolve.PRESOLVE_COLS|LpSolve.PRESOLVE_PROBEFIX|LpSolve.PRESOLVE_PROBEREDUCE , solver.getPresolveloops()); + solver.setPresolve(LpSolve.PRESOLVE_ROWS|LpSolve.PRESOLVE_COLS , solver.getPresolveloops()); + } + + public static void getSolverInformation(int modelStatus){ + + Error.addSolvingError(solver.getStatustext(modelStatus)); + Error.addSolvingError(lpFilePath); + } + + private static void collectDvar() throws LpSolveException{ + //Map dvarMap=SolverData.getDvarMap(); + + varDoubleMap = new HashMap(); + + int rn = solver.getNorigRows(); + int cn = solver.getNorigColumns(); + + //System.out.println("solver.getNorigColumns():" + cn); + //System.out.println("solver.getNorigRows():" + rn); + + for (int i = 1; i <= cn; i++) { + + //System.out.println(i + ":"+solver.getOrigcolName(i)); + //varDoubleMap.put(solver.getOrigcolName(i), solver.getVarPrimalresult(i+rn)); + varDoubleMap.put(origcolName.get(i-1), solver.getVarPrimalresult(i+rn)); + //System.out.println(solver.getOrigcolName(i)+" : "+solver.getVarPrimalresult(i+rn)); + + // TODO: add the following line before sending the problem to the solver using direct link. + // it's too late here. need to assign value. + // if (!dvarMap.containsKey(origcolName.get(i-1))) addConditionalSlackSurplusToDvarMap(dvarMap, origcolName.get(i-1)); + } + + } + + private static void assignDvar() throws LpSolveException{ + Map> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); + Map> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); + Set dvarUsedByLaterCycle = ControlData.currModelDataSet.dvarUsedByLaterCycle; + Set dvarTimeArrayUsedByLaterCycle = ControlData.currModelDataSet.dvarTimeArrayUsedByLaterCycle; + ArrayList timeArrayDvList = ControlData.currModelDataSet.timeArrayDvList; + String model=ControlData.currCycleName; + + StudyDataSet sds = ControlData.currStudyDataSet; + ArrayList varCycleIndexList = sds.getVarCycleIndexList(); + ArrayList dvarTimeArrayCycleIndexList = sds.getDvarTimeArrayCycleIndexList(); + Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); + + Map dvarMap = SolverData.getDvarMap(); + Set dvarCollection = dvarMap.keySet(); + Iterator dvarIterator = dvarCollection.iterator(); + + while(dvarIterator.hasNext()){ + String dvName=(String)dvarIterator.next(); + Dvar dvar=dvarMap.get(dvName); + + double value = -77777777; + try { + value=varDoubleMap.get(dvName); + } catch (Exception e) { + //value = 0; // TODO: warning!! needs work here!! + + //System.out.println(" This dvName not found: "+ dvName); + //continue; + try { + value = (Double) dvar.getData().getData(); // use whatever is in the container. + } catch (Exception e2) { + value=-77777777; // TODO: if this value is used, then this is probably an error in the wresl code. need to give warning. + } + } + IntDouble id=new IntDouble(value,false); + dvar.setData(id); + if(dvarUsedByLaterCycle.contains(dvName)){ + varCycleValueMap.get(dvName).put(model, id); + }else if (dvarTimeArrayUsedByLaterCycle.contains(dvName)){ + if (varTimeArrayCycleValueMap.containsKey(dvName)){ + varTimeArrayCycleValueMap.get(dvName).put(model, dvar.data); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, dvar.data); + varTimeArrayCycleValueMap.put(dvName, cycleValue); + } + } + if (varCycleIndexList.contains(dvName) || dvarTimeArrayCycleIndexList.contains(dvName)){ + if (varCycleIndexValueMap.containsKey(dvName)){ + varCycleIndexValueMap.get(dvName).put(model, dvar.data); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, dvar.data); + varCycleIndexValueMap.put(dvName, cycleValue); + } + } + String entryNameTS=DssOperation.entryNameTS(dvName, ControlData.timeStep); + DataTimeSeries.saveDataToTimeSeries(dvName, entryNameTS, value, dvar); + if (timeArrayDvList.contains(dvName)){ + entryNameTS=DssOperation.entryNameTS(dvName+"__fut__0", ControlData.timeStep); + DataTimeSeries.saveDataToTimeSeries(entryNameTS, value, dvar, 0); + } + } + + if (ControlData.showRunTimeMessage) { + System.out.println("Objective Value: "+ControlData.lpsolve_objective); + System.out.println("Assign Dvar Done."); + } + } + public static void addConditionalSlackSurplusToDvarMap(Map dvarMap, String multName){ + Dvar dvar=new Dvar(); + dvar.upperBoundValue=1.0e23; + dvar.lowerBoundValue=0.0; + dvarMap.put(multName, dvar); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/SetXALog.java b/wrims-core/src/main/java/wrimsv2/solver/SetXALog.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/SetXALog.java rename to wrims-core/src/main/java/wrimsv2/solver/SetXALog.java index 1150b2b5f..92dc9d664 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/SetXALog.java +++ b/wrims-core/src/main/java/wrimsv2/solver/SetXALog.java @@ -1,42 +1,42 @@ -package wrimsv2.solver; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; - -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; - -public class SetXALog { - static boolean isConfigRead=false; - static String line="set sortName YES MPSX Yes Set FreqLog :01"; - - public static void enableXALog(){ - File config=new File ("xa_config.dat"); - if (config.exists() && !isConfigRead){ - BufferedReader br; - try { - FileReader fr=new FileReader(config); - br = new BufferedReader(fr); - line = br.readLine(); - isConfigRead=true; - System.out.println("Retrieve XA configuation from xa_config.dat file"); - ControlData.xasolver.setCommand( "set debug no ToRcc Yes FileName "+FilePaths.mainDirectory+" Output "+FilePaths.mainDirectory+"\\xa.log "+line); - br.close(); - fr.close(); - } catch (Exception e) { - e.printStackTrace(); - ControlData.xasolver.setCommand( "set debug no ToRcc Yes FileName "+FilePaths.mainDirectory+" Output "+FilePaths.mainDirectory+"\\xa.log set sortName YES MPSX Yes Set FreqLog :01") ; - } - }else{ - ControlData.xasolver.setCommand( "set debug no ToRcc Yes FileName "+FilePaths.mainDirectory+" Output "+FilePaths.mainDirectory+"\\xa.log "+line) ; - //ControlData.xasolver.setCommand("When +10920 FileName d:\\xatemp\\xa%d ToRcc Yes Output xa%d set sortName YES MPSX Yes"); - } - } - - public static void disableXALog(){ - ControlData.xasolver.setCommand("set debug no"); - } -} +package wrimsv2.solver; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; + +public class SetXALog { + static boolean isConfigRead=false; + static String line="set sortName YES MPSX Yes Set FreqLog :01"; + + public static void enableXALog(){ + File config=new File ("xa_config.dat"); + if (config.exists() && !isConfigRead){ + BufferedReader br; + try { + FileReader fr=new FileReader(config); + br = new BufferedReader(fr); + line = br.readLine(); + isConfigRead=true; + System.out.println("Retrieve XA configuation from xa_config.dat file"); + ControlData.xasolver.setCommand( "set debug no ToRcc Yes FileName "+FilePaths.mainDirectory+" Output "+FilePaths.mainDirectory+"\\xa.log "+line); + br.close(); + fr.close(); + } catch (Exception e) { + e.printStackTrace(); + ControlData.xasolver.setCommand( "set debug no ToRcc Yes FileName "+FilePaths.mainDirectory+" Output "+FilePaths.mainDirectory+"\\xa.log set sortName YES MPSX Yes Set FreqLog :01") ; + } + }else{ + ControlData.xasolver.setCommand( "set debug no ToRcc Yes FileName "+FilePaths.mainDirectory+" Output "+FilePaths.mainDirectory+"\\xa.log "+line) ; + //ControlData.xasolver.setCommand("When +10920 FileName d:\\xatemp\\xa%d ToRcc Yes Output xa%d set sortName YES MPSX Yes"); + } + } + + public static void disableXALog(){ + ControlData.xasolver.setCommand("set debug no"); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/XASolver.java b/wrims-core/src/main/java/wrimsv2/solver/XASolver.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/XASolver.java rename to wrims-core/src/main/java/wrimsv2/solver/XASolver.java index 2dcd5d5c0..26dd11290 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/XASolver.java +++ b/wrims-core/src/main/java/wrimsv2/solver/XASolver.java @@ -1,246 +1,246 @@ -package wrimsv2.solver; -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Iterator; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; - -import com.sunsetsoft.xa.Optimizer; -import com.sunsetsoft.xa.XAException; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.commondata.solverdata.*; -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; -import wrimsv2.components.IntDouble; -import wrimsv2.components.Error; -import wrimsv2.evaluator.DataTimeSeries; -import wrimsv2.evaluator.DssDataSetFixLength; -import wrimsv2.evaluator.DssOperation; -import wrimsv2.evaluator.EvalConstraint; -import wrimsv2.evaluator.EvaluatorLexer; -import wrimsv2.evaluator.EvaluatorParser; - -public class XASolver { - int modelStatus; - - public XASolver(){ - long t1 = Calendar.getInstance().getTimeInMillis(); - ControlData.xasolver.loadNewModel(); - setConstraints(); - setDVars(); - setWeights(); - - int ci=ControlData.currCycleIndex+1; - if (ControlData.showRunTimeMessage) System.out.println("XA Solver: Solving "+ControlData.currMonth+"/"+ControlData.currDay+"/"+ControlData.currYear+" Cycle "+ci+" ["+ControlData.currCycleName+"]"); - ControlData.xasolver.solveWithInfeasibleAnalysis("Output console:"); - - modelStatus=ControlData.xasolver.getModelStatus(); - if (ControlData.showRunTimeMessage) System.out.println("Model status: "+modelStatus); - if (modelStatus>=2) getSolverInformation(); - if (Error.error_solving.size()<1) assignDvar(); - long t2 = Calendar.getInstance().getTimeInMillis(); - ControlData.t_xa=ControlData.t_xa+(int) (t2-t1); - } - - public void getSolverInformation(){ - System.out.println("Solver status: "+ControlData.xasolver.getSolverStatus()); - //System.out.println("Exception: "+ControlData.xasolver.getExceptionCode()); - //System.out.println("Message: "+ControlData.xasolver.getMessage()); - //System.out.println("Return code: "+ControlData.xasolver.getRc()); - - switch (modelStatus){ - case 2: Error.addSolvingError("Integer Solution (not proven the optimal integer solution).");break; - case 3: Error.addSolvingError("Unbounded solution."); break; - case 4: Error.addSolvingError("Infeasible solution."); break; - case 5: Error.addSolvingError("Callback function indicates Infeasible solution."); break; - case 6: Error.addSolvingError("Intermediate infeasible solution."); break; - case 7: Error.addSolvingError("Intermediate nonoptimal solution."); break; - case 9: Error.addSolvingError("Intermediate Non-integer solution."); break; - case 10: Error.addSolvingError("Integer Infeasible."); break; - case 13: Error.addSolvingError("More memory required to load/solve model. Increase memory request in XAINIT call."); break; - case 32: Error.addSolvingError("Integer branch and bound process currently active, model has not completed solving."); break; - case 99: Error.addSolvingError("Currently solving model, model has not completed solving."); break; - default: Error.addSolvingError("Solving failed"); break; - } - } - - public void setDVars(){ - if (ControlData.showRunTimeMessage) System.out.println("XA Solver: Setting dvars"); - - Map dvarMap = SolverData.getDvarMap(); - for (int i=0; i<=1; i++){ - ArrayList dvarCollection; - if (i==0){ - dvarCollection = ControlData.currModelDataSet.dvList; - }else{ - dvarCollection = ControlData.currModelDataSet.dvTimeArrayList; - } - Iterator dvarIterator=dvarCollection.iterator(); - - while(dvarIterator.hasNext()){ - String dvarName=(String)dvarIterator.next(); - Dvar dvar=dvarMap.get(dvarName); - - double lb = dvar.lowerBoundValue.doubleValue(); - double ub = dvar.upperBoundValue.doubleValue(); - - if (dvar.integer.equals("y")){ - ControlData.xasolver.setColumnInteger(dvarName, lb, ub); } - else { - ControlData.xasolver.setColumnMinMax(dvarName, lb, ub);} - } - } - } - - public void setWeights(){ - if (ControlData.showRunTimeMessage) System.out.println("XA Solver: Setting weights"); - - Map weightMap = SolverData.getWeightMap(); - for (int i=0; i<=1; i++){ - ArrayList weightCollection; - if (i==0){ - weightCollection = ControlData.currModelDataSet.wtList; - }else{ - weightCollection = ControlData.currModelDataSet.wtTimeArrayList; - } - Iterator weightIterator = weightCollection.iterator(); - - while(weightIterator.hasNext()){ - String weightName=(String)weightIterator.next(); - ControlData.xasolver.setColumnObjective(weightName, weightMap.get(weightName).getValue()); - } - } - Map weightSlackSurplusMap = SolverData.getWeightSlackSurplusMap(); - CopyOnWriteArrayList usedWeightSlackSurplusCollection = ControlData.currModelDataSet.usedWtSlackSurplusList; - Iterator usedWeightSlackSurplusIterator = usedWeightSlackSurplusCollection.iterator(); - - while(usedWeightSlackSurplusIterator.hasNext()){ - String usedWeightSlackSurplusName=(String)usedWeightSlackSurplusIterator.next(); - ControlData.xasolver.setColumnObjective(usedWeightSlackSurplusName, weightSlackSurplusMap.get(usedWeightSlackSurplusName).getValue()); - } - } - - private void setConstraints() { - if (ControlData.showRunTimeMessage) System.out.println("XA Solver: Setting constraints"); - - Map constraintMap = SolverData.getConstraintDataMap(); - Map dvarMap=SolverData.getDvarMap(); - for (int i=0; i<=1; i++){ - ArrayList constraintCollection; - if (i==0){ - constraintCollection = new ArrayList(ControlData.currModelDataSet.gList); - constraintCollection.retainAll(constraintMap.keySet()); - }else{ - constraintCollection = new ArrayList(ControlData.currModelDataSet.gTimeArrayList); - } - Iterator constraintIterator = constraintCollection.iterator(); - - while(constraintIterator.hasNext()){ - String constraintName=(String)constraintIterator.next(); - EvalConstraint ec=constraintMap.get(constraintName); - - if (ec.getSign().equals("=")) { - ControlData.xasolver.setRowFix(constraintName, -ec.getEvalExpression().getValue().getData().doubleValue()); //string constraint name - } - else if (ec.getSign().equals("<") || ec.getSign().equals("<=")){ - ControlData.xasolver.setRowMax(constraintName, -ec.getEvalExpression().getValue().getData().doubleValue()); //string constraint name - } - else if (ec.getSign().equals(">")){ - ControlData.xasolver.setRowMin(constraintName, -ec.getEvalExpression().getValue().getData().doubleValue()); //string constraint name - } - - HashMap multMap = ec.getEvalExpression().getMultiplier(); - Set multCollection = multMap.keySet(); - Iterator multIterator = multCollection.iterator(); - - while(multIterator.hasNext()){ - String multName=(String)multIterator.next(); - if (!dvarMap.containsKey(multName)) addConditionalSlackSurplusToDvarMap(dvarMap, multName); - ControlData.xasolver.loadToCurrentRow(multName, multMap.get(multName).getData().doubleValue()); - } - } - } - } - - public void assignDvar(){ - if (ControlData.showRunTimeMessage) System.out.println("XA Solver: Assigning dvars\' values"); - - Map> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); - Map> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); - Set dvarUsedByLaterCycle = ControlData.currModelDataSet.dvarUsedByLaterCycle; - Set dvarTimeArrayUsedByLaterCycle = ControlData.currModelDataSet.dvarTimeArrayUsedByLaterCycle; - ArrayList timeArrayDvList = ControlData.currModelDataSet.timeArrayDvList; - String model=ControlData.currCycleName; - - StudyDataSet sds = ControlData.currStudyDataSet; - ArrayList varCycleIndexList = sds.getVarCycleIndexList(); - ArrayList dvarTimeArrayCycleIndexList = sds.getDvarTimeArrayCycleIndexList(); - Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); - - Map dvarMap = SolverData.getDvarMap(); - Set dvarCollection = dvarMap.keySet(); - Iterator dvarIterator = dvarCollection.iterator(); - - while(dvarIterator.hasNext()){ - String dvName=(String)dvarIterator.next(); - Dvar dvar=dvarMap.get(dvName); - double value=ControlData.xasolver.getColumnActivity(dvName); - IntDouble id=new IntDouble(value,false); - dvar.setData(id); - if(dvarUsedByLaterCycle.contains(dvName)){ - varCycleValueMap.get(dvName).put(model, id); - }else if (dvarTimeArrayUsedByLaterCycle.contains(dvName)){ - if (varTimeArrayCycleValueMap.containsKey(dvName)){ - varTimeArrayCycleValueMap.get(dvName).put(model, dvar.data); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, dvar.data); - varTimeArrayCycleValueMap.put(dvName, cycleValue); - } - } - if (varCycleIndexList.contains(dvName) || dvarTimeArrayCycleIndexList.contains(dvName)){ - if (varCycleIndexValueMap.containsKey(dvName)){ - varCycleIndexValueMap.get(dvName).put(model, dvar.data); - }else{ - Map cycleValue = new HashMap(); - cycleValue.put(model, dvar.data); - varCycleIndexValueMap.put(dvName, cycleValue); - } - } - String entryNameTS=DssOperation.entryNameTS(dvName, ControlData.timeStep); - DataTimeSeries.saveDataToTimeSeries(dvName, entryNameTS, value, dvar); - if (timeArrayDvList.contains(dvName)){ - entryNameTS=DssOperation.entryNameTS(dvName+"__fut__0", ControlData.timeStep); - DataTimeSeries.saveDataToTimeSeries(entryNameTS, value, dvar, 0); - } - } - - if (ControlData.showRunTimeMessage) { - System.out.println("Objective Value: "+ControlData.xasolver.getObjective()); - System.out.println("Assign Dvar Done."); - } - } - - public void addConditionalSlackSurplusToDvarMap(Map dvarMap, String multName){ - Dvar dvar=new Dvar(); - dvar.upperBoundValue=1.0e23; - dvar.lowerBoundValue=0.0; - dvarMap.put(multName, dvar); - } -} +package wrimsv2.solver; +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Iterator; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.TokenStream; + +import com.sunsetsoft.xa.Optimizer; +import com.sunsetsoft.xa.XAException; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.commondata.solverdata.*; +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; +import wrimsv2.components.IntDouble; +import wrimsv2.components.Error; +import wrimsv2.evaluator.DataTimeSeries; +import wrimsv2.evaluator.DssDataSetFixLength; +import wrimsv2.evaluator.DssOperation; +import wrimsv2.evaluator.EvalConstraint; +import wrimsv2.evaluator.EvaluatorLexer; +import wrimsv2.evaluator.EvaluatorParser; + +public class XASolver { + int modelStatus; + + public XASolver(){ + long t1 = Calendar.getInstance().getTimeInMillis(); + ControlData.xasolver.loadNewModel(); + setConstraints(); + setDVars(); + setWeights(); + + int ci=ControlData.currCycleIndex+1; + if (ControlData.showRunTimeMessage) System.out.println("XA Solver: Solving "+ControlData.currMonth+"/"+ControlData.currDay+"/"+ControlData.currYear+" Cycle "+ci+" ["+ControlData.currCycleName+"]"); + ControlData.xasolver.solveWithInfeasibleAnalysis("Output console:"); + + modelStatus=ControlData.xasolver.getModelStatus(); + if (ControlData.showRunTimeMessage) System.out.println("Model status: "+modelStatus); + if (modelStatus>=2) getSolverInformation(); + if (Error.error_solving.size()<1) assignDvar(); + long t2 = Calendar.getInstance().getTimeInMillis(); + ControlData.t_xa=ControlData.t_xa+(int) (t2-t1); + } + + public void getSolverInformation(){ + System.out.println("Solver status: "+ControlData.xasolver.getSolverStatus()); + //System.out.println("Exception: "+ControlData.xasolver.getExceptionCode()); + //System.out.println("Message: "+ControlData.xasolver.getMessage()); + //System.out.println("Return code: "+ControlData.xasolver.getRc()); + + switch (modelStatus){ + case 2: Error.addSolvingError("Integer Solution (not proven the optimal integer solution).");break; + case 3: Error.addSolvingError("Unbounded solution."); break; + case 4: Error.addSolvingError("Infeasible solution."); break; + case 5: Error.addSolvingError("Callback function indicates Infeasible solution."); break; + case 6: Error.addSolvingError("Intermediate infeasible solution."); break; + case 7: Error.addSolvingError("Intermediate nonoptimal solution."); break; + case 9: Error.addSolvingError("Intermediate Non-integer solution."); break; + case 10: Error.addSolvingError("Integer Infeasible."); break; + case 13: Error.addSolvingError("More memory required to load/solve model. Increase memory request in XAINIT call."); break; + case 32: Error.addSolvingError("Integer branch and bound process currently active, model has not completed solving."); break; + case 99: Error.addSolvingError("Currently solving model, model has not completed solving."); break; + default: Error.addSolvingError("Solving failed"); break; + } + } + + public void setDVars(){ + if (ControlData.showRunTimeMessage) System.out.println("XA Solver: Setting dvars"); + + Map dvarMap = SolverData.getDvarMap(); + for (int i=0; i<=1; i++){ + ArrayList dvarCollection; + if (i==0){ + dvarCollection = ControlData.currModelDataSet.dvList; + }else{ + dvarCollection = ControlData.currModelDataSet.dvTimeArrayList; + } + Iterator dvarIterator=dvarCollection.iterator(); + + while(dvarIterator.hasNext()){ + String dvarName=(String)dvarIterator.next(); + Dvar dvar=dvarMap.get(dvarName); + + double lb = dvar.lowerBoundValue.doubleValue(); + double ub = dvar.upperBoundValue.doubleValue(); + + if (dvar.integer.equals("y")){ + ControlData.xasolver.setColumnInteger(dvarName, lb, ub); } + else { + ControlData.xasolver.setColumnMinMax(dvarName, lb, ub);} + } + } + } + + public void setWeights(){ + if (ControlData.showRunTimeMessage) System.out.println("XA Solver: Setting weights"); + + Map weightMap = SolverData.getWeightMap(); + for (int i=0; i<=1; i++){ + ArrayList weightCollection; + if (i==0){ + weightCollection = ControlData.currModelDataSet.wtList; + }else{ + weightCollection = ControlData.currModelDataSet.wtTimeArrayList; + } + Iterator weightIterator = weightCollection.iterator(); + + while(weightIterator.hasNext()){ + String weightName=(String)weightIterator.next(); + ControlData.xasolver.setColumnObjective(weightName, weightMap.get(weightName).getValue()); + } + } + Map weightSlackSurplusMap = SolverData.getWeightSlackSurplusMap(); + CopyOnWriteArrayList usedWeightSlackSurplusCollection = ControlData.currModelDataSet.usedWtSlackSurplusList; + Iterator usedWeightSlackSurplusIterator = usedWeightSlackSurplusCollection.iterator(); + + while(usedWeightSlackSurplusIterator.hasNext()){ + String usedWeightSlackSurplusName=(String)usedWeightSlackSurplusIterator.next(); + ControlData.xasolver.setColumnObjective(usedWeightSlackSurplusName, weightSlackSurplusMap.get(usedWeightSlackSurplusName).getValue()); + } + } + + private void setConstraints() { + if (ControlData.showRunTimeMessage) System.out.println("XA Solver: Setting constraints"); + + Map constraintMap = SolverData.getConstraintDataMap(); + Map dvarMap=SolverData.getDvarMap(); + for (int i=0; i<=1; i++){ + ArrayList constraintCollection; + if (i==0){ + constraintCollection = new ArrayList(ControlData.currModelDataSet.gList); + constraintCollection.retainAll(constraintMap.keySet()); + }else{ + constraintCollection = new ArrayList(ControlData.currModelDataSet.gTimeArrayList); + } + Iterator constraintIterator = constraintCollection.iterator(); + + while(constraintIterator.hasNext()){ + String constraintName=(String)constraintIterator.next(); + EvalConstraint ec=constraintMap.get(constraintName); + + if (ec.getSign().equals("=")) { + ControlData.xasolver.setRowFix(constraintName, -ec.getEvalExpression().getValue().getData().doubleValue()); //string constraint name + } + else if (ec.getSign().equals("<") || ec.getSign().equals("<=")){ + ControlData.xasolver.setRowMax(constraintName, -ec.getEvalExpression().getValue().getData().doubleValue()); //string constraint name + } + else if (ec.getSign().equals(">")){ + ControlData.xasolver.setRowMin(constraintName, -ec.getEvalExpression().getValue().getData().doubleValue()); //string constraint name + } + + HashMap multMap = ec.getEvalExpression().getMultiplier(); + Set multCollection = multMap.keySet(); + Iterator multIterator = multCollection.iterator(); + + while(multIterator.hasNext()){ + String multName=(String)multIterator.next(); + if (!dvarMap.containsKey(multName)) addConditionalSlackSurplusToDvarMap(dvarMap, multName); + ControlData.xasolver.loadToCurrentRow(multName, multMap.get(multName).getData().doubleValue()); + } + } + } + } + + public void assignDvar(){ + if (ControlData.showRunTimeMessage) System.out.println("XA Solver: Assigning dvars\' values"); + + Map> varCycleValueMap=ControlData.currStudyDataSet.getVarCycleValueMap(); + Map> varTimeArrayCycleValueMap=ControlData.currStudyDataSet.getVarTimeArrayCycleValueMap(); + Set dvarUsedByLaterCycle = ControlData.currModelDataSet.dvarUsedByLaterCycle; + Set dvarTimeArrayUsedByLaterCycle = ControlData.currModelDataSet.dvarTimeArrayUsedByLaterCycle; + ArrayList timeArrayDvList = ControlData.currModelDataSet.timeArrayDvList; + String model=ControlData.currCycleName; + + StudyDataSet sds = ControlData.currStudyDataSet; + ArrayList varCycleIndexList = sds.getVarCycleIndexList(); + ArrayList dvarTimeArrayCycleIndexList = sds.getDvarTimeArrayCycleIndexList(); + Map> varCycleIndexValueMap = sds.getVarCycleIndexValueMap(); + + Map dvarMap = SolverData.getDvarMap(); + Set dvarCollection = dvarMap.keySet(); + Iterator dvarIterator = dvarCollection.iterator(); + + while(dvarIterator.hasNext()){ + String dvName=(String)dvarIterator.next(); + Dvar dvar=dvarMap.get(dvName); + double value=ControlData.xasolver.getColumnActivity(dvName); + IntDouble id=new IntDouble(value,false); + dvar.setData(id); + if(dvarUsedByLaterCycle.contains(dvName)){ + varCycleValueMap.get(dvName).put(model, id); + }else if (dvarTimeArrayUsedByLaterCycle.contains(dvName)){ + if (varTimeArrayCycleValueMap.containsKey(dvName)){ + varTimeArrayCycleValueMap.get(dvName).put(model, dvar.data); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, dvar.data); + varTimeArrayCycleValueMap.put(dvName, cycleValue); + } + } + if (varCycleIndexList.contains(dvName) || dvarTimeArrayCycleIndexList.contains(dvName)){ + if (varCycleIndexValueMap.containsKey(dvName)){ + varCycleIndexValueMap.get(dvName).put(model, dvar.data); + }else{ + Map cycleValue = new HashMap(); + cycleValue.put(model, dvar.data); + varCycleIndexValueMap.put(dvName, cycleValue); + } + } + String entryNameTS=DssOperation.entryNameTS(dvName, ControlData.timeStep); + DataTimeSeries.saveDataToTimeSeries(dvName, entryNameTS, value, dvar); + if (timeArrayDvList.contains(dvName)){ + entryNameTS=DssOperation.entryNameTS(dvName+"__fut__0", ControlData.timeStep); + DataTimeSeries.saveDataToTimeSeries(entryNameTS, value, dvar, 0); + } + } + + if (ControlData.showRunTimeMessage) { + System.out.println("Objective Value: "+ControlData.xasolver.getObjective()); + System.out.println("Assign Dvar Done."); + } + } + + public void addConditionalSlackSurplusToDvarMap(Map dvarMap, String multName){ + Dvar dvar=new Dvar(); + dvar.upperBoundValue=1.0e23; + dvar.lowerBoundValue=0.0; + dvarMap.put(multName, dvar); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/cbc/FilePassingUtils.java b/wrims-core/src/main/java/wrimsv2/solver/cbc/FilePassingUtils.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/cbc/FilePassingUtils.java rename to wrims-core/src/main/java/wrimsv2/solver/cbc/FilePassingUtils.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/clp/FilePassingUtils.java b/wrims-core/src/main/java/wrimsv2/solver/clp/FilePassingUtils.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/clp/FilePassingUtils.java rename to wrims-core/src/main/java/wrimsv2/solver/clp/FilePassingUtils.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/MPModel.java b/wrims-core/src/main/java/wrimsv2/solver/mpmodel/MPModel.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/MPModel.java rename to wrims-core/src/main/java/wrimsv2/solver/mpmodel/MPModel.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/MPModelUtils.java b/wrims-core/src/main/java/wrimsv2/solver/mpmodel/MPModelUtils.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/MPModelUtils.java rename to wrims-core/src/main/java/wrimsv2/solver/mpmodel/MPModelUtils.java index df51715a9..3da294619 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/MPModelUtils.java +++ b/wrims-core/src/main/java/wrimsv2/solver/mpmodel/MPModelUtils.java @@ -1,55 +1,55 @@ -package wrimsv2.solver.mpmodel; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.PrintWriter; - -import wrimsv2.solver.mpmodel.export.LpSolveExport; -import wrimsv2.wreslparser.elements.Tools; - - -public class MPModelUtils { - - public static void toLpSolve(MPModel in, String dir, String fileName) { - - String lpsolveStr = toLpSolve(in); - - PrintWriter pw; - - try { - pw = Tools.openFile(dir, fileName); - pw.write(lpsolveStr); - pw.flush(); - pw.close(); - - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public static String toLpSolve(MPModel in) { - - String out = ""; - - - String objStr = LpSolveExport.writeObj(in.objFunction); - String constraintStr = LpSolveExport.writeConstraint(in.constraintLhs, in.constraintRhs); - String dvarStr = LpSolveExport.writeDvar(in); - - out = objStr + constraintStr + dvarStr; - return out; - } - - public static MPModel load(String MPModelPath) throws FileNotFoundException, IOException, ClassNotFoundException { - - ObjectInputStream ois = new ObjectInputStream(new FileInputStream(MPModelPath)); - MPModel m = (MPModel) (ois.readObject()); - - return m; - - } - -} +package wrimsv2.solver.mpmodel; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.PrintWriter; + +import wrimsv2.solver.mpmodel.export.LpSolveExport; +import wrimsv2.wreslparser.elements.Tools; + + +public class MPModelUtils { + + public static void toLpSolve(MPModel in, String dir, String fileName) { + + String lpsolveStr = toLpSolve(in); + + PrintWriter pw; + + try { + pw = Tools.openFile(dir, fileName); + pw.write(lpsolveStr); + pw.flush(); + pw.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static String toLpSolve(MPModel in) { + + String out = ""; + + + String objStr = LpSolveExport.writeObj(in.objFunction); + String constraintStr = LpSolveExport.writeConstraint(in.constraintLhs, in.constraintRhs); + String dvarStr = LpSolveExport.writeDvar(in); + + out = objStr + constraintStr + dvarStr; + return out; + } + + public static MPModel load(String MPModelPath) throws FileNotFoundException, IOException, ClassNotFoundException { + + ObjectInputStream ois = new ObjectInputStream(new FileInputStream(MPModelPath)); + MPModel m = (MPModel) (ois.readObject()); + + return m; + + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/TransformModel.java b/wrims-core/src/main/java/wrimsv2/solver/mpmodel/TransformModel.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/TransformModel.java rename to wrims-core/src/main/java/wrimsv2/solver/mpmodel/TransformModel.java index c15957672..b5d11008f 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/TransformModel.java +++ b/wrims-core/src/main/java/wrimsv2/solver/mpmodel/TransformModel.java @@ -1,351 +1,351 @@ -package wrimsv2.solver.mpmodel; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; - - -public class TransformModel { - - private static final String slack_append = "___tslac"; - private static final String surplus_append = "___tsurp"; - - // original var and transformed var mapping - // e.g., x_new, x_new = x_old + 5 => - // - public static LinkedHashMap tvarOffsetMap = null; - // e.g., x_new = 3* x_old + 2* y_old - // => - public static LinkedHashMap> tvarEquationMap = null; - - public static MPModel transform(MPModel in) { - - tvarOffsetMap = new LinkedHashMap(); - tvarEquationMap = new LinkedHashMap>(); - - MPModel out = new MPModel("Transformed"); - out.constraintLhs = new LinkedHashMap>( - in.constraintLhs); - - // updated with var shift - LinkedHashMap transConstraintRhs = new LinkedHashMap(); - LinkedHashMap> tranConstraintLhs = new LinkedHashMap>(); - - // original var and transformed var mapping - // e.g., x_new, x_new = x_old + 5 => - // - LinkedHashMap tvarOffsetMap = new LinkedHashMap(); - // e.g., x_new = 3* x_old + 2* - // y_old => - LinkedHashMap> tvarEquationMap = new LinkedHashMap>(); - - // add binary var (0, 1) - for (String key : in.var_int_binary) { - - out.addBinaryVar(key); - } - - // add nonnegative integer var (0, ub) - for (String key : in.var_int_nonnegative) { - - double ub = in.varMap_integer.get(key)[1]; - - out.addIntVar(key, 0, ub); - } - - // TODO: add general integer var - - // add std num var (0, inf) - for (String key : in.var_standard) { - - out.addStdVar(key); - } - - // replace free num var (-inf, inf) with slack - surplus - for (String key : in.var_free) { - - String slack = key + slack_append; - String surpl = key + surplus_append; - - out.addStdVar(slack); - out.addStdVar(surpl); - - // transform equation x = x___surplus - x___slack - LinkedHashMap equ = new LinkedHashMap(); - equ.put(slack, -1.0); - equ.put(surpl, 1.0); - - tvarEquationMap.put(key, equ); - } - - // replace general vars - for (String key : in.var_general) { - - double lb = in.varMap_number.get(key)[0]; - double ub = in.varMap_number.get(key)[1]; - - // / case 1 - // (-inf, inf) => surplus(std) - slack(std) - - // / case 2 - // (-inf, 0) => shift( 0) => - slack(std) - // (-inf, b) => shift(-b) => - slack(std) - // (-inf, -a) => shift( a) => - slack(std) - - // / case 3 - // (-a, 0) => shift(a) => surplus(0, a) - // (-a, b) => shift(a) => surplus(0, a+b) - // (-a, inf) => shift(a) => surplus(std) - // (-a, -b) => shift(a) => surplus(a-b) - - // / case 4 - // (0, inf) => no change - // (0, b) => no change - - // / case 5 - // (a, b) => shift(-a) => surplus(b-a) - // (a, inf) => shift(-a) => surplus(std) - - if (lb < -Param.inf_assumed) { - - if (ub > Param.inf_assumed) { - // / case 1 - // (-inf, inf) => surplus(std) - slack(std) - - String slack = key + slack_append; - String surpl = key + surplus_append; - - out.addStdVar(slack); - out.addStdVar(surpl); - - // transform equation x = x___surplus - x___slack - LinkedHashMap equ = new LinkedHashMap(); - equ.put(slack, -1.0); - equ.put(surpl, 1.0); - - tvarEquationMap.put(key, equ); - - } else { - // / case 2 - // (-inf, 0) => shift( 0) => - slack(std) - // (-inf, b) => shift(-b) => - slack(std) - // (-inf, -a) => shift( a) => - slack(std) - - // shift , slack - tvarOffsetMap.put(key, -ub); - String slack = key + slack_append; - - out.addStdVar(slack); - - LinkedHashMap equ = new LinkedHashMap(); - equ.put(slack, -1.0); - - tvarEquationMap.put(key, equ); - } - - } else if (lb < 0) { - // / case 3 - // (-a, 0) => shift(a) => surplus(0, a) - // (-a, b) => shift(a) => surplus(0, a+b) - // (-a, inf) => shift(a) => surplus(std) - // (-a, -b) => shift(a) => surplus(a-b) - - // shift, surplus - tvarOffsetMap.put(key, -lb); - String surpl = key + surplus_append; - - out.addGeneralVar(surpl, 0, -lb + ub); - - LinkedHashMap equ = new LinkedHashMap(); - equ.put(surpl, 1.0); - - tvarEquationMap.put(key, equ); - - } else if (lb == 0) { - // / case 4 - // (0, inf) => no change - // (0, b) => no change - - out.addGeneralVar(key, 0, ub); - - } else if (lb > 0) { - - // / case 5 - // (a, b) => shift(-a) => surplus(b-a) - // (a, inf) => shift(-a) => surplus(std) - - // shift, surplus - tvarOffsetMap.put(key, -lb); - String surpl = key + surplus_append; - - out.addGeneralVar(surpl, 0, -lb + ub); - - LinkedHashMap equ = new LinkedHashMap(); - equ.put(surpl, 1.0); - - tvarEquationMap.put(key, equ); - - } - } - - // find transformed constraint - for (String constName : in.constraintLhs.keySet()) { - - double[] rhs = in.constraintRhs.get(constName); - LinkedHashMap varCoef = in.constraintLhs - .get(constName); - LinkedHashMap newVarCoef = new LinkedHashMap(); - - for (String term : varCoef.keySet()) { - - double coef = varCoef.get(term); - - // use equ terms instead of term in lhs - if (tvarEquationMap.keySet().contains(term)) { - - LinkedHashMap equ = tvarEquationMap - .get(term); - - for (String newTerm : equ.keySet()) { - newVarCoef.put(newTerm, equ.get(newTerm) * coef); - } - - // adjust rhs //TODO: put objectFunction offset here? - if (tvarOffsetMap.keySet().contains(term)) { - - double offset = tvarOffsetMap.get(term); - - rhs[0] = rhs[0] + offset; - rhs[1] = rhs[1] + offset; - } - } else { - - newVarCoef.put(term, coef); - } - } - - out.createConstraint(constName, newVarCoef, rhs[0], rhs[1]); - } - - - // transform obj function - - LinkedHashMap newObjFunction = new LinkedHashMap(); - - for (String o : in.objFunction.keySet()) { - - double oCoef = in.objFunction.get(o); - - // use equ terms instead of term in lhs - if (tvarEquationMap.keySet().contains(o)) { - - LinkedHashMap equ = tvarEquationMap.get(o); - - for (String newTerm : equ.keySet()) { - out.objFunction.put(newTerm, equ.get(newTerm) * oCoef); - } - - } else { - - out.objFunction.put(o, oCoef); - } - - } - - out.tvarEquationMap = tvarEquationMap; - out.tvarOffsetMap = tvarOffsetMap; - - // solve transformed lp problem // in Detector - - // shift back solution // in Detector - // LinkedHashMap revertedSolution = - // shiftSolution(transM.solution, varOffsetMap); - - return out; - } - - public static ArrayList> restoreSolutions( - ArrayList> inSolutions, - LinkedHashMap varOffsetMap, - LinkedHashMap> varEquationMap) { - - ArrayList> restoredSolutions = new ArrayList>(); - - for (LinkedHashMap solution : inSolutions) { - - restoredSolutions.add(restoreSolution(solution, varOffsetMap, - varEquationMap)); - - } - - return restoredSolutions; - - } - - // pre transform solution - public static LinkedHashMap restoreSolution( - LinkedHashMap inSolution, - LinkedHashMap varOffsetMap, - LinkedHashMap> varEquationMap) { - - LinkedHashMap outSolution = new LinkedHashMap( - inSolution); - - Set removeTheseFromSolution = new HashSet(); - - for (String k : varEquationMap.keySet()) { - - double v = 0; - LinkedHashMap equ = varEquationMap.get(k); - - for (String term : equ.keySet()) { - - v = v + inSolution.get(term) * equ.get(term); - outSolution.put(k, v); - - removeTheseFromSolution.add(term); - - } - - } - - // restore offset - for (String k : varOffsetMap.keySet()) { - - double offset = varOffsetMap.get(k); - - double newValue = outSolution.get(k) - offset; - - outSolution.put(k, newValue); - - } - - for (String k : removeTheseFromSolution) { - - outSolution.remove(k); - - } - - return outSolution; - } - - public static double restoreObjValue( - LinkedHashMap originalObjFunction, - LinkedHashMap restoredSolution) { - - double outObjValue = 0; - - for (String k : originalObjFunction.keySet()) { - - outObjValue = outObjValue + restoredSolution.get(k) - * originalObjFunction.get(k); - - } - - return outObjValue; - } - -} +package wrimsv2.solver.mpmodel; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; + + +public class TransformModel { + + private static final String slack_append = "___tslac"; + private static final String surplus_append = "___tsurp"; + + // original var and transformed var mapping + // e.g., x_new, x_new = x_old + 5 => + // + public static LinkedHashMap tvarOffsetMap = null; + // e.g., x_new = 3* x_old + 2* y_old + // => + public static LinkedHashMap> tvarEquationMap = null; + + public static MPModel transform(MPModel in) { + + tvarOffsetMap = new LinkedHashMap(); + tvarEquationMap = new LinkedHashMap>(); + + MPModel out = new MPModel("Transformed"); + out.constraintLhs = new LinkedHashMap>( + in.constraintLhs); + + // updated with var shift + LinkedHashMap transConstraintRhs = new LinkedHashMap(); + LinkedHashMap> tranConstraintLhs = new LinkedHashMap>(); + + // original var and transformed var mapping + // e.g., x_new, x_new = x_old + 5 => + // + LinkedHashMap tvarOffsetMap = new LinkedHashMap(); + // e.g., x_new = 3* x_old + 2* + // y_old => + LinkedHashMap> tvarEquationMap = new LinkedHashMap>(); + + // add binary var (0, 1) + for (String key : in.var_int_binary) { + + out.addBinaryVar(key); + } + + // add nonnegative integer var (0, ub) + for (String key : in.var_int_nonnegative) { + + double ub = in.varMap_integer.get(key)[1]; + + out.addIntVar(key, 0, ub); + } + + // TODO: add general integer var + + // add std num var (0, inf) + for (String key : in.var_standard) { + + out.addStdVar(key); + } + + // replace free num var (-inf, inf) with slack - surplus + for (String key : in.var_free) { + + String slack = key + slack_append; + String surpl = key + surplus_append; + + out.addStdVar(slack); + out.addStdVar(surpl); + + // transform equation x = x___surplus - x___slack + LinkedHashMap equ = new LinkedHashMap(); + equ.put(slack, -1.0); + equ.put(surpl, 1.0); + + tvarEquationMap.put(key, equ); + } + + // replace general vars + for (String key : in.var_general) { + + double lb = in.varMap_number.get(key)[0]; + double ub = in.varMap_number.get(key)[1]; + + // / case 1 + // (-inf, inf) => surplus(std) - slack(std) + + // / case 2 + // (-inf, 0) => shift( 0) => - slack(std) + // (-inf, b) => shift(-b) => - slack(std) + // (-inf, -a) => shift( a) => - slack(std) + + // / case 3 + // (-a, 0) => shift(a) => surplus(0, a) + // (-a, b) => shift(a) => surplus(0, a+b) + // (-a, inf) => shift(a) => surplus(std) + // (-a, -b) => shift(a) => surplus(a-b) + + // / case 4 + // (0, inf) => no change + // (0, b) => no change + + // / case 5 + // (a, b) => shift(-a) => surplus(b-a) + // (a, inf) => shift(-a) => surplus(std) + + if (lb < -Param.inf_assumed) { + + if (ub > Param.inf_assumed) { + // / case 1 + // (-inf, inf) => surplus(std) - slack(std) + + String slack = key + slack_append; + String surpl = key + surplus_append; + + out.addStdVar(slack); + out.addStdVar(surpl); + + // transform equation x = x___surplus - x___slack + LinkedHashMap equ = new LinkedHashMap(); + equ.put(slack, -1.0); + equ.put(surpl, 1.0); + + tvarEquationMap.put(key, equ); + + } else { + // / case 2 + // (-inf, 0) => shift( 0) => - slack(std) + // (-inf, b) => shift(-b) => - slack(std) + // (-inf, -a) => shift( a) => - slack(std) + + // shift , slack + tvarOffsetMap.put(key, -ub); + String slack = key + slack_append; + + out.addStdVar(slack); + + LinkedHashMap equ = new LinkedHashMap(); + equ.put(slack, -1.0); + + tvarEquationMap.put(key, equ); + } + + } else if (lb < 0) { + // / case 3 + // (-a, 0) => shift(a) => surplus(0, a) + // (-a, b) => shift(a) => surplus(0, a+b) + // (-a, inf) => shift(a) => surplus(std) + // (-a, -b) => shift(a) => surplus(a-b) + + // shift, surplus + tvarOffsetMap.put(key, -lb); + String surpl = key + surplus_append; + + out.addGeneralVar(surpl, 0, -lb + ub); + + LinkedHashMap equ = new LinkedHashMap(); + equ.put(surpl, 1.0); + + tvarEquationMap.put(key, equ); + + } else if (lb == 0) { + // / case 4 + // (0, inf) => no change + // (0, b) => no change + + out.addGeneralVar(key, 0, ub); + + } else if (lb > 0) { + + // / case 5 + // (a, b) => shift(-a) => surplus(b-a) + // (a, inf) => shift(-a) => surplus(std) + + // shift, surplus + tvarOffsetMap.put(key, -lb); + String surpl = key + surplus_append; + + out.addGeneralVar(surpl, 0, -lb + ub); + + LinkedHashMap equ = new LinkedHashMap(); + equ.put(surpl, 1.0); + + tvarEquationMap.put(key, equ); + + } + } + + // find transformed constraint + for (String constName : in.constraintLhs.keySet()) { + + double[] rhs = in.constraintRhs.get(constName); + LinkedHashMap varCoef = in.constraintLhs + .get(constName); + LinkedHashMap newVarCoef = new LinkedHashMap(); + + for (String term : varCoef.keySet()) { + + double coef = varCoef.get(term); + + // use equ terms instead of term in lhs + if (tvarEquationMap.keySet().contains(term)) { + + LinkedHashMap equ = tvarEquationMap + .get(term); + + for (String newTerm : equ.keySet()) { + newVarCoef.put(newTerm, equ.get(newTerm) * coef); + } + + // adjust rhs //TODO: put objectFunction offset here? + if (tvarOffsetMap.keySet().contains(term)) { + + double offset = tvarOffsetMap.get(term); + + rhs[0] = rhs[0] + offset; + rhs[1] = rhs[1] + offset; + } + } else { + + newVarCoef.put(term, coef); + } + } + + out.createConstraint(constName, newVarCoef, rhs[0], rhs[1]); + } + + + // transform obj function + + LinkedHashMap newObjFunction = new LinkedHashMap(); + + for (String o : in.objFunction.keySet()) { + + double oCoef = in.objFunction.get(o); + + // use equ terms instead of term in lhs + if (tvarEquationMap.keySet().contains(o)) { + + LinkedHashMap equ = tvarEquationMap.get(o); + + for (String newTerm : equ.keySet()) { + out.objFunction.put(newTerm, equ.get(newTerm) * oCoef); + } + + } else { + + out.objFunction.put(o, oCoef); + } + + } + + out.tvarEquationMap = tvarEquationMap; + out.tvarOffsetMap = tvarOffsetMap; + + // solve transformed lp problem // in Detector + + // shift back solution // in Detector + // LinkedHashMap revertedSolution = + // shiftSolution(transM.solution, varOffsetMap); + + return out; + } + + public static ArrayList> restoreSolutions( + ArrayList> inSolutions, + LinkedHashMap varOffsetMap, + LinkedHashMap> varEquationMap) { + + ArrayList> restoredSolutions = new ArrayList>(); + + for (LinkedHashMap solution : inSolutions) { + + restoredSolutions.add(restoreSolution(solution, varOffsetMap, + varEquationMap)); + + } + + return restoredSolutions; + + } + + // pre transform solution + public static LinkedHashMap restoreSolution( + LinkedHashMap inSolution, + LinkedHashMap varOffsetMap, + LinkedHashMap> varEquationMap) { + + LinkedHashMap outSolution = new LinkedHashMap( + inSolution); + + Set removeTheseFromSolution = new HashSet(); + + for (String k : varEquationMap.keySet()) { + + double v = 0; + LinkedHashMap equ = varEquationMap.get(k); + + for (String term : equ.keySet()) { + + v = v + inSolution.get(term) * equ.get(term); + outSolution.put(k, v); + + removeTheseFromSolution.add(term); + + } + + } + + // restore offset + for (String k : varOffsetMap.keySet()) { + + double offset = varOffsetMap.get(k); + + double newValue = outSolution.get(k) - offset; + + outSolution.put(k, newValue); + + } + + for (String k : removeTheseFromSolution) { + + outSolution.remove(k); + + } + + return outSolution; + } + + public static double restoreObjValue( + LinkedHashMap originalObjFunction, + LinkedHashMap restoredSolution) { + + double outObjValue = 0; + + for (String k : originalObjFunction.keySet()) { + + outObjValue = outObjValue + restoredSolution.get(k) + * originalObjFunction.get(k); + + } + + return outObjValue; + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/export/CplexExport.java b/wrims-core/src/main/java/wrimsv2/solver/mpmodel/export/CplexExport.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/export/CplexExport.java rename to wrims-core/src/main/java/wrimsv2/solver/mpmodel/export/CplexExport.java index 372d10e49..952a3b12e 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/export/CplexExport.java +++ b/wrims-core/src/main/java/wrimsv2/solver/mpmodel/export/CplexExport.java @@ -1,222 +1,222 @@ -package wrimsv2.solver.mpmodel.export; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.evaluator.EvalConstraint; - - - -public class CplexExport { - - private CplexExport() { - - } - - public static void writeComment(PrintWriter outFile, String msg) { - - - outFile.println("\\ " + msg ); - - } - - public static void writeObjValue() { - - - } - - - protected static void writeObj(PrintWriter outFile, Map activeWeightMap) { - - outFile.println("\\ objective function "); - outFile.println("Maximize"); - - - String toPrint = ""; - - ArrayList sortedTerm = new ArrayList(activeWeightMap.keySet()); - - Collections.sort(sortedTerm); - - for (String dvar : sortedTerm) { - - double weight = activeWeightMap.get(dvar).getValue(); - - if (weight > 0) { - - toPrint = toPrint + "+ " + weight + " " + dvar + " "; - outFile.println("+ " + weight + " " + dvar); - - } - else if (weight < 0) { - toPrint = toPrint + weight + " " + dvar + " "; - outFile.println(weight + " " + dvar); - } - - } - - //outFile.println(";"); - - } - - protected static void writeConstraint(PrintWriter outFile) { - - outFile.println(""); - outFile.println("\\ constraint"); - outFile.println("Subject To"); - - Map constraintMap = SolverData.getConstraintDataMap(); - - ArrayList sortedConstraint = new ArrayList(constraintMap.keySet()); - Collections.sort(sortedConstraint); - - for (String constraintName : sortedConstraint) { - - String lhs = ""; - - if (!constraintMap.get(constraintName).getEvalExpression().isNumeric()) { - - ArrayList sortedTerm = new ArrayList(constraintMap.get(constraintName) - .getEvalExpression().getMultiplier().keySet()); - Collections.sort(sortedTerm); - - for (String var : sortedTerm) { - - Number coef = constraintMap.get(constraintName).getEvalExpression().getMultiplier().get(var) - .getData(); - double coefDouble = coef.doubleValue(); - String coefStr = coef.toString(); - String term; - - if (coefDouble == 1.0) { - term = " + " + var; - } - else if (coefDouble == -1.0) { - term = " - " + var; - } - else if (coefDouble < 0) { - term = " " + coefStr + " " + var; - } - else { // coefDouble >= 0 - term = " + " + coefStr + " " + var; - } - lhs = lhs + term; - } - - } - else { - - lhs = "0"; - } - - String sign = constraintMap.get(constraintName).getSign(); - double val = constraintMap.get(constraintName).getEvalExpression().getValue().getData().doubleValue(); - - if (sign.equals(">")) sign = ">="; - if (sign.equals("<")) sign = "<="; - - if (val == 0) { - lhs = constraintName + ": " + lhs + " " + sign + " " + "0"; - } - else { - lhs = constraintName + ": " + lhs + " " + sign + " " + val * -1; - } - - outFile.println(lhs); - - } - - } - - protected static void writeDvar(PrintWriter outFile, Set dvar_effective) { - - - Map dvarMap = SolverData.getDvarMap(); - - ArrayList sortedDvar_effective = new ArrayList(dvarMap.keySet()); - sortedDvar_effective.retainAll(dvar_effective); - Collections.sort(sortedDvar_effective); - - - // TODO: separate integer list in the parsing stage for efficiency - ArrayList intList = new ArrayList(); - ArrayList freeList = new ArrayList(); - - outFile.println(""); - outFile.println("\\ dvar"); - outFile.println("Bounds"); - - for (String key : sortedDvar_effective) { - double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); - double upper = dvarMap.get(key).upperBoundValue.doubleValue(); - String lowerStr = dvarMap.get(key).lowerBound; - String upperStr = dvarMap.get(key).upperBound; - - if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); - - if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { - freeList.add(key); //TODO: test what happen if it's a free integer ??? - continue; - } - if (lowerParam.upper_unbounded_double) { - freeList.add(key); //TODO: test what happen if it's a free integer ??? - continue; - } - else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) || lowerParam.upper_unbounded_double){ - - if (lower != 0) outFile.print(key + " >= " + lower + " \n"); - } - else { - if (lower != 0) { - outFile.print(lower + " <= " + key + " <= " + upper + " \n"); - } else { - outFile.print(key + " <= " + upper + " \n"); - } - } - } - - if (freeList.size() > 0) { - //outFile.print("free "); - - for (int i = 0; i < freeList.size(); i++) { - String term = freeList.get(i); - - outFile.print(" -inf <= " + term + " \n"); - - } - - } - - if (intList.size() > 0) { - outFile.println(""); - outFile.println("\\ Integer"); - outFile.println("Generals"); - - for (int i = 0; i < intList.size(); i++) { - String term = intList.get(i); - - //if (i == 0) { - outFile.println(term); - //} - //else { - // outFile.print(", " + term); - //} - } - - //outFile.print(" ;\n"); - } - - - } - -} +package wrimsv2.solver.mpmodel.export; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.evaluator.EvalConstraint; + + + +public class CplexExport { + + private CplexExport() { + + } + + public static void writeComment(PrintWriter outFile, String msg) { + + + outFile.println("\\ " + msg ); + + } + + public static void writeObjValue() { + + + } + + + protected static void writeObj(PrintWriter outFile, Map activeWeightMap) { + + outFile.println("\\ objective function "); + outFile.println("Maximize"); + + + String toPrint = ""; + + ArrayList sortedTerm = new ArrayList(activeWeightMap.keySet()); + + Collections.sort(sortedTerm); + + for (String dvar : sortedTerm) { + + double weight = activeWeightMap.get(dvar).getValue(); + + if (weight > 0) { + + toPrint = toPrint + "+ " + weight + " " + dvar + " "; + outFile.println("+ " + weight + " " + dvar); + + } + else if (weight < 0) { + toPrint = toPrint + weight + " " + dvar + " "; + outFile.println(weight + " " + dvar); + } + + } + + //outFile.println(";"); + + } + + protected static void writeConstraint(PrintWriter outFile) { + + outFile.println(""); + outFile.println("\\ constraint"); + outFile.println("Subject To"); + + Map constraintMap = SolverData.getConstraintDataMap(); + + ArrayList sortedConstraint = new ArrayList(constraintMap.keySet()); + Collections.sort(sortedConstraint); + + for (String constraintName : sortedConstraint) { + + String lhs = ""; + + if (!constraintMap.get(constraintName).getEvalExpression().isNumeric()) { + + ArrayList sortedTerm = new ArrayList(constraintMap.get(constraintName) + .getEvalExpression().getMultiplier().keySet()); + Collections.sort(sortedTerm); + + for (String var : sortedTerm) { + + Number coef = constraintMap.get(constraintName).getEvalExpression().getMultiplier().get(var) + .getData(); + double coefDouble = coef.doubleValue(); + String coefStr = coef.toString(); + String term; + + if (coefDouble == 1.0) { + term = " + " + var; + } + else if (coefDouble == -1.0) { + term = " - " + var; + } + else if (coefDouble < 0) { + term = " " + coefStr + " " + var; + } + else { // coefDouble >= 0 + term = " + " + coefStr + " " + var; + } + lhs = lhs + term; + } + + } + else { + + lhs = "0"; + } + + String sign = constraintMap.get(constraintName).getSign(); + double val = constraintMap.get(constraintName).getEvalExpression().getValue().getData().doubleValue(); + + if (sign.equals(">")) sign = ">="; + if (sign.equals("<")) sign = "<="; + + if (val == 0) { + lhs = constraintName + ": " + lhs + " " + sign + " " + "0"; + } + else { + lhs = constraintName + ": " + lhs + " " + sign + " " + val * -1; + } + + outFile.println(lhs); + + } + + } + + protected static void writeDvar(PrintWriter outFile, Set dvar_effective) { + + + Map dvarMap = SolverData.getDvarMap(); + + ArrayList sortedDvar_effective = new ArrayList(dvarMap.keySet()); + sortedDvar_effective.retainAll(dvar_effective); + Collections.sort(sortedDvar_effective); + + + // TODO: separate integer list in the parsing stage for efficiency + ArrayList intList = new ArrayList(); + ArrayList freeList = new ArrayList(); + + outFile.println(""); + outFile.println("\\ dvar"); + outFile.println("Bounds"); + + for (String key : sortedDvar_effective) { + double lower = dvarMap.get(key).lowerBoundValue.doubleValue(); + double upper = dvarMap.get(key).upperBoundValue.doubleValue(); + String lowerStr = dvarMap.get(key).lowerBound; + String upperStr = dvarMap.get(key).upperBound; + + if (dvarMap.get(key).integer.equalsIgnoreCase(Param.yes)) intList.add(key); + + if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) && upperStr.equalsIgnoreCase(Param.upper_unbounded)) { + freeList.add(key); //TODO: test what happen if it's a free integer ??? + continue; + } + if (lowerParam.upper_unbounded_double) { + freeList.add(key); //TODO: test what happen if it's a free integer ??? + continue; + } + else if (lowerStr.equalsIgnoreCase(Param.lower_unbounded) || lowerParam.upper_unbounded_double){ + + if (lower != 0) outFile.print(key + " >= " + lower + " \n"); + } + else { + if (lower != 0) { + outFile.print(lower + " <= " + key + " <= " + upper + " \n"); + } else { + outFile.print(key + " <= " + upper + " \n"); + } + } + } + + if (freeList.size() > 0) { + //outFile.print("free "); + + for (int i = 0; i < freeList.size(); i++) { + String term = freeList.get(i); + + outFile.print(" -inf <= " + term + " \n"); + + } + + } + + if (intList.size() > 0) { + outFile.println(""); + outFile.println("\\ Integer"); + outFile.println("Generals"); + + for (int i = 0; i < intList.size(); i++) { + String term = intList.get(i); + + //if (i == 0) { + outFile.println(term); + //} + //else { + // outFile.print(", " + term); + //} + } + + //outFile.print(" ;\n"); + } + + + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/export/LpSolveExport.java b/wrims-core/src/main/java/wrimsv2/solver/mpmodel/export/LpSolveExport.java similarity index 92% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/export/LpSolveExport.java rename to wrims-core/src/main/java/wrimsv2/solver/mpmodel/export/LpSolveExport.java index edff205d6..a1b956a30 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/solver/mpmodel/export/LpSolveExport.java +++ b/wrims-core/src/main/java/wrimsv2/solver/mpmodel/export/LpSolveExport.java @@ -1,266 +1,262 @@ -package wrimsv2.solver.mpmodel.export; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.solver.mpmodel.MPModel; - - -public class LpSolveExport { - - - private LpSolveExport() { - - } - - public static void writeComment(PrintWriter outFile, String msg) { - - - outFile.println("// " + msg ); - - } - - public static void writeObjValue() { - - - } - - - public static String writeObj(LinkedHashMap activeWeightMap) { - - String out = "// objective function\n"; - - out = out + "max:\n"; - - ArrayList sortedTerm = new ArrayList(activeWeightMap.keySet()); - - Collections.sort(sortedTerm); - - for (String dvar : sortedTerm) { - - double weight = activeWeightMap.get(dvar); - - if (weight > 0) { - - out = out + "+ " + weight + " " + dvar + "\n"; - - } - else if (weight < 0) { - out = out + weight + " " + dvar + "\n"; - - } - - } - - out = out + ";\n"; - return out; - - } - - public static String writeConstraint(LinkedHashMap> constraintLhs, LinkedHashMap constraintRhs) { - - - String out ="/* constraint */\n"; - - - for (String constraintName : constraintLhs.keySet()) { - - LinkedHashMap lhs_map = constraintLhs.get(constraintName); - - String lhs = ""; - - // TODO: this constraint might be always true or always false - if (lhs_map.keySet().size()==0) { - System.err.println("# Error: check constraint named: "+constraintName); - } - - for (String key: lhs_map.keySet()){ - - lhs = lhs + " + " + lhs_map.get(key) + " " + key ; - - } - - - double lb = constraintRhs.get(constraintName)[0]; - double ub = constraintRhs.get(constraintName)[1]; - - String lbStr = "constraint lb error"; - String ubStr = "constraint ub error"; - - if ( lb < -Param.inf_assumed ) { - lbStr = ""; - } else { - lbStr = lb + " <= "; - } - - if ( ub > Param.inf_assumed ) { - ubStr = ""; - } else { - ubStr = " <= " + ub; - } - - if (lb == ub) { - lbStr = ""; - ubStr = " = " + ub; - } - - // TODO: what if unbounded - - out = out + constraintName + ": "+ lbStr + lhs + ubStr + ";\n"; - - } - - return out; - - } - - public static String writeDvar(MPModel in) { - - String out = "/* dvar */\n"; - - - // number nonstd nonfree - ArrayList number_general = new ArrayList(in.var_general); - Collections.sort(number_general); - - // integer nonbinary - ArrayList integer_nonbinary = new ArrayList(in.varMap_integer.keySet()); - integer_nonbinary.removeAll(in.var_int_binary); - Collections.sort(integer_nonbinary); - - double lb = Param.inf_assumed; - double ub = -Param.inf_assumed; - - String lbStr = "lb error"; - String ubStr = "ub error"; - - - for (String key : number_general) { - - lb = in.varMap_number.get(key)[0]; - ub = in.varMap_number.get(key)[1]; - - if ( lb < -Param.inf_assumed ) { - lbStr = ""; - } else { - lbStr = lb + " <= "; - } - - if ( ub > Param.inf_assumed ) { - ubStr = ""; - } else { - ubStr = " <= " + ub; - } - - // TODO: what if unbounded - - out = out + lbStr + key + ubStr + ";\n"; - } - - - - - for (String key : integer_nonbinary) { - - lb = in.varMap_integer.get(key)[0]; - ub = in.varMap_integer.get(key)[1]; - - if ( lb < -Param.inf_assumed ) { - lbStr = ""; - } else { - lbStr = lb + " <= "; - } - - if ( ub > Param.inf_assumed ) { - ubStr = ""; - } else { - ubStr = " <= " + ub; - } - - // TODO: what if unbounded - - out = out + lbStr + key + ubStr + ";\n"; - } - - if (in.var_free.size() > 0) { - out = out + "free\n"; - - ArrayList var_free_list = new ArrayList(in.var_free); - Collections.sort(var_free_list); - - for (int i = 0; i < var_free_list.size(); i++) { - String term = var_free_list.get(i); - - if (i == 0) { - out = out + term; - } - else { - out = out + ", "+term; - } - } - - out = out + ";\n"; - } - - if (in.varMap_integer.size() > 0) { - - if (in.var_int_binary.size()>0) { - - out = out + "bin\n"; - - ArrayList var_binary_list = new ArrayList(in.var_int_binary); - Collections.sort(var_binary_list); - - for (int i = 0; i < var_binary_list.size(); i++) { - String term = var_binary_list.get(i); - - if (i == 0) { - out = out + term; - } - else { - out = out + ", "+term; - } - } - - out = out + ";\n"; - - } - - - if (in.varMap_integer.size() - in.var_int_binary.size()>0) { - - out = out + "int\n"; - - ArrayList var_int_list = new ArrayList(in.varMap_integer.keySet()); - var_int_list.removeAll(in.var_int_binary); - Collections.sort(var_int_list); - - for (int i = 0; i < var_int_list.size(); i++) { - String term = var_int_list.get(i); - - if (i == 0) { - out = out + term; - } - else { - out = out + ", "+term; - } - } - - out = out + ";\n"; - - } - - } - return out; - - - } - -} +package wrimsv2.solver.mpmodel.export; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.solver.mpmodel.MPModel; + + +public class LpSolveExport { + + + private LpSolveExport() { + + } + + public static void writeComment(PrintWriter outFile, String msg) { + + + outFile.println("// " + msg ); + + } + + public static void writeObjValue() { + + + } + + + public static String writeObj(LinkedHashMap activeWeightMap) { + + String out = "// objective function\n"; + + out = out + "max:\n"; + + ArrayList sortedTerm = new ArrayList(activeWeightMap.keySet()); + + Collections.sort(sortedTerm); + + for (String dvar : sortedTerm) { + + double weight = activeWeightMap.get(dvar); + + if (weight > 0) { + + out = out + "+ " + weight + " " + dvar + "\n"; + + } + else if (weight < 0) { + out = out + weight + " " + dvar + "\n"; + + } + + } + + out = out + ";\n"; + return out; + + } + + public static String writeConstraint(LinkedHashMap> constraintLhs, LinkedHashMap constraintRhs) { + + + String out ="/* constraint */\n"; + + + for (String constraintName : constraintLhs.keySet()) { + + LinkedHashMap lhs_map = constraintLhs.get(constraintName); + + String lhs = ""; + + // TODO: this constraint might be always true or always false + if (lhs_map.keySet().size()==0) { + System.err.println("# Error: check constraint named: "+constraintName); + } + + for (String key: lhs_map.keySet()){ + + lhs = lhs + " + " + lhs_map.get(key) + " " + key ; + + } + + + double lb = constraintRhs.get(constraintName)[0]; + double ub = constraintRhs.get(constraintName)[1]; + + String lbStr = "constraint lb error"; + String ubStr = "constraint ub error"; + + if ( lb < -Param.inf_assumed ) { + lbStr = ""; + } else { + lbStr = lb + " <= "; + } + + if ( ub > Param.inf_assumed ) { + ubStr = ""; + } else { + ubStr = " <= " + ub; + } + + if (lb == ub) { + lbStr = ""; + ubStr = " = " + ub; + } + + // TODO: what if unbounded + + out = out + constraintName + ": "+ lbStr + lhs + ubStr + ";\n"; + + } + + return out; + + } + + public static String writeDvar(MPModel in) { + + String out = "/* dvar */\n"; + + + // number nonstd nonfree + ArrayList number_general = new ArrayList(in.var_general); + Collections.sort(number_general); + + // integer nonbinary + ArrayList integer_nonbinary = new ArrayList(in.varMap_integer.keySet()); + integer_nonbinary.removeAll(in.var_int_binary); + Collections.sort(integer_nonbinary); + + double lb = Param.inf_assumed; + double ub = -Param.inf_assumed; + + String lbStr = "lb error"; + String ubStr = "ub error"; + + + for (String key : number_general) { + + lb = in.varMap_number.get(key)[0]; + ub = in.varMap_number.get(key)[1]; + + if ( lb < -Param.inf_assumed ) { + lbStr = ""; + } else { + lbStr = lb + " <= "; + } + + if ( ub > Param.inf_assumed ) { + ubStr = ""; + } else { + ubStr = " <= " + ub; + } + + // TODO: what if unbounded + + out = out + lbStr + key + ubStr + ";\n"; + } + + + + + for (String key : integer_nonbinary) { + + lb = in.varMap_integer.get(key)[0]; + ub = in.varMap_integer.get(key)[1]; + + if ( lb < -Param.inf_assumed ) { + lbStr = ""; + } else { + lbStr = lb + " <= "; + } + + if ( ub > Param.inf_assumed ) { + ubStr = ""; + } else { + ubStr = " <= " + ub; + } + + // TODO: what if unbounded + + out = out + lbStr + key + ubStr + ";\n"; + } + + if (in.var_free.size() > 0) { + out = out + "free\n"; + + ArrayList var_free_list = new ArrayList(in.var_free); + Collections.sort(var_free_list); + + for (int i = 0; i < var_free_list.size(); i++) { + String term = var_free_list.get(i); + + if (i == 0) { + out = out + term; + } + else { + out = out + ", "+term; + } + } + + out = out + ";\n"; + } + + if (in.varMap_integer.size() > 0) { + + if (in.var_int_binary.size()>0) { + + out = out + "bin\n"; + + ArrayList var_binary_list = new ArrayList(in.var_int_binary); + Collections.sort(var_binary_list); + + for (int i = 0; i < var_binary_list.size(); i++) { + String term = var_binary_list.get(i); + + if (i == 0) { + out = out + term; + } + else { + out = out + ", "+term; + } + } + + out = out + ";\n"; + + } + + + if (in.varMap_integer.size() - in.var_int_binary.size()>0) { + + out = out + "int\n"; + + ArrayList var_int_list = new ArrayList(in.varMap_integer.keySet()); + var_int_list.removeAll(in.var_int_binary); + Collections.sort(var_int_list); + + for (int i = 0; i < var_int_list.size(); i++) { + String term = var_int_list.get(i); + + if (i == 0) { + out = out + term; + } + else { + out = out + ", "+term; + } + } + + out = out + ";\n"; + + } + + } + return out; + + + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/ortools/Misc.java b/wrims-core/src/main/java/wrimsv2/solver/ortools/Misc.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/ortools/Misc.java rename to wrims-core/src/main/java/wrimsv2/solver/ortools/Misc.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/solver/ortools/OrToolsSolver.java b/wrims-core/src/main/java/wrimsv2/solver/ortools/OrToolsSolver.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/solver/ortools/OrToolsSolver.java rename to wrims-core/src/main/java/wrimsv2/solver/ortools/OrToolsSolver.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/sql/DataBaseProfile.java b/wrims-core/src/main/java/wrimsv2/sql/DataBaseProfile.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/sql/DataBaseProfile.java rename to wrims-core/src/main/java/wrimsv2/sql/DataBaseProfile.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/sql/DssToSQLDatabase.java b/wrims-core/src/main/java/wrimsv2/sql/DssToSQLDatabase.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/sql/DssToSQLDatabase.java rename to wrims-core/src/main/java/wrimsv2/sql/DssToSQLDatabase.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/sql/MySQLCWriter.java b/wrims-core/src/main/java/wrimsv2/sql/MySQLCWriter.java similarity index 99% rename from wrims_v2/wrims_v2/src/wrimsv2/sql/MySQLCWriter.java rename to wrims-core/src/main/java/wrimsv2/sql/MySQLCWriter.java index 48f5bd35a..cd9e73c17 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/sql/MySQLCWriter.java +++ b/wrims-core/src/main/java/wrimsv2/sql/MySQLCWriter.java @@ -13,8 +13,6 @@ import java.util.Set; import java.util.TreeSet; -import com.sun.java.util.collections.Collections; - import wrimsv2.components.ControlData; import wrimsv2.components.FilePaths; import wrimsv2.evaluator.DataTimeSeries; diff --git a/wrims_v2/wrims_v2/src/wrimsv2/sql/MySQLRWriter.java b/wrims-core/src/main/java/wrimsv2/sql/MySQLRWriter.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/sql/MySQLRWriter.java rename to wrims-core/src/main/java/wrimsv2/sql/MySQLRWriter.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/sql/MySQLRWriterAlt.java b/wrims-core/src/main/java/wrimsv2/sql/MySQLRWriterAlt.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/sql/MySQLRWriterAlt.java rename to wrims-core/src/main/java/wrimsv2/sql/MySQLRWriterAlt.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/sql/SQLServerRWriter.java b/wrims-core/src/main/java/wrimsv2/sql/SQLServerRWriter.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/sql/SQLServerRWriter.java rename to wrims-core/src/main/java/wrimsv2/sql/SQLServerRWriter.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/sql/SQLServerRWriterAlt.java b/wrims-core/src/main/java/wrimsv2/sql/SQLServerRWriterAlt.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/sql/SQLServerRWriterAlt.java rename to wrims-core/src/main/java/wrimsv2/sql/SQLServerRWriterAlt.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/sql/socket/Client.java b/wrims-core/src/main/java/wrimsv2/sql/socket/Client.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/sql/socket/Client.java rename to wrims-core/src/main/java/wrimsv2/sql/socket/Client.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/sql/socket/FileEvent.java b/wrims-core/src/main/java/wrimsv2/sql/socket/FileEvent.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/sql/socket/FileEvent.java rename to wrims-core/src/main/java/wrimsv2/sql/socket/FileEvent.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/sql/socket/SQLServer.java b/wrims-core/src/main/java/wrimsv2/sql/socket/SQLServer.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/sql/socket/SQLServer.java rename to wrims-core/src/main/java/wrimsv2/sql/socket/SQLServer.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tf/HelloTensorFlow.java b/wrims-core/src/main/java/wrimsv2/tf/HelloTensorFlow.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tf/HelloTensorFlow.java rename to wrims-core/src/main/java/wrimsv2/tf/HelloTensorFlow.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tf/TF.java b/wrims-core/src/main/java/wrimsv2/tf/TF.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tf/TF.java rename to wrims-core/src/main/java/wrimsv2/tf/TF.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/CheckWeightSlackSurplus.java b/wrims-core/src/main/java/wrimsv2/tools/CheckWeightSlackSurplus.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/CheckWeightSlackSurplus.java rename to wrims-core/src/main/java/wrimsv2/tools/CheckWeightSlackSurplus.java index cb3b64d1a..1c4f3da81 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/tools/CheckWeightSlackSurplus.java +++ b/wrims-core/src/main/java/wrimsv2/tools/CheckWeightSlackSurplus.java @@ -1,50 +1,50 @@ -package wrimsv2.tools; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArrayList; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.components.ControlData; -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.EvalConstraint; - -public class CheckWeightSlackSurplus { - - public CheckWeightSlackSurplus(){ - CopyOnWriteArrayList usedWeightSlackSurplusCollection = ControlData.currModelDataSet.usedWtSlackSurplusList; - Map weightSlackSurplusMap=SolverData.getWeightSlackSurplusMap(); - - Map constraintMap=SolverData.getConstraintDataMap(); - ArrayList constraintCollection = new ArrayList(ControlData.currModelDataSet.gList); - constraintCollection.retainAll(constraintMap.keySet()); - Iterator constraintIterator = constraintCollection.iterator(); - - while(constraintIterator.hasNext()){ - String constraintName=(String)constraintIterator.next(); - EvalConstraint ec=constraintMap.get(constraintName); - - Map multipliers=ec.getEvalExpression().getMultiplier(); - Set keySet=multipliers.keySet(); - Iterator multipliersIterator=keySet.iterator(); - while (multipliersIterator.hasNext()){ - String multiplierName=(String)multipliersIterator.next(); - if (usedWeightSlackSurplusCollection.contains(multiplierName)){ - usedWeightSlackSurplusCollection.remove(multiplierName); - }else{ - if (weightSlackSurplusMap.containsKey(multiplierName)){ - if (multiplierName.startsWith("surlus__") || multiplierName.startsWith("slack__")){ - System.out.println(multiplierName+" is not in weight table!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); - } - } - } - } - } - if (usedWeightSlackSurplusCollection.size()>0){ - System.out.println(usedWeightSlackSurplusCollection+" is not used in constraint!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); - } - } -} +package wrimsv2.tools; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.components.ControlData; +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.EvalConstraint; + +public class CheckWeightSlackSurplus { + + public CheckWeightSlackSurplus(){ + CopyOnWriteArrayList usedWeightSlackSurplusCollection = ControlData.currModelDataSet.usedWtSlackSurplusList; + Map weightSlackSurplusMap=SolverData.getWeightSlackSurplusMap(); + + Map constraintMap=SolverData.getConstraintDataMap(); + ArrayList constraintCollection = new ArrayList(ControlData.currModelDataSet.gList); + constraintCollection.retainAll(constraintMap.keySet()); + Iterator constraintIterator = constraintCollection.iterator(); + + while(constraintIterator.hasNext()){ + String constraintName=(String)constraintIterator.next(); + EvalConstraint ec=constraintMap.get(constraintName); + + Map multipliers=ec.getEvalExpression().getMultiplier(); + Set keySet=multipliers.keySet(); + Iterator multipliersIterator=keySet.iterator(); + while (multipliersIterator.hasNext()){ + String multiplierName=(String)multipliersIterator.next(); + if (usedWeightSlackSurplusCollection.contains(multiplierName)){ + usedWeightSlackSurplusCollection.remove(multiplierName); + }else{ + if (weightSlackSurplusMap.containsKey(multiplierName)){ + if (multiplierName.startsWith("surlus__") || multiplierName.startsWith("slack__")){ + System.out.println(multiplierName+" is not in weight table!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); + } + } + } + } + } + if (usedWeightSlackSurplusCollection.size()>0){ + System.out.println(usedWeightSlackSurplusCollection+" is not used in constraint!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/Decryption.java b/wrims-core/src/main/java/wrimsv2/tools/Decryption.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/Decryption.java rename to wrims-core/src/main/java/wrimsv2/tools/Decryption.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/DiffNestedObjects.java b/wrims-core/src/main/java/wrimsv2/tools/DiffNestedObjects.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/DiffNestedObjects.java rename to wrims-core/src/main/java/wrimsv2/tools/DiffNestedObjects.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/DiffObjects.java b/wrims-core/src/main/java/wrimsv2/tools/DiffObjects.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/DiffObjects.java rename to wrims-core/src/main/java/wrimsv2/tools/DiffObjects.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/General.java b/wrims-core/src/main/java/wrimsv2/tools/General.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/General.java rename to wrims-core/src/main/java/wrimsv2/tools/General.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/InfeasibilityAnalysis.java b/wrims-core/src/main/java/wrimsv2/tools/InfeasibilityAnalysis.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/InfeasibilityAnalysis.java rename to wrims-core/src/main/java/wrimsv2/tools/InfeasibilityAnalysis.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/MultiStepAnalyzer.java b/wrims-core/src/main/java/wrimsv2/tools/MultiStepAnalyzer.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/MultiStepAnalyzer.java rename to wrims-core/src/main/java/wrimsv2/tools/MultiStepAnalyzer.java index f2d63a7c5..7ea8e1ee0 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/tools/MultiStepAnalyzer.java +++ b/wrims-core/src/main/java/wrimsv2/tools/MultiStepAnalyzer.java @@ -1,104 +1,104 @@ -package wrimsv2.tools; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.EvalConstraint; -import wrimsv2.evaluator.EvalExpression; - -public class MultiStepAnalyzer { - private Map constraintMap; - private int fammonths=4; - private BufferedWriter out; - private ArrayList sortedConstraintKeys; - private int ifut; - - public MultiStepAnalyzer(){ - constraintMap=SolverData.getConstraintDataMap(); - Set constraintKeys=constraintMap.keySet(); - sortedConstraintKeys = new ArrayList(constraintKeys); - Collections.sort(sortedConstraintKeys); - - for (ifut=0; ifut<=fammonths; ifut++){ - new File(FilePaths.mainDirectory+"=MultiStepAnalyzer=").mkdir(); - String outPath=FilePaths.mainDirectory+"=MultiStepAnalyzer=\\"+ControlData.currYear+"_"+ControlData.currMonth+"_"+ControlData.currCycleIndex+"_"+"fut"+ifut+".txt"; - FileWriter outstream; - try { - outstream = new FileWriter(outPath); - out = new BufferedWriter(outstream); - - analyzeConstraints(); - - out.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - private void analyzeConstraints(){ - for (int j=0; j multipliers = ee.getMultiplier(); - Set multiplierKeys = multipliers.keySet(); - ArrayList sortedMultiKeys = new ArrayList(multiplierKeys); - Collections.sort(sortedMultiKeys); - for (int k=0; k=0){ - line=line+"+"+value+"*"+procVariable; - }else{ - line=line+value+"*"+procVariable; - } - } - line=line+ec.getSign()+(-ee.getValue().getData().doubleValue())+"\n"; - try { - out.write(line); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - private String processVariable(String variable){ - if (variable.contains("__fut__")){ - String[] procVariable=variable.split("__fut__"); - int timeStep=Integer.parseInt(procVariable[1])-ifut; - return procVariable[0]+"("+timeStep+")"; - }else{ - return variable; - } - } -} +package wrimsv2.tools; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.EvalConstraint; +import wrimsv2.evaluator.EvalExpression; + +public class MultiStepAnalyzer { + private Map constraintMap; + private int fammonths=4; + private BufferedWriter out; + private ArrayList sortedConstraintKeys; + private int ifut; + + public MultiStepAnalyzer(){ + constraintMap=SolverData.getConstraintDataMap(); + Set constraintKeys=constraintMap.keySet(); + sortedConstraintKeys = new ArrayList(constraintKeys); + Collections.sort(sortedConstraintKeys); + + for (ifut=0; ifut<=fammonths; ifut++){ + new File(FilePaths.mainDirectory+"=MultiStepAnalyzer=").mkdir(); + String outPath=FilePaths.mainDirectory+"=MultiStepAnalyzer=\\"+ControlData.currYear+"_"+ControlData.currMonth+"_"+ControlData.currCycleIndex+"_"+"fut"+ifut+".txt"; + FileWriter outstream; + try { + outstream = new FileWriter(outPath); + out = new BufferedWriter(outstream); + + analyzeConstraints(); + + out.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + private void analyzeConstraints(){ + for (int j=0; j multipliers = ee.getMultiplier(); + Set multiplierKeys = multipliers.keySet(); + ArrayList sortedMultiKeys = new ArrayList(multiplierKeys); + Collections.sort(sortedMultiKeys); + for (int k=0; k=0){ + line=line+"+"+value+"*"+procVariable; + }else{ + line=line+value+"*"+procVariable; + } + } + line=line+ec.getSign()+(-ee.getValue().getData().doubleValue())+"\n"; + try { + out.write(line); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + private String processVariable(String variable){ + if (variable.contains("__fut__")){ + String[] procVariable=variable.split("__fut__"); + int timeStep=Integer.parseInt(procVariable[1])-ifut; + return procVariable[0]+"("+timeStep+")"; + }else{ + return variable; + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/RCCComparison.java b/wrims-core/src/main/java/wrimsv2/tools/RCCComparison.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/RCCComparison.java rename to wrims-core/src/main/java/wrimsv2/tools/RCCComparison.java index 22ced0611..31559e5ef 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/tools/RCCComparison.java +++ b/wrims-core/src/main/java/wrimsv2/tools/RCCComparison.java @@ -1,242 +1,242 @@ -package wrimsv2.tools; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.DataInputStream; -import java.io.FileInputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.solverdata.SolverData; -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.Goal; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.EvalConstraint; - -public class RCCComparison { - private int cycle=1; - private String cycleName; - private BufferedWriter out; - private BufferedWriter out1; - private BufferedWriter out2; - private String gName; - private ArrayList gNameArrayList=new ArrayList (); - private ArrayList wNameArrayList=new ArrayList (); - private ArrayList dvarArrayList=new ArrayList (); - private Map weightMap; - private Map dvarMap; - private Map aliasMap; - - public RCCComparison() { - if (cycle<10){ - cycleName="0"+cycle; - }else{ - cycleName=""+cycle; - } - - Map constraintMap=SolverData.getConstraintDataMap(); - Object[] gNameArray=constraintMap.keySet().toArray(); - Collections.addAll(gNameArrayList, gNameArray); - - weightMap=SolverData.getWeightMap(); - Object[] wNameArray=weightMap.keySet().toArray(); - Collections.addAll(wNameArrayList, wNameArray); - - - - try{ - String outPath=FilePaths.mainDirectory+"comparegoal.txt"; - FileWriter outstream = new FileWriter(outPath); - out = new BufferedWriter(outstream); - - String outPath1=FilePaths.mainDirectory+"compareobject.txt"; - FileWriter outstream1 = new FileWriter(outPath1); - out1 = new BufferedWriter(outstream1); - - String filePath=FilePaths.mainDirectory+"rcc_reformatted_"+cycle+".txt"; - FileInputStream fstream = new FileInputStream(filePath); - DataInputStream in = new DataInputStream(fstream); - BufferedReader br = new BufferedReader(new InputStreamReader(in)); - - String strLine; - boolean isEnd=false; - int line=0; - while (!isEnd){ - strLine=br.readLine(); - if (strLine==null || strLine.equals("")) { - isEnd=true; - }else{ - if (strLine.startsWith("00") || strLine.startsWith(cycleName)){ - if (strLine.startsWith("00"+"Objective") || strLine.startsWith(cycleName+"Objective")){ - compareObject(strLine); - } - else{ - compareConstraint(strLine); - } - } - } - } - - for (int i=0; i0.1){ - outLine=outLine+"("+bounds[0]+","+lowBound+")lower:"; - isDifferent=true; - } - double upBound=dvar.upperBoundValue.doubleValue(); - if (Math.abs(Double.parseDouble(bounds[1])-upBound)>0.1){ - outLine=outLine+"("+bounds[1]+","+upBound+")upper"; - isDifferent=true; - } - }else{ - if (!aliasMap.containsKey(subStrs[1])) out2.write(subStrs[1]+" is not in WRIMS v2.\n"); - } - if (isDifferent) out2.write(outLine+"\n"); - } - - public void compareObject(String strLine) throws IOException{ - String outLine="Object:"; - boolean isDifferent =false; - strLine=strLine.substring(2, strLine.length()).toLowerCase(); - String[] subStrs=strLine.split(":"); - String[] weightVariable=subStrs[1].replaceAll(" ","").split(";"); - for (int i=1; i0.1){ - isDifferent=true; - outLine=outLine+"("+multiStrs[1]+"|"+coef+")*"+multiStrs[0]+";"; - } - }else{ - out1.write(multiStrs[1]+"*"+multiStrs[0]+" is not in WRIMS v2.\n"); - } - } - if (isDifferent) out1.write(outLine+"\n"); - } - - public void compareConstraint(String strLine) throws IOException{ - strLine=strLine.substring(2, strLine.length()).toLowerCase(); - String[] subStrs=strLine.split(":"); - gName=subStrs[0].substring(0, subStrs[0].lastIndexOf("/")); - Map constraintMap=SolverData.getConstraintDataMap(); - if (constraintMap.containsKey(gName)){ - EvalConstraint ec=constraintMap.get(gName); - gNameArrayList.remove(gName); - Map multiplier=ec.getEvalExpression().getMultiplier(); - Object[] multiplierArray=multiplier.keySet().toArray(); - ArrayList multiplierArrayList=new ArrayList (); - Collections.addAll(multiplierArrayList, multiplierArray); - String outLine=gName+":"; - String[] coefVariable=subStrs[1].replaceAll(" ","").split(";"); - boolean isDifferent=false; - for (int i=0; i0.1){ - isDifferent=true; - outLine=outLine+"("+multiStrs[1]+"|"+coef+")*"+multiStrs[0]+";"; - } - }else{ - isDifferent=true; - outLine=outLine+"("+multiStrs[1]+"|no)*"+multiStrs[0]+";"; - } - } - for (int i=0; i0.1){ - isDifferent=true; - outLine=outLine+"("+signValue[1]+"|"+value+")"; - } - if (isDifferent) out.write(outLine+"\n"); - }else{ - if (!gName.endsWith("_alias")) out.write(gName+" is not in WRIMS v2.\n"); - } - } -} +package wrimsv2.tools; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.solverdata.SolverData; +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.Goal; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.EvalConstraint; + +public class RCCComparison { + private int cycle=1; + private String cycleName; + private BufferedWriter out; + private BufferedWriter out1; + private BufferedWriter out2; + private String gName; + private ArrayList gNameArrayList=new ArrayList (); + private ArrayList wNameArrayList=new ArrayList (); + private ArrayList dvarArrayList=new ArrayList (); + private Map weightMap; + private Map dvarMap; + private Map aliasMap; + + public RCCComparison() { + if (cycle<10){ + cycleName="0"+cycle; + }else{ + cycleName=""+cycle; + } + + Map constraintMap=SolverData.getConstraintDataMap(); + Object[] gNameArray=constraintMap.keySet().toArray(); + Collections.addAll(gNameArrayList, gNameArray); + + weightMap=SolverData.getWeightMap(); + Object[] wNameArray=weightMap.keySet().toArray(); + Collections.addAll(wNameArrayList, wNameArray); + + + + try{ + String outPath=FilePaths.mainDirectory+"comparegoal.txt"; + FileWriter outstream = new FileWriter(outPath); + out = new BufferedWriter(outstream); + + String outPath1=FilePaths.mainDirectory+"compareobject.txt"; + FileWriter outstream1 = new FileWriter(outPath1); + out1 = new BufferedWriter(outstream1); + + String filePath=FilePaths.mainDirectory+"rcc_reformatted_"+cycle+".txt"; + FileInputStream fstream = new FileInputStream(filePath); + DataInputStream in = new DataInputStream(fstream); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + + String strLine; + boolean isEnd=false; + int line=0; + while (!isEnd){ + strLine=br.readLine(); + if (strLine==null || strLine.equals("")) { + isEnd=true; + }else{ + if (strLine.startsWith("00") || strLine.startsWith(cycleName)){ + if (strLine.startsWith("00"+"Objective") || strLine.startsWith(cycleName+"Objective")){ + compareObject(strLine); + } + else{ + compareConstraint(strLine); + } + } + } + } + + for (int i=0; i0.1){ + outLine=outLine+"("+bounds[0]+","+lowBound+")lower:"; + isDifferent=true; + } + double upBound=dvar.upperBoundValue.doubleValue(); + if (Math.abs(Double.parseDouble(bounds[1])-upBound)>0.1){ + outLine=outLine+"("+bounds[1]+","+upBound+")upper"; + isDifferent=true; + } + }else{ + if (!aliasMap.containsKey(subStrs[1])) out2.write(subStrs[1]+" is not in WRIMS v2.\n"); + } + if (isDifferent) out2.write(outLine+"\n"); + } + + public void compareObject(String strLine) throws IOException{ + String outLine="Object:"; + boolean isDifferent =false; + strLine=strLine.substring(2, strLine.length()).toLowerCase(); + String[] subStrs=strLine.split(":"); + String[] weightVariable=subStrs[1].replaceAll(" ","").split(";"); + for (int i=1; i0.1){ + isDifferent=true; + outLine=outLine+"("+multiStrs[1]+"|"+coef+")*"+multiStrs[0]+";"; + } + }else{ + out1.write(multiStrs[1]+"*"+multiStrs[0]+" is not in WRIMS v2.\n"); + } + } + if (isDifferent) out1.write(outLine+"\n"); + } + + public void compareConstraint(String strLine) throws IOException{ + strLine=strLine.substring(2, strLine.length()).toLowerCase(); + String[] subStrs=strLine.split(":"); + gName=subStrs[0].substring(0, subStrs[0].lastIndexOf("/")); + Map constraintMap=SolverData.getConstraintDataMap(); + if (constraintMap.containsKey(gName)){ + EvalConstraint ec=constraintMap.get(gName); + gNameArrayList.remove(gName); + Map multiplier=ec.getEvalExpression().getMultiplier(); + Object[] multiplierArray=multiplier.keySet().toArray(); + ArrayList multiplierArrayList=new ArrayList (); + Collections.addAll(multiplierArrayList, multiplierArray); + String outLine=gName+":"; + String[] coefVariable=subStrs[1].replaceAll(" ","").split(";"); + boolean isDifferent=false; + for (int i=0; i0.1){ + isDifferent=true; + outLine=outLine+"("+multiStrs[1]+"|"+coef+")*"+multiStrs[0]+";"; + } + }else{ + isDifferent=true; + outLine=outLine+"("+multiStrs[1]+"|no)*"+multiStrs[0]+";"; + } + } + for (int i=0; i0.1){ + isDifferent=true; + outLine=outLine+"("+signValue[1]+"|"+value+")"; + } + if (isDifferent) out.write(outLine+"\n"); + }else{ + if (!gName.endsWith("_alias")) out.write(gName+" is not in WRIMS v2.\n"); + } + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/Warmstart.java b/wrims-core/src/main/java/wrimsv2/tools/Warmstart.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/Warmstart.java rename to wrims-core/src/main/java/wrimsv2/tools/Warmstart.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/AltSolutionFinder.java b/wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/AltSolutionFinder.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/AltSolutionFinder.java rename to wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/AltSolutionFinder.java index c810ecf1a..8f7ad0a50 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/AltSolutionFinder.java +++ b/wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/AltSolutionFinder.java @@ -1,137 +1,137 @@ -package wrimsv2.tools.solutionRangeFinder; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; - -import wrimsv2.solver.mpmodel.MPModel; -import wrimsv2.solver.mpmodel.MPModelUtils; -import wrimsv2.solver.ortools.OrToolsSolver; -import wrimsv2.wreslplus.elements.Tools; - -public class AltSolutionFinder { - - - // required - private String id; - private MPModel asfModel = null; - private List searchVars; // will be modified (reduced) in the searching process .. - private int searchObjSign; // 1 for + and -1 for - - private ArrayList reportVars; // only report these vars - - - - // optional - private boolean lpsLogging = false; - private String lpsDir = ""; - private String lpsFileNamePrepend = ""; - - - public AltSolutionFinder(String id, MPModel inModel, List searchVars, int searchObjSign, ArrayList reportVars) { - - this.asfModel = inModel; - this.id = id; - this.searchVars = searchVars; - this.searchObjSign = searchObjSign; - this.reportVars = reportVars; - - } - - - // optional. This is for lps file logging. if not set then no logging. - public void setLpsLoggingPath(String dirName, String lpsFileNamePrepend){ - - this.lpsLogging = true; - this.lpsDir = dirName; - this.lpsFileNamePrepend = lpsFileNamePrepend+"_"+id; - - } - - public ArrayList> go() { - - OrToolsSolver sSolver = new OrToolsSolver("CBC_MIXED_INTEGER_PROGRAMMING"); - sSolver.setModel(asfModel); - - ArrayList> altSolutions = new ArrayList>(); - - int i = 0; - - for ( String sv: searchVars) { - i++; - System.out.println(id+" seach: "+i+": "+sv); - - LinkedHashMap searchObjFunc = new LinkedHashMap(); - searchObjFunc.put(sv, (double)searchObjSign); - double searchObjOffset = asfModel.solution.get(sv)*searchObjSign; - - - System.out.println("Var to search: "+sv); - - System.out.println("searchObjFunc: "+searchObjFunc); - System.out.println("searchObjOffset: "+searchObjOffset); - - sSolver.refreshObjFunc(searchObjFunc); - - // log search model - - //TODO: sSolver.model searchObjFunc is wrong - if (DetectorParam.lpsLogging) MPModelUtils.toLpSolve(sSolver.model, lpsDir, lpsFileNamePrepend+"_search_"+i+".lps"); - - // TODO: if solve fail then need to skip current obj function and continue to next search - // TODO: need to log solver fail for that specific variable - if (sSolver.solve()!=0) { - System.err.println("# Error ... no optimal solution for search variable: "+sv); - if (DetectorParam.continueOnErrors) continue; - } - - System.out.println("obj value: "+sSolver.solver.objectiveValue()); - if (DetectorParam.showSolutionInConsole) System.out.println("solution: "+sSolver.solution); - - // TODO: simplify this - boolean hasNewObjValue = false; - - - if (searchObjSign>0) { - hasNewObjValue = sSolver.solver.objectiveValue() > searchObjOffset; - } else if (searchObjSign<0) { - hasNewObjValue = sSolver.solver.objectiveValue() * searchObjSign < searchObjOffset * searchObjSign; - } - - System.out.println("New solution found? "+hasNewObjValue); - - if (hasNewObjValue) { - - // post new solution - - LinkedHashMap report_solution = new LinkedHashMap(sSolver.solution); - Tools.mapRetainAll(report_solution, reportVars); - altSolutions.add(report_solution); - - } - - } - - sSolver.delete(); - sSolver = null; - return altSolutions; - - } - - - public static double createObjFunc(LinkedHashMap out_searchObjFunc, ArrayList vars, int searchObjSign, LinkedHashMap baseSolution){ - - - double out_searchObjOffset = 0; - - for (String key: vars){ - - out_searchObjFunc.put(key, (double)searchObjSign); - out_searchObjOffset = out_searchObjOffset + baseSolution.get(key)*searchObjSign; - - } - - return out_searchObjOffset; - - } - -} +package wrimsv2.tools.solutionRangeFinder; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; + +import wrimsv2.solver.mpmodel.MPModel; +import wrimsv2.solver.mpmodel.MPModelUtils; +import wrimsv2.solver.ortools.OrToolsSolver; +import wrimsv2.wreslplus.elements.Tools; + +public class AltSolutionFinder { + + + // required + private String id; + private MPModel asfModel = null; + private List searchVars; // will be modified (reduced) in the searching process .. + private int searchObjSign; // 1 for + and -1 for - + private ArrayList reportVars; // only report these vars + + + + // optional + private boolean lpsLogging = false; + private String lpsDir = ""; + private String lpsFileNamePrepend = ""; + + + public AltSolutionFinder(String id, MPModel inModel, List searchVars, int searchObjSign, ArrayList reportVars) { + + this.asfModel = inModel; + this.id = id; + this.searchVars = searchVars; + this.searchObjSign = searchObjSign; + this.reportVars = reportVars; + + } + + + // optional. This is for lps file logging. if not set then no logging. + public void setLpsLoggingPath(String dirName, String lpsFileNamePrepend){ + + this.lpsLogging = true; + this.lpsDir = dirName; + this.lpsFileNamePrepend = lpsFileNamePrepend+"_"+id; + + } + + public ArrayList> go() { + + OrToolsSolver sSolver = new OrToolsSolver("CBC_MIXED_INTEGER_PROGRAMMING"); + sSolver.setModel(asfModel); + + ArrayList> altSolutions = new ArrayList>(); + + int i = 0; + + for ( String sv: searchVars) { + i++; + System.out.println(id+" seach: "+i+": "+sv); + + LinkedHashMap searchObjFunc = new LinkedHashMap(); + searchObjFunc.put(sv, (double)searchObjSign); + double searchObjOffset = asfModel.solution.get(sv)*searchObjSign; + + + System.out.println("Var to search: "+sv); + + System.out.println("searchObjFunc: "+searchObjFunc); + System.out.println("searchObjOffset: "+searchObjOffset); + + sSolver.refreshObjFunc(searchObjFunc); + + // log search model + + //TODO: sSolver.model searchObjFunc is wrong + if (DetectorParam.lpsLogging) MPModelUtils.toLpSolve(sSolver.model, lpsDir, lpsFileNamePrepend+"_search_"+i+".lps"); + + // TODO: if solve fail then need to skip current obj function and continue to next search + // TODO: need to log solver fail for that specific variable + if (sSolver.solve()!=0) { + System.err.println("# Error ... no optimal solution for search variable: "+sv); + if (DetectorParam.continueOnErrors) continue; + } + + System.out.println("obj value: "+sSolver.solver.objectiveValue()); + if (DetectorParam.showSolutionInConsole) System.out.println("solution: "+sSolver.solution); + + // TODO: simplify this + boolean hasNewObjValue = false; + + + if (searchObjSign>0) { + hasNewObjValue = sSolver.solver.objectiveValue() > searchObjOffset; + } else if (searchObjSign<0) { + hasNewObjValue = sSolver.solver.objectiveValue() * searchObjSign < searchObjOffset * searchObjSign; + } + + System.out.println("New solution found? "+hasNewObjValue); + + if (hasNewObjValue) { + + // post new solution + + LinkedHashMap report_solution = new LinkedHashMap(sSolver.solution); + Tools.mapRetainAll(report_solution, reportVars); + altSolutions.add(report_solution); + + } + + } + + sSolver.delete(); + sSolver = null; + return altSolutions; + + } + + + public static double createObjFunc(LinkedHashMap out_searchObjFunc, ArrayList vars, int searchObjSign, LinkedHashMap baseSolution){ + + + double out_searchObjOffset = 0; + + for (String key: vars){ + + out_searchObjFunc.put(key, (double)searchObjSign); + out_searchObjOffset = out_searchObjOffset + baseSolution.get(key)*searchObjSign; + + } + + return out_searchObjOffset; + + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/Detector.java b/wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/Detector.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/Detector.java rename to wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/Detector.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/DetectorParam.java b/wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/DetectorParam.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/DetectorParam.java rename to wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/DetectorParam.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/DetectorWorkflow.java b/wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/DetectorWorkflow.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/DetectorWorkflow.java rename to wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/DetectorWorkflow.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/Main.java b/wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/Main.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/Main.java rename to wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/Main.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/Misc.java b/wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/Misc.java similarity index 100% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/Misc.java rename to wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/Misc.java diff --git a/wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/VarsGroup.java b/wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/VarsGroup.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/VarsGroup.java rename to wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/VarsGroup.java index 6ddaab535..84e5bed27 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/tools/solutionRangeFinder/VarsGroup.java +++ b/wrims-core/src/main/java/wrimsv2/tools/solutionRangeFinder/VarsGroup.java @@ -1,187 +1,187 @@ -package wrimsv2.tools.solutionRangeFinder; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; - -import wrimsv2.solver.mpmodel.MPModel; -import wrimsv2.wreslplus.elements.Tools; - -public class VarsGroup { - - public List lowerVertexVars_number; - public List lowerVertexVars_integer; - - public List notLowerVertexVars_number; - public List notLowerVertexVars_integer; - - public List notUpperVertexVars_number; - public List notUpperVertexVars_integer; - - // required - private final double vertax_tolerance; // tolerance for determining if a var is at vertex - private MPModel baseModel; - - // optional - private ArrayList excludeStrings = null; // if not set then exclude none - private ArrayList includeStrings = null; // if not set then include all - public ArrayList varsPool; // default is base solution - - // processed - public ArrayList varsPool_number; // subset of varsPool - public ArrayList varsPool_integer; // subset of varsPool - - public VarsGroup(MPModel in, double vertax_tolerance) { - - lowerVertexVars_number = new ArrayList(); - lowerVertexVars_integer = new ArrayList(); - - excludeStrings = null; - includeStrings = null; - - baseModel = in; - this.vertax_tolerance = vertax_tolerance; - this.varsPool = new ArrayList(baseModel.solution.keySet()); - } - - public void setIncludeStrings(ArrayList in){ - - includeStrings = in; - - } - - public void setExcludeStrings(ArrayList in){ - - excludeStrings = in; - - } - - - public void setVarsPool(ArrayList varsToSearch_in){ - - - ArrayList p = new ArrayList(Tools.allToLowerCase(varsToSearch_in)); - - if (p.retainAll(baseModel.solution.keySet())){ - // unknown vars... - ArrayList unknownVars = new ArrayList(Tools.allToLowerCase(varsToSearch_in)); - unknownVars.removeAll(p); - System.err.println("# Error: unknown vars in varsPool:"+ unknownVars); - - } else { - - varsPool = p; - - varsPool_integer = new ArrayList(varsPool); - varsPool_integer.retainAll(baseModel.varMap_integer.keySet()); - - varsPool_number = new ArrayList(varsPool); - varsPool_number.retainAll(baseModel.varMap_number.keySet()); - - } - - } - - public void filterVarsPool(ArrayList includeStrings, ArrayList excludeStrings ){ - - - if (includeStrings!=null && includeStrings.size()>0) { - - this.includeStrings = new ArrayList(Tools.allToLowerCase(includeStrings)); - - - ArrayList varsPool_t = new ArrayList(varsPool); - for (String incStr: this.includeStrings){ - - for (String key: varsPool_t){ - - if (!key.contains(incStr)) varsPool.remove(key); - - } - - } - - } - - if (excludeStrings!=null && excludeStrings.size()>0) { - - this.excludeStrings = new ArrayList(Tools.allToLowerCase(excludeStrings)); - - - ArrayList varsPool_t = new ArrayList(varsPool); - for (String excStr: this.excludeStrings){ - - for (String key: varsPool_t){ - - if (key.contains(excStr)) varsPool.remove(key); - - } - - } - - } - - } - - public void findVarsAtVertex(){ - - lowerVertexVars_number = findLowerVertaxVars(varsPool_number, baseModel.solution, baseModel.varMap_number); - lowerVertexVars_integer = findLowerVertaxVars(varsPool_integer, baseModel.solution, baseModel.varMap_integer); - - notLowerVertexVars_number = findNotLowerVertaxVars(varsPool_number, baseModel.solution, baseModel.varMap_number); - notLowerVertexVars_integer = findNotLowerVertaxVars(varsPool_integer, baseModel.solution, baseModel.varMap_integer); - - notUpperVertexVars_number = findNotUpperVertaxVars(varsPool_number, baseModel.solution, baseModel.varMap_number); - notUpperVertexVars_integer = findNotUpperVertaxVars(varsPool_integer, baseModel.solution, baseModel.varMap_integer); - - } - - private ArrayList findNotUpperVertaxVars(ArrayList vars, LinkedHashMap solutionMap, LinkedHashMap varBounds) { - - ArrayList out = new ArrayList(); - - for (String key : vars) { - - if (solutionMap.get(key) < varBounds.get(key)[1]) { - - out.add(key); - - } - } - - return out; - } - - private ArrayList findNotLowerVertaxVars(ArrayList vars, LinkedHashMap solutionMap, LinkedHashMap varBounds) { - - ArrayList out = new ArrayList(); - - for (String key : vars) { - - if (solutionMap.get(key) > varBounds.get(key)[0]) { - - out.add(key); - - } - } - - return out; - } - - private ArrayList findLowerVertaxVars(ArrayList vars, LinkedHashMap solutionMap, LinkedHashMap varBounds) { - - ArrayList out = new ArrayList(); - - for (String key : vars) { - - if (solutionMap.get(key) < varBounds.get(key)[0] + vertax_tolerance) { - - out.add(key); - - } - } - - return out; - } - -} +package wrimsv2.tools.solutionRangeFinder; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; + +import wrimsv2.solver.mpmodel.MPModel; +import wrimsv2.wreslplus.elements.Tools; + +public class VarsGroup { + + public List lowerVertexVars_number; + public List lowerVertexVars_integer; + + public List notLowerVertexVars_number; + public List notLowerVertexVars_integer; + + public List notUpperVertexVars_number; + public List notUpperVertexVars_integer; + + // required + private final double vertax_tolerance; // tolerance for determining if a var is at vertex + private MPModel baseModel; + + // optional + private ArrayList excludeStrings = null; // if not set then exclude none + private ArrayList includeStrings = null; // if not set then include all + public ArrayList varsPool; // default is base solution + + // processed + public ArrayList varsPool_number; // subset of varsPool + public ArrayList varsPool_integer; // subset of varsPool + + public VarsGroup(MPModel in, double vertax_tolerance) { + + lowerVertexVars_number = new ArrayList(); + lowerVertexVars_integer = new ArrayList(); + + excludeStrings = null; + includeStrings = null; + + baseModel = in; + this.vertax_tolerance = vertax_tolerance; + this.varsPool = new ArrayList(baseModel.solution.keySet()); + } + + public void setIncludeStrings(ArrayList in){ + + includeStrings = in; + + } + + public void setExcludeStrings(ArrayList in){ + + excludeStrings = in; + + } + + + public void setVarsPool(ArrayList varsToSearch_in){ + + + ArrayList p = new ArrayList(Tools.allToLowerCase(varsToSearch_in)); + + if (p.retainAll(baseModel.solution.keySet())){ + // unknown vars... + ArrayList unknownVars = new ArrayList(Tools.allToLowerCase(varsToSearch_in)); + unknownVars.removeAll(p); + System.err.println("# Error: unknown vars in varsPool:"+ unknownVars); + + } else { + + varsPool = p; + + varsPool_integer = new ArrayList(varsPool); + varsPool_integer.retainAll(baseModel.varMap_integer.keySet()); + + varsPool_number = new ArrayList(varsPool); + varsPool_number.retainAll(baseModel.varMap_number.keySet()); + + } + + } + + public void filterVarsPool(ArrayList includeStrings, ArrayList excludeStrings ){ + + + if (includeStrings!=null && includeStrings.size()>0) { + + this.includeStrings = new ArrayList(Tools.allToLowerCase(includeStrings)); + + + ArrayList varsPool_t = new ArrayList(varsPool); + for (String incStr: this.includeStrings){ + + for (String key: varsPool_t){ + + if (!key.contains(incStr)) varsPool.remove(key); + + } + + } + + } + + if (excludeStrings!=null && excludeStrings.size()>0) { + + this.excludeStrings = new ArrayList(Tools.allToLowerCase(excludeStrings)); + + + ArrayList varsPool_t = new ArrayList(varsPool); + for (String excStr: this.excludeStrings){ + + for (String key: varsPool_t){ + + if (key.contains(excStr)) varsPool.remove(key); + + } + + } + + } + + } + + public void findVarsAtVertex(){ + + lowerVertexVars_number = findLowerVertaxVars(varsPool_number, baseModel.solution, baseModel.varMap_number); + lowerVertexVars_integer = findLowerVertaxVars(varsPool_integer, baseModel.solution, baseModel.varMap_integer); + + notLowerVertexVars_number = findNotLowerVertaxVars(varsPool_number, baseModel.solution, baseModel.varMap_number); + notLowerVertexVars_integer = findNotLowerVertaxVars(varsPool_integer, baseModel.solution, baseModel.varMap_integer); + + notUpperVertexVars_number = findNotUpperVertaxVars(varsPool_number, baseModel.solution, baseModel.varMap_number); + notUpperVertexVars_integer = findNotUpperVertaxVars(varsPool_integer, baseModel.solution, baseModel.varMap_integer); + + } + + private ArrayList findNotUpperVertaxVars(ArrayList vars, LinkedHashMap solutionMap, LinkedHashMap varBounds) { + + ArrayList out = new ArrayList(); + + for (String key : vars) { + + if (solutionMap.get(key) < varBounds.get(key)[1]) { + + out.add(key); + + } + } + + return out; + } + + private ArrayList findNotLowerVertaxVars(ArrayList vars, LinkedHashMap solutionMap, LinkedHashMap varBounds) { + + ArrayList out = new ArrayList(); + + for (String key : vars) { + + if (solutionMap.get(key) > varBounds.get(key)[0]) { + + out.add(key); + + } + } + + return out; + } + + private ArrayList findLowerVertaxVars(ArrayList vars, LinkedHashMap solutionMap, LinkedHashMap varBounds) { + + ArrayList out = new ArrayList(); + + for (String key : vars) { + + if (solutionMap.get(key) < varBounds.get(key)[0] + vertax_tolerance) { + + out.add(key); + + } + } + + return out; + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Comparison.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/Comparison.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Comparison.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/Comparison.java index a2019ed33..54b654b64 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Comparison.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/Comparison.java @@ -1,34 +1,34 @@ -package wrimsv2.wreslparser.elements; - -import java.io.IOException; -import java.util.Map; -import java.util.Set; - -import org.testng.Assert; - -public class Comparison { - - public static void compareFolder(Set modelSet, String outParent, String expectedParent ){ - - for (String model : modelSet) { - - String outFolder = outParent + model; - String expectedFolder = expectedParent + model; - - Map actual; - Map expected; - - try { - actual = Tools.readFilesFromDirAsMap(outFolder); - expected = Tools.readFilesFromDirAsMap(expectedFolder); - Assert.assertEquals(actual, expected); - } - catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - -} +package wrimsv2.wreslparser.elements; + +import java.io.IOException; +import java.util.Map; +import java.util.Set; + +import org.testng.Assert; + +public class Comparison { + + public static void compareFolder(Set modelSet, String outParent, String expectedParent ){ + + for (String model : modelSet) { + + String outFolder = outParent + model; + String expectedFolder = expectedParent + model; + + Map actual; + Map expected; + + try { + actual = Tools.readFilesFromDirAsMap(outFolder); + expected = Tools.readFilesFromDirAsMap(expectedFolder); + Assert.assertEquals(actual, expected); + } + catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/FatalErrorException.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/FatalErrorException.java similarity index 90% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/FatalErrorException.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/FatalErrorException.java index 131791555..d48d1f2dd 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/FatalErrorException.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/FatalErrorException.java @@ -1,17 +1,17 @@ -package wrimsv2.wreslparser.elements; - - - -public class FatalErrorException extends Exception{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - - - - -} - +package wrimsv2.wreslparser.elements; + + + +public class FatalErrorException extends Exception{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + + + + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/FileParser.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/FileParser.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/FileParser.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/FileParser.java index 1632e3a43..7778ae7b9 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/FileParser.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/FileParser.java @@ -1,315 +1,315 @@ -package wrimsv2.wreslparser.elements; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import org.antlr.runtime.ANTLRFileStream; -import org.antlr.runtime.CharStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; -import org.antlr.runtime.tree.CommonTree; -import org.antlr.runtime.tree.CommonTreeNodeStream; - - - - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.wreslparser.grammar.WreslTreeLexer; -import wrimsv2.wreslparser.grammar.WreslTreeParser; -import wrimsv2.wreslparser.grammar.WreslTreeWalker; - -public class FileParser { - - private static CharStream stream; - public String scope; - public String kind; - public String units; - public String expression; - - - public FileParser(){ - scope=Param.undefined; - kind=Param.undefined; - units=Param.undefined; - expression=Param.undefined; - - - } - - public static WreslTreeWalker parseFile(String inputFilePath) throws RecognitionException{ - - return parseFile(inputFilePath, false); - } - public static WreslTreeWalker parseFile(String inputFilePath, boolean showTree) throws RecognitionException { - - - try { - stream = new ANTLRFileStream(inputFilePath, "UTF8"); - } - catch(Exception e) { - //e.printStackTrace(); - - LogUtils.errMsg("File not found: "+ inputFilePath); - LogUtils.closeLogFile(); - return null; - //System.exit(1); - - } - - WreslTreeLexer lexer = new WreslTreeLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - - WreslTreeParser parser = new WreslTreeParser(tokenStream); - - parser.currentAbsolutePath = new File(inputFilePath).getAbsolutePath(); - parser.currentAbsoluteParent = new File(inputFilePath).getAbsoluteFile().getParent(); - - LogUtils.importantMsg("Parsing file: "+parser.currentAbsolutePath); - - WreslTreeParser.evaluator_return parser_evaluator = parser.evaluator(); - -// // / check if sequence contains models not defined -// ArrayList undefined_models = parser.model_in_sequence; -// parser.model_in_sequence.removeAll(parser.model_list); -// if (undefined_models.size()>0 ){ -// LogUtils.errMsg("Sequence has undefined models: ", undefined_models); -// } - - // / for debug info - parser.commonTree = (CommonTree) parser_evaluator.getTree(); - if (showTree) LogUtils.importantMsg("tree = " + parser.commonTree.toStringTree()); - - // / feed walker with parser's tree output - CommonTreeNodeStream nodeStream = new CommonTreeNodeStream(parser_evaluator.getTree()); - nodeStream.setTokenStream(tokenStream); // important trick to avoid null exception in tree walker - WreslTreeWalker walker = new WreslTreeWalker(nodeStream); - - walker.commonTree = parser.commonTree; - walker.currentAbsolutePath = parser.currentAbsolutePath; - walker.currentAbsoluteParent = parser.currentAbsoluteParent; - - if (showTree) LogUtils.importantMsg("Walking tree: "+parser.currentAbsolutePath); - - walker.evaluator(); - - return walker; - - } - - - - public static Map processNestedFile(String inputFilePath) throws RecognitionException, IOException { - - SimulationDataSet mainData = parseFile(inputFilePath).thisFileDataSet; - - - Map out = new HashMap(); - out.put(inputFilePath, mainData); - - if (mainData.incFileList.isEmpty()) {return out;} - else { - for (String file : mainData.incFileList) { - - Map eachMap = processNestedFile(file); - - out.putAll(eachMap); - } - - return out; - } - } - - public static Map processNestedFileExceptFor(String inputFilePath, Set existingSet) throws RecognitionException, IOException { - - //if(existingSet.contains(inputFilePath)) return null; - - SimulationDataSet mainData = parseFile(inputFilePath).thisFileDataSet; - - Map out = new HashMap(); - out.put(inputFilePath, mainData); - - if (mainData.incFileSet.isEmpty()) return out; - else { - for (String file : mainData.incFileSet) { - - if (existingSet.contains(file)) continue; - else { - Map eachMap = processNestedFile(file); - - out.putAll(eachMap); - } - } - - return out; - } - } - - public static SimulationDataSet processFileIntoSimulationDataSet(String inputFilePath, String scope) throws RecognitionException, IOException { - - WreslTreeWalker parser = parseFile(inputFilePath); - - SimulationDataSet out = new SimulationDataSet(); - out = parser.thisFileDataSet; - - if (scope == "Local"){ - out =Tools.convertSimulationDataSetToLocal(out); - } - else if (scope == "Global"){ /* Do nothing */ } - else { LogUtils.errMsg("Wrong scope: "+scope+ " for file: ", inputFilePath);} - - - return out; - } - - public static Map processNestedFileIntoSimulationDataSetMap(String inputFilePath, String scope) throws RecognitionException, IOException { - - SimulationDataSet mainData = processFileIntoSimulationDataSet(inputFilePath, scope); - - Map out = new HashMap(); - out.put(inputFilePath, mainData); - - if (mainData.incFileList.isEmpty()) {return out;} - else { - for (String file : mainData.incFileList) { - - String subscope; - if (scope == "local") { - subscope = "local"; - } // main file scope overrides subfile scope - else { - subscope = mainData.incFileMap.get(file).scope; - } - - //SimulationDataSet each = processFileIntoSimulationDataSet(file, subscope); - Map eachMap = processNestedFileIntoSimulationDataSetMap(file, subscope); - - //out.put(file, each); - out.putAll(eachMap); - } - - return out; - } - } - - public static WreslTreeWalker parseMainFile(String inputFilePath) throws RecognitionException{ - - return parseMainFile(inputFilePath, false); - } - - public static WreslTreeWalker parseMainFile(String inputFilePath, boolean showTree) throws RecognitionException { - - - try { - stream = new ANTLRFileStream(inputFilePath, "UTF8"); - } - catch(Exception e) { - //e.printStackTrace(); - - LogUtils.errMsg("File not found: "+ inputFilePath); - LogUtils.closeLogFile(); - return null; - //System.exit(1); - - } - - WreslTreeLexer lexer = new WreslTreeLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - - WreslTreeParser parser = new WreslTreeParser(tokenStream); - - parser.currentAbsolutePath = new File(inputFilePath).getAbsolutePath(); - parser.currentAbsoluteParent = new File(inputFilePath).getAbsoluteFile().getParent(); - - LogUtils.importantMsg("Parsing file: "+parser.currentAbsolutePath); - - WreslTreeParser.mainFile_return parser_return = parser.mainFile(); - - // / check if sequence contains models not defined - ArrayList undefined_models = parser.model_in_sequence; - parser.model_in_sequence.removeAll(parser.model_list); - if (undefined_models.size()>0 ){ - LogUtils.errMsg("Sequence has undefined models: ", undefined_models); - } - - // / for debug info - parser.commonTree = (CommonTree) parser_return.getTree(); - if (showTree) LogUtils.importantMsg("tree = " + parser.commonTree.toStringTree()); - - // / feed walker with parser's tree output - CommonTreeNodeStream nodeStream = new CommonTreeNodeStream(parser_return.getTree()); - nodeStream.setTokenStream(tokenStream); // important trick to avoid null exception in tree walker - WreslTreeWalker walker = new WreslTreeWalker(nodeStream); - - walker.commonTree = parser.commonTree; - walker.currentAbsolutePath = parser.currentAbsolutePath; - walker.currentAbsoluteParent = parser.currentAbsoluteParent; - - if (showTree) LogUtils.importantMsg("Walking tree: "+parser.currentAbsolutePath); - - walker.evaluator(); - - return walker; - - } - - public static WreslTreeWalker parseOneFileForDebug(String inputFilePath) throws RecognitionException { - - - try { - stream = new ANTLRFileStream(inputFilePath, "UTF8"); - } - catch(Exception e) { - //e.printStackTrace(); - - System.out.println("File not found: "+ inputFilePath); - return null; - //System.exit(1); - - } - - WreslTreeLexer lexer = new WreslTreeLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - - WreslTreeParser parser = new WreslTreeParser(tokenStream); - - parser.currentAbsolutePath = new File(inputFilePath).getAbsolutePath(); - parser.currentAbsoluteParent = new File(inputFilePath).getAbsoluteFile().getParent(); - - //LogUtils.importantMsg("Parsing file: "+parser.currentAbsolutePath); - - WreslTreeParser.evaluator_return parser_evaluator = parser.evaluator(); - -// // / check if sequence contains models not defined -// ArrayList undefined_models = parser.model_in_sequence; -// parser.model_in_sequence.removeAll(parser.model_list); -// if (undefined_models.size()>0 ){ -// LogUtils.errMsg("Sequence has undefined models: ", undefined_models); -// } - - // / for debug info - parser.commonTree = (CommonTree) parser_evaluator.getTree(); - //if (showTree) LogUtils.importantMsg("tree = " + parser.commonTree.toStringTree()); - - // / feed walker with parser's tree output - CommonTreeNodeStream nodeStream = new CommonTreeNodeStream(parser_evaluator.getTree()); - nodeStream.setTokenStream(tokenStream); // important trick to avoid null exception in tree walker - WreslTreeWalker walker = new WreslTreeWalker(nodeStream); - - walker.commonTree = parser.commonTree; - walker.currentAbsolutePath = parser.currentAbsolutePath; - walker.currentAbsoluteParent = parser.currentAbsoluteParent; - - //if (showTree) LogUtils.importantMsg("Walking tree: "+parser.currentAbsolutePath); - - walker.evaluator(); - - return walker; - - } -} - +package wrimsv2.wreslparser.elements; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.antlr.runtime.ANTLRFileStream; +import org.antlr.runtime.CharStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.TokenStream; +import org.antlr.runtime.tree.CommonTree; +import org.antlr.runtime.tree.CommonTreeNodeStream; + + + + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.wreslparser.grammar.WreslTreeLexer; +import wrimsv2.wreslparser.grammar.WreslTreeParser; +import wrimsv2.wreslparser.grammar.WreslTreeWalker; + +public class FileParser { + + private static CharStream stream; + public String scope; + public String kind; + public String units; + public String expression; + + + public FileParser(){ + scope=Param.undefined; + kind=Param.undefined; + units=Param.undefined; + expression=Param.undefined; + + + } + + public static WreslTreeWalker parseFile(String inputFilePath) throws RecognitionException{ + + return parseFile(inputFilePath, false); + } + public static WreslTreeWalker parseFile(String inputFilePath, boolean showTree) throws RecognitionException { + + + try { + stream = new ANTLRFileStream(inputFilePath, "UTF8"); + } + catch(Exception e) { + //e.printStackTrace(); + + LogUtils.errMsg("File not found: "+ inputFilePath); + LogUtils.closeLogFile(); + return null; + //System.exit(1); + + } + + WreslTreeLexer lexer = new WreslTreeLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + + WreslTreeParser parser = new WreslTreeParser(tokenStream); + + parser.currentAbsolutePath = new File(inputFilePath).getAbsolutePath(); + parser.currentAbsoluteParent = new File(inputFilePath).getAbsoluteFile().getParent(); + + LogUtils.importantMsg("Parsing file: "+parser.currentAbsolutePath); + + WreslTreeParser.evaluator_return parser_evaluator = parser.evaluator(); + +// // / check if sequence contains models not defined +// ArrayList undefined_models = parser.model_in_sequence; +// parser.model_in_sequence.removeAll(parser.model_list); +// if (undefined_models.size()>0 ){ +// LogUtils.errMsg("Sequence has undefined models: ", undefined_models); +// } + + // / for debug info + parser.commonTree = (CommonTree) parser_evaluator.getTree(); + if (showTree) LogUtils.importantMsg("tree = " + parser.commonTree.toStringTree()); + + // / feed walker with parser's tree output + CommonTreeNodeStream nodeStream = new CommonTreeNodeStream(parser_evaluator.getTree()); + nodeStream.setTokenStream(tokenStream); // important trick to avoid null exception in tree walker + WreslTreeWalker walker = new WreslTreeWalker(nodeStream); + + walker.commonTree = parser.commonTree; + walker.currentAbsolutePath = parser.currentAbsolutePath; + walker.currentAbsoluteParent = parser.currentAbsoluteParent; + + if (showTree) LogUtils.importantMsg("Walking tree: "+parser.currentAbsolutePath); + + walker.evaluator(); + + return walker; + + } + + + + public static Map processNestedFile(String inputFilePath) throws RecognitionException, IOException { + + SimulationDataSet mainData = parseFile(inputFilePath).thisFileDataSet; + + + Map out = new HashMap(); + out.put(inputFilePath, mainData); + + if (mainData.incFileList.isEmpty()) {return out;} + else { + for (String file : mainData.incFileList) { + + Map eachMap = processNestedFile(file); + + out.putAll(eachMap); + } + + return out; + } + } + + public static Map processNestedFileExceptFor(String inputFilePath, Set existingSet) throws RecognitionException, IOException { + + //if(existingSet.contains(inputFilePath)) return null; + + SimulationDataSet mainData = parseFile(inputFilePath).thisFileDataSet; + + Map out = new HashMap(); + out.put(inputFilePath, mainData); + + if (mainData.incFileSet.isEmpty()) return out; + else { + for (String file : mainData.incFileSet) { + + if (existingSet.contains(file)) continue; + else { + Map eachMap = processNestedFile(file); + + out.putAll(eachMap); + } + } + + return out; + } + } + + public static SimulationDataSet processFileIntoSimulationDataSet(String inputFilePath, String scope) throws RecognitionException, IOException { + + WreslTreeWalker parser = parseFile(inputFilePath); + + SimulationDataSet out = new SimulationDataSet(); + out = parser.thisFileDataSet; + + if (scope == "Local"){ + out =Tools.convertSimulationDataSetToLocal(out); + } + else if (scope == "Global"){ /* Do nothing */ } + else { LogUtils.errMsg("Wrong scope: "+scope+ " for file: ", inputFilePath);} + + + return out; + } + + public static Map processNestedFileIntoSimulationDataSetMap(String inputFilePath, String scope) throws RecognitionException, IOException { + + SimulationDataSet mainData = processFileIntoSimulationDataSet(inputFilePath, scope); + + Map out = new HashMap(); + out.put(inputFilePath, mainData); + + if (mainData.incFileList.isEmpty()) {return out;} + else { + for (String file : mainData.incFileList) { + + String subscope; + if (scope == "local") { + subscope = "local"; + } // main file scope overrides subfile scope + else { + subscope = mainData.incFileMap.get(file).scope; + } + + //SimulationDataSet each = processFileIntoSimulationDataSet(file, subscope); + Map eachMap = processNestedFileIntoSimulationDataSetMap(file, subscope); + + //out.put(file, each); + out.putAll(eachMap); + } + + return out; + } + } + + public static WreslTreeWalker parseMainFile(String inputFilePath) throws RecognitionException{ + + return parseMainFile(inputFilePath, false); + } + + public static WreslTreeWalker parseMainFile(String inputFilePath, boolean showTree) throws RecognitionException { + + + try { + stream = new ANTLRFileStream(inputFilePath, "UTF8"); + } + catch(Exception e) { + //e.printStackTrace(); + + LogUtils.errMsg("File not found: "+ inputFilePath); + LogUtils.closeLogFile(); + return null; + //System.exit(1); + + } + + WreslTreeLexer lexer = new WreslTreeLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + + WreslTreeParser parser = new WreslTreeParser(tokenStream); + + parser.currentAbsolutePath = new File(inputFilePath).getAbsolutePath(); + parser.currentAbsoluteParent = new File(inputFilePath).getAbsoluteFile().getParent(); + + LogUtils.importantMsg("Parsing file: "+parser.currentAbsolutePath); + + WreslTreeParser.mainFile_return parser_return = parser.mainFile(); + + // / check if sequence contains models not defined + ArrayList undefined_models = parser.model_in_sequence; + parser.model_in_sequence.removeAll(parser.model_list); + if (undefined_models.size()>0 ){ + LogUtils.errMsg("Sequence has undefined models: ", undefined_models); + } + + // / for debug info + parser.commonTree = (CommonTree) parser_return.getTree(); + if (showTree) LogUtils.importantMsg("tree = " + parser.commonTree.toStringTree()); + + // / feed walker with parser's tree output + CommonTreeNodeStream nodeStream = new CommonTreeNodeStream(parser_return.getTree()); + nodeStream.setTokenStream(tokenStream); // important trick to avoid null exception in tree walker + WreslTreeWalker walker = new WreslTreeWalker(nodeStream); + + walker.commonTree = parser.commonTree; + walker.currentAbsolutePath = parser.currentAbsolutePath; + walker.currentAbsoluteParent = parser.currentAbsoluteParent; + + if (showTree) LogUtils.importantMsg("Walking tree: "+parser.currentAbsolutePath); + + walker.evaluator(); + + return walker; + + } + + public static WreslTreeWalker parseOneFileForDebug(String inputFilePath) throws RecognitionException { + + + try { + stream = new ANTLRFileStream(inputFilePath, "UTF8"); + } + catch(Exception e) { + //e.printStackTrace(); + + System.out.println("File not found: "+ inputFilePath); + return null; + //System.exit(1); + + } + + WreslTreeLexer lexer = new WreslTreeLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + + WreslTreeParser parser = new WreslTreeParser(tokenStream); + + parser.currentAbsolutePath = new File(inputFilePath).getAbsolutePath(); + parser.currentAbsoluteParent = new File(inputFilePath).getAbsoluteFile().getParent(); + + //LogUtils.importantMsg("Parsing file: "+parser.currentAbsolutePath); + + WreslTreeParser.evaluator_return parser_evaluator = parser.evaluator(); + +// // / check if sequence contains models not defined +// ArrayList undefined_models = parser.model_in_sequence; +// parser.model_in_sequence.removeAll(parser.model_list); +// if (undefined_models.size()>0 ){ +// LogUtils.errMsg("Sequence has undefined models: ", undefined_models); +// } + + // / for debug info + parser.commonTree = (CommonTree) parser_evaluator.getTree(); + //if (showTree) LogUtils.importantMsg("tree = " + parser.commonTree.toStringTree()); + + // / feed walker with parser's tree output + CommonTreeNodeStream nodeStream = new CommonTreeNodeStream(parser_evaluator.getTree()); + nodeStream.setTokenStream(tokenStream); // important trick to avoid null exception in tree walker + WreslTreeWalker walker = new WreslTreeWalker(nodeStream); + + walker.commonTree = parser.commonTree; + walker.currentAbsolutePath = parser.currentAbsolutePath; + walker.currentAbsoluteParent = parser.currentAbsoluteParent; + + //if (showTree) LogUtils.importantMsg("Walking tree: "+parser.currentAbsolutePath); + + walker.evaluator(); + + return walker; + + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/IncludeFile.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/IncludeFile.java similarity index 93% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/IncludeFile.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/IncludeFile.java index 9081c7c8d..19b733aab 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/IncludeFile.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/IncludeFile.java @@ -1,45 +1,45 @@ -package wrimsv2.wreslparser.elements; - -import wrimsv2.commondata.wresldata.Param; - -public class IncludeFile { - - public String scope; - public String absFilePath; - public String fromWresl; - - public IncludeFile(){ - scope=Param.undefined; - fromWresl=Param.undefined; - - } - - public String equalEva(){ - - String temp = scope; - - return temp; - } - - @Override - public boolean equals(Object obj) - { - - if ((obj == null) || (obj.getClass() != this.getClass())) { - return false; - } - - else if (((IncludeFile) obj).equalEva() == null) { - return false; - } - - else if (this.equalEva() == ((IncludeFile) obj).equalEva()) { - return true; - } - - else { - return false; - } - } -} - +package wrimsv2.wreslparser.elements; + +import wrimsv2.commondata.wresldata.Param; + +public class IncludeFile { + + public String scope; + public String absFilePath; + public String fromWresl; + + public IncludeFile(){ + scope=Param.undefined; + fromWresl=Param.undefined; + + } + + public String equalEva(){ + + String temp = scope; + + return temp; + } + + @Override + public boolean equals(Object obj) + { + + if ((obj == null) || (obj.getClass() != this.getClass())) { + return false; + } + + else if (((IncludeFile) obj).equalEva() == null) { + return false; + } + + else if (this.equalEva() == ((IncludeFile) obj).equalEva()) { + return true; + } + + else { + return false; + } + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/LogUtils.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/LogUtils.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/LogUtils.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/LogUtils.java index ff16c9314..508dd66f2 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/LogUtils.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/LogUtils.java @@ -1,362 +1,362 @@ -package wrimsv2.wreslparser.elements; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.components.ControlData; - - - -public class LogUtils { - - public static PrintWriter _logFile; - - public static void closeLogFile(){ - - _logFile.close(); - } - - public static void setLogFile(String parentDir, String logFileName){ - - try { - _logFile = Tools.openFile(parentDir, logFileName); - - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - - public static void setLogFile(String logFileName){ - - try { - if (logFileName.contains(":")) { - _logFile = Tools.openFile(logFileName); - } else { - _logFile = Tools.openFile(System.getProperty("user.dir"), logFileName); - } - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - - public static void dvarsList(String msg, ArrayList list_all, ArrayList list_g, ArrayList list_l, Map dvMap){ - - String description = "Dvars"; - - LogUtils.importantMsg("------------------------------"); - LogUtils.importantMsg(msg+"Include total "+list_all.size()+" "+description+":"); - LogUtils.importantMsg(msg, list_all, dvMap); - LogUtils.importantMsg("------------------------------"); - LogUtils.importantMsg(msg+"Include total "+list_g.size()+" global "+description+":"); - LogUtils.importantMsg(msg, list_g, dvMap); - LogUtils.importantMsg("------------------------------"); - LogUtils.importantMsg(msg+"Include total "+list_l.size()+" local "+description+":"); - LogUtils.importantMsg(msg, list_l, dvMap); - LogUtils.importantMsg("------------------------------"); - - } - - public static void dvarsList(String msg, ArrayList list_all, Map dvMap){ - - String description = "Dvars"; - - LogUtils.importantMsg("------------------------------"); - LogUtils.importantMsg(msg+"Include total "+list_all.size()+" "+description+":"); - LogUtils.importantMsg(msg, list_all, dvMap); - LogUtils.importantMsg("------------------------------"); - - } - - public static void varsList(String msg, ArrayList list_all, ArrayList list_g, ArrayList list_l, String description){ - - LogUtils.importantMsg("------------------------------"); - LogUtils.importantMsg(msg+"Include total "+list_all.size()+" "+description+":"); - LogUtils.importantMsg(list_all); - LogUtils.importantMsg("------------------------------"); - LogUtils.importantMsg(msg+"Include total "+list_g.size()+" global "+description+":"); - LogUtils.importantMsg(list_g); - LogUtils.importantMsg("------------------------------"); - LogUtils.importantMsg(msg+"Include total "+list_l.size()+" local "+description+":"); - LogUtils.importantMsg(list_l); - LogUtils.importantMsg("------------------------------"); - - } - public static void varsList(String msg, ArrayList list_all, String description){ - - LogUtils.importantMsg("------------------------------"); - LogUtils.importantMsg(msg+"Include total "+list_all.size()+" "+description+":"); - LogUtils.importantMsg(list_all); - LogUtils.importantMsg("------------------------------"); - - } - - public static void seqList(ArrayList list, Map seqMap){ - - LogUtils.importantMsg("------------------------------"); - LogUtils.importantMsg("Include total "+list.size()+" sequences:"); - for (int i: seqMap.keySet()){ - LogUtils.importantMsg("Order: "+i+" Sequence: "+seqMap.get(i).sequenceName+" Model: "+seqMap.get(i).modelName); - } - LogUtils.importantMsg("------------------------------"); - - } - - public static void fileSummary(SimulationDataSet S){ - - //seqList(S.seqList, S.seqMap); - //varsList(S.model_list, "models"); - varsList("", S.incFileList, S.incFileList_global, S.incFileList_local, "files"); - varsList("", S.dvList, S.dvList_global, S.dvList_local, "Dvars"); - varsList("", S.svList, S.svList_global, S.svList_local, "Svars"); - - } - - public static void mainFileSummary(StudyConfig studyConfig){ - - - seqList(studyConfig.sequenceList, studyConfig.sequenceMap); - //varsList(mainDataSet.model_list, "models"); - - for (Integer i: studyConfig.sequenceMap.keySet()){ - String modelName = studyConfig.sequenceMap.get(i).modelName; - SimulationDataSet M = studyConfig.modelDataMap.get(modelName); - LogUtils.importantMsg("##### Model: "+ modelName); - varsList("", M.incFileList, M.incFileList_global, M.incFileList_local, "files"); - varsList("", M.dvList, M.dvList_global, M.dvList_local, "Dvars"); - varsList("", M.svList, M.svList_global, M.svList_local, "Svars"); - } - } - - public static void studySummary_details(StudyConfig studyConfig, Map modelDataMap){ - - seqList(studyConfig.sequenceList, studyConfig.sequenceMap); - - - for (String key: studyConfig.modelList){ - SimulationDataSet M = modelDataMap.get(key); - LogUtils.importantMsg("##### Model: "+ key); - - String msg = "Model "+key+" "; - varsList(msg, M.incFileList, M.incFileList_global, M.incFileList_local, "files"); - dvarsList(msg, M.dvList, M.dvList_global, M.dvList_local, M.dvMap); - varsList(msg, M.svList, M.svList_global, M.svList_local, "Svars"); - } - } - - public static void studySummary(StudyConfig studyConfig, Map modelDataMap){ - - seqList(studyConfig.sequenceList, studyConfig.sequenceMap); - - - for (String key: studyConfig.modelList){ - SimulationDataSet M = modelDataMap.get(key); - LogUtils.importantMsg("##### Model: "+ key); - - String msg = "Model "+key+" "; - varsList(msg, M.incFileList, M.incFileList_global, M.incFileList_local, "files"); - varsList(msg, M.dvList, M.dvList_global, M.dvList_local, "Dvars"); - varsList(msg, M.svList, M.svList_global, M.svList_local, "Svars"); - } - } - - public static void studySummary_details(StudyDataSet sd){ - - for (String key: sd.getModelList()){ - ModelDataSet M = sd.getModelDataSetMap().get(key); - LogUtils.importantMsg("##### Model: "+ key); - - String msg = "Model "+key+" "; - - dvarsList(msg, M.dvList, M.dvMap); - - } - } - - public static void titleMsg(String msg){ - - System.out.println("============================================"); - System.out.println(msg); - System.out.println("============================================"); - - _logFile.println("============================================"); - _logFile.println(msg); - _logFile.println("============================================"); - - _logFile.flush(); - } - - public static void parsingSummaryMsg(String msg, int errors){ - - System.out.println("============================================"); - System.out.println(msg); - System.out.println("Total errors: "+errors); - System.out.println("============================================"); - - _logFile.println("============================================"); - _logFile.println(msg); - _logFile.println("Total errors: "+errors); - _logFile.println("============================================"); - - _logFile.flush(); - } - - public static void criticalMsg(String msg){ - - System.out.println(msg); - _logFile.println(msg); - _logFile.flush(); - } - - public static void importantMsg(String msg){ - - if (ControlData.showWreslLog) System.out.println(msg); - _logFile.println(msg); - _logFile.flush(); - } - - public static void importantMsg(ArrayList msg){ - - for(String e: msg){ - importantMsg(e+"\n"); - } - } - - public static void importantMsg(String msg, ArrayList dvList, Map dvMap){ - - for(String e: dvList){ - importantMsg(msg + e + " kind: "+dvMap.get(e).kind +"\n"); - } - } - - public static void normalMsg(String msg){ - - if (Param.printLevel>1){ - - if (ControlData.showWreslLog) System.out.println(msg); - _logFile.println(msg); - - } - } - - public static void consoleMsgOnly(String msg){ - - if (ControlData.showWreslLog) System.out.println(msg); - - } - - public static void warningMsg(String msg){ - - StudyParser.total_warnings++; - - if (ControlData.showWreslLog) System.out.println("# Warning: "+msg); - _logFile.println("# Warning: "+msg); - _logFile.flush(); - - } - - public static void warningMsgLocation(String filePath, int lineNumber, String msg){ - - if (ControlData.showWreslLog) System.out.println( "("+filePath+":"+lineNumber+") "+msg ); - _logFile.println("# Warning: " + "("+filePath+":"+lineNumber+") "+msg ); - _logFile.flush(); - - } - - public static void typeRedefinedErrMsg(String msg) throws TypeRedefinedException { - - StudyParser.total_errors++; - - if (ControlData.showWreslLog) System.out.println("# Error: "+msg); - _logFile.println("# Error: "+msg); - _logFile.flush(); - - throw new TypeRedefinedException(); - //if (!Param.debug) System.exit(0); - } - - public static void errMsgLocation(String filePath, int lineNumber, String msg){ - - StudyParser.total_errors++; - StudyParser.error_summary.add("# Error: ("+filePath+":"+lineNumber+") "+msg ); - if (ControlData.showWreslLog) System.err.println( "# Error: ("+filePath+":"+lineNumber+") "+msg ); - _logFile.println("# Error: " + "("+filePath+":"+lineNumber+") "+msg ); - _logFile.flush(); - - } - - public static void errMsg(String msg){ - - StudyParser.total_errors++; - - if (ControlData.showWreslLog) System.err.println("# Error: "+msg); - _logFile.println("# Error: "+msg); - _logFile.flush(); - - } - - public static void errMsg(String msg, ArrayList list){ - - for (String e: list){ - errMsg(msg+e); - } - - } - - public static void errMsg(String msg, String file){ - - errMsg(msg+" in file: "+file); - - } - - public static void errMsg(String msg, String file1, String file2, Map> reverseMap) { - - errMsg(msg + " in files: "); - - String sp = " "; - if (ControlData.showWreslLog) System.out.println(sp + file1); - _logFile.println(sp + file1); - printTree(file1, reverseMap, sp); - if (ControlData.showWreslLog) System.out.println(sp + file2); - _logFile.println(sp + file2); - printTree(file2, reverseMap, sp); - - _logFile.flush(); - - } - - private static void printTree(String f, Map> reverseMap, String level) { - - // String arrow = ">"; - if (reverseMap.get(f) != null) { - level = level + "--"; - Set parents = reverseMap.get(f); - for (String s : parents) { - if (ControlData.showWreslLog) System.out.println(" "+level + "> "+ s); - _logFile.println(" "+level + "> "+ s); - - printTree(s, reverseMap, level); - - } - - } - - - } - - - - - -} - +package wrimsv2.wreslparser.elements; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.components.ControlData; + + + +public class LogUtils { + + public static PrintWriter _logFile; + + public static void closeLogFile(){ + + _logFile.close(); + } + + public static void setLogFile(String parentDir, String logFileName){ + + try { + _logFile = Tools.openFile(parentDir, logFileName); + + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + public static void setLogFile(String logFileName){ + + try { + if (logFileName.contains(":")) { + _logFile = Tools.openFile(logFileName); + } else { + _logFile = Tools.openFile(System.getProperty("user.dir"), logFileName); + } + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + public static void dvarsList(String msg, ArrayList list_all, ArrayList list_g, ArrayList list_l, Map dvMap){ + + String description = "Dvars"; + + LogUtils.importantMsg("------------------------------"); + LogUtils.importantMsg(msg+"Include total "+list_all.size()+" "+description+":"); + LogUtils.importantMsg(msg, list_all, dvMap); + LogUtils.importantMsg("------------------------------"); + LogUtils.importantMsg(msg+"Include total "+list_g.size()+" global "+description+":"); + LogUtils.importantMsg(msg, list_g, dvMap); + LogUtils.importantMsg("------------------------------"); + LogUtils.importantMsg(msg+"Include total "+list_l.size()+" local "+description+":"); + LogUtils.importantMsg(msg, list_l, dvMap); + LogUtils.importantMsg("------------------------------"); + + } + + public static void dvarsList(String msg, ArrayList list_all, Map dvMap){ + + String description = "Dvars"; + + LogUtils.importantMsg("------------------------------"); + LogUtils.importantMsg(msg+"Include total "+list_all.size()+" "+description+":"); + LogUtils.importantMsg(msg, list_all, dvMap); + LogUtils.importantMsg("------------------------------"); + + } + + public static void varsList(String msg, ArrayList list_all, ArrayList list_g, ArrayList list_l, String description){ + + LogUtils.importantMsg("------------------------------"); + LogUtils.importantMsg(msg+"Include total "+list_all.size()+" "+description+":"); + LogUtils.importantMsg(list_all); + LogUtils.importantMsg("------------------------------"); + LogUtils.importantMsg(msg+"Include total "+list_g.size()+" global "+description+":"); + LogUtils.importantMsg(list_g); + LogUtils.importantMsg("------------------------------"); + LogUtils.importantMsg(msg+"Include total "+list_l.size()+" local "+description+":"); + LogUtils.importantMsg(list_l); + LogUtils.importantMsg("------------------------------"); + + } + public static void varsList(String msg, ArrayList list_all, String description){ + + LogUtils.importantMsg("------------------------------"); + LogUtils.importantMsg(msg+"Include total "+list_all.size()+" "+description+":"); + LogUtils.importantMsg(list_all); + LogUtils.importantMsg("------------------------------"); + + } + + public static void seqList(ArrayList list, Map seqMap){ + + LogUtils.importantMsg("------------------------------"); + LogUtils.importantMsg("Include total "+list.size()+" sequences:"); + for (int i: seqMap.keySet()){ + LogUtils.importantMsg("Order: "+i+" Sequence: "+seqMap.get(i).sequenceName+" Model: "+seqMap.get(i).modelName); + } + LogUtils.importantMsg("------------------------------"); + + } + + public static void fileSummary(SimulationDataSet S){ + + //seqList(S.seqList, S.seqMap); + //varsList(S.model_list, "models"); + varsList("", S.incFileList, S.incFileList_global, S.incFileList_local, "files"); + varsList("", S.dvList, S.dvList_global, S.dvList_local, "Dvars"); + varsList("", S.svList, S.svList_global, S.svList_local, "Svars"); + + } + + public static void mainFileSummary(StudyConfig studyConfig){ + + + seqList(studyConfig.sequenceList, studyConfig.sequenceMap); + //varsList(mainDataSet.model_list, "models"); + + for (Integer i: studyConfig.sequenceMap.keySet()){ + String modelName = studyConfig.sequenceMap.get(i).modelName; + SimulationDataSet M = studyConfig.modelDataMap.get(modelName); + LogUtils.importantMsg("##### Model: "+ modelName); + varsList("", M.incFileList, M.incFileList_global, M.incFileList_local, "files"); + varsList("", M.dvList, M.dvList_global, M.dvList_local, "Dvars"); + varsList("", M.svList, M.svList_global, M.svList_local, "Svars"); + } + } + + public static void studySummary_details(StudyConfig studyConfig, Map modelDataMap){ + + seqList(studyConfig.sequenceList, studyConfig.sequenceMap); + + + for (String key: studyConfig.modelList){ + SimulationDataSet M = modelDataMap.get(key); + LogUtils.importantMsg("##### Model: "+ key); + + String msg = "Model "+key+" "; + varsList(msg, M.incFileList, M.incFileList_global, M.incFileList_local, "files"); + dvarsList(msg, M.dvList, M.dvList_global, M.dvList_local, M.dvMap); + varsList(msg, M.svList, M.svList_global, M.svList_local, "Svars"); + } + } + + public static void studySummary(StudyConfig studyConfig, Map modelDataMap){ + + seqList(studyConfig.sequenceList, studyConfig.sequenceMap); + + + for (String key: studyConfig.modelList){ + SimulationDataSet M = modelDataMap.get(key); + LogUtils.importantMsg("##### Model: "+ key); + + String msg = "Model "+key+" "; + varsList(msg, M.incFileList, M.incFileList_global, M.incFileList_local, "files"); + varsList(msg, M.dvList, M.dvList_global, M.dvList_local, "Dvars"); + varsList(msg, M.svList, M.svList_global, M.svList_local, "Svars"); + } + } + + public static void studySummary_details(StudyDataSet sd){ + + for (String key: sd.getModelList()){ + ModelDataSet M = sd.getModelDataSetMap().get(key); + LogUtils.importantMsg("##### Model: "+ key); + + String msg = "Model "+key+" "; + + dvarsList(msg, M.dvList, M.dvMap); + + } + } + + public static void titleMsg(String msg){ + + System.out.println("============================================"); + System.out.println(msg); + System.out.println("============================================"); + + _logFile.println("============================================"); + _logFile.println(msg); + _logFile.println("============================================"); + + _logFile.flush(); + } + + public static void parsingSummaryMsg(String msg, int errors){ + + System.out.println("============================================"); + System.out.println(msg); + System.out.println("Total errors: "+errors); + System.out.println("============================================"); + + _logFile.println("============================================"); + _logFile.println(msg); + _logFile.println("Total errors: "+errors); + _logFile.println("============================================"); + + _logFile.flush(); + } + + public static void criticalMsg(String msg){ + + System.out.println(msg); + _logFile.println(msg); + _logFile.flush(); + } + + public static void importantMsg(String msg){ + + if (ControlData.showWreslLog) System.out.println(msg); + _logFile.println(msg); + _logFile.flush(); + } + + public static void importantMsg(ArrayList msg){ + + for(String e: msg){ + importantMsg(e+"\n"); + } + } + + public static void importantMsg(String msg, ArrayList dvList, Map dvMap){ + + for(String e: dvList){ + importantMsg(msg + e + " kind: "+dvMap.get(e).kind +"\n"); + } + } + + public static void normalMsg(String msg){ + + if (Param.printLevel>1){ + + if (ControlData.showWreslLog) System.out.println(msg); + _logFile.println(msg); + + } + } + + public static void consoleMsgOnly(String msg){ + + if (ControlData.showWreslLog) System.out.println(msg); + + } + + public static void warningMsg(String msg){ + + StudyParser.total_warnings++; + + if (ControlData.showWreslLog) System.out.println("# Warning: "+msg); + _logFile.println("# Warning: "+msg); + _logFile.flush(); + + } + + public static void warningMsgLocation(String filePath, int lineNumber, String msg){ + + if (ControlData.showWreslLog) System.out.println( "("+filePath+":"+lineNumber+") "+msg ); + _logFile.println("# Warning: " + "("+filePath+":"+lineNumber+") "+msg ); + _logFile.flush(); + + } + + public static void typeRedefinedErrMsg(String msg) throws TypeRedefinedException { + + StudyParser.total_errors++; + + if (ControlData.showWreslLog) System.out.println("# Error: "+msg); + _logFile.println("# Error: "+msg); + _logFile.flush(); + + throw new TypeRedefinedException(); + //if (!Param.debug) System.exit(0); + } + + public static void errMsgLocation(String filePath, int lineNumber, String msg){ + + StudyParser.total_errors++; + StudyParser.error_summary.add("# Error: ("+filePath+":"+lineNumber+") "+msg ); + if (ControlData.showWreslLog) System.err.println( "# Error: ("+filePath+":"+lineNumber+") "+msg ); + _logFile.println("# Error: " + "("+filePath+":"+lineNumber+") "+msg ); + _logFile.flush(); + + } + + public static void errMsg(String msg){ + + StudyParser.total_errors++; + + if (ControlData.showWreslLog) System.err.println("# Error: "+msg); + _logFile.println("# Error: "+msg); + _logFile.flush(); + + } + + public static void errMsg(String msg, ArrayList list){ + + for (String e: list){ + errMsg(msg+e); + } + + } + + public static void errMsg(String msg, String file){ + + errMsg(msg+" in file: "+file); + + } + + public static void errMsg(String msg, String file1, String file2, Map> reverseMap) { + + errMsg(msg + " in files: "); + + String sp = " "; + if (ControlData.showWreslLog) System.out.println(sp + file1); + _logFile.println(sp + file1); + printTree(file1, reverseMap, sp); + if (ControlData.showWreslLog) System.out.println(sp + file2); + _logFile.println(sp + file2); + printTree(file2, reverseMap, sp); + + _logFile.flush(); + + } + + private static void printTree(String f, Map> reverseMap, String level) { + + // String arrow = ">"; + if (reverseMap.get(f) != null) { + level = level + "--"; + Set parents = reverseMap.get(f); + for (String s : parents) { + if (ControlData.showWreslLog) System.out.println(" "+level + "> "+ s); + _logFile.println(" "+level + "> "+ s); + + printTree(s, reverseMap, level); + + } + + } + + + } + + + + + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/PathUtils.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/PathUtils.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/PathUtils.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/PathUtils.java index 54db9899c..ad3493e6e 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/PathUtils.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/PathUtils.java @@ -1,72 +1,72 @@ -package wrimsv2.wreslparser.elements; - -public class PathUtils { - - private PathUtils() { - - } - - public static String findRelativePath(String referencePath, String targetPath) { - - // Thanks to Peter Morris - StringBuilder relativePath = null; - - referencePath = referencePath.replaceAll("\\\\", "/"); - targetPath = targetPath.replaceAll("\\\\", "/"); - - if (referencePath.equalsIgnoreCase(targetPath)) { - - } - else { - String[] absoluteDirectories = referencePath.split("/"); - String[] relativeDirectories = targetPath.split("/"); - - // Get the shortest of the two paths - int length = absoluteDirectories.length < relativeDirectories.length ? absoluteDirectories.length - : relativeDirectories.length; - - // Use to determine where in the loop we exited - int lastCommonRoot = -1; - int index; - - // Find common root - for (index = 0; index < length; index++) { - if (absoluteDirectories[index].equalsIgnoreCase(relativeDirectories[index])) { - lastCommonRoot = index; - } - else { - break; - // If we didn't find a common prefix then throw - } - } - if (lastCommonRoot != -1) { - // Build up the relative path - relativePath = new StringBuilder(); - // Add on the .. - for (index = lastCommonRoot + 1; index < absoluteDirectories.length; index++) { - if (absoluteDirectories[index].length() > 0) { - relativePath.append("../"); - } - } - for (index = lastCommonRoot + 1; index < relativeDirectories.length - 1; index++) { - relativePath.append(relativeDirectories[index] + "/"); - } - relativePath.append(relativeDirectories[relativeDirectories.length - 1]); - } - } - - if (relativePath == null) { - return null; - } - else { - String result = relativePath.toString(); - - // convert to windows style separator - result = result.replaceAll("/", "\\\\"); - - return result; - } - - } - +package wrimsv2.wreslparser.elements; + +public class PathUtils { + + private PathUtils() { + + } + + public static String findRelativePath(String referencePath, String targetPath) { + + // Thanks to Peter Morris + StringBuilder relativePath = null; + + referencePath = referencePath.replaceAll("\\\\", "/"); + targetPath = targetPath.replaceAll("\\\\", "/"); + + if (referencePath.equalsIgnoreCase(targetPath)) { + + } + else { + String[] absoluteDirectories = referencePath.split("/"); + String[] relativeDirectories = targetPath.split("/"); + + // Get the shortest of the two paths + int length = absoluteDirectories.length < relativeDirectories.length ? absoluteDirectories.length + : relativeDirectories.length; + + // Use to determine where in the loop we exited + int lastCommonRoot = -1; + int index; + + // Find common root + for (index = 0; index < length; index++) { + if (absoluteDirectories[index].equalsIgnoreCase(relativeDirectories[index])) { + lastCommonRoot = index; + } + else { + break; + // If we didn't find a common prefix then throw + } + } + if (lastCommonRoot != -1) { + // Build up the relative path + relativePath = new StringBuilder(); + // Add on the .. + for (index = lastCommonRoot + 1; index < absoluteDirectories.length; index++) { + if (absoluteDirectories[index].length() > 0) { + relativePath.append("../"); + } + } + for (index = lastCommonRoot + 1; index < relativeDirectories.length - 1; index++) { + relativePath.append(relativeDirectories[index] + "/"); + } + relativePath.append(relativeDirectories[relativeDirectories.length - 1]); + } + } + + if (relativePath == null) { + return null; + } + else { + String result = relativePath.toString(); + + // convert to windows style separator + result = result.replaceAll("/", "\\\\"); + + return result; + } + + } + } \ No newline at end of file diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/RegUtils.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/RegUtils.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/RegUtils.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/RegUtils.java index 31988efa3..601925179 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/RegUtils.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/RegUtils.java @@ -1,64 +1,64 @@ -package wrimsv2.wreslparser.elements; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class RegUtils { - - - public static String getLastMatch(String inputStr, String patternStr) { - - // String patternStr = "([a-zA-Z]+[0-9]+)"; - String output = null; - - int total = 0; - // Compile regular expression - Pattern pattern = Pattern.compile(patternStr); - Matcher matcher = pattern.matcher(inputStr); - - // Count all occurrences of pattern in input - while (matcher.find()) { - - total = total + 1; - output = matcher.group(); - } - return output; - } - - - - - public static String replaceWith(String inputStr, String patternStr, String replaceStr ) { - - - // Compile regular expression - Pattern pattern = Pattern.compile(patternStr); - - // Replace all occurrences of pattern in input - Matcher matcher = pattern.matcher(inputStr); - String output = matcher.replaceAll(replaceStr); - - return output; - - } - - public static int timesOfMatches(String inputStr, String patternStr) - { - //String patternStr = "([a-zA-Z]+[0-9]+)"; - - int total = 0; - // Compile regular expression - Pattern pattern = Pattern.compile(patternStr); - Matcher matcher = pattern.matcher(inputStr); - - // Count all occurrences of pattern in input - while (matcher.find()) { - - total = total +1; - } - - return total; - } - - -} +package wrimsv2.wreslparser.elements; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class RegUtils { + + + public static String getLastMatch(String inputStr, String patternStr) { + + // String patternStr = "([a-zA-Z]+[0-9]+)"; + String output = null; + + int total = 0; + // Compile regular expression + Pattern pattern = Pattern.compile(patternStr); + Matcher matcher = pattern.matcher(inputStr); + + // Count all occurrences of pattern in input + while (matcher.find()) { + + total = total + 1; + output = matcher.group(); + } + return output; + } + + + + + public static String replaceWith(String inputStr, String patternStr, String replaceStr ) { + + + // Compile regular expression + Pattern pattern = Pattern.compile(patternStr); + + // Replace all occurrences of pattern in input + Matcher matcher = pattern.matcher(inputStr); + String output = matcher.replaceAll(replaceStr); + + return output; + + } + + public static int timesOfMatches(String inputStr, String patternStr) + { + //String patternStr = "([a-zA-Z]+[0-9]+)"; + + int total = 0; + // Compile regular expression + Pattern pattern = Pattern.compile(patternStr); + Matcher matcher = pattern.matcher(inputStr); + + // Count all occurrences of pattern in input + while (matcher.find()) { + + total = total +1; + } + + return total; + } + + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Sequence.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/Sequence.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Sequence.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/Sequence.java index 7dab67315..fca0e8f07 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Sequence.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/Sequence.java @@ -1,52 +1,52 @@ -package wrimsv2.wreslparser.elements; - -import wrimsv2.commondata.wresldata.Param; - -public class Sequence { - - public String sequenceName; - public String modelName; - public String condition; - public String fromWresl; - public String timeStep; - - public Sequence(){ - sequenceName=Param.undefined; - modelName=Param.undefined; - condition=Param.always; - fromWresl = Param.undefined; - timeStep = Param.undefined; - } - - public String equalEva(){ - - String s = "|"; - - - String temp = sequenceName+s+modelName+s+condition+s+timeStep; - - return temp; - } - - @Override - public boolean equals(Object obj) - { - - if ((obj == null) || (obj.getClass() != this.getClass())) { - return false; - } - - else if (((Sequence) obj).equalEva() == null) { - return false; - } - - else if (this.equalEva() == ((Sequence) obj).equalEva()) { - return true; - } - - else { - return false; - } - } -} - +package wrimsv2.wreslparser.elements; + +import wrimsv2.commondata.wresldata.Param; + +public class Sequence { + + public String sequenceName; + public String modelName; + public String condition; + public String fromWresl; + public String timeStep; + + public Sequence(){ + sequenceName=Param.undefined; + modelName=Param.undefined; + condition=Param.always; + fromWresl = Param.undefined; + timeStep = Param.undefined; + } + + public String equalEva(){ + + String s = "|"; + + + String temp = sequenceName+s+modelName+s+condition+s+timeStep; + + return temp; + } + + @Override + public boolean equals(Object obj) + { + + if ((obj == null) || (obj.getClass() != this.getClass())) { + return false; + } + + else if (((Sequence) obj).equalEva() == null) { + return false; + } + + else if (this.equalEva() == ((Sequence) obj).equalEva()) { + return true; + } + + else { + return false; + } + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/SimulationDataSet.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/SimulationDataSet.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/SimulationDataSet.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/SimulationDataSet.java index cbcd13e79..165f4830a 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/SimulationDataSet.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/SimulationDataSet.java @@ -1,1154 +1,1154 @@ -package wrimsv2.wreslparser.elements; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.External; -import wrimsv2.commondata.wresldata.Goal; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.commondata.wresldata.Timeseries; -import wrimsv2.commondata.wresldata.WeightElement; - -public class SimulationDataSet -{ - public String currentAbsolutePath; - public String currentAbsoluteParent; - - public ArrayList model_list = new ArrayList(); - public ArrayList error_model_redefined = new ArrayList(); - - public ArrayList error_sequence_redefined = new ArrayList(); - public ArrayList error_sequence_order_redefined = new ArrayList(); - - public Map seqMap = new HashMap(); - public ArrayList seqList = new ArrayList(); - - public Set wtSet = new LinkedHashSet(); - public Set wtSet_global = new LinkedHashSet(); - public Set wtSet_local = new LinkedHashSet(); - public ArrayList wtList = new ArrayList(); - public ArrayList wtList_global = new ArrayList(); - public ArrayList wtList_local = new ArrayList(); - public Map wtMap = new HashMap(); - public Map error_weightVar_redefined = new HashMap(); - - public Set incFileSet = new LinkedHashSet(); - public Set incFileSet_global = new LinkedHashSet(); - public Set incFileSet_local = new LinkedHashSet(); - public ArrayList incFileList = new ArrayList(); - public ArrayList incFileList_global = new ArrayList(); - public ArrayList incFileList_local = new ArrayList(); - public Map incFileMap = new HashMap(); - public ArrayList error_includeFile_redefined = new ArrayList(); - - public ArrayList ordered_list_including_files = new ArrayList(); - public ArrayList ordered_list = new ArrayList(); - - public ArrayList ordered_list_including_files_global = new ArrayList(); - public ArrayList ordered_list_global = new ArrayList(); - - public Map var_all = new HashMap(); - public Map error_var_redefined = new HashMap(); - - public Set exSet = new LinkedHashSet(); - public Set exSet_global = new LinkedHashSet(); - public Set exSet_local = new LinkedHashSet(); - public ArrayList exList = new ArrayList(); - public ArrayList exList_global = new ArrayList(); - public ArrayList exList_local = new ArrayList(); - public Map exMap = new HashMap(); - - public Set tsSet = new LinkedHashSet(); - public Set tsSet_global = new LinkedHashSet(); - public Set tsSet_local = new LinkedHashSet(); - public ArrayList tsList = new ArrayList(); - public ArrayList tsList_global = new ArrayList(); - public ArrayList tsList_local = new ArrayList(); - public Map tsMap = new HashMap(); - - public Set svSet_unknown = new LinkedHashSet(); - public Set svSet = new LinkedHashSet(); - public Set svSet_global = new LinkedHashSet(); - public Set svSet_local = new LinkedHashSet(); - public ArrayList svList = new ArrayList(); - public ArrayList svList_global = new ArrayList(); - public ArrayList svList_local = new ArrayList(); - public Map svMap = new HashMap(); - - public Set dvSet = new LinkedHashSet(); - public Set dvSet_global = new LinkedHashSet(); - public Set dvSet_local = new LinkedHashSet(); - public ArrayList dvList = new ArrayList(); - public ArrayList dvList_global = new ArrayList(); - public ArrayList dvList_local = new ArrayList(); - public Map dvMap = new HashMap(); - - public Set asSet_unknown = new LinkedHashSet(); - public Set asSet = new LinkedHashSet(); - public Set asSet_global = new LinkedHashSet(); - public Set asSet_local = new LinkedHashSet(); - public ArrayList asList = new ArrayList(); - public ArrayList asList_global = new ArrayList(); - public ArrayList asList_local = new ArrayList(); - public Map asMap = new HashMap(); - - public Set gSet = new LinkedHashSet(); - public Set gSet_global = new LinkedHashSet(); - public Set gSet_local = new LinkedHashSet(); - public ArrayList gList = new ArrayList(); - public ArrayList gList_global = new ArrayList(); - public ArrayList gList_local = new ArrayList(); - public Map gMap = new HashMap(); - - public Set varNeedEarlierCycle = new LinkedHashSet(); - public Map> var_neededVarCycle_map = new HashMap>(); - - - public SimulationDataSet() - { - - } - - /// warning: this is partial copy - public SimulationDataSet(SimulationDataSet s) - { - this.overwrittenWith_set(s); - - } - - public SimulationDataSet overwrittenWith(SimulationDataSet s) - { - remove(s); - add(s); - return this; - } - - public SimulationDataSet overwrite(SimulationDataSet s) - { - SimulationDataSet p = new SimulationDataSet(s); - p.remove(this); - add(p); - return this; - } - - public boolean hasDuplicateIn(SimulationDataSet s, String filePath, Map> reverseMap) - { - boolean b = false; - - if (s == null) System.out.println("Fatal error!!! SimulationDataSet is null in file: " + filePath); - - for (String e : s.wtList) { - if (this.wtList.contains(e)) { - String f1 = ((WeightElement)s.wtMap.get(e)).fromWresl; - String f2 = ((WeightElement)this.wtMap.get(e)).fromWresl; - LogUtils.errMsg("Weight table variable redefined: " + e, f1, f2, reverseMap); - b = true; - } - } - - for (String e : s.incFileList) { - if (!this.incFileList.contains(e)) { - continue; - } - String f1 = ((IncludeFile)s.incFileMap.get(e)).fromWresl; - String f2 = ((IncludeFile)this.incFileMap.get(e)).fromWresl; - LogUtils.errMsg("Include file redefined: " + e, f1, f2, reverseMap); - b = true; - } - - for (String e : s.tsList) { - if (this.tsList.contains(e)) { - String f1 = ((Timeseries)s.tsMap.get(e)).fromWresl; - String f2 = ((Timeseries)this.tsMap.get(e)).fromWresl; - LogUtils.errMsg("State variable redefined: " + e, f1, f2, reverseMap); - b = true; - } - } - - for (String e : s.svList) { - if (this.svList.contains(e)) { - String f1 = ((Svar)s.svMap.get(e)).fromWresl; - String f2 = ((Svar)this.svMap.get(e)).fromWresl; - LogUtils.errMsg("State variable redefined: " + e, f1, f2, reverseMap); - b = true; - } - } - - for (String e : s.dvList) { - if (this.dvList.contains(e)) { - String f1 = ((Dvar)s.dvMap.get(e)).fromWresl; - String f2 = ((Dvar)this.dvMap.get(e)).fromWresl; - LogUtils.errMsg("Decision varriable redefined: " + e, f1, f2, reverseMap); - b = true; - } - } - - for (String e : s.gList) { - if (this.gList.contains(e)) { - String f1 = ((Goal)s.gMap.get(e)).fromWresl; - String f2 = ((Goal)this.gMap.get(e)).fromWresl; - LogUtils.errMsg("Goal redefined: " + e, f1, f2, reverseMap); - b = true; - } - } - - for (String e : s.asList) { - if (this.asList.contains(e)) { - String f1 = ((Alias)s.asMap.get(e)).fromWresl; - String f2 = ((Alias)this.asMap.get(e)).fromWresl; - LogUtils.errMsg("Alias redefined: " + e, f1, f2, reverseMap); - b = true; - } - } - - for (String e : s.model_list) { - if (!this.model_list.contains(e)) - continue; - LogUtils.errMsg("Error!!! Model redefined: " + e + " in file: " + filePath); - b = true; - } - - for (String e : s.seqList) { - if (!this.seqList.contains(e)) - continue; - LogUtils.errMsg("Error!!! Sequence redefined: " + e + " in file: " + filePath); - b = true; - } - - return b; - } - - public SimulationDataSet convertToLocal() - { - if (!this.wtList.isEmpty()) { - this.wtList_local = new ArrayList(); - this.wtList_local.addAll(this.wtList); - this.wtList_global = new ArrayList(); - } - - if (!this.incFileList.isEmpty()) { - this.incFileList_local = new ArrayList(); - this.incFileList_local.addAll(this.incFileList); - this.incFileList_global = new ArrayList(); - } - - if (!this.tsList.isEmpty()) { - this.tsList_local = new ArrayList(); - this.tsList_local.addAll(this.tsList); - this.tsList_global = new ArrayList(); - } - - if (!this.svList.isEmpty()) { - this.svList_local = new ArrayList(); - this.svList_local.addAll(this.svList); - this.svList_global = new ArrayList(); - } - - if (!this.dvList.isEmpty()) { - this.dvList_local = new ArrayList(); - this.dvList_local.addAll(this.dvList); - this.dvList_global = new ArrayList(); - } - if (!this.asList.isEmpty()) { - this.asList_local = new ArrayList(); - this.asList_local.addAll(this.asList); - this.asList_global = new ArrayList(); - } - - if (!this.gList.isEmpty()) { - this.gList_local = new ArrayList(); - this.gList_local.addAll(this.gList); - this.gList_global = new ArrayList(); - } - - return this; - } - - public SimulationDataSet getGlobalVars() - { - SimulationDataSet out = new SimulationDataSet(); - - if (!this.wtList_global.isEmpty()) { - out.wtList.addAll(this.wtList_global); - out.wtList_global.addAll(this.wtList_global); - - for (String key : this.wtList_global) { - out.wtMap.put(key, (WeightElement)this.wtMap.get(key)); - } - } - - if (!this.incFileList_global.isEmpty()) { - out.incFileList.addAll(this.incFileList_global); - out.incFileList_global.addAll(this.incFileList_global); - - for (String key : this.incFileList_global) { - out.incFileMap.put(key, (IncludeFile)this.incFileMap.get(key)); - } - } - - if (!this.exList_global.isEmpty()) { - out.exList.addAll(this.exList_global); - out.exList_global.addAll(this.exList_global); - - for (String key : this.exList_global) { - out.exMap.put(key, (External)this.exMap.get(key)); - } - } - - if (!this.tsList_global.isEmpty()) { - out.tsList.addAll(this.tsList_global); - out.tsList_global.addAll(this.tsList_global); - - for (String key : this.tsList_global) { - out.tsMap.put(key, (Timeseries)this.tsMap.get(key)); - } - } - - if (!this.svList_global.isEmpty()) { - out.svList.addAll(this.svList_global); - out.svList_global.addAll(this.svList_global); - - for (String key : this.svList_global) { - out.svMap.put(key, (Svar)this.svMap.get(key)); - } - } - - if (!this.dvList_global.isEmpty()) { - out.dvList.addAll(this.dvList_global); - out.dvList_global.addAll(this.dvList_global); - - for (String key : this.dvList_global) { - out.dvMap.put(key, (Dvar)this.dvMap.get(key)); - } - } - - if (!this.gList_global.isEmpty()) { - out.gList.addAll(this.gList_global); - out.gList_global.addAll(this.gList_global); - - for (String key : this.gList_global) { - out.gMap.put(key, (Goal)this.gMap.get(key)); - } - - } - - if (!this.varNeedEarlierCycle.isEmpty()) { - out.varNeedEarlierCycle.addAll(this.varNeedEarlierCycle); - out.varNeedEarlierCycle.retainAll(out.svList_global); - out.varNeedEarlierCycle.retainAll(out.asList_global); - - for (String key : out.varNeedEarlierCycle) { - out.var_neededVarCycle_map.put(key, this.var_neededVarCycle_map.get(key)); - } - - } - - return out; - } - - public SimulationDataSet remove(SimulationDataSet s) - { - if (!s.wtList.isEmpty()) { - this.wtList.removeAll(s.wtList); - this.wtList_global.removeAll(s.wtList); - this.wtList_local.removeAll(s.wtList); - - Tools.mapRemoveAll(this.wtMap, s.wtList); - } - - if (!s.incFileList.isEmpty()) { - this.incFileList.removeAll(s.incFileList); - this.incFileList_global.removeAll(s.incFileList); - this.incFileList_local.removeAll(s.incFileList); - - Tools.mapRemoveAll(this.incFileMap, s.incFileList); - } - - if (!s.exList.isEmpty()) { - this.exList.removeAll(s.exList); - if (!s.exList_global.isEmpty()) this.exList_global.removeAll(s.exList); - if (!s.exList_local.isEmpty()) this.exList_local.removeAll(s.exList); - - Tools.mapRemoveAll(this.exMap, s.exList); - } - - if (!s.tsList.isEmpty()) { - this.tsList.removeAll(s.tsList); - if (!s.tsList_global.isEmpty()) this.tsList_global.removeAll(s.tsList); - if (!s.tsList_local.isEmpty()) this.tsList_local.removeAll(s.tsList); - - Tools.mapRemoveAll(this.tsMap, s.tsList); - } - - if (!s.svList.isEmpty()) { - this.svList.removeAll(s.svList); - if (!s.svList_global.isEmpty()) this.svList_global.removeAll(s.svList); - if (!s.svList_local.isEmpty()) this.svList_local.removeAll(s.svList); - - Tools.mapRemoveAll(this.svMap, s.svList); - } - - if (!s.dvList.isEmpty()) { - this.dvList.removeAll(s.dvList); - if (!s.dvList_global.isEmpty()) this.dvList_global.removeAll(s.dvList); - if (!s.dvList_local.isEmpty()) this.dvList_local.removeAll(s.dvList); - - Tools.mapRemoveAll(this.dvMap, s.dvList); - } - if (!s.asList.isEmpty()) { - this.asList.removeAll(s.gList); - if (!s.asList_global.isEmpty()) this.asList_global.removeAll(s.asList); - if (!s.asList_local.isEmpty()) this.asList_local.removeAll(s.asList); - - Tools.mapRemoveAll(this.asMap, s.asList); - } - - if (!s.gList.isEmpty()) { - this.gList.removeAll(s.gList); - if (!s.gList_global.isEmpty()) this.gList_global.removeAll(s.gList); - if (!s.gList_local.isEmpty()) this.gList_local.removeAll(s.gList); - - Tools.mapRemoveAll(this.gMap, s.gList); - } - - if (!s.varNeedEarlierCycle.isEmpty()) { - this.varNeedEarlierCycle.removeAll(s.varNeedEarlierCycle); - - Tools.mapRemoveAll(this.var_neededVarCycle_map, s.varNeedEarlierCycle); - } - - if (!s.model_list.isEmpty()) { - this.model_list.removeAll(s.model_list); - } - - return this; - } - - public SimulationDataSet add(SimulationDataSet s) - { - if (!s.wtList.isEmpty()) { - this.wtList.addAll(s.wtList); - if (!s.wtList_global.isEmpty()) this.wtList_global.addAll(s.wtList_global); - if (!s.wtList_local.isEmpty()) this.wtList_local.addAll(s.wtList_local); - this.wtMap.putAll(s.wtMap); - } - - if (!s.incFileList.isEmpty()) { - this.incFileList.addAll(s.incFileList); - if (!s.incFileList_global.isEmpty()) this.incFileList_global.addAll(s.incFileList_global); - if (!s.incFileList_local.isEmpty()) this.incFileList_local.addAll(s.incFileList_local); - this.incFileMap.putAll(s.incFileMap); - } - - if (!s.exList.isEmpty()) { - this.exList.addAll(s.exList); - if (!s.exList_global.isEmpty()) this.exList_global.addAll(s.exList_global); - if (!s.exList_local.isEmpty()) this.exList_local.addAll(s.exList_local); - this.exMap.putAll(s.exMap); - } - - if (!s.tsList.isEmpty()) { - this.tsList.addAll(0, s.tsList); - if (!s.tsList_global.isEmpty()) this.tsList_global.addAll(s.tsList_global); - if (!s.tsList_local.isEmpty()) this.tsList_local.addAll(s.tsList_local); - this.tsMap.putAll(s.tsMap); - } - - if (!s.svList.isEmpty()) { - this.svList.addAll(s.svList); - if (!s.svList_global.isEmpty()) this.svList_global.addAll(s.svList_global); - if (!s.svList_local.isEmpty()) this.svList_local.addAll(s.svList_local); - this.svMap.putAll(s.svMap); - } - - if (!s.dvList.isEmpty()) { - this.dvList.addAll(s.dvList); - if (!s.dvList_global.isEmpty()) this.dvList_global.addAll(s.dvList_global); - if (!s.dvList_local.isEmpty()) this.dvList_local.addAll(s.dvList_local); - this.dvMap.putAll(s.dvMap); - } - if (!s.asList.isEmpty()) { - this.asList.addAll(s.asList); - if (!s.asList_global.isEmpty()) this.asList_global.addAll(s.asList_global); - if (!s.asList_local.isEmpty()) this.asList_local.addAll(s.asList_local); - this.asMap.putAll(s.asMap); - } - - if (!s.gList.isEmpty()) { - this.gList.addAll(s.gList); - if (!s.gList_global.isEmpty()) this.gList_global.addAll(s.gList_global); - if (!s.gList_local.isEmpty()) this.gList_local.addAll(s.gList_local); - this.gMap.putAll(s.gMap); - } - - if (!s.varNeedEarlierCycle.isEmpty()) { - this.varNeedEarlierCycle.addAll(s.varNeedEarlierCycle); - this.var_neededVarCycle_map.putAll(s.var_neededVarCycle_map); - } - - if (!s.model_list.isEmpty()) { - this.model_list.addAll(s.model_list); - } - - if (!s.seqList.isEmpty()) { - this.seqList.addAll(s.seqList); - this.seqMap.putAll(s.seqMap); - } - - return this; - } - - public SimulationDataSet addNonDuplicate(SimulationDataSet s) - { - s.remove(this); - - return add(s); - } - - public SimulationDataSet dePrioritize(SimulationDataSet laterFileData, String filePath_forErrorMessage, Map> reverseMap) - { - if (laterFileData == null) System.out.println("Fatal error!!! SimulationDataSet is null in file: " + filePath_forErrorMessage); - - if (hasDuplicateIn(laterFileData, filePath_forErrorMessage, reverseMap)) - overwrite(laterFileData); - else { - add(laterFileData); - } - - return this; - } - - public SimulationDataSet prioritize_append(SimulationDataSet laterFileData, String filePath_forErrorMessage, Map> reverseMap) - { - if (laterFileData == null) System.out.println("Fatal error!!! SimulationDataSet is null in file: " + filePath_forErrorMessage); - - if (hasDuplicateIn(laterFileData, filePath_forErrorMessage, reverseMap)) { - remove(laterFileData); - } - - return add(laterFileData); - } - - public SimulationDataSet prioritize_prepend(SimulationDataSet laterFileData, String filePath_forErrorMessage, Map> reverseMap) - { - if (laterFileData == null) System.out.println("Fatal error!!! SimulationDataSet is null in file: " + filePath_forErrorMessage); - - if (hasDuplicateIn(laterFileData, filePath_forErrorMessage, reverseMap)) { - remove(laterFileData); - } - - return insert(laterFileData); - } - - public SimulationDataSet addChildren(String nodeFile, Map> t1Map, Map fileDataMap) - { - for (String childFile : t1Map.get(nodeFile)) - { - if (t1Map.get(childFile) != null) addChildren(childFile, t1Map, fileDataMap); - - overwrittenWith_set((SimulationDataSet)fileDataMap.get(childFile)); - } - - return this; - } - - public SimulationDataSet insert(SimulationDataSet s) - { - if (!s.wtList.isEmpty()) { - this.wtList.addAll(0, s.wtList); - if (!s.wtList_global.isEmpty()) this.wtList_global.addAll(0, s.wtList_global); - if (!s.wtList_local.isEmpty()) this.wtList_local.addAll(0, s.wtList_local); - this.wtMap.putAll(s.wtMap); - } - - if (!s.incFileList.isEmpty()) { - this.incFileList.addAll(0, s.incFileList); - if (!s.incFileList_global.isEmpty()) this.incFileList_global.addAll(0, s.incFileList_global); - if (!s.incFileList_local.isEmpty()) this.incFileList_local.addAll(0, s.incFileList_local); - this.incFileMap.putAll(s.incFileMap); - } - - if (!s.exList.isEmpty()) { - this.exList.addAll(0, s.exList); - if (!s.exList_global.isEmpty()) this.exList_global.addAll(0, s.exList_global); - if (!s.exList_local.isEmpty()) this.exList_local.addAll(0, s.exList_local); - this.exMap.putAll(s.exMap); - } - - if (!s.tsList.isEmpty()) { - this.tsList.addAll(0, s.tsList); - if (!s.tsList_global.isEmpty()) this.tsList_global.addAll(0, s.tsList_global); - if (!s.tsList_local.isEmpty()) this.tsList_local.addAll(0, s.tsList_local); - this.tsMap.putAll(s.tsMap); - } - - if (!s.svList.isEmpty()) { - this.svList.addAll(0, s.svList); - if (!s.svList_global.isEmpty()) this.svList_global.addAll(0, s.svList_global); - if (!s.svList_local.isEmpty()) this.svList_local.addAll(0, s.svList_local); - this.svMap.putAll(s.svMap); - } - - if (!s.dvList.isEmpty()) { - this.dvList.addAll(0, s.dvList); - if (!s.dvList_global.isEmpty()) this.dvList_global.addAll(0, s.dvList_global); - if (!s.dvList_local.isEmpty()) this.dvList_local.addAll(0, s.dvList_local); - this.dvMap.putAll(s.dvMap); - } - if (!s.asList.isEmpty()) { - this.asList.addAll(0, s.asList); - if (!s.asList_global.isEmpty()) this.asList_global.addAll(0, s.asList_global); - if (!s.asList_local.isEmpty()) this.asList_local.addAll(0, s.asList_local); - this.asMap.putAll(s.asMap); - } - - if (!s.gList.isEmpty()) { - this.gList.addAll(0, s.gList); - if (!s.gList_global.isEmpty()) this.gList_global.addAll(0, s.gList_global); - if (!s.gList_local.isEmpty()) this.gList_local.addAll(0, s.gList_local); - this.gMap.putAll(s.gMap); - } - - if (!s.varNeedEarlierCycle.isEmpty()) { - // TODO: find a way to insert linkedHashSet - this.varNeedEarlierCycle.addAll(s.varNeedEarlierCycle); - this.var_neededVarCycle_map.putAll(s.var_neededVarCycle_map); - } - - if (!s.model_list.isEmpty()) { - this.model_list.addAll(0, s.model_list); - } - - if (!s.seqList.isEmpty()) { - this.seqList.addAll(0, s.seqList); - this.seqMap.putAll(s.seqMap); - } - - return this; - } - - public SimulationDataSet overwrite_set(SimulationDataSet s) { - return overwrite_set(s, false); - } - public SimulationDataSet overwrite_set(SimulationDataSet s, boolean errMessage) { - -// this.ordered_list_including_files.addAll(0,s.ordered_list_including_files); -// this.ordered_list.addAll(0,s.ordered_list); - - SimulationDataSet x = new SimulationDataSet(s); - //x.overwrittenWith_set(s); - - Tools.mapRemoveAll(x.dvMap, this.dvSet); - Tools.mapRemoveAll(x.svMap, this.svSet); - Tools.mapRemoveAll(x.asMap, this.asSet); - Tools.mapRemoveAll(x.wtMap, this.wtSet); - Tools.mapRemoveAll(x.tsMap, this.tsSet); - Tools.mapRemoveAll(x.gMap, this.gSet); - Tools.mapRemoveAll(x.exMap, this.exSet); - Tools.mapRemoveAll(x.incFileMap, this.incFileSet); - Tools.mapRemoveAll(x.var_neededVarCycle_map, this.varNeedEarlierCycle); - - x.dvSet.addAll(this.dvSet); - x.dvSet_global.addAll(this.dvSet_global); - x.dvSet_local.addAll(this.dvSet_local); - this.dvSet = x.dvSet; - this.dvSet_global = x.dvSet_global; - this.dvSet_local = x.dvSet_local; - this.dvMap.putAll(x.dvMap); - - x.svSet.addAll(this.svSet); - x.svSet_global.addAll(this.svSet_global); - x.svSet_local.addAll(this.svSet_local); - this.svSet = x.svSet; - this.svSet_global = x.svSet_global; - this.svSet_local = x.svSet_local; - this.svMap.putAll(x.svMap); - - x.tsSet.addAll(this.tsSet); - x.tsSet_global.addAll(this.tsSet_global); - x.tsSet_local.addAll(this.tsSet_local); - this.tsSet = x.tsSet; - this.tsSet_global = x.tsSet_global; - this.tsSet_local = x.tsSet_local; - this.tsMap.putAll(x.tsMap); - - x.asSet.addAll(this.asSet); - x.asSet_global.addAll(this.asSet_global); - x.asSet_local.addAll(this.asSet_local); - this.asSet = x.asSet; - this.asSet_global = x.asSet_global; - this.asSet_local = x.asSet_local; - this.asMap.putAll(x.asMap); - - x.gSet.addAll(this.gSet); - x.gSet_global.addAll(this.gSet_global); - x.gSet_local.addAll(this.gSet_local); - this.gSet = x.gSet; - this.gSet_global = x.gSet_global; - this.gSet_local = x.gSet_local; - this.gMap.putAll(x.gMap); - - x.wtSet.addAll(this.wtSet); - x.wtSet_global.addAll(this.wtSet_global); - x.wtSet_local.addAll(this.wtSet_local); - this.wtSet = x.wtSet; - this.wtSet_global = x.wtSet_global; - this.wtSet_local = x.wtSet_local; - this.wtMap.putAll(x.wtMap); - - x.exSet.addAll(this.exSet); - x.exSet_global.addAll(this.exSet_global); - x.exSet_local.addAll(this.exSet_local); - this.exSet = x.exSet; - this.exSet_global = x.exSet_global; - this.exSet_local = x.exSet_local; - this.exMap.putAll(x.exMap); - - x.incFileSet.addAll(this.incFileSet); - x.incFileSet_global.addAll(this.incFileSet_global); - x.incFileSet_local.addAll(this.incFileSet_local); - this.incFileSet = x.incFileSet; - this.incFileSet_global = x.incFileSet_global; - this.incFileSet_local = x.incFileSet_local; - this.incFileMap.putAll(x.incFileMap); - - x.varNeedEarlierCycle.addAll(this.varNeedEarlierCycle); - this.varNeedEarlierCycle = x.varNeedEarlierCycle; - this.var_neededVarCycle_map.putAll(x.var_neededVarCycle_map); - - return this; - } - - public SimulationDataSet replaceGlobalWithDuplicateGlobal(Set keys, SimulationDataSet s) { - - for (String k : keys) { - - if (this.dvSet.contains(k)){ -// this.dvSet_global.remove(k); -// this.dvSet_local.add(k); - this.dvMap.put(k,s.dvMap.get(k)); - } - if (this.svSet.contains(k)){ -// this.svSet_global.remove(k); -// this.svSet_local.add(k); - this.svMap.put(k,s.svMap.get(k)); - } - - if (this.tsSet.contains(k)){ -// this.tsSet_global.remove(k); -// this.tsSet_local.add(k); - this.tsMap.put(k,s.tsMap.get(k)); - } - if (this.asSet.contains(k)){ -// this.asSet_global.remove(k); -// this.asSet_local.add(k); - this.asMap.put(k,s.asMap.get(k)); - } - if (this.gSet.contains(k)){ -// this.gSet_global.remove(k); -// this.gSet_local.add(k); - this.gMap.put(k,s.gMap.get(k)); - } - if (this.exSet.contains(k)){ -// this.exSet_global.remove(k); -// this.exSet_local.add(k); - this.exMap.put(k,s.exMap.get(k)); - } - if (this.varNeedEarlierCycle.contains(k)){ - this.var_neededVarCycle_map.put(k,s.var_neededVarCycle_map.get(k)); - } - } - - return this; - } - - public SimulationDataSet replaceGlobalWithDuplicateLocal(Set keys, SimulationDataSet s) throws TypeRedefinedException { - - for (String k : keys) { - - if (this.dvSet.contains(k)){ - - if( !s.dvSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); - - this.dvSet_global.remove(k); - this.dvSet_local.add(k); - this.dvMap.put(k,s.dvMap.get(k)); - } - if (this.svSet.contains(k)){ - if( !s.svSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); - this.svSet_global.remove(k); - this.svSet_local.add(k); - this.svMap.put(k,s.svMap.get(k)); - } - - if (this.tsSet.contains(k)){ - if( !s.tsSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); - this.tsSet_global.remove(k); - this.tsSet_local.add(k); - this.tsMap.put(k,s.tsMap.get(k)); - } - if (this.asSet.contains(k)){ - if( !s.asSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); - this.asSet_global.remove(k); - this.asSet_local.add(k); - this.asMap.put(k,s.asMap.get(k)); - } - if (this.gSet.contains(k)){ - if( !s.gSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); - this.gSet_global.remove(k); - this.gSet_local.add(k); - this.gMap.put(k,s.gMap.get(k)); - } - if (this.exSet.contains(k)){ - if( !s.exSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); - this.exSet_global.remove(k); - this.exSet_local.add(k); - this.exMap.put(k,s.exMap.get(k)); - } - if (this.varNeedEarlierCycle.contains(k)){ - this.var_neededVarCycle_map.put(k,s.var_neededVarCycle_map.get(k)); - } - } - - return this; - } - - public SimulationDataSet getGlobalVars_set() - { - SimulationDataSet out = new SimulationDataSet(); - - Set t; - t= new LinkedHashSet(this.asSet); - t.retainAll(this.asSet_global); - out.asSet.addAll(t); - out.asSet_global.addAll(t); - - for (String key : this.asSet_global) { - out.asMap.put(key, (Alias)this.asMap.get(key)); - } - - t = new LinkedHashSet(this.wtSet); - t.retainAll(this.wtSet_global); - out.wtSet.addAll(t); - out.wtSet_global.addAll(t); - - for (String key : this.wtSet_global) { - out.wtMap.put(key, (WeightElement)this.wtMap.get(key)); - } - - t = new LinkedHashSet(this.incFileSet); - t.retainAll(this.incFileSet_global); - out.incFileSet.addAll(t); - out.incFileSet_global.addAll(t); - - for (String key : this.incFileSet_global) { - out.incFileMap.put(key, (IncludeFile)this.incFileMap.get(key)); - } - - t = new LinkedHashSet(this.exSet); - t.retainAll(this.exSet_global); - out.exSet.addAll(t); - out.exSet_global.addAll(t); - - for (String key : this.exSet_global) { - out.exMap.put(key, (External)this.exMap.get(key)); - } - - t = new LinkedHashSet(this.svSet); - t.retainAll(this.svSet_global); - - out.svSet.addAll(t); - out.svSet_global.addAll(t); - - for (String key : this.svSet_global) { - out.svMap.put(key, (Svar)this.svMap.get(key)); - } - - t = new LinkedHashSet(this.tsSet); - t.retainAll(this.tsSet_global); - out.tsSet.addAll(t); - out.tsSet_global.addAll(t); - - for (String key : this.tsSet_global) { - out.tsMap.put(key, (Timeseries)this.tsMap.get(key)); - } - - t = new LinkedHashSet(this.dvSet); - t.retainAll(this.dvSet_global); - out.dvSet.addAll(t); - out.dvSet_global.addAll(t); - - for (String key : this.dvSet_global) { - out.dvMap.put(key, (Dvar)this.dvMap.get(key)); - } - - t = new LinkedHashSet(this.gSet); - t.retainAll(this.gSet_global); - out.gSet.addAll(t); - out.gSet_global.addAll(t); - - for (String key : this.gSet_global) { - out.gMap.put(key, (Goal)this.gMap.get(key)); - } - - //////// - t = new LinkedHashSet(this.varNeedEarlierCycle); - t.retainAll(this.svSet_global); - t.retainAll(this.asSet_global); - out.varNeedEarlierCycle.addAll(t); - for (String key : out.varNeedEarlierCycle) { - out.var_neededVarCycle_map.put(key, this.var_neededVarCycle_map.get(key)); - } - - return out; - } - - public SimulationDataSet convertToLocal_set(){ - - this.asSet_local.addAll(this.asSet); - this.asSet_global.clear(); - - this.wtSet_local.addAll(this.wtSet); - this.wtSet_global.clear(); - - this.tsSet_local.addAll(this.tsSet); - this.tsSet_global.clear(); - - this.dvSet_local.addAll(this.dvSet); - this.dvSet_global.clear(); - - this.svSet_local.addAll(this.svSet); - this.svSet_global.clear(); - - this.exSet_local.addAll(this.exSet); - this.exSet_global.clear(); - - this.gSet_local.addAll(this.gSet); - this.gSet_global.clear(); - - this.incFileSet_local.addAll(this.incFileSet); - this.incFileSet_global.clear(); - - return this; - } - -public Set getAllGlobalVarsSet_except_file_and_weight(){ - - Set out = new HashSet(); - - out.addAll(this.asSet_global); - out.addAll(this.dvSet_global); - out.addAll(this.svSet_global); - out.addAll(this.gSet_global); - out.addAll(this.exSet_global); - - return out; - } - -public Set getAllLocalVarsSet_except_file_and_weight(){ - - Set out = new HashSet(); - - out.addAll(this.asSet_local); - out.addAll(this.dvSet_local); - out.addAll(this.svSet_local); - out.addAll(this.gSet_local); - out.addAll(this.exSet_local); - - return out; - } - -public Set getAllVarsSet_except_file_and_weight(){ - - Set out = new HashSet(); - - out.addAll(this.asSet); - out.addAll(this.dvSet); - out.addAll(this.svSet); - out.addAll(this.gSet); - out.addAll(this.exSet); - - return out; - } - -public Set getSvarAliasExternTimeseries(){ - - Set out = new HashSet(); - - out.addAll(this.asSet); - out.addAll(this.svSet); - out.addAll(this.tsSet); - out.addAll(this.exSet); - - return out; - } - -public SimulationDataSet remove_set(Set s) - { - -// this.wtSet.removeAll(s); -// this.wtSet_global.removeAll(s); -// this.wtSet_local.removeAll(s); -// -// Tools.mapRemoveAll(this.wtMap, s); - - - this.incFileSet.removeAll(s); - this.incFileSet_global.removeAll(s); - this.incFileSet_local.removeAll(s); - - Tools.mapRemoveAll(this.incFileMap, s); - - - this.exSet.removeAll(s); - this.exSet_global.removeAll(s); - this.exSet_local.removeAll(s); - - Tools.mapRemoveAll(this.exMap, s); - - - this.tsSet.removeAll(s); - this.tsSet_global.removeAll(s); - this.tsSet_local.removeAll(s); - - Tools.mapRemoveAll(this.tsMap, s); - - - this.svSet.removeAll(s); - this.svSet_global.removeAll(s); - this.svSet_local.removeAll(s); - - Tools.mapRemoveAll(this.svMap, s); - - - this.dvSet.removeAll(s); - this.dvSet_global.removeAll(s); - this.dvSet_local.removeAll(s); - - Tools.mapRemoveAll(this.dvMap, s); - - - this.asSet.removeAll(s); - this.asSet_global.removeAll(s); - this.asSet_local.removeAll(s); - - Tools.mapRemoveAll(this.asMap, s); - - - this.gSet.removeAll(s); - this.gSet_global.removeAll(s); - this.gSet_local.removeAll(s); - - Tools.mapRemoveAll(this.gMap, s); - - - this.varNeedEarlierCycle.removeAll(s); - - Tools.mapRemoveAll(this.var_neededVarCycle_map, s); - - - return this; - } - -public SimulationDataSet overwrittenWith_set(SimulationDataSet s) { - - //this.ordered_list_including_files.addAll(s.ordered_list_including_files); - //this.ordered_list.addAll(s.ordered_list); - - this.dvSet.addAll(s.dvSet); - this.dvSet_global.addAll(s.dvSet_global); - this.dvSet_local.addAll(s.dvSet_local); - this.dvMap.putAll(s.dvMap); - - this.svSet.addAll(s.svSet); - this.svSet_global.addAll(s.svSet_global); - this.svSet_local.addAll(s.svSet_local); - -// /// experiment with deep copy -// Map t = new HashMap(); -// for (Map.Entry e : s.svMap.entrySet()){ -// t.put(e.getKey(), new Svar(e.getValue())); -// } - - this.svMap.putAll(s.svMap); - - this.tsSet.addAll(s.tsSet); - this.tsSet_global.addAll(s.tsSet_global); - this.tsSet_local.addAll(s.tsSet_local); - this.tsMap.putAll(s.tsMap); - - this.asSet.addAll(s.asSet); - this.asSet_global.addAll(s.asSet_global); - this.asSet_local.addAll(s.asSet_local); - this.asMap.putAll(s.asMap); - - this.gSet.addAll(s.gSet); - this.gSet_global.addAll(s.gSet_global); - this.gSet_local.addAll(s.gSet_local); - this.gMap.putAll(s.gMap); - - this.wtSet.addAll(s.wtSet); - this.wtSet_global.addAll(s.wtSet_global); - this.wtSet_local.addAll(s.wtSet_local); - this.wtMap.putAll(s.wtMap); - - this.exSet.addAll(s.exSet); - this.exSet_global.addAll(s.exSet_global); - this.exSet_local.addAll(s.exSet_local); - this.exMap.putAll(s.exMap); - - this.incFileSet.addAll(s.incFileSet); - this.incFileSet_global.addAll(s.incFileSet_global); - this.incFileSet_local.addAll(s.incFileSet_local); - this.incFileMap.putAll(s.incFileMap); - - this.varNeedEarlierCycle.addAll(s.varNeedEarlierCycle); - this.var_neededVarCycle_map.putAll(s.var_neededVarCycle_map); - - this.lousyConvert(); - - return this; - } - -public void lousyConvert() { - - this.asList = new ArrayList(this.asSet); - this.asList_global = new ArrayList(this.asSet_global); - this.asList_local = new ArrayList(this.asSet_local); - - this.wtList = new ArrayList(this.wtSet); - this.wtList_global = new ArrayList(this.wtSet_global); - this.wtList_local = new ArrayList(this.wtSet_local); - - this.svList = new ArrayList(this.svSet); - this.svList_global = new ArrayList(this.svSet_global); - this.svList_local = new ArrayList(this.svSet_local); - - this.dvList = new ArrayList(this.dvSet); - this.dvList_global = new ArrayList(this.dvSet_global); - this.dvList_local = new ArrayList(this.dvSet_local); - - this.tsList = new ArrayList(this.tsSet); - this.tsList_global = new ArrayList(this.tsSet_global); - this.tsList_local = new ArrayList(this.tsSet_local); - - this.exList = new ArrayList(this.exSet); - this.exList_global = new ArrayList(this.exSet_global); - this.exList_local = new ArrayList(this.exSet_local); - - this.gList = new ArrayList(this.gSet); - this.gList_global = new ArrayList(this.gSet_global); - this.gList_local = new ArrayList(this.gSet_local); - - this.incFileList = new ArrayList(this.incFileSet); - this.incFileList_global = new ArrayList(this.incFileSet_global); - this.incFileList_local = new ArrayList(this.incFileSet_local); - -} +package wrimsv2.wreslparser.elements; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.External; +import wrimsv2.commondata.wresldata.Goal; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.commondata.wresldata.Timeseries; +import wrimsv2.commondata.wresldata.WeightElement; + +public class SimulationDataSet +{ + public String currentAbsolutePath; + public String currentAbsoluteParent; + + public ArrayList model_list = new ArrayList(); + public ArrayList error_model_redefined = new ArrayList(); + + public ArrayList error_sequence_redefined = new ArrayList(); + public ArrayList error_sequence_order_redefined = new ArrayList(); + + public Map seqMap = new HashMap(); + public ArrayList seqList = new ArrayList(); + + public Set wtSet = new LinkedHashSet(); + public Set wtSet_global = new LinkedHashSet(); + public Set wtSet_local = new LinkedHashSet(); + public ArrayList wtList = new ArrayList(); + public ArrayList wtList_global = new ArrayList(); + public ArrayList wtList_local = new ArrayList(); + public Map wtMap = new HashMap(); + public Map error_weightVar_redefined = new HashMap(); + + public Set incFileSet = new LinkedHashSet(); + public Set incFileSet_global = new LinkedHashSet(); + public Set incFileSet_local = new LinkedHashSet(); + public ArrayList incFileList = new ArrayList(); + public ArrayList incFileList_global = new ArrayList(); + public ArrayList incFileList_local = new ArrayList(); + public Map incFileMap = new HashMap(); + public ArrayList error_includeFile_redefined = new ArrayList(); + + public ArrayList ordered_list_including_files = new ArrayList(); + public ArrayList ordered_list = new ArrayList(); + + public ArrayList ordered_list_including_files_global = new ArrayList(); + public ArrayList ordered_list_global = new ArrayList(); + + public Map var_all = new HashMap(); + public Map error_var_redefined = new HashMap(); + + public Set exSet = new LinkedHashSet(); + public Set exSet_global = new LinkedHashSet(); + public Set exSet_local = new LinkedHashSet(); + public ArrayList exList = new ArrayList(); + public ArrayList exList_global = new ArrayList(); + public ArrayList exList_local = new ArrayList(); + public Map exMap = new HashMap(); + + public Set tsSet = new LinkedHashSet(); + public Set tsSet_global = new LinkedHashSet(); + public Set tsSet_local = new LinkedHashSet(); + public ArrayList tsList = new ArrayList(); + public ArrayList tsList_global = new ArrayList(); + public ArrayList tsList_local = new ArrayList(); + public Map tsMap = new HashMap(); + + public Set svSet_unknown = new LinkedHashSet(); + public Set svSet = new LinkedHashSet(); + public Set svSet_global = new LinkedHashSet(); + public Set svSet_local = new LinkedHashSet(); + public ArrayList svList = new ArrayList(); + public ArrayList svList_global = new ArrayList(); + public ArrayList svList_local = new ArrayList(); + public Map svMap = new HashMap(); + + public Set dvSet = new LinkedHashSet(); + public Set dvSet_global = new LinkedHashSet(); + public Set dvSet_local = new LinkedHashSet(); + public ArrayList dvList = new ArrayList(); + public ArrayList dvList_global = new ArrayList(); + public ArrayList dvList_local = new ArrayList(); + public Map dvMap = new HashMap(); + + public Set asSet_unknown = new LinkedHashSet(); + public Set asSet = new LinkedHashSet(); + public Set asSet_global = new LinkedHashSet(); + public Set asSet_local = new LinkedHashSet(); + public ArrayList asList = new ArrayList(); + public ArrayList asList_global = new ArrayList(); + public ArrayList asList_local = new ArrayList(); + public Map asMap = new HashMap(); + + public Set gSet = new LinkedHashSet(); + public Set gSet_global = new LinkedHashSet(); + public Set gSet_local = new LinkedHashSet(); + public ArrayList gList = new ArrayList(); + public ArrayList gList_global = new ArrayList(); + public ArrayList gList_local = new ArrayList(); + public Map gMap = new HashMap(); + + public Set varNeedEarlierCycle = new LinkedHashSet(); + public Map> var_neededVarCycle_map = new HashMap>(); + + + public SimulationDataSet() + { + + } + + /// warning: this is partial copy + public SimulationDataSet(SimulationDataSet s) + { + this.overwrittenWith_set(s); + + } + + public SimulationDataSet overwrittenWith(SimulationDataSet s) + { + remove(s); + add(s); + return this; + } + + public SimulationDataSet overwrite(SimulationDataSet s) + { + SimulationDataSet p = new SimulationDataSet(s); + p.remove(this); + add(p); + return this; + } + + public boolean hasDuplicateIn(SimulationDataSet s, String filePath, Map> reverseMap) + { + boolean b = false; + + if (s == null) System.out.println("Fatal error!!! SimulationDataSet is null in file: " + filePath); + + for (String e : s.wtList) { + if (this.wtList.contains(e)) { + String f1 = ((WeightElement)s.wtMap.get(e)).fromWresl; + String f2 = ((WeightElement)this.wtMap.get(e)).fromWresl; + LogUtils.errMsg("Weight table variable redefined: " + e, f1, f2, reverseMap); + b = true; + } + } + + for (String e : s.incFileList) { + if (!this.incFileList.contains(e)) { + continue; + } + String f1 = ((IncludeFile)s.incFileMap.get(e)).fromWresl; + String f2 = ((IncludeFile)this.incFileMap.get(e)).fromWresl; + LogUtils.errMsg("Include file redefined: " + e, f1, f2, reverseMap); + b = true; + } + + for (String e : s.tsList) { + if (this.tsList.contains(e)) { + String f1 = ((Timeseries)s.tsMap.get(e)).fromWresl; + String f2 = ((Timeseries)this.tsMap.get(e)).fromWresl; + LogUtils.errMsg("State variable redefined: " + e, f1, f2, reverseMap); + b = true; + } + } + + for (String e : s.svList) { + if (this.svList.contains(e)) { + String f1 = ((Svar)s.svMap.get(e)).fromWresl; + String f2 = ((Svar)this.svMap.get(e)).fromWresl; + LogUtils.errMsg("State variable redefined: " + e, f1, f2, reverseMap); + b = true; + } + } + + for (String e : s.dvList) { + if (this.dvList.contains(e)) { + String f1 = ((Dvar)s.dvMap.get(e)).fromWresl; + String f2 = ((Dvar)this.dvMap.get(e)).fromWresl; + LogUtils.errMsg("Decision varriable redefined: " + e, f1, f2, reverseMap); + b = true; + } + } + + for (String e : s.gList) { + if (this.gList.contains(e)) { + String f1 = ((Goal)s.gMap.get(e)).fromWresl; + String f2 = ((Goal)this.gMap.get(e)).fromWresl; + LogUtils.errMsg("Goal redefined: " + e, f1, f2, reverseMap); + b = true; + } + } + + for (String e : s.asList) { + if (this.asList.contains(e)) { + String f1 = ((Alias)s.asMap.get(e)).fromWresl; + String f2 = ((Alias)this.asMap.get(e)).fromWresl; + LogUtils.errMsg("Alias redefined: " + e, f1, f2, reverseMap); + b = true; + } + } + + for (String e : s.model_list) { + if (!this.model_list.contains(e)) + continue; + LogUtils.errMsg("Error!!! Model redefined: " + e + " in file: " + filePath); + b = true; + } + + for (String e : s.seqList) { + if (!this.seqList.contains(e)) + continue; + LogUtils.errMsg("Error!!! Sequence redefined: " + e + " in file: " + filePath); + b = true; + } + + return b; + } + + public SimulationDataSet convertToLocal() + { + if (!this.wtList.isEmpty()) { + this.wtList_local = new ArrayList(); + this.wtList_local.addAll(this.wtList); + this.wtList_global = new ArrayList(); + } + + if (!this.incFileList.isEmpty()) { + this.incFileList_local = new ArrayList(); + this.incFileList_local.addAll(this.incFileList); + this.incFileList_global = new ArrayList(); + } + + if (!this.tsList.isEmpty()) { + this.tsList_local = new ArrayList(); + this.tsList_local.addAll(this.tsList); + this.tsList_global = new ArrayList(); + } + + if (!this.svList.isEmpty()) { + this.svList_local = new ArrayList(); + this.svList_local.addAll(this.svList); + this.svList_global = new ArrayList(); + } + + if (!this.dvList.isEmpty()) { + this.dvList_local = new ArrayList(); + this.dvList_local.addAll(this.dvList); + this.dvList_global = new ArrayList(); + } + if (!this.asList.isEmpty()) { + this.asList_local = new ArrayList(); + this.asList_local.addAll(this.asList); + this.asList_global = new ArrayList(); + } + + if (!this.gList.isEmpty()) { + this.gList_local = new ArrayList(); + this.gList_local.addAll(this.gList); + this.gList_global = new ArrayList(); + } + + return this; + } + + public SimulationDataSet getGlobalVars() + { + SimulationDataSet out = new SimulationDataSet(); + + if (!this.wtList_global.isEmpty()) { + out.wtList.addAll(this.wtList_global); + out.wtList_global.addAll(this.wtList_global); + + for (String key : this.wtList_global) { + out.wtMap.put(key, (WeightElement)this.wtMap.get(key)); + } + } + + if (!this.incFileList_global.isEmpty()) { + out.incFileList.addAll(this.incFileList_global); + out.incFileList_global.addAll(this.incFileList_global); + + for (String key : this.incFileList_global) { + out.incFileMap.put(key, (IncludeFile)this.incFileMap.get(key)); + } + } + + if (!this.exList_global.isEmpty()) { + out.exList.addAll(this.exList_global); + out.exList_global.addAll(this.exList_global); + + for (String key : this.exList_global) { + out.exMap.put(key, (External)this.exMap.get(key)); + } + } + + if (!this.tsList_global.isEmpty()) { + out.tsList.addAll(this.tsList_global); + out.tsList_global.addAll(this.tsList_global); + + for (String key : this.tsList_global) { + out.tsMap.put(key, (Timeseries)this.tsMap.get(key)); + } + } + + if (!this.svList_global.isEmpty()) { + out.svList.addAll(this.svList_global); + out.svList_global.addAll(this.svList_global); + + for (String key : this.svList_global) { + out.svMap.put(key, (Svar)this.svMap.get(key)); + } + } + + if (!this.dvList_global.isEmpty()) { + out.dvList.addAll(this.dvList_global); + out.dvList_global.addAll(this.dvList_global); + + for (String key : this.dvList_global) { + out.dvMap.put(key, (Dvar)this.dvMap.get(key)); + } + } + + if (!this.gList_global.isEmpty()) { + out.gList.addAll(this.gList_global); + out.gList_global.addAll(this.gList_global); + + for (String key : this.gList_global) { + out.gMap.put(key, (Goal)this.gMap.get(key)); + } + + } + + if (!this.varNeedEarlierCycle.isEmpty()) { + out.varNeedEarlierCycle.addAll(this.varNeedEarlierCycle); + out.varNeedEarlierCycle.retainAll(out.svList_global); + out.varNeedEarlierCycle.retainAll(out.asList_global); + + for (String key : out.varNeedEarlierCycle) { + out.var_neededVarCycle_map.put(key, this.var_neededVarCycle_map.get(key)); + } + + } + + return out; + } + + public SimulationDataSet remove(SimulationDataSet s) + { + if (!s.wtList.isEmpty()) { + this.wtList.removeAll(s.wtList); + this.wtList_global.removeAll(s.wtList); + this.wtList_local.removeAll(s.wtList); + + Tools.mapRemoveAll(this.wtMap, s.wtList); + } + + if (!s.incFileList.isEmpty()) { + this.incFileList.removeAll(s.incFileList); + this.incFileList_global.removeAll(s.incFileList); + this.incFileList_local.removeAll(s.incFileList); + + Tools.mapRemoveAll(this.incFileMap, s.incFileList); + } + + if (!s.exList.isEmpty()) { + this.exList.removeAll(s.exList); + if (!s.exList_global.isEmpty()) this.exList_global.removeAll(s.exList); + if (!s.exList_local.isEmpty()) this.exList_local.removeAll(s.exList); + + Tools.mapRemoveAll(this.exMap, s.exList); + } + + if (!s.tsList.isEmpty()) { + this.tsList.removeAll(s.tsList); + if (!s.tsList_global.isEmpty()) this.tsList_global.removeAll(s.tsList); + if (!s.tsList_local.isEmpty()) this.tsList_local.removeAll(s.tsList); + + Tools.mapRemoveAll(this.tsMap, s.tsList); + } + + if (!s.svList.isEmpty()) { + this.svList.removeAll(s.svList); + if (!s.svList_global.isEmpty()) this.svList_global.removeAll(s.svList); + if (!s.svList_local.isEmpty()) this.svList_local.removeAll(s.svList); + + Tools.mapRemoveAll(this.svMap, s.svList); + } + + if (!s.dvList.isEmpty()) { + this.dvList.removeAll(s.dvList); + if (!s.dvList_global.isEmpty()) this.dvList_global.removeAll(s.dvList); + if (!s.dvList_local.isEmpty()) this.dvList_local.removeAll(s.dvList); + + Tools.mapRemoveAll(this.dvMap, s.dvList); + } + if (!s.asList.isEmpty()) { + this.asList.removeAll(s.gList); + if (!s.asList_global.isEmpty()) this.asList_global.removeAll(s.asList); + if (!s.asList_local.isEmpty()) this.asList_local.removeAll(s.asList); + + Tools.mapRemoveAll(this.asMap, s.asList); + } + + if (!s.gList.isEmpty()) { + this.gList.removeAll(s.gList); + if (!s.gList_global.isEmpty()) this.gList_global.removeAll(s.gList); + if (!s.gList_local.isEmpty()) this.gList_local.removeAll(s.gList); + + Tools.mapRemoveAll(this.gMap, s.gList); + } + + if (!s.varNeedEarlierCycle.isEmpty()) { + this.varNeedEarlierCycle.removeAll(s.varNeedEarlierCycle); + + Tools.mapRemoveAll(this.var_neededVarCycle_map, s.varNeedEarlierCycle); + } + + if (!s.model_list.isEmpty()) { + this.model_list.removeAll(s.model_list); + } + + return this; + } + + public SimulationDataSet add(SimulationDataSet s) + { + if (!s.wtList.isEmpty()) { + this.wtList.addAll(s.wtList); + if (!s.wtList_global.isEmpty()) this.wtList_global.addAll(s.wtList_global); + if (!s.wtList_local.isEmpty()) this.wtList_local.addAll(s.wtList_local); + this.wtMap.putAll(s.wtMap); + } + + if (!s.incFileList.isEmpty()) { + this.incFileList.addAll(s.incFileList); + if (!s.incFileList_global.isEmpty()) this.incFileList_global.addAll(s.incFileList_global); + if (!s.incFileList_local.isEmpty()) this.incFileList_local.addAll(s.incFileList_local); + this.incFileMap.putAll(s.incFileMap); + } + + if (!s.exList.isEmpty()) { + this.exList.addAll(s.exList); + if (!s.exList_global.isEmpty()) this.exList_global.addAll(s.exList_global); + if (!s.exList_local.isEmpty()) this.exList_local.addAll(s.exList_local); + this.exMap.putAll(s.exMap); + } + + if (!s.tsList.isEmpty()) { + this.tsList.addAll(0, s.tsList); + if (!s.tsList_global.isEmpty()) this.tsList_global.addAll(s.tsList_global); + if (!s.tsList_local.isEmpty()) this.tsList_local.addAll(s.tsList_local); + this.tsMap.putAll(s.tsMap); + } + + if (!s.svList.isEmpty()) { + this.svList.addAll(s.svList); + if (!s.svList_global.isEmpty()) this.svList_global.addAll(s.svList_global); + if (!s.svList_local.isEmpty()) this.svList_local.addAll(s.svList_local); + this.svMap.putAll(s.svMap); + } + + if (!s.dvList.isEmpty()) { + this.dvList.addAll(s.dvList); + if (!s.dvList_global.isEmpty()) this.dvList_global.addAll(s.dvList_global); + if (!s.dvList_local.isEmpty()) this.dvList_local.addAll(s.dvList_local); + this.dvMap.putAll(s.dvMap); + } + if (!s.asList.isEmpty()) { + this.asList.addAll(s.asList); + if (!s.asList_global.isEmpty()) this.asList_global.addAll(s.asList_global); + if (!s.asList_local.isEmpty()) this.asList_local.addAll(s.asList_local); + this.asMap.putAll(s.asMap); + } + + if (!s.gList.isEmpty()) { + this.gList.addAll(s.gList); + if (!s.gList_global.isEmpty()) this.gList_global.addAll(s.gList_global); + if (!s.gList_local.isEmpty()) this.gList_local.addAll(s.gList_local); + this.gMap.putAll(s.gMap); + } + + if (!s.varNeedEarlierCycle.isEmpty()) { + this.varNeedEarlierCycle.addAll(s.varNeedEarlierCycle); + this.var_neededVarCycle_map.putAll(s.var_neededVarCycle_map); + } + + if (!s.model_list.isEmpty()) { + this.model_list.addAll(s.model_list); + } + + if (!s.seqList.isEmpty()) { + this.seqList.addAll(s.seqList); + this.seqMap.putAll(s.seqMap); + } + + return this; + } + + public SimulationDataSet addNonDuplicate(SimulationDataSet s) + { + s.remove(this); + + return add(s); + } + + public SimulationDataSet dePrioritize(SimulationDataSet laterFileData, String filePath_forErrorMessage, Map> reverseMap) + { + if (laterFileData == null) System.out.println("Fatal error!!! SimulationDataSet is null in file: " + filePath_forErrorMessage); + + if (hasDuplicateIn(laterFileData, filePath_forErrorMessage, reverseMap)) + overwrite(laterFileData); + else { + add(laterFileData); + } + + return this; + } + + public SimulationDataSet prioritize_append(SimulationDataSet laterFileData, String filePath_forErrorMessage, Map> reverseMap) + { + if (laterFileData == null) System.out.println("Fatal error!!! SimulationDataSet is null in file: " + filePath_forErrorMessage); + + if (hasDuplicateIn(laterFileData, filePath_forErrorMessage, reverseMap)) { + remove(laterFileData); + } + + return add(laterFileData); + } + + public SimulationDataSet prioritize_prepend(SimulationDataSet laterFileData, String filePath_forErrorMessage, Map> reverseMap) + { + if (laterFileData == null) System.out.println("Fatal error!!! SimulationDataSet is null in file: " + filePath_forErrorMessage); + + if (hasDuplicateIn(laterFileData, filePath_forErrorMessage, reverseMap)) { + remove(laterFileData); + } + + return insert(laterFileData); + } + + public SimulationDataSet addChildren(String nodeFile, Map> t1Map, Map fileDataMap) + { + for (String childFile : t1Map.get(nodeFile)) + { + if (t1Map.get(childFile) != null) addChildren(childFile, t1Map, fileDataMap); + + overwrittenWith_set((SimulationDataSet)fileDataMap.get(childFile)); + } + + return this; + } + + public SimulationDataSet insert(SimulationDataSet s) + { + if (!s.wtList.isEmpty()) { + this.wtList.addAll(0, s.wtList); + if (!s.wtList_global.isEmpty()) this.wtList_global.addAll(0, s.wtList_global); + if (!s.wtList_local.isEmpty()) this.wtList_local.addAll(0, s.wtList_local); + this.wtMap.putAll(s.wtMap); + } + + if (!s.incFileList.isEmpty()) { + this.incFileList.addAll(0, s.incFileList); + if (!s.incFileList_global.isEmpty()) this.incFileList_global.addAll(0, s.incFileList_global); + if (!s.incFileList_local.isEmpty()) this.incFileList_local.addAll(0, s.incFileList_local); + this.incFileMap.putAll(s.incFileMap); + } + + if (!s.exList.isEmpty()) { + this.exList.addAll(0, s.exList); + if (!s.exList_global.isEmpty()) this.exList_global.addAll(0, s.exList_global); + if (!s.exList_local.isEmpty()) this.exList_local.addAll(0, s.exList_local); + this.exMap.putAll(s.exMap); + } + + if (!s.tsList.isEmpty()) { + this.tsList.addAll(0, s.tsList); + if (!s.tsList_global.isEmpty()) this.tsList_global.addAll(0, s.tsList_global); + if (!s.tsList_local.isEmpty()) this.tsList_local.addAll(0, s.tsList_local); + this.tsMap.putAll(s.tsMap); + } + + if (!s.svList.isEmpty()) { + this.svList.addAll(0, s.svList); + if (!s.svList_global.isEmpty()) this.svList_global.addAll(0, s.svList_global); + if (!s.svList_local.isEmpty()) this.svList_local.addAll(0, s.svList_local); + this.svMap.putAll(s.svMap); + } + + if (!s.dvList.isEmpty()) { + this.dvList.addAll(0, s.dvList); + if (!s.dvList_global.isEmpty()) this.dvList_global.addAll(0, s.dvList_global); + if (!s.dvList_local.isEmpty()) this.dvList_local.addAll(0, s.dvList_local); + this.dvMap.putAll(s.dvMap); + } + if (!s.asList.isEmpty()) { + this.asList.addAll(0, s.asList); + if (!s.asList_global.isEmpty()) this.asList_global.addAll(0, s.asList_global); + if (!s.asList_local.isEmpty()) this.asList_local.addAll(0, s.asList_local); + this.asMap.putAll(s.asMap); + } + + if (!s.gList.isEmpty()) { + this.gList.addAll(0, s.gList); + if (!s.gList_global.isEmpty()) this.gList_global.addAll(0, s.gList_global); + if (!s.gList_local.isEmpty()) this.gList_local.addAll(0, s.gList_local); + this.gMap.putAll(s.gMap); + } + + if (!s.varNeedEarlierCycle.isEmpty()) { + // TODO: find a way to insert linkedHashSet + this.varNeedEarlierCycle.addAll(s.varNeedEarlierCycle); + this.var_neededVarCycle_map.putAll(s.var_neededVarCycle_map); + } + + if (!s.model_list.isEmpty()) { + this.model_list.addAll(0, s.model_list); + } + + if (!s.seqList.isEmpty()) { + this.seqList.addAll(0, s.seqList); + this.seqMap.putAll(s.seqMap); + } + + return this; + } + + public SimulationDataSet overwrite_set(SimulationDataSet s) { + return overwrite_set(s, false); + } + public SimulationDataSet overwrite_set(SimulationDataSet s, boolean errMessage) { + +// this.ordered_list_including_files.addAll(0,s.ordered_list_including_files); +// this.ordered_list.addAll(0,s.ordered_list); + + SimulationDataSet x = new SimulationDataSet(s); + //x.overwrittenWith_set(s); + + Tools.mapRemoveAll(x.dvMap, this.dvSet); + Tools.mapRemoveAll(x.svMap, this.svSet); + Tools.mapRemoveAll(x.asMap, this.asSet); + Tools.mapRemoveAll(x.wtMap, this.wtSet); + Tools.mapRemoveAll(x.tsMap, this.tsSet); + Tools.mapRemoveAll(x.gMap, this.gSet); + Tools.mapRemoveAll(x.exMap, this.exSet); + Tools.mapRemoveAll(x.incFileMap, this.incFileSet); + Tools.mapRemoveAll(x.var_neededVarCycle_map, this.varNeedEarlierCycle); + + x.dvSet.addAll(this.dvSet); + x.dvSet_global.addAll(this.dvSet_global); + x.dvSet_local.addAll(this.dvSet_local); + this.dvSet = x.dvSet; + this.dvSet_global = x.dvSet_global; + this.dvSet_local = x.dvSet_local; + this.dvMap.putAll(x.dvMap); + + x.svSet.addAll(this.svSet); + x.svSet_global.addAll(this.svSet_global); + x.svSet_local.addAll(this.svSet_local); + this.svSet = x.svSet; + this.svSet_global = x.svSet_global; + this.svSet_local = x.svSet_local; + this.svMap.putAll(x.svMap); + + x.tsSet.addAll(this.tsSet); + x.tsSet_global.addAll(this.tsSet_global); + x.tsSet_local.addAll(this.tsSet_local); + this.tsSet = x.tsSet; + this.tsSet_global = x.tsSet_global; + this.tsSet_local = x.tsSet_local; + this.tsMap.putAll(x.tsMap); + + x.asSet.addAll(this.asSet); + x.asSet_global.addAll(this.asSet_global); + x.asSet_local.addAll(this.asSet_local); + this.asSet = x.asSet; + this.asSet_global = x.asSet_global; + this.asSet_local = x.asSet_local; + this.asMap.putAll(x.asMap); + + x.gSet.addAll(this.gSet); + x.gSet_global.addAll(this.gSet_global); + x.gSet_local.addAll(this.gSet_local); + this.gSet = x.gSet; + this.gSet_global = x.gSet_global; + this.gSet_local = x.gSet_local; + this.gMap.putAll(x.gMap); + + x.wtSet.addAll(this.wtSet); + x.wtSet_global.addAll(this.wtSet_global); + x.wtSet_local.addAll(this.wtSet_local); + this.wtSet = x.wtSet; + this.wtSet_global = x.wtSet_global; + this.wtSet_local = x.wtSet_local; + this.wtMap.putAll(x.wtMap); + + x.exSet.addAll(this.exSet); + x.exSet_global.addAll(this.exSet_global); + x.exSet_local.addAll(this.exSet_local); + this.exSet = x.exSet; + this.exSet_global = x.exSet_global; + this.exSet_local = x.exSet_local; + this.exMap.putAll(x.exMap); + + x.incFileSet.addAll(this.incFileSet); + x.incFileSet_global.addAll(this.incFileSet_global); + x.incFileSet_local.addAll(this.incFileSet_local); + this.incFileSet = x.incFileSet; + this.incFileSet_global = x.incFileSet_global; + this.incFileSet_local = x.incFileSet_local; + this.incFileMap.putAll(x.incFileMap); + + x.varNeedEarlierCycle.addAll(this.varNeedEarlierCycle); + this.varNeedEarlierCycle = x.varNeedEarlierCycle; + this.var_neededVarCycle_map.putAll(x.var_neededVarCycle_map); + + return this; + } + + public SimulationDataSet replaceGlobalWithDuplicateGlobal(Set keys, SimulationDataSet s) { + + for (String k : keys) { + + if (this.dvSet.contains(k)){ +// this.dvSet_global.remove(k); +// this.dvSet_local.add(k); + this.dvMap.put(k,s.dvMap.get(k)); + } + if (this.svSet.contains(k)){ +// this.svSet_global.remove(k); +// this.svSet_local.add(k); + this.svMap.put(k,s.svMap.get(k)); + } + + if (this.tsSet.contains(k)){ +// this.tsSet_global.remove(k); +// this.tsSet_local.add(k); + this.tsMap.put(k,s.tsMap.get(k)); + } + if (this.asSet.contains(k)){ +// this.asSet_global.remove(k); +// this.asSet_local.add(k); + this.asMap.put(k,s.asMap.get(k)); + } + if (this.gSet.contains(k)){ +// this.gSet_global.remove(k); +// this.gSet_local.add(k); + this.gMap.put(k,s.gMap.get(k)); + } + if (this.exSet.contains(k)){ +// this.exSet_global.remove(k); +// this.exSet_local.add(k); + this.exMap.put(k,s.exMap.get(k)); + } + if (this.varNeedEarlierCycle.contains(k)){ + this.var_neededVarCycle_map.put(k,s.var_neededVarCycle_map.get(k)); + } + } + + return this; + } + + public SimulationDataSet replaceGlobalWithDuplicateLocal(Set keys, SimulationDataSet s) throws TypeRedefinedException { + + for (String k : keys) { + + if (this.dvSet.contains(k)){ + + if( !s.dvSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); + + this.dvSet_global.remove(k); + this.dvSet_local.add(k); + this.dvMap.put(k,s.dvMap.get(k)); + } + if (this.svSet.contains(k)){ + if( !s.svSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); + this.svSet_global.remove(k); + this.svSet_local.add(k); + this.svMap.put(k,s.svMap.get(k)); + } + + if (this.tsSet.contains(k)){ + if( !s.tsSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); + this.tsSet_global.remove(k); + this.tsSet_local.add(k); + this.tsMap.put(k,s.tsMap.get(k)); + } + if (this.asSet.contains(k)){ + if( !s.asSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); + this.asSet_global.remove(k); + this.asSet_local.add(k); + this.asMap.put(k,s.asMap.get(k)); + } + if (this.gSet.contains(k)){ + if( !s.gSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); + this.gSet_global.remove(k); + this.gSet_local.add(k); + this.gMap.put(k,s.gMap.get(k)); + } + if (this.exSet.contains(k)){ + if( !s.exSet.contains(k)) LogUtils.typeRedefinedErrMsg("Variable is redefined as different type: "+k); + this.exSet_global.remove(k); + this.exSet_local.add(k); + this.exMap.put(k,s.exMap.get(k)); + } + if (this.varNeedEarlierCycle.contains(k)){ + this.var_neededVarCycle_map.put(k,s.var_neededVarCycle_map.get(k)); + } + } + + return this; + } + + public SimulationDataSet getGlobalVars_set() + { + SimulationDataSet out = new SimulationDataSet(); + + Set t; + t= new LinkedHashSet(this.asSet); + t.retainAll(this.asSet_global); + out.asSet.addAll(t); + out.asSet_global.addAll(t); + + for (String key : this.asSet_global) { + out.asMap.put(key, (Alias)this.asMap.get(key)); + } + + t = new LinkedHashSet(this.wtSet); + t.retainAll(this.wtSet_global); + out.wtSet.addAll(t); + out.wtSet_global.addAll(t); + + for (String key : this.wtSet_global) { + out.wtMap.put(key, (WeightElement)this.wtMap.get(key)); + } + + t = new LinkedHashSet(this.incFileSet); + t.retainAll(this.incFileSet_global); + out.incFileSet.addAll(t); + out.incFileSet_global.addAll(t); + + for (String key : this.incFileSet_global) { + out.incFileMap.put(key, (IncludeFile)this.incFileMap.get(key)); + } + + t = new LinkedHashSet(this.exSet); + t.retainAll(this.exSet_global); + out.exSet.addAll(t); + out.exSet_global.addAll(t); + + for (String key : this.exSet_global) { + out.exMap.put(key, (External)this.exMap.get(key)); + } + + t = new LinkedHashSet(this.svSet); + t.retainAll(this.svSet_global); + + out.svSet.addAll(t); + out.svSet_global.addAll(t); + + for (String key : this.svSet_global) { + out.svMap.put(key, (Svar)this.svMap.get(key)); + } + + t = new LinkedHashSet(this.tsSet); + t.retainAll(this.tsSet_global); + out.tsSet.addAll(t); + out.tsSet_global.addAll(t); + + for (String key : this.tsSet_global) { + out.tsMap.put(key, (Timeseries)this.tsMap.get(key)); + } + + t = new LinkedHashSet(this.dvSet); + t.retainAll(this.dvSet_global); + out.dvSet.addAll(t); + out.dvSet_global.addAll(t); + + for (String key : this.dvSet_global) { + out.dvMap.put(key, (Dvar)this.dvMap.get(key)); + } + + t = new LinkedHashSet(this.gSet); + t.retainAll(this.gSet_global); + out.gSet.addAll(t); + out.gSet_global.addAll(t); + + for (String key : this.gSet_global) { + out.gMap.put(key, (Goal)this.gMap.get(key)); + } + + //////// + t = new LinkedHashSet(this.varNeedEarlierCycle); + t.retainAll(this.svSet_global); + t.retainAll(this.asSet_global); + out.varNeedEarlierCycle.addAll(t); + for (String key : out.varNeedEarlierCycle) { + out.var_neededVarCycle_map.put(key, this.var_neededVarCycle_map.get(key)); + } + + return out; + } + + public SimulationDataSet convertToLocal_set(){ + + this.asSet_local.addAll(this.asSet); + this.asSet_global.clear(); + + this.wtSet_local.addAll(this.wtSet); + this.wtSet_global.clear(); + + this.tsSet_local.addAll(this.tsSet); + this.tsSet_global.clear(); + + this.dvSet_local.addAll(this.dvSet); + this.dvSet_global.clear(); + + this.svSet_local.addAll(this.svSet); + this.svSet_global.clear(); + + this.exSet_local.addAll(this.exSet); + this.exSet_global.clear(); + + this.gSet_local.addAll(this.gSet); + this.gSet_global.clear(); + + this.incFileSet_local.addAll(this.incFileSet); + this.incFileSet_global.clear(); + + return this; + } + +public Set getAllGlobalVarsSet_except_file_and_weight(){ + + Set out = new HashSet(); + + out.addAll(this.asSet_global); + out.addAll(this.dvSet_global); + out.addAll(this.svSet_global); + out.addAll(this.gSet_global); + out.addAll(this.exSet_global); + + return out; + } + +public Set getAllLocalVarsSet_except_file_and_weight(){ + + Set out = new HashSet(); + + out.addAll(this.asSet_local); + out.addAll(this.dvSet_local); + out.addAll(this.svSet_local); + out.addAll(this.gSet_local); + out.addAll(this.exSet_local); + + return out; + } + +public Set getAllVarsSet_except_file_and_weight(){ + + Set out = new HashSet(); + + out.addAll(this.asSet); + out.addAll(this.dvSet); + out.addAll(this.svSet); + out.addAll(this.gSet); + out.addAll(this.exSet); + + return out; + } + +public Set getSvarAliasExternTimeseries(){ + + Set out = new HashSet(); + + out.addAll(this.asSet); + out.addAll(this.svSet); + out.addAll(this.tsSet); + out.addAll(this.exSet); + + return out; + } + +public SimulationDataSet remove_set(Set s) + { + +// this.wtSet.removeAll(s); +// this.wtSet_global.removeAll(s); +// this.wtSet_local.removeAll(s); +// +// Tools.mapRemoveAll(this.wtMap, s); + + + this.incFileSet.removeAll(s); + this.incFileSet_global.removeAll(s); + this.incFileSet_local.removeAll(s); + + Tools.mapRemoveAll(this.incFileMap, s); + + + this.exSet.removeAll(s); + this.exSet_global.removeAll(s); + this.exSet_local.removeAll(s); + + Tools.mapRemoveAll(this.exMap, s); + + + this.tsSet.removeAll(s); + this.tsSet_global.removeAll(s); + this.tsSet_local.removeAll(s); + + Tools.mapRemoveAll(this.tsMap, s); + + + this.svSet.removeAll(s); + this.svSet_global.removeAll(s); + this.svSet_local.removeAll(s); + + Tools.mapRemoveAll(this.svMap, s); + + + this.dvSet.removeAll(s); + this.dvSet_global.removeAll(s); + this.dvSet_local.removeAll(s); + + Tools.mapRemoveAll(this.dvMap, s); + + + this.asSet.removeAll(s); + this.asSet_global.removeAll(s); + this.asSet_local.removeAll(s); + + Tools.mapRemoveAll(this.asMap, s); + + + this.gSet.removeAll(s); + this.gSet_global.removeAll(s); + this.gSet_local.removeAll(s); + + Tools.mapRemoveAll(this.gMap, s); + + + this.varNeedEarlierCycle.removeAll(s); + + Tools.mapRemoveAll(this.var_neededVarCycle_map, s); + + + return this; + } + +public SimulationDataSet overwrittenWith_set(SimulationDataSet s) { + + //this.ordered_list_including_files.addAll(s.ordered_list_including_files); + //this.ordered_list.addAll(s.ordered_list); + + this.dvSet.addAll(s.dvSet); + this.dvSet_global.addAll(s.dvSet_global); + this.dvSet_local.addAll(s.dvSet_local); + this.dvMap.putAll(s.dvMap); + + this.svSet.addAll(s.svSet); + this.svSet_global.addAll(s.svSet_global); + this.svSet_local.addAll(s.svSet_local); + +// /// experiment with deep copy +// Map t = new HashMap(); +// for (Map.Entry e : s.svMap.entrySet()){ +// t.put(e.getKey(), new Svar(e.getValue())); +// } + + this.svMap.putAll(s.svMap); + + this.tsSet.addAll(s.tsSet); + this.tsSet_global.addAll(s.tsSet_global); + this.tsSet_local.addAll(s.tsSet_local); + this.tsMap.putAll(s.tsMap); + + this.asSet.addAll(s.asSet); + this.asSet_global.addAll(s.asSet_global); + this.asSet_local.addAll(s.asSet_local); + this.asMap.putAll(s.asMap); + + this.gSet.addAll(s.gSet); + this.gSet_global.addAll(s.gSet_global); + this.gSet_local.addAll(s.gSet_local); + this.gMap.putAll(s.gMap); + + this.wtSet.addAll(s.wtSet); + this.wtSet_global.addAll(s.wtSet_global); + this.wtSet_local.addAll(s.wtSet_local); + this.wtMap.putAll(s.wtMap); + + this.exSet.addAll(s.exSet); + this.exSet_global.addAll(s.exSet_global); + this.exSet_local.addAll(s.exSet_local); + this.exMap.putAll(s.exMap); + + this.incFileSet.addAll(s.incFileSet); + this.incFileSet_global.addAll(s.incFileSet_global); + this.incFileSet_local.addAll(s.incFileSet_local); + this.incFileMap.putAll(s.incFileMap); + + this.varNeedEarlierCycle.addAll(s.varNeedEarlierCycle); + this.var_neededVarCycle_map.putAll(s.var_neededVarCycle_map); + + this.lousyConvert(); + + return this; + } + +public void lousyConvert() { + + this.asList = new ArrayList(this.asSet); + this.asList_global = new ArrayList(this.asSet_global); + this.asList_local = new ArrayList(this.asSet_local); + + this.wtList = new ArrayList(this.wtSet); + this.wtList_global = new ArrayList(this.wtSet_global); + this.wtList_local = new ArrayList(this.wtSet_local); + + this.svList = new ArrayList(this.svSet); + this.svList_global = new ArrayList(this.svSet_global); + this.svList_local = new ArrayList(this.svSet_local); + + this.dvList = new ArrayList(this.dvSet); + this.dvList_global = new ArrayList(this.dvSet_global); + this.dvList_local = new ArrayList(this.dvSet_local); + + this.tsList = new ArrayList(this.tsSet); + this.tsList_global = new ArrayList(this.tsSet_global); + this.tsList_local = new ArrayList(this.tsSet_local); + + this.exList = new ArrayList(this.exSet); + this.exList_global = new ArrayList(this.exSet_global); + this.exList_local = new ArrayList(this.exSet_local); + + this.gList = new ArrayList(this.gSet); + this.gList_global = new ArrayList(this.gSet_global); + this.gList_local = new ArrayList(this.gSet_local); + + this.incFileList = new ArrayList(this.incFileSet); + this.incFileList_global = new ArrayList(this.incFileSet_global); + this.incFileList_local = new ArrayList(this.incFileSet_local); + +} } \ No newline at end of file diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Sort.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/Sort.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Sort.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/Sort.java index 1c9fb2975..ea21f5e14 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Sort.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/Sort.java @@ -1,159 +1,159 @@ -package wrimsv2.wreslparser.elements; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.Svar; - -public class Sort { - - private Map> varDependentMap; - private Map varTypeMap = new HashMap(); - private Set previousSet = new HashSet();; - - // for iteration only - private Set outSet = new HashSet(); - - - - //sorting - - // Group dv: previous step dv that will be needed. - // TODO: this might need more work to get the number of prior steps are needed for dv. - - // Group 1: No dependents or ONLY dependent on timeseries, and control data like month or water year ( dependant.size ==0 ) - - // NextGroup : recursive - - public Sort(Map file_data_map ){ - - varDependentMap = new HashMap>(); - - for (Map.Entry e: file_data_map.entrySet()){ - - Set d = e.getValue().incFileSet; - varDependentMap.put(e.getKey(), d); - varTypeMap.put(e.getKey(), "Include File"); - } - } - - // sorting based on union of svar and alias - public Sort(Map in_svMap, Map in_asMap, SetdvSet, SettsSet, SetexSet){ - - varDependentMap = new HashMap>(); - - for (String key : exSet){ - Set d = new HashSet(); // empty set - varDependentMap.put(key, d); - varTypeMap.put(key, "External"); - } - - for (Map.Entry e: in_svMap.entrySet()){ - - Set d = e.getValue().dependants; - d.removeAll(Param.reservedSet); - d.removeAll(dvSet);d.removeAll(tsSet);//d.removeAll(externalSet); - varDependentMap.put(e.getKey(), d); - varTypeMap.put(e.getKey(), "Svar"); - } - - for (Map.Entry e: in_asMap.entrySet()){ - - Set d = e.getValue().dependants; - d.removeAll(Param.reservedSet); - d.removeAll(dvSet);d.removeAll(tsSet);//d.removeAll(externalSet); - varDependentMap.put(e.getKey(), d); - varTypeMap.put(e.getKey(), "Alias"); - } - - } - - - public Set sort(ArrayList toBeSortedList){ - - toBeSortedList.clear(); - - // get first group - toBeSortedList.addAll(getGroup1()); - - // recursive - while (getNextGroup(outSet)) { - - ArrayList outList = new ArrayList(outSet); - Collections.sort(outList); - - toBeSortedList.addAll(outList); - } - - // var depend on unknowns - if (varDependentMap.keySet().size()>0) { - - //allows recursive svar definition for future array - //LogUtils.errMsg("Variables with unknown dependants: "+ varDependentMap.keySet()); - LogUtils.warningMsg("Variables with unknown dependants: "+ varDependentMap.keySet()); - if (Param.debug){ - for (String key:varDependentMap.keySet() ){ - LogUtils.warningMsg("Variables type of "+ key +": "+ varTypeMap.get(key)); - } - } - } - - // var depend on unknowns - return varDependentMap.keySet(); - } - - - // Group 1 : dependant.size ==0 - private Set getGroup1() { - - Set out = new HashSet(); - - for ( Map.Entry> e : varDependentMap.entrySet() ) { - - //System.out.println(" *** before: " + e.getKey()); - - if (e.getValue().size()==0) { - - out.add(e.getKey()); - } - } - - for ( String o : out ) { - varDependentMap.remove(o); - } - previousSet.addAll(out); - return out; - } - - - private boolean getNextGroup( Set out ) { - - boolean OK = false; - - out.clear(); - - for ( Map.Entry> e : varDependentMap.entrySet() ) { - - if (previousSet.containsAll(e.getValue()) ) { - - out.add(e.getKey()); - } - } - - for ( String o : out ) { - varDependentMap.remove(o); - } - - previousSet.addAll(out); - - if (out.size()>0) OK = true; - - return OK; - } -} +package wrimsv2.wreslparser.elements; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.commondata.wresldata.Svar; + +public class Sort { + + private Map> varDependentMap; + private Map varTypeMap = new HashMap(); + private Set previousSet = new HashSet();; + + // for iteration only + private Set outSet = new HashSet(); + + + + //sorting + + // Group dv: previous step dv that will be needed. + // TODO: this might need more work to get the number of prior steps are needed for dv. + + // Group 1: No dependents or ONLY dependent on timeseries, and control data like month or water year ( dependant.size ==0 ) + + // NextGroup : recursive + + public Sort(Map file_data_map ){ + + varDependentMap = new HashMap>(); + + for (Map.Entry e: file_data_map.entrySet()){ + + Set d = e.getValue().incFileSet; + varDependentMap.put(e.getKey(), d); + varTypeMap.put(e.getKey(), "Include File"); + } + } + + // sorting based on union of svar and alias + public Sort(Map in_svMap, Map in_asMap, SetdvSet, SettsSet, SetexSet){ + + varDependentMap = new HashMap>(); + + for (String key : exSet){ + Set d = new HashSet(); // empty set + varDependentMap.put(key, d); + varTypeMap.put(key, "External"); + } + + for (Map.Entry e: in_svMap.entrySet()){ + + Set d = e.getValue().dependants; + d.removeAll(Param.reservedSet); + d.removeAll(dvSet);d.removeAll(tsSet);//d.removeAll(externalSet); + varDependentMap.put(e.getKey(), d); + varTypeMap.put(e.getKey(), "Svar"); + } + + for (Map.Entry e: in_asMap.entrySet()){ + + Set d = e.getValue().dependants; + d.removeAll(Param.reservedSet); + d.removeAll(dvSet);d.removeAll(tsSet);//d.removeAll(externalSet); + varDependentMap.put(e.getKey(), d); + varTypeMap.put(e.getKey(), "Alias"); + } + + } + + + public Set sort(ArrayList toBeSortedList){ + + toBeSortedList.clear(); + + // get first group + toBeSortedList.addAll(getGroup1()); + + // recursive + while (getNextGroup(outSet)) { + + ArrayList outList = new ArrayList(outSet); + Collections.sort(outList); + + toBeSortedList.addAll(outList); + } + + // var depend on unknowns + if (varDependentMap.keySet().size()>0) { + + //allows recursive svar definition for future array + //LogUtils.errMsg("Variables with unknown dependants: "+ varDependentMap.keySet()); + LogUtils.warningMsg("Variables with unknown dependants: "+ varDependentMap.keySet()); + if (Param.debug){ + for (String key:varDependentMap.keySet() ){ + LogUtils.warningMsg("Variables type of "+ key +": "+ varTypeMap.get(key)); + } + } + } + + // var depend on unknowns + return varDependentMap.keySet(); + } + + + // Group 1 : dependant.size ==0 + private Set getGroup1() { + + Set out = new HashSet(); + + for ( Map.Entry> e : varDependentMap.entrySet() ) { + + //System.out.println(" *** before: " + e.getKey()); + + if (e.getValue().size()==0) { + + out.add(e.getKey()); + } + } + + for ( String o : out ) { + varDependentMap.remove(o); + } + previousSet.addAll(out); + return out; + } + + + private boolean getNextGroup( Set out ) { + + boolean OK = false; + + out.clear(); + + for ( Map.Entry> e : varDependentMap.entrySet() ) { + + if (previousSet.containsAll(e.getValue()) ) { + + out.add(e.getKey()); + } + } + + for ( String o : out ) { + varDependentMap.remove(o); + } + + previousSet.addAll(out); + + if (out.size()>0) OK = true; + + return OK; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StructTree.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/StructTree.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StructTree.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/StructTree.java index d99adfc84..ae929b205 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StructTree.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/StructTree.java @@ -1,772 +1,772 @@ -package wrimsv2.wreslparser.elements; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.External; -import wrimsv2.commondata.wresldata.Goal; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.commondata.wresldata.Timeseries; -import wrimsv2.commondata.wresldata.WeightElement; - -public class StructTree -{ - public SimulationDataSet S; - public WeightElement wt; - public Sequence seq; - public IncludeFile incFile; - public External ex; - public Timeseries svTs; - public Svar sv; - public Dvar dv; - public Alias as; - public Goal gl; - private static String[] keys = { "define", "goal" }; - private static String[] mons = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", - "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" }; - - public static List r_keys = Arrays.asList(keys); - public static List r_mons = Arrays.asList(mons); - - public void modelList(String name) - { - name = name.toLowerCase(); - - if (this.S.model_list.contains(name)) { - LogUtils.errMsg("Model redefined: " + name, this.S.currentAbsolutePath); - this.S.error_model_redefined.add(name); - } - else { - this.S.model_list.add(name); - this.S.var_all.put(name, "model"); - } - } - - public void mergeWeightTable(String name, String value, String scope){ - mergeWeightTable(name, value, scope, "0"); - } - - public void mergeWeightTable(String name, String value, String scope, String timeArraySizeStr){ - - // TODO: weights redefined in different files are not checked within the same model - - name = name.toLowerCase(); - value = value.toLowerCase(); - timeArraySizeStr=timeArraySizeStr.toLowerCase(); - - if (this.S.wtList.contains(name)) { - LogUtils.errMsg("Weight redefined: " + name, this.S.currentAbsolutePath); - this.S.error_weightVar_redefined.put(name, this.S.currentAbsolutePath); - //this.S.wtList.remove(name); this.S.wtList_global.remove(name); this.S.wtList_local.remove(name); - } - - this.wt = new WeightElement(); - this.wt.weight = value; - this.wt.fromWresl = this.S.currentAbsolutePath; - this.wt.timeArraySize=timeArraySizeStr; - this.S.wtMap.put(name, this.wt); - - this.S.wtList.add(name); - this.S.wtSet.add(name); - - if (scope == null) { - this.S.wtList_global.add(name); this.S.wtSet_global.add(name);} - else if (scope.equalsIgnoreCase(Param.local)) { - this.S.wtList_local.add(name); this.S.wtSet_local.add(name); } - else { - LogUtils.errMsg("Weight table scope undefined: " + name, this.S.currentAbsolutePath); - } - - } - - public void includeFile(String fileRelativePath, String scope) - { - fileRelativePath = fileRelativePath.toLowerCase(); - fileRelativePath = Tools.replace_pathseperator(fileRelativePath); - - File absIncludeFile = new File(this.S.currentAbsoluteParent, fileRelativePath).getAbsoluteFile(); - String absIncludeFilePath = "Error with include file: " + fileRelativePath; - try { - absIncludeFilePath = absIncludeFile.getCanonicalPath().toLowerCase(); - } - catch (IOException e) - { - e.printStackTrace(); - LogUtils.errMsg("Include file IOException: " + fileRelativePath, this.S.currentAbsolutePath); - } - - if (this.S.var_all.containsKey(absIncludeFilePath)) { - LogUtils.errMsg("Include file redefined: " + fileRelativePath, this.S.currentAbsolutePath); - this.S.error_var_redefined.put(absIncludeFilePath, "file"); - //this.S.incFileList.remove(absIncludeFilePath); this.S.incFileList_global.remove(absIncludeFilePath); this.S.incFileList_local.remove(absIncludeFilePath); - } - - this.S.ordered_list_including_files.add(absIncludeFilePath); - - this.S.var_all.put(absIncludeFilePath, "file"); - - this.incFile = new IncludeFile(); - - this.incFile.fromWresl = this.S.currentAbsolutePath; - - this.S.incFileMap.put(absIncludeFilePath, this.incFile); - this.S.incFileList.add(absIncludeFilePath); - - this.S.incFileSet.add(absIncludeFilePath); - - if (scope == null) { - this.S.incFileList_global.add(absIncludeFilePath); - this.S.incFileSet_global.add(absIncludeFilePath); - this.incFile.scope = Param.global; - - this.S.ordered_list_including_files_global.add(absIncludeFilePath); - } - else if (scope.equalsIgnoreCase(Param.local)) { - this.S.incFileList_local.add(absIncludeFilePath); - this.S.incFileSet_local.add(absIncludeFilePath); - this.incFile.scope = Param.local; } - else { - LogUtils.errMsg("Include file scope undefined: " + fileRelativePath, this.S.currentAbsolutePath); - } - } - - public Goal goalSimple(String name, String scope, String expression, String dependants, String varInCycle){ - return goalSimple(name, scope, expression, dependants, varInCycle, "0"); - } - - public Goal goalSimple(String name, String scope, String expression, String dependants, String varInCycle, String timeArraySizeStr) - { - timeArraySizeStr=timeArraySizeStr.toLowerCase(); - name = name.toLowerCase(); - expression = expression.toLowerCase(); - if (dependants != null) dependants = dependants.toLowerCase(); - if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("Goal redefined: " + name, this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "goal"); - // this.S.gList.remove(name); this.S.gList_global.remove(name); this.S.gList_local.remove(name); - } - - this.S.ordered_list.add(name); - this.S.ordered_list_including_files.add(name); - - this.S.var_all.put(name, "goal"); - - this.gl = new Goal(); - this.gl.caseCondition.add(Param.always); - this.gl.caseName.add(Param.defaultCaseName); - this.gl.caseExpression.add(expression); - this.gl.fromWresl = this.S.currentAbsolutePath; - if (dependants != null) { - this.gl.expressionDependants.addAll(Tools.convertStrToSet(dependants)); - this.gl.expressionDependants.removeAll(Param.reservedSet); - } - if (varInCycle != null) { - this.gl.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); - this.gl.needVarFromEarlierCycle = true; - } - this.gl.timeArraySize=timeArraySizeStr; - - - this.S.gMap.put(name, this.gl); - this.S.gList.add(name); - this.S.gSet.add(name); - - if (scope == null) { - this.S.gList_global.add(name); this.S.gSet_global.add(name); this.gl.scope = Param.global; - this.S.ordered_list_global.add(name); - this.S.ordered_list_including_files_global.add(name); - } else if (scope.equalsIgnoreCase(Param.local)) { - this.S.gList_local.add(name); this.S.gSet_local.add(name); this.gl.scope = Param.local; } else { - LogUtils.errMsg("Goal scope undefined: " + name, this.S.currentAbsolutePath); - } - return gl; - } - - public void goalCase(String name, String scope, Goal gl){ - goalCase(name, scope, gl, "0"); - } - - public void goalCase(String name, String scope, Goal gl, String timeArraySizeStr) - { - name = name.toLowerCase(); - timeArraySizeStr=timeArraySizeStr.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("Goal redefined: " + name, this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "goal"); - // this.S.gList.remove(name); this.S.gList_global.remove(name); this.S.gList_local.remove(name); - } - - this.S.ordered_list.add(name); - this.S.ordered_list_including_files.add(name); - - this.S.var_all.put(name, "goal"); - - gl.fromWresl = this.S.currentAbsolutePath; - - this.S.gMap.put(name, gl); - this.S.gList.add(name); - this.S.gSet.add(name); - - - gl.timeArraySize=timeArraySizeStr; - if (scope == null) { - this.S.gList_global.add(name); this.S.gSet_global.add(name); gl.scope = Param.global; - this.S.ordered_list_global.add(name); - this.S.ordered_list_including_files_global.add(name); - } else if (scope.equalsIgnoreCase(Param.local)) { - this.S.gList_local.add(name); this.S.gSet_local.add(name); gl.scope = Param.local; } else { - LogUtils.errMsg("Goal scope undefined: " + name, this.S.currentAbsolutePath); - } - } - - public void alias(String name, String scope, String kind, String units, String expression, String dependants, String varInCycle){ - alias(name, scope, kind, units, expression, dependants, varInCycle, "0"); - } - - public void alias(String name, String scope, String kind, String units, String expression, String dependants, String varInCycle, String timeArraySizeStr) - { - name = name.toLowerCase(); - if (kind != null) kind = kind.toLowerCase(); - if (units != null) units = units.toLowerCase(); - expression = expression.toLowerCase(); - if (dependants != null) dependants = dependants.toLowerCase(); - if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); - timeArraySizeStr=timeArraySizeStr.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("Alias redefined: " + name, this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "alias"); - //this.S.asList.remove(name); this.S.asList_global.remove(name); this.S.asList_local.remove(name); - } - - this.S.ordered_list.add(name); - this.S.ordered_list_including_files.add(name); - - this.S.var_all.put(name, "alias"); - - this.as = new Alias(); - - if (kind != null) this.as.kind = kind; - if (units != null) this.as.units = units; - this.as.expression = expression; - this.as.fromWresl = this.S.currentAbsolutePath; - this.as.timeArraySize=timeArraySizeStr; - if (dependants != null) this.as.dependants = Tools.convertStrToSet(dependants); - if (varInCycle != null) { - this.as.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); - this.as.needVarFromEarlierCycle = true; - } - - this.S.asMap.put(name, this.as); - this.S.asList.add(name); - this.S.asSet.add(name); - - if (scope == null) { - this.S.asList_global.add(name); this.S.asSet_global.add(name); this.as.scope = Param.global; - this.S.ordered_list_global.add(name); - this.S.ordered_list_including_files_global.add(name); - } else if (scope.toLowerCase().equals(Param.local)) { - this.S.asList_local.add(name); this.S.asSet_local.add(name); this.as.scope = Param.local; } else { - LogUtils.errMsg("Alias scope undefined: " + name, this.S.currentAbsolutePath); - } - } - - public void svarCase(String name, String scope, Svar sv, String dependants, String varInCycle) - { - svarCase(name, scope, sv, dependants, varInCycle, "0"); - } - - public void svarCase(String name, String scope, Svar sv, String dependants, String varInCycle, String timeArraySizeStr) - { - timeArraySizeStr = timeArraySizeStr.toLowerCase(); - name = name.toLowerCase(); - if (dependants != null) dependants = dependants.toLowerCase(); - if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("Svar redefined: " + name, this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "svar"); - //this.S.svList.remove(name); this.S.svList_global.remove(name); this.S.svList_local.remove(name); - } - - this.S.ordered_list.add(name); - this.S.ordered_list_including_files.add(name); - - this.S.var_all.put(name, "svar"); - - sv.fromWresl = this.S.currentAbsolutePath; - sv.timeArraySize = timeArraySizeStr; - - if (dependants != null) sv.dependants = Tools.convertStrToSet(dependants); - if (varInCycle != null) { - sv.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); - sv.needVarFromEarlierCycle = true; - } - - this.S.svMap.put(name, sv); - this.S.svList.add(name); - this.S.svSet.add(name); - - if (scope == null) { - this.S.svList_global.add(name); this.S.svSet_global.add(name); sv.scope = Param.global; - this.S.ordered_list_global.add(name); - this.S.ordered_list_including_files_global.add(name); - } else if (scope.equalsIgnoreCase(Param.local)) { - this.S.svList_local.add(name); this.S.svSet_local.add(name); sv.scope = Param.local; } else { - LogUtils.errMsg("Svar scope undefined: " + name, this.S.currentAbsolutePath); - } - } - - public void external(String name, String scope, String externalType) - { - name = name.toLowerCase(); - externalType = externalType.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("External variable redefined: " + name, this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "external"); - //this.S.exList.remove(name); this.S.exList_global.remove(name); this.S.exList_local.remove(name); - } - - this.S.ordered_list.add(name); - this.S.ordered_list_including_files.add(name); - - this.S.var_all.put(name, "external"); - - this.ex = new External(); - this.ex.type = externalType; - this.ex.fromWresl = this.S.currentAbsolutePath; - - this.S.exMap.put(name, this.ex); - this.S.exList.add(name); - this.S.exSet.add(name); - - if (scope == null) { - this.S.exList_global.add(name); this.S.exSet_global.add(name); this.ex.scope = Param.global; - this.S.ordered_list_global.add(name); - this.S.ordered_list_including_files_global.add(name); - } - else if (scope.equalsIgnoreCase(Param.local)) { - this.S.exList_local.add(name); this.S.exSet_local.add(name); this.ex.scope = Param.local; } else { - LogUtils.errMsg("External scope undefined: " + name, this.S.currentAbsolutePath); - } - } - - public void svarExpression(String name, String scope, String expression, String dependants, String varInCycle) - { - svarExpression(name, scope, expression, dependants, varInCycle, "0"); - } - - public void svarExpression(String name, String scope, String expression, String dependants, String varInCycle, String timeArraySizeStr) - { - timeArraySizeStr = timeArraySizeStr.toLowerCase(); - name = name.toLowerCase(); - expression = expression.toLowerCase(); - if (dependants != null) dependants = dependants.toLowerCase(); - if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("State variable redefined: " + name, this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "svar"); - //this.S.svList.remove(name); this.S.svList_global.remove(name); this.S.svList_local.remove(name); - } - - this.S.ordered_list.add(name); - this.S.ordered_list_including_files.add(name); - - this.S.var_all.put(name, "svar"); - - String caseName = Param.defaultCaseName; - String condition = Param.always; - - this.sv = new Svar(); - - this.sv.caseName.add(caseName); - this.sv.caseCondition.add(condition); - this.sv.caseExpression.add(expression); - this.sv.fromWresl = this.S.currentAbsolutePath; - this.sv.timeArraySize = timeArraySizeStr; - - if (dependants != null) this.sv.dependants = Tools.convertStrToSet(dependants); - if (varInCycle != null) { - this.sv.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); - this.sv.needVarFromEarlierCycle = true; - } - - this.S.svMap.put(name, this.sv); - this.S.svList.add(name); - this.S.svSet.add(name); - - if (scope == null) { - this.S.svList_global.add(name); this.S.svSet_global.add(name); this.sv.scope = Param.global; - this.S.ordered_list_global.add(name); - this.S.ordered_list_including_files_global.add(name); - } else if (scope.equalsIgnoreCase(Param.local)) { - this.S.svList_local.add(name); this.S.svSet_local.add(name); this.sv.scope = Param.local; } else { - LogUtils.errMsg("Svar scope undefined: " + name, this.S.currentAbsolutePath); - } - } - - public void svarSum(String name, String scope, String hdr, String expression, String dependants, String varInCycle) - { - svarSum(name, scope, hdr, expression, dependants, varInCycle, "0"); - } - - public void svarSum(String name, String scope, String hdr, String expression, String dependants, String varInCycle, String timeArraySizeStr) - { - name = name.toLowerCase(); - hdr = hdr.toLowerCase(); - expression = expression.toLowerCase(); - if (dependants != null) dependants = dependants.toLowerCase(); - if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); - timeArraySizeStr=timeArraySizeStr.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("State variable redefined: " + name, this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "svar"); - //this.S.svList.remove(name); this.S.svList_global.remove(name); this.S.svList_local.remove(name); - } - - this.S.ordered_list.add(name); - this.S.ordered_list_including_files.add(name); - - this.S.var_all.put(name, "svar"); - - this.sv = new Svar(); - - this.sv.caseName.add(Param.defaultCaseName); - this.sv.caseCondition.add("always"); - this.sv.caseExpression.add(hdr + " " + expression); - this.sv.fromWresl = this.S.currentAbsolutePath; - if (dependants != null) this.sv.dependants = Tools.convertStrToSet(dependants); - if (varInCycle != null) { - this.sv.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); - this.sv.needVarFromEarlierCycle = true; - } - this.sv.timeArraySize=timeArraySizeStr; - - this.S.svMap.put(name, this.sv); - this.S.svList.add(name); - this.S.svSet.add(name); - - if (scope == null) { - this.S.svList_global.add(name); this.S.svSet_global.add(name); this.sv.scope = Param.global; - this.S.ordered_list_global.add(name); - this.S.ordered_list_including_files_global.add(name); - } else if (scope.equalsIgnoreCase(Param.local)) { - this.S.svList_local.add(name); this.S.svSet_local.add(name); this.sv.scope = Param.local; } else { - LogUtils.errMsg("Svar scope undefined: " + name, this.S.currentAbsolutePath); - } - } - - public void svarTable(String name, String scope, String sqlStr, String dependants, String varInCycle){ - svarTable(name, scope, sqlStr, dependants, varInCycle, "0"); - } - - public void svarTable(String name, String scope, String sqlStr, String dependants, String varInCycle, String timeArraySizeStr) - { - name = name.toLowerCase(); - sqlStr = sqlStr.toLowerCase(); - timeArraySizeStr=timeArraySizeStr.toLowerCase(); - - if (dependants != null) dependants = dependants.toLowerCase(); - if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("State variable redefined: " + name, this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "svar"); - //this.S.svList.remove(name); this.S.svList_global.remove(name); this.S.svList_local.remove(name); - } - - this.S.ordered_list.add(name); - this.S.ordered_list_including_files.add(name); - - this.S.var_all.put(name, "svar"); - - this.sv = new Svar(); - - this.sv.format = "lookup_table"; - this.sv.caseCondition.add("always"); - this.sv.caseName.add(Param.defaultCaseName); - this.sv.caseExpression.add(sqlStr); - this.sv.fromWresl = this.S.currentAbsolutePath; - if (dependants != null) this.sv.dependants = Tools.convertStrToSet(dependants); - if (varInCycle != null) { - this.sv.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); - this.sv.needVarFromEarlierCycle = true; - } - this.sv.timeArraySize=timeArraySizeStr; - - this.S.svMap.put(name, this.sv); - this.S.svList.add(name); - this.S.svSet.add(name); - - if (scope == null) { - this.S.svList_global.add(name); this.S.svSet_global.add(name); this.sv.scope = Param.global; - this.S.ordered_list_global.add(name); - this.S.ordered_list_including_files_global.add(name); - } else if (scope.equalsIgnoreCase(Param.local)) { - this.S.svList_local.add(name); this.S.svSet_local.add(name); this.sv.scope = Param.local; } else { - LogUtils.errMsg("Svar scope undefined: " + name, this.S.currentAbsolutePath); - } - } - - public void timeseriesDss(String name, String scope, String b_part, String kind, String units, String convertToUnits) - { - name = name.toLowerCase(); - if (b_part != null) b_part = b_part.toLowerCase(); - kind = kind.toLowerCase(); - units = units.toLowerCase(); - if (convertToUnits != null) convertToUnits = convertToUnits.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("State variable redefined: " + name, this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "timeseries"); - //this.S.tsList.remove(name); this.S.tsList_global.remove(name); this.S.tsList_local.remove(name); - } - - this.S.var_all.put(name, "timeseries"); - - Timeseries ts = new Timeseries(); - - ts.dssBPart = name; - if (b_part != null) ts.dssBPart = b_part; - ts.kind = kind; - ts.units = units; - if (convertToUnits != null) ts.convertToUnits = convertToUnits; - ts.format = "dss"; - ts.fromWresl = this.S.currentAbsolutePath; - this.S.tsMap.put(name, ts); - this.S.tsList.add(name); - this.S.tsSet.add(name); - - if (scope == null) { - this.S.tsList_global.add(name); this.S.tsSet_global.add(name); ts.scope = Param.global; - } - else if (scope.equalsIgnoreCase(Param.local)) { - this.S.tsList_local.add(name); this.S.tsSet_local.add(name); ts.scope = Param.local; } else { - LogUtils.errMsg("Timeseries scope undefined: " + name, this.S.currentAbsolutePath); - } - } - - public void dvarStd(String name, String scope, String integer, String kind, String units) - { - dvarStd(name, scope, integer, kind, units, "0"); - } - - public void dvarStd(String name, String scope, String integer, String kind, String units, String timeArraySizeStr) - { - name = name.toLowerCase(); - timeArraySizeStr = timeArraySizeStr.toLowerCase(); - if (kind.length()>0) kind = kind.toLowerCase(); - if (units.length()>0) units = units.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("Dvar redefined: " + name, "\n" + this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "dvar"); - // this.S.dvList.remove(name); this.S.dvList_global.remove(name); this.S.dvList_local.remove(name); - } - - this.S.ordered_list.add(name); - this.S.ordered_list_including_files.add(name); - - this.S.var_all.put(name, "dvar"); - - this.S.dvSet.add(name); - - this.dv = new Dvar(); - if (kind.length()>0) this.dv.kind = kind; - if (units.length()>0) this.dv.units = units; - this.dv.lowerBound = Param.dv_std_lowerBound; - this.dv.upperBound = Param.dv_std_upperBound; - this.dv.fromWresl = this.S.currentAbsolutePath; - this.dv.timeArraySize = timeArraySizeStr; - - if (integer != null) - { - this.dv.integer = Param.yes; - this.dv.lowerBound = Param.dv_std_integer_lowerBound; - this.dv.upperBound = Param.dv_std_integer_upperBound; - } - - this.S.dvMap.put(name, this.dv); - this.S.dvList.add(name); - this.S.dvSet.add(name); - - if (scope == null) { - this.S.dvList_global.add(name); this.S.dvSet_global.add(name); this.dv.scope = Param.global; - this.S.ordered_list_global.add(name); - this.S.ordered_list_including_files_global.add(name); - } else if (scope.equalsIgnoreCase(Param.local)) { - this.S.dvList_local.add(name); this.S.dvSet_local.add(name); this.dv.scope = Param.local; } else { - LogUtils.errMsg("Dvar scope undefined: " + name, this.S.currentAbsolutePath); - } - } - - public void dvarNonStd(String name, String scope, String integer, String kind, String units, String lowerBound, String upperBound) - { - dvarNonStd(name, scope, integer, kind, units, lowerBound, upperBound, "0"); - } - - public void dvarNonStd(String name, String scope, String integer, String kind, String units, String lowerBound, String upperBound, String timeArraySizeStr) - { - name = name.toLowerCase(); - timeArraySizeStr = timeArraySizeStr.toLowerCase(); - if (kind != null) kind = kind.toLowerCase(); - if (units != null) units = units.toLowerCase(); - lowerBound = lowerBound.toLowerCase(); - upperBound = upperBound.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("Dvar redefined: " + name, this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "dvar"); - // this.S.dvList.remove(name); this.S.dvList_global.remove(name); this.S.dvList_local.remove(name); - } - - this.S.ordered_list.add(name); - this.S.ordered_list_including_files.add(name); - - this.S.var_all.put(name, "dvar"); - - this.dv = new Dvar(); - - if (kind != null) this.dv.kind = kind; - if (units != null) this.dv.units = units; - this.dv.lowerBound = lowerBound; - this.dv.upperBound = upperBound; - this.dv.fromWresl = this.S.currentAbsolutePath; - this.dv.timeArraySize = timeArraySizeStr; - - if (integer != null){ - this.dv.integer = Param.yes; - } - - this.S.dvMap.put(name, this.dv); - this.S.dvList.add(name); - this.S.dvSet.add(name); - - if (scope == null) { - this.S.dvList_global.add(name); this.S.dvSet_global.add(name); this.dv.scope = Param.global; - this.S.ordered_list_global.add(name); - this.S.ordered_list_including_files_global.add(name); - } else if (scope.equalsIgnoreCase(Param.local)) { - this.S.dvList_local.add(name); this.S.dvSet_local.add(name); this.dv.scope = Param.local; } else { - LogUtils.errMsg("Dvar scope undefined: " + name, this.S.currentAbsolutePath); - } - } - -public void sequenceOrder(String sequenceName, String order, String modelName, String condition, String timeStep) - { - sequenceName = sequenceName.toLowerCase(); - order = order.toLowerCase(); - modelName = modelName.toLowerCase(); - if (condition != null) condition = condition.toLowerCase(); - - Integer i = Integer.valueOf(Integer.parseInt(order)); - - if (this.S.seqList.contains(sequenceName)) { - this.S.error_sequence_redefined.add(sequenceName); - } else if (this.S.seqMap.containsKey(i)) { - this.S.error_sequence_order_redefined.add(i); - } - else { - this.seq = new Sequence(); - this.seq.sequenceName = sequenceName; - this.seq.condition = Param.always; - if (condition != null) this.seq.condition = condition; - this.seq.modelName = modelName; - this.seq.fromWresl = this.S.currentAbsolutePath; - this.seq.timeStep=timeStep; - this.S.seqMap.put(i, this.seq); - this.S.seqList.add(sequenceName); - } - } - -public void dvarSlackSurplus(String name, String scope, String kind, String units, String conditionStr) - { - dvarSlackSurplus(name, scope, kind, units, conditionStr, "0"); - } - -public void dvarSlackSurplus(String name, String scope, String kind, String units, String conditionStr, String timeArraySizeStr) - { - name = name.toLowerCase(); - timeArraySizeStr=timeArraySizeStr.toLowerCase(); - if (kind.length()>0) kind = kind.toLowerCase(); - if (units.length()>0) units = units.toLowerCase(); - - if (this.S.var_all.containsKey(name)) { - LogUtils.errMsg("Dvar redefined: " + name, "\n" + this.S.currentAbsolutePath); - this.S.error_var_redefined.put(name, "dvar"); - // this.S.dvList.remove(name); this.S.dvList_global.remove(name); this.S.dvList_local.remove(name); - } - - this.S.ordered_list.add(name); - this.S.ordered_list_including_files.add(name); - - this.S.var_all.put(name, "dvar"); - - this.dv = new Dvar(); - if (kind.length()>0) this.dv.kind = kind; - if (units.length()>0) this.dv.units = units; - this.dv.lowerBound = Param.dv_std_lowerBound; - this.dv.upperBound = Param.dv_std_upperBound; - this.dv.fromWresl = this.S.currentAbsolutePath; - this.dv.condition = conditionStr; - this.dv.timeArraySize=timeArraySizeStr; - - - this.S.dvMap.put(name, this.dv); - this.S.dvList.add(name); - this.S.dvSet.add(name); - - if (scope == null) { - this.S.dvList_global.add(name); this.S.dvSet_global.add(name); this.dv.scope = Param.global; - this.S.ordered_list_global.add(name); - this.S.ordered_list_including_files_global.add(name); - } else if (scope.equalsIgnoreCase(Param.local)) { - this.S.dvList_local.add(name); this.S.dvSet_local.add(name); this.dv.scope = Param.local; } else { - LogUtils.errMsg("Dvar (Slack or Surplus) scope undefined: " + name, this.S.currentAbsolutePath); - } - } - -public void mergeSlackSurplusIntoWeightTable(String name, String value, String scope, String conditionStr, String timeArraySizeStr){ - - // TODO: weights redefined in different files are not checked within the same model - - name = name.toLowerCase(); - value = value.toLowerCase(); - timeArraySizeStr = timeArraySizeStr.toLowerCase(); - - if (this.S.wtList.contains(name)) { - LogUtils.errMsg("Weight redefined: " + name, this.S.currentAbsolutePath); - this.S.error_weightVar_redefined.put(name, this.S.currentAbsolutePath); - //this.S.wtList.remove(name); this.S.wtList_global.remove(name); this.S.wtList_local.remove(name); - } - - this.wt = new WeightElement(); - this.wt.weight = value; - this.wt.fromWresl = this.S.currentAbsolutePath; - this.wt.condition = conditionStr; - this.wt.timeArraySize=timeArraySizeStr; - this.S.wtMap.put(name, this.wt); - - this.S.wtList.add(name); - this.S.wtSet.add(name); - - if (scope == null) { - this.S.wtList_global.add(name); this.S.wtSet_global.add(name);} - else if (scope.equalsIgnoreCase(Param.local)) { - this.S.wtList_local.add(name); this.S.wtSet_local.add(name); } - else { - LogUtils.errMsg("Weight table (Slack or Surplus) scope undefined: " + name, this.S.currentAbsolutePath); - } - - } +package wrimsv2.wreslparser.elements; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.External; +import wrimsv2.commondata.wresldata.Goal; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.commondata.wresldata.Timeseries; +import wrimsv2.commondata.wresldata.WeightElement; + +public class StructTree +{ + public SimulationDataSet S; + public WeightElement wt; + public Sequence seq; + public IncludeFile incFile; + public External ex; + public Timeseries svTs; + public Svar sv; + public Dvar dv; + public Alias as; + public Goal gl; + private static String[] keys = { "define", "goal" }; + private static String[] mons = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", + "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" }; + + public static List r_keys = Arrays.asList(keys); + public static List r_mons = Arrays.asList(mons); + + public void modelList(String name) + { + name = name.toLowerCase(); + + if (this.S.model_list.contains(name)) { + LogUtils.errMsg("Model redefined: " + name, this.S.currentAbsolutePath); + this.S.error_model_redefined.add(name); + } + else { + this.S.model_list.add(name); + this.S.var_all.put(name, "model"); + } + } + + public void mergeWeightTable(String name, String value, String scope){ + mergeWeightTable(name, value, scope, "0"); + } + + public void mergeWeightTable(String name, String value, String scope, String timeArraySizeStr){ + + // TODO: weights redefined in different files are not checked within the same model + + name = name.toLowerCase(); + value = value.toLowerCase(); + timeArraySizeStr=timeArraySizeStr.toLowerCase(); + + if (this.S.wtList.contains(name)) { + LogUtils.errMsg("Weight redefined: " + name, this.S.currentAbsolutePath); + this.S.error_weightVar_redefined.put(name, this.S.currentAbsolutePath); + //this.S.wtList.remove(name); this.S.wtList_global.remove(name); this.S.wtList_local.remove(name); + } + + this.wt = new WeightElement(); + this.wt.weight = value; + this.wt.fromWresl = this.S.currentAbsolutePath; + this.wt.timeArraySize=timeArraySizeStr; + this.S.wtMap.put(name, this.wt); + + this.S.wtList.add(name); + this.S.wtSet.add(name); + + if (scope == null) { + this.S.wtList_global.add(name); this.S.wtSet_global.add(name);} + else if (scope.equalsIgnoreCase(Param.local)) { + this.S.wtList_local.add(name); this.S.wtSet_local.add(name); } + else { + LogUtils.errMsg("Weight table scope undefined: " + name, this.S.currentAbsolutePath); + } + + } + + public void includeFile(String fileRelativePath, String scope) + { + fileRelativePath = fileRelativePath.toLowerCase(); + fileRelativePath = Tools.replace_pathseperator(fileRelativePath); + + File absIncludeFile = new File(this.S.currentAbsoluteParent, fileRelativePath).getAbsoluteFile(); + String absIncludeFilePath = "Error with include file: " + fileRelativePath; + try { + absIncludeFilePath = absIncludeFile.getCanonicalPath().toLowerCase(); + } + catch (IOException e) + { + e.printStackTrace(); + LogUtils.errMsg("Include file IOException: " + fileRelativePath, this.S.currentAbsolutePath); + } + + if (this.S.var_all.containsKey(absIncludeFilePath)) { + LogUtils.errMsg("Include file redefined: " + fileRelativePath, this.S.currentAbsolutePath); + this.S.error_var_redefined.put(absIncludeFilePath, "file"); + //this.S.incFileList.remove(absIncludeFilePath); this.S.incFileList_global.remove(absIncludeFilePath); this.S.incFileList_local.remove(absIncludeFilePath); + } + + this.S.ordered_list_including_files.add(absIncludeFilePath); + + this.S.var_all.put(absIncludeFilePath, "file"); + + this.incFile = new IncludeFile(); + + this.incFile.fromWresl = this.S.currentAbsolutePath; + + this.S.incFileMap.put(absIncludeFilePath, this.incFile); + this.S.incFileList.add(absIncludeFilePath); + + this.S.incFileSet.add(absIncludeFilePath); + + if (scope == null) { + this.S.incFileList_global.add(absIncludeFilePath); + this.S.incFileSet_global.add(absIncludeFilePath); + this.incFile.scope = Param.global; + + this.S.ordered_list_including_files_global.add(absIncludeFilePath); + } + else if (scope.equalsIgnoreCase(Param.local)) { + this.S.incFileList_local.add(absIncludeFilePath); + this.S.incFileSet_local.add(absIncludeFilePath); + this.incFile.scope = Param.local; } + else { + LogUtils.errMsg("Include file scope undefined: " + fileRelativePath, this.S.currentAbsolutePath); + } + } + + public Goal goalSimple(String name, String scope, String expression, String dependants, String varInCycle){ + return goalSimple(name, scope, expression, dependants, varInCycle, "0"); + } + + public Goal goalSimple(String name, String scope, String expression, String dependants, String varInCycle, String timeArraySizeStr) + { + timeArraySizeStr=timeArraySizeStr.toLowerCase(); + name = name.toLowerCase(); + expression = expression.toLowerCase(); + if (dependants != null) dependants = dependants.toLowerCase(); + if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("Goal redefined: " + name, this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "goal"); + // this.S.gList.remove(name); this.S.gList_global.remove(name); this.S.gList_local.remove(name); + } + + this.S.ordered_list.add(name); + this.S.ordered_list_including_files.add(name); + + this.S.var_all.put(name, "goal"); + + this.gl = new Goal(); + this.gl.caseCondition.add(Param.always); + this.gl.caseName.add(Param.defaultCaseName); + this.gl.caseExpression.add(expression); + this.gl.fromWresl = this.S.currentAbsolutePath; + if (dependants != null) { + this.gl.expressionDependants.addAll(Tools.convertStrToSet(dependants)); + this.gl.expressionDependants.removeAll(Param.reservedSet); + } + if (varInCycle != null) { + this.gl.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); + this.gl.needVarFromEarlierCycle = true; + } + this.gl.timeArraySize=timeArraySizeStr; + + + this.S.gMap.put(name, this.gl); + this.S.gList.add(name); + this.S.gSet.add(name); + + if (scope == null) { + this.S.gList_global.add(name); this.S.gSet_global.add(name); this.gl.scope = Param.global; + this.S.ordered_list_global.add(name); + this.S.ordered_list_including_files_global.add(name); + } else if (scope.equalsIgnoreCase(Param.local)) { + this.S.gList_local.add(name); this.S.gSet_local.add(name); this.gl.scope = Param.local; } else { + LogUtils.errMsg("Goal scope undefined: " + name, this.S.currentAbsolutePath); + } + return gl; + } + + public void goalCase(String name, String scope, Goal gl){ + goalCase(name, scope, gl, "0"); + } + + public void goalCase(String name, String scope, Goal gl, String timeArraySizeStr) + { + name = name.toLowerCase(); + timeArraySizeStr=timeArraySizeStr.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("Goal redefined: " + name, this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "goal"); + // this.S.gList.remove(name); this.S.gList_global.remove(name); this.S.gList_local.remove(name); + } + + this.S.ordered_list.add(name); + this.S.ordered_list_including_files.add(name); + + this.S.var_all.put(name, "goal"); + + gl.fromWresl = this.S.currentAbsolutePath; + + this.S.gMap.put(name, gl); + this.S.gList.add(name); + this.S.gSet.add(name); + + + gl.timeArraySize=timeArraySizeStr; + if (scope == null) { + this.S.gList_global.add(name); this.S.gSet_global.add(name); gl.scope = Param.global; + this.S.ordered_list_global.add(name); + this.S.ordered_list_including_files_global.add(name); + } else if (scope.equalsIgnoreCase(Param.local)) { + this.S.gList_local.add(name); this.S.gSet_local.add(name); gl.scope = Param.local; } else { + LogUtils.errMsg("Goal scope undefined: " + name, this.S.currentAbsolutePath); + } + } + + public void alias(String name, String scope, String kind, String units, String expression, String dependants, String varInCycle){ + alias(name, scope, kind, units, expression, dependants, varInCycle, "0"); + } + + public void alias(String name, String scope, String kind, String units, String expression, String dependants, String varInCycle, String timeArraySizeStr) + { + name = name.toLowerCase(); + if (kind != null) kind = kind.toLowerCase(); + if (units != null) units = units.toLowerCase(); + expression = expression.toLowerCase(); + if (dependants != null) dependants = dependants.toLowerCase(); + if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); + timeArraySizeStr=timeArraySizeStr.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("Alias redefined: " + name, this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "alias"); + //this.S.asList.remove(name); this.S.asList_global.remove(name); this.S.asList_local.remove(name); + } + + this.S.ordered_list.add(name); + this.S.ordered_list_including_files.add(name); + + this.S.var_all.put(name, "alias"); + + this.as = new Alias(); + + if (kind != null) this.as.kind = kind; + if (units != null) this.as.units = units; + this.as.expression = expression; + this.as.fromWresl = this.S.currentAbsolutePath; + this.as.timeArraySize=timeArraySizeStr; + if (dependants != null) this.as.dependants = Tools.convertStrToSet(dependants); + if (varInCycle != null) { + this.as.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); + this.as.needVarFromEarlierCycle = true; + } + + this.S.asMap.put(name, this.as); + this.S.asList.add(name); + this.S.asSet.add(name); + + if (scope == null) { + this.S.asList_global.add(name); this.S.asSet_global.add(name); this.as.scope = Param.global; + this.S.ordered_list_global.add(name); + this.S.ordered_list_including_files_global.add(name); + } else if (scope.toLowerCase().equals(Param.local)) { + this.S.asList_local.add(name); this.S.asSet_local.add(name); this.as.scope = Param.local; } else { + LogUtils.errMsg("Alias scope undefined: " + name, this.S.currentAbsolutePath); + } + } + + public void svarCase(String name, String scope, Svar sv, String dependants, String varInCycle) + { + svarCase(name, scope, sv, dependants, varInCycle, "0"); + } + + public void svarCase(String name, String scope, Svar sv, String dependants, String varInCycle, String timeArraySizeStr) + { + timeArraySizeStr = timeArraySizeStr.toLowerCase(); + name = name.toLowerCase(); + if (dependants != null) dependants = dependants.toLowerCase(); + if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("Svar redefined: " + name, this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "svar"); + //this.S.svList.remove(name); this.S.svList_global.remove(name); this.S.svList_local.remove(name); + } + + this.S.ordered_list.add(name); + this.S.ordered_list_including_files.add(name); + + this.S.var_all.put(name, "svar"); + + sv.fromWresl = this.S.currentAbsolutePath; + sv.timeArraySize = timeArraySizeStr; + + if (dependants != null) sv.dependants = Tools.convertStrToSet(dependants); + if (varInCycle != null) { + sv.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); + sv.needVarFromEarlierCycle = true; + } + + this.S.svMap.put(name, sv); + this.S.svList.add(name); + this.S.svSet.add(name); + + if (scope == null) { + this.S.svList_global.add(name); this.S.svSet_global.add(name); sv.scope = Param.global; + this.S.ordered_list_global.add(name); + this.S.ordered_list_including_files_global.add(name); + } else if (scope.equalsIgnoreCase(Param.local)) { + this.S.svList_local.add(name); this.S.svSet_local.add(name); sv.scope = Param.local; } else { + LogUtils.errMsg("Svar scope undefined: " + name, this.S.currentAbsolutePath); + } + } + + public void external(String name, String scope, String externalType) + { + name = name.toLowerCase(); + externalType = externalType.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("External variable redefined: " + name, this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "external"); + //this.S.exList.remove(name); this.S.exList_global.remove(name); this.S.exList_local.remove(name); + } + + this.S.ordered_list.add(name); + this.S.ordered_list_including_files.add(name); + + this.S.var_all.put(name, "external"); + + this.ex = new External(); + this.ex.type = externalType; + this.ex.fromWresl = this.S.currentAbsolutePath; + + this.S.exMap.put(name, this.ex); + this.S.exList.add(name); + this.S.exSet.add(name); + + if (scope == null) { + this.S.exList_global.add(name); this.S.exSet_global.add(name); this.ex.scope = Param.global; + this.S.ordered_list_global.add(name); + this.S.ordered_list_including_files_global.add(name); + } + else if (scope.equalsIgnoreCase(Param.local)) { + this.S.exList_local.add(name); this.S.exSet_local.add(name); this.ex.scope = Param.local; } else { + LogUtils.errMsg("External scope undefined: " + name, this.S.currentAbsolutePath); + } + } + + public void svarExpression(String name, String scope, String expression, String dependants, String varInCycle) + { + svarExpression(name, scope, expression, dependants, varInCycle, "0"); + } + + public void svarExpression(String name, String scope, String expression, String dependants, String varInCycle, String timeArraySizeStr) + { + timeArraySizeStr = timeArraySizeStr.toLowerCase(); + name = name.toLowerCase(); + expression = expression.toLowerCase(); + if (dependants != null) dependants = dependants.toLowerCase(); + if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("State variable redefined: " + name, this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "svar"); + //this.S.svList.remove(name); this.S.svList_global.remove(name); this.S.svList_local.remove(name); + } + + this.S.ordered_list.add(name); + this.S.ordered_list_including_files.add(name); + + this.S.var_all.put(name, "svar"); + + String caseName = Param.defaultCaseName; + String condition = Param.always; + + this.sv = new Svar(); + + this.sv.caseName.add(caseName); + this.sv.caseCondition.add(condition); + this.sv.caseExpression.add(expression); + this.sv.fromWresl = this.S.currentAbsolutePath; + this.sv.timeArraySize = timeArraySizeStr; + + if (dependants != null) this.sv.dependants = Tools.convertStrToSet(dependants); + if (varInCycle != null) { + this.sv.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); + this.sv.needVarFromEarlierCycle = true; + } + + this.S.svMap.put(name, this.sv); + this.S.svList.add(name); + this.S.svSet.add(name); + + if (scope == null) { + this.S.svList_global.add(name); this.S.svSet_global.add(name); this.sv.scope = Param.global; + this.S.ordered_list_global.add(name); + this.S.ordered_list_including_files_global.add(name); + } else if (scope.equalsIgnoreCase(Param.local)) { + this.S.svList_local.add(name); this.S.svSet_local.add(name); this.sv.scope = Param.local; } else { + LogUtils.errMsg("Svar scope undefined: " + name, this.S.currentAbsolutePath); + } + } + + public void svarSum(String name, String scope, String hdr, String expression, String dependants, String varInCycle) + { + svarSum(name, scope, hdr, expression, dependants, varInCycle, "0"); + } + + public void svarSum(String name, String scope, String hdr, String expression, String dependants, String varInCycle, String timeArraySizeStr) + { + name = name.toLowerCase(); + hdr = hdr.toLowerCase(); + expression = expression.toLowerCase(); + if (dependants != null) dependants = dependants.toLowerCase(); + if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); + timeArraySizeStr=timeArraySizeStr.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("State variable redefined: " + name, this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "svar"); + //this.S.svList.remove(name); this.S.svList_global.remove(name); this.S.svList_local.remove(name); + } + + this.S.ordered_list.add(name); + this.S.ordered_list_including_files.add(name); + + this.S.var_all.put(name, "svar"); + + this.sv = new Svar(); + + this.sv.caseName.add(Param.defaultCaseName); + this.sv.caseCondition.add("always"); + this.sv.caseExpression.add(hdr + " " + expression); + this.sv.fromWresl = this.S.currentAbsolutePath; + if (dependants != null) this.sv.dependants = Tools.convertStrToSet(dependants); + if (varInCycle != null) { + this.sv.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); + this.sv.needVarFromEarlierCycle = true; + } + this.sv.timeArraySize=timeArraySizeStr; + + this.S.svMap.put(name, this.sv); + this.S.svList.add(name); + this.S.svSet.add(name); + + if (scope == null) { + this.S.svList_global.add(name); this.S.svSet_global.add(name); this.sv.scope = Param.global; + this.S.ordered_list_global.add(name); + this.S.ordered_list_including_files_global.add(name); + } else if (scope.equalsIgnoreCase(Param.local)) { + this.S.svList_local.add(name); this.S.svSet_local.add(name); this.sv.scope = Param.local; } else { + LogUtils.errMsg("Svar scope undefined: " + name, this.S.currentAbsolutePath); + } + } + + public void svarTable(String name, String scope, String sqlStr, String dependants, String varInCycle){ + svarTable(name, scope, sqlStr, dependants, varInCycle, "0"); + } + + public void svarTable(String name, String scope, String sqlStr, String dependants, String varInCycle, String timeArraySizeStr) + { + name = name.toLowerCase(); + sqlStr = sqlStr.toLowerCase(); + timeArraySizeStr=timeArraySizeStr.toLowerCase(); + + if (dependants != null) dependants = dependants.toLowerCase(); + if (varInCycle != null) varInCycle = varInCycle.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("State variable redefined: " + name, this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "svar"); + //this.S.svList.remove(name); this.S.svList_global.remove(name); this.S.svList_local.remove(name); + } + + this.S.ordered_list.add(name); + this.S.ordered_list_including_files.add(name); + + this.S.var_all.put(name, "svar"); + + this.sv = new Svar(); + + this.sv.format = "lookup_table"; + this.sv.caseCondition.add("always"); + this.sv.caseName.add(Param.defaultCaseName); + this.sv.caseExpression.add(sqlStr); + this.sv.fromWresl = this.S.currentAbsolutePath; + if (dependants != null) this.sv.dependants = Tools.convertStrToSet(dependants); + if (varInCycle != null) { + this.sv.neededVarInCycleSet = Tools.convertStrToSet(varInCycle); + this.sv.needVarFromEarlierCycle = true; + } + this.sv.timeArraySize=timeArraySizeStr; + + this.S.svMap.put(name, this.sv); + this.S.svList.add(name); + this.S.svSet.add(name); + + if (scope == null) { + this.S.svList_global.add(name); this.S.svSet_global.add(name); this.sv.scope = Param.global; + this.S.ordered_list_global.add(name); + this.S.ordered_list_including_files_global.add(name); + } else if (scope.equalsIgnoreCase(Param.local)) { + this.S.svList_local.add(name); this.S.svSet_local.add(name); this.sv.scope = Param.local; } else { + LogUtils.errMsg("Svar scope undefined: " + name, this.S.currentAbsolutePath); + } + } + + public void timeseriesDss(String name, String scope, String b_part, String kind, String units, String convertToUnits) + { + name = name.toLowerCase(); + if (b_part != null) b_part = b_part.toLowerCase(); + kind = kind.toLowerCase(); + units = units.toLowerCase(); + if (convertToUnits != null) convertToUnits = convertToUnits.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("State variable redefined: " + name, this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "timeseries"); + //this.S.tsList.remove(name); this.S.tsList_global.remove(name); this.S.tsList_local.remove(name); + } + + this.S.var_all.put(name, "timeseries"); + + Timeseries ts = new Timeseries(); + + ts.dssBPart = name; + if (b_part != null) ts.dssBPart = b_part; + ts.kind = kind; + ts.units = units; + if (convertToUnits != null) ts.convertToUnits = convertToUnits; + ts.format = "dss"; + ts.fromWresl = this.S.currentAbsolutePath; + this.S.tsMap.put(name, ts); + this.S.tsList.add(name); + this.S.tsSet.add(name); + + if (scope == null) { + this.S.tsList_global.add(name); this.S.tsSet_global.add(name); ts.scope = Param.global; + } + else if (scope.equalsIgnoreCase(Param.local)) { + this.S.tsList_local.add(name); this.S.tsSet_local.add(name); ts.scope = Param.local; } else { + LogUtils.errMsg("Timeseries scope undefined: " + name, this.S.currentAbsolutePath); + } + } + + public void dvarStd(String name, String scope, String integer, String kind, String units) + { + dvarStd(name, scope, integer, kind, units, "0"); + } + + public void dvarStd(String name, String scope, String integer, String kind, String units, String timeArraySizeStr) + { + name = name.toLowerCase(); + timeArraySizeStr = timeArraySizeStr.toLowerCase(); + if (kind.length()>0) kind = kind.toLowerCase(); + if (units.length()>0) units = units.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("Dvar redefined: " + name, "\n" + this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "dvar"); + // this.S.dvList.remove(name); this.S.dvList_global.remove(name); this.S.dvList_local.remove(name); + } + + this.S.ordered_list.add(name); + this.S.ordered_list_including_files.add(name); + + this.S.var_all.put(name, "dvar"); + + this.S.dvSet.add(name); + + this.dv = new Dvar(); + if (kind.length()>0) this.dv.kind = kind; + if (units.length()>0) this.dv.units = units; + this.dv.lowerBound = Param.dv_std_lowerBound; + this.dv.upperBound = Param.dv_std_upperBound; + this.dv.fromWresl = this.S.currentAbsolutePath; + this.dv.timeArraySize = timeArraySizeStr; + + if (integer != null) + { + this.dv.integer = Param.yes; + this.dv.lowerBound = Param.dv_std_integer_lowerBound; + this.dv.upperBound = Param.dv_std_integer_upperBound; + } + + this.S.dvMap.put(name, this.dv); + this.S.dvList.add(name); + this.S.dvSet.add(name); + + if (scope == null) { + this.S.dvList_global.add(name); this.S.dvSet_global.add(name); this.dv.scope = Param.global; + this.S.ordered_list_global.add(name); + this.S.ordered_list_including_files_global.add(name); + } else if (scope.equalsIgnoreCase(Param.local)) { + this.S.dvList_local.add(name); this.S.dvSet_local.add(name); this.dv.scope = Param.local; } else { + LogUtils.errMsg("Dvar scope undefined: " + name, this.S.currentAbsolutePath); + } + } + + public void dvarNonStd(String name, String scope, String integer, String kind, String units, String lowerBound, String upperBound) + { + dvarNonStd(name, scope, integer, kind, units, lowerBound, upperBound, "0"); + } + + public void dvarNonStd(String name, String scope, String integer, String kind, String units, String lowerBound, String upperBound, String timeArraySizeStr) + { + name = name.toLowerCase(); + timeArraySizeStr = timeArraySizeStr.toLowerCase(); + if (kind != null) kind = kind.toLowerCase(); + if (units != null) units = units.toLowerCase(); + lowerBound = lowerBound.toLowerCase(); + upperBound = upperBound.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("Dvar redefined: " + name, this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "dvar"); + // this.S.dvList.remove(name); this.S.dvList_global.remove(name); this.S.dvList_local.remove(name); + } + + this.S.ordered_list.add(name); + this.S.ordered_list_including_files.add(name); + + this.S.var_all.put(name, "dvar"); + + this.dv = new Dvar(); + + if (kind != null) this.dv.kind = kind; + if (units != null) this.dv.units = units; + this.dv.lowerBound = lowerBound; + this.dv.upperBound = upperBound; + this.dv.fromWresl = this.S.currentAbsolutePath; + this.dv.timeArraySize = timeArraySizeStr; + + if (integer != null){ + this.dv.integer = Param.yes; + } + + this.S.dvMap.put(name, this.dv); + this.S.dvList.add(name); + this.S.dvSet.add(name); + + if (scope == null) { + this.S.dvList_global.add(name); this.S.dvSet_global.add(name); this.dv.scope = Param.global; + this.S.ordered_list_global.add(name); + this.S.ordered_list_including_files_global.add(name); + } else if (scope.equalsIgnoreCase(Param.local)) { + this.S.dvList_local.add(name); this.S.dvSet_local.add(name); this.dv.scope = Param.local; } else { + LogUtils.errMsg("Dvar scope undefined: " + name, this.S.currentAbsolutePath); + } + } + +public void sequenceOrder(String sequenceName, String order, String modelName, String condition, String timeStep) + { + sequenceName = sequenceName.toLowerCase(); + order = order.toLowerCase(); + modelName = modelName.toLowerCase(); + if (condition != null) condition = condition.toLowerCase(); + + Integer i = Integer.valueOf(Integer.parseInt(order)); + + if (this.S.seqList.contains(sequenceName)) { + this.S.error_sequence_redefined.add(sequenceName); + } else if (this.S.seqMap.containsKey(i)) { + this.S.error_sequence_order_redefined.add(i); + } + else { + this.seq = new Sequence(); + this.seq.sequenceName = sequenceName; + this.seq.condition = Param.always; + if (condition != null) this.seq.condition = condition; + this.seq.modelName = modelName; + this.seq.fromWresl = this.S.currentAbsolutePath; + this.seq.timeStep=timeStep; + this.S.seqMap.put(i, this.seq); + this.S.seqList.add(sequenceName); + } + } + +public void dvarSlackSurplus(String name, String scope, String kind, String units, String conditionStr) + { + dvarSlackSurplus(name, scope, kind, units, conditionStr, "0"); + } + +public void dvarSlackSurplus(String name, String scope, String kind, String units, String conditionStr, String timeArraySizeStr) + { + name = name.toLowerCase(); + timeArraySizeStr=timeArraySizeStr.toLowerCase(); + if (kind.length()>0) kind = kind.toLowerCase(); + if (units.length()>0) units = units.toLowerCase(); + + if (this.S.var_all.containsKey(name)) { + LogUtils.errMsg("Dvar redefined: " + name, "\n" + this.S.currentAbsolutePath); + this.S.error_var_redefined.put(name, "dvar"); + // this.S.dvList.remove(name); this.S.dvList_global.remove(name); this.S.dvList_local.remove(name); + } + + this.S.ordered_list.add(name); + this.S.ordered_list_including_files.add(name); + + this.S.var_all.put(name, "dvar"); + + this.dv = new Dvar(); + if (kind.length()>0) this.dv.kind = kind; + if (units.length()>0) this.dv.units = units; + this.dv.lowerBound = Param.dv_std_lowerBound; + this.dv.upperBound = Param.dv_std_upperBound; + this.dv.fromWresl = this.S.currentAbsolutePath; + this.dv.condition = conditionStr; + this.dv.timeArraySize=timeArraySizeStr; + + + this.S.dvMap.put(name, this.dv); + this.S.dvList.add(name); + this.S.dvSet.add(name); + + if (scope == null) { + this.S.dvList_global.add(name); this.S.dvSet_global.add(name); this.dv.scope = Param.global; + this.S.ordered_list_global.add(name); + this.S.ordered_list_including_files_global.add(name); + } else if (scope.equalsIgnoreCase(Param.local)) { + this.S.dvList_local.add(name); this.S.dvSet_local.add(name); this.dv.scope = Param.local; } else { + LogUtils.errMsg("Dvar (Slack or Surplus) scope undefined: " + name, this.S.currentAbsolutePath); + } + } + +public void mergeSlackSurplusIntoWeightTable(String name, String value, String scope, String conditionStr, String timeArraySizeStr){ + + // TODO: weights redefined in different files are not checked within the same model + + name = name.toLowerCase(); + value = value.toLowerCase(); + timeArraySizeStr = timeArraySizeStr.toLowerCase(); + + if (this.S.wtList.contains(name)) { + LogUtils.errMsg("Weight redefined: " + name, this.S.currentAbsolutePath); + this.S.error_weightVar_redefined.put(name, this.S.currentAbsolutePath); + //this.S.wtList.remove(name); this.S.wtList_global.remove(name); this.S.wtList_local.remove(name); + } + + this.wt = new WeightElement(); + this.wt.weight = value; + this.wt.fromWresl = this.S.currentAbsolutePath; + this.wt.condition = conditionStr; + this.wt.timeArraySize=timeArraySizeStr; + this.S.wtMap.put(name, this.wt); + + this.S.wtList.add(name); + this.S.wtSet.add(name); + + if (scope == null) { + this.S.wtList_global.add(name); this.S.wtSet_global.add(name);} + else if (scope.equalsIgnoreCase(Param.local)) { + this.S.wtList_local.add(name); this.S.wtSet_local.add(name); } + else { + LogUtils.errMsg("Weight table (Slack or Surplus) scope undefined: " + name, this.S.currentAbsolutePath); + } + + } } \ No newline at end of file diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StudyConfig.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/StudyConfig.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StudyConfig.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/StudyConfig.java index e1d62bc6d..58b0fe843 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StudyConfig.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/StudyConfig.java @@ -1,34 +1,34 @@ -package wrimsv2.wreslparser.elements; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -public class StudyConfig { - public String absMainFilePath; - public Map sequenceMap; - public ArrayList sequenceOrder; - public ArrayList sequenceList; - public ArrayList modelList; // sorted model list based on sequence order - public ArrayList modelConditionList; // sorted condition for model on sequence order - public ArrayList modelTimeStepList; - - public Map modelDataMap; - - - public StudyConfig() { - - - absMainFilePath=null; - sequenceMap = new HashMap(); - sequenceOrder = new ArrayList(); - sequenceList = new ArrayList(); - modelList = new ArrayList(); - modelConditionList = new ArrayList(); - modelTimeStepList = new ArrayList(); - modelDataMap = new HashMap(); - - - } - -}; +package wrimsv2.wreslparser.elements; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class StudyConfig { + public String absMainFilePath; + public Map sequenceMap; + public ArrayList sequenceOrder; + public ArrayList sequenceList; + public ArrayList modelList; // sorted model list based on sequence order + public ArrayList modelConditionList; // sorted condition for model on sequence order + public ArrayList modelTimeStepList; + + public Map modelDataMap; + + + public StudyConfig() { + + + absMainFilePath=null; + sequenceMap = new HashMap(); + sequenceOrder = new ArrayList(); + sequenceList = new ArrayList(); + modelList = new ArrayList(); + modelConditionList = new ArrayList(); + modelTimeStepList = new ArrayList(); + modelDataMap = new HashMap(); + + + } + +}; diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StudyParser.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/StudyParser.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StudyParser.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/StudyParser.java index 5704f30e7..3ce13c1f4 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StudyParser.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/StudyParser.java @@ -1,968 +1,968 @@ -package wrimsv2.wreslparser.elements; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import org.antlr.runtime.RecognitionException; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.Goal; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.commondata.wresldata.Timeseries; -import wrimsv2.components.ControlData; -import wrimsv2.components.IntDouble; -import wrimsv2.wreslparser.grammar.WreslTreeWalker; -import wrimsv2.wreslplus.elements.VarCycleIndex; - -public class StudyParser{ - - public static int total_errors = 0; - public static ArrayList error_summary = new ArrayList(); - public static int total_warnings = 0; - private static Map> cycleVarTypeMap; - private static Set allValidCycleNames; - private static Map cycleNameConditionMap; - private static Map cycleNameTimeStepMap; - private static int n_buffer = 3; - - - public static void reset(){ - total_errors = 0; - error_summary = new ArrayList(); - total_warnings = 0; - cycleVarTypeMap = null; - allValidCycleNames = null; - cycleNameConditionMap = null; - cycleNameTimeStepMap = null; - } - - public static StudyDataSet writeWreslData(StudyConfig sc, TempData td){ - StudyDataSet studyDataSet = new StudyDataSet(); - - studyDataSet.setModelList(sc.modelList); - studyDataSet.setModelConditionList(sc.modelConditionList); - studyDataSet.setModelTimeStepList(sc.modelTimeStepList); - - Map modelDataSetMap = new HashMap(); - Map timeseriesMap = new HashMap(); - Map> timeseriesTimeStepMap = new HashMap>(); - - for (String modelName : studyDataSet.getModelList()) - { - SimulationDataSet ds = (SimulationDataSet)td.model_dataset_map.get(modelName); - ModelDataSet thisModelDataSet = new ModelDataSet(); - - thisModelDataSet.dvList = ds.dvList; - Collections.sort(thisModelDataSet.dvList,String.CASE_INSENSITIVE_ORDER); - thisModelDataSet.dvList_global = ds.dvList_global; - thisModelDataSet.dvList_local = ds.dvList_local; - - for (String d: ds.dvList){ - if (ds.dvMap.get(d).condition.equalsIgnoreCase(Param.conditional)){ - thisModelDataSet.dvSlackSurplusList.add(d); - thisModelDataSet.dvSlackSurplusMap.put(d, ds.dvMap.get(d)); - ds.dvMap.remove(d); - } - } - - thisModelDataSet.dvList.removeAll(thisModelDataSet.dvSlackSurplusList); - thisModelDataSet.dvList_global.removeAll(thisModelDataSet.dvSlackSurplusList); - thisModelDataSet.dvList_local.removeAll(thisModelDataSet.dvSlackSurplusList); - thisModelDataSet.dvMap = ds.dvMap; - - thisModelDataSet.tsList = ds.tsList; - thisModelDataSet.tsList_global = ds.tsList_global; - thisModelDataSet.tsList_local = ds.tsList_local; - thisModelDataSet.tsMap = ds.tsMap; - - thisModelDataSet.svSet_unknown = ds.svSet_unknown; - thisModelDataSet.svList = ds.svList; - thisModelDataSet.svList_global = ds.svList_global; - thisModelDataSet.svList_local = ds.svList_local; - thisModelDataSet.svMap = ds.svMap; - - thisModelDataSet.gList = ds.gList; - Collections.sort(thisModelDataSet.gList,String.CASE_INSENSITIVE_ORDER); - thisModelDataSet.gList_global = ds.gList_global; - thisModelDataSet.gList_local = ds.gList_local; - thisModelDataSet.gMap = ds.gMap; - - thisModelDataSet.asSet_unknown = ds.asSet_unknown; - thisModelDataSet.asList = ds.asList; - thisModelDataSet.asList_global = ds.asList_global; - thisModelDataSet.asList_local = ds.asList_local; - thisModelDataSet.asMap = ds.asMap; - - thisModelDataSet.exList = ds.exList; - thisModelDataSet.exList_global = ds.exList_global; - thisModelDataSet.exList_local = ds.exList_local; - thisModelDataSet.exMap = ds.exMap; - - - thisModelDataSet.wtList = ds.wtList; - Collections.sort(thisModelDataSet.wtList,String.CASE_INSENSITIVE_ORDER); - - for (String w: ds.wtList){ - if (ds.wtMap.get(w).condition.equalsIgnoreCase(Param.conditional)){ - thisModelDataSet.wtSlackSurplusList.add(w); - thisModelDataSet.wtSlackSurplusMap.put(w, ds.wtMap.get(w)); - ds.wtMap.remove(w); - } - } - - thisModelDataSet.wtList.removeAll(thisModelDataSet.wtSlackSurplusList); - //System.out.println("thisModelDataSet.wtList : "+thisModelDataSet.wtList); - thisModelDataSet.wtMap = ds.wtMap; - - - - - thisModelDataSet.incFileList = ds.incFileList; - thisModelDataSet.incFileList_global = ds.incFileList_global; - thisModelDataSet.incFileList_local = ds.incFileList_local; - - modelDataSetMap.put(modelName, thisModelDataSet); - timeseriesMap.putAll(ds.tsMap); - int modelIndex=studyDataSet.getModelList().indexOf(modelName); - String timeStep=sc.modelTimeStepList.get(modelIndex); - String definedTimeStep; - if (timeStep.equals(Param.undefined)){ - definedTimeStep=ControlData.defaultTimeStep; - }else{ - definedTimeStep=timeStep; - } - for (String timeseriesName:ds.tsMap.keySet()){ - if (timeseriesTimeStepMap.containsKey(timeseriesName)){ - ArrayList timeStepList=timeseriesTimeStepMap.get(timeseriesName); - if (!timeStepList.contains(definedTimeStep)){ - timeStepList.add(definedTimeStep); - } - }else{ - timeseriesTimeStepMap.put(timeseriesName, new ArrayList(Arrays.asList(definedTimeStep))); - } - } - } - - studyDataSet.setModelDataSetMap(modelDataSetMap); - studyDataSet.setTimeseriesMap(timeseriesMap); - studyDataSet.setTimeseriesTimeStepMap(timeseriesTimeStepMap); - studyDataSet.setVarCycleIndexList(VarCycleIndex.varCycleIndexList); - - return studyDataSet; - } - - public static StudyConfig processMainFileIntoStudyConfig(String relativeMainFilePath) throws RecognitionException, IOException { - /// reset total errors - total_errors = 0; - return processMainFileIntoStudyConfig(relativeMainFilePath, false); - } - - public static StudyConfig processMainFileIntoStudyConfig(String relativeMainFilePath, boolean showTree) throws RecognitionException, IOException - { - File absMainFile = new File(relativeMainFilePath).getAbsoluteFile(); - String absMainFilePath = absMainFile.getCanonicalPath().toLowerCase(); - - LogUtils.importantMsg("Parsing study main file: " + absMainFilePath); - - WreslTreeWalker walker = FileParser.parseMainFile(absMainFilePath, showTree); - - StudyConfig sc = new StudyConfig(); - - sc.sequenceMap = walker.thisFileDataSet.seqMap; - - /// Sort sequence order - - for ( Integer i : sc.sequenceMap.keySet()){ sc.sequenceOrder.add(i); } - Collections.sort(sc.sequenceOrder); - - cycleNameConditionMap = new HashMap(); - cycleNameTimeStepMap = new HashMap(); - - for (Integer i : sc.sequenceOrder) { - sc.sequenceList.add(sc.sequenceMap.get(i).sequenceName); - sc.modelList.add(sc.sequenceMap.get(i).modelName); - - sc.modelConditionList.add(sc.sequenceMap.get(i).condition); - sc.modelTimeStepList.add(sc.sequenceMap.get(i).timeStep); - cycleNameConditionMap.put(sc.sequenceMap.get(i).modelName, sc.sequenceMap.get(i).condition ); - cycleNameTimeStepMap.put(sc.sequenceMap.get(i).modelName, sc.sequenceMap.get(i).timeStep ); - } - - sc.absMainFilePath = absMainFilePath; - sc.modelDataMap = walker.modelDataMap; - - for (Integer i : sc.sequenceOrder) { - LogUtils.importantMsg("Sequence: " + i + " : " + ((Sequence)sc.sequenceMap.get(i)).sequenceName + " Model: " + ((Sequence)sc.sequenceMap.get(i)).modelName); - } - - return sc; - } - - public static Map parseModels(StudyConfig sc, TempData td) throws RecognitionException, IOException - { - return parseModels(sc, td, false, false); - } - - public static Map parseModels(StudyConfig sc, TempData td, boolean rewrite_list_based_on_dependency, boolean send_all_alias_to_dvar) throws RecognitionException, IOException - { - Map model_dataset_map = new HashMap(); - - for (Integer iSequence : sc.sequenceOrder) - { - String modelName = sc.sequenceMap.get(iSequence).modelName; - - LogUtils.importantMsg("Processing sequence: " + iSequence + ", model: " + modelName); - - SimulationDataSet adhoc = sc.modelDataMap.get(modelName); - - Map fileDataMap_new = getNewDataSet(adhoc.incFileSet, td.fileDataMap_wholeStudy.keySet()); - - td.fileDataMap_wholeStudy.putAll(fileDataMap_new); - - td.t1Map_wholeStudy.putAll(Tools.getType1Map(fileDataMap_new)); - td.fileScopeMap_wholeStudy.putAll(Tools.getFileScopeMap(fileDataMap_new)); - - Map fileDataMap_thisModel = copyDataSetToThisModel(adhoc.incFileSet, td.fileDataMap_wholeStudy); - - ArrayList ordered_list_for_all_vars = getOrderedList(fileDataMap_thisModel, adhoc); - - - Set duplicates = Tools.removeDuplicates(ordered_list_for_all_vars); - - - if (duplicates.size() > 0) { - LogUtils.errMsg("Variables redefined in model " + modelName + ": " + duplicates); - } - - - SimulationDataSet model_dataset = correctScopeAndPrioritize(modelName, - adhoc, - sc.absMainFilePath, - fileDataMap_thisModel, - td.fileDataMap_wholeStudy, - td.t1Map_wholeStudy, - td.fileScopeMap_wholeStudy); - - model_dataset.svSet = Tools.restoreOrder(model_dataset.svList, ordered_list_for_all_vars, model_dataset.svSet); - model_dataset.asSet = Tools.restoreOrder(model_dataset.asList, ordered_list_for_all_vars, model_dataset.asSet); - - td.t1Map_wholeStudy.put(sc.absMainFilePath, adhoc.incFileSet); - @SuppressWarnings("unused") - Map> t1ReverseMap_wholeStudy = Tools.getReverseMap(td.t1Map_wholeStudy); - - - ///////// add previous globals - //LogUtils.importantMsg("Adding previous global vars into model: "+modelName); - - /// check for redefined weight // TODO: what to do? - Set redefined_globals_wt = new LinkedHashSet(td.cumulative_global_complete.wtSet); - redefined_globals_wt.retainAll(model_dataset.wtSet_global); - if (redefined_globals_wt.size()>0) LogUtils.errMsg("Global weights redefined: "+ redefined_globals_wt); - - /// check for redefined file - Set redefined_global_file = new LinkedHashSet(td.cumulative_global_complete.incFileSet); - redefined_global_file.retainAll(model_dataset.incFileSet_global); - if (redefined_global_file.size()>0) LogUtils.errMsg("Global include files redefined: "+ redefined_global_file); - - /// check for redefined globals - Set redefined_globals = new LinkedHashSet(td.cumulative_global_complete.getAllVarsSet_except_file_and_weight()); - Set redefined_globals_as_locals = new LinkedHashSet(td.cumulative_global_complete.getAllVarsSet_except_file_and_weight()); - - - redefined_globals.retainAll(model_dataset.getAllGlobalVarsSet_except_file_and_weight()); - - redefined_globals_as_locals.retainAll(model_dataset.getAllLocalVarsSet_except_file_and_weight()); - - if (redefined_globals.size()>0) LogUtils.errMsg("Global variables redefined: "+ redefined_globals); - if (redefined_globals_as_locals.size()>0) LogUtils.warningMsg("Global variables redefined as local: "+ redefined_globals_as_locals); - - - - /// add previous globals - - - -// // option 1 : remove redefined -// SimulationDataSet cumulative_global_remove_redefined = new SimulationDataSet(td.cumulative_global_complete); -// cumulative_global_remove_redefined.remove_set(redefined_globals); -// cumulative_global_remove_redefined.remove_set(redefined_globals_as_locals); - - - // option 2 : replace redefined - SimulationDataSet cumulative_global_replace_redefined = new SimulationDataSet(td.cumulative_global_complete); - - - // comment out. redefining globals is not allowed - // cumulative_global_replace_redefined.replaceGlobalWithDuplicateGlobal(redefined_globals,model_dataset ); - - - - try { - cumulative_global_replace_redefined.replaceGlobalWithDuplicateLocal(redefined_globals_as_locals,model_dataset); - } - catch (TypeRedefinedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - // put all previous global vars into current cycle - model_dataset.overwrite_set(cumulative_global_replace_redefined); - - //LogUtils.importantMsg("Finish adding previous global vars into model: "+modelName); - /// finish adding globals - - - model_dataset.lousyConvert(); - - - // check if dependency is unknown TODO: sorted list will not have the same sequence as user's define in wresl - sortDependency(model_dataset, rewrite_list_based_on_dependency); - - //// check if vars are used before being defined - Set svar_alias_extern_set = new HashSet(); - svar_alias_extern_set.addAll(model_dataset.svSet); - svar_alias_extern_set.addAll(model_dataset.asSet); - svar_alias_extern_set.addAll(model_dataset.exSet); - - ArrayList ordered_list_svar_alias_extern = new ArrayList(ordered_list_for_all_vars); - ordered_list_svar_alias_extern.retainAll(svar_alias_extern_set); - - Set previous_global_svar_alias_extern_timeseries = new LinkedHashSet(td.cumulative_global_complete.getSvarAliasExternTimeseries()); - - checkUsedBeforeDefined(new SimulationDataSet(model_dataset), ordered_list_svar_alias_extern, previous_global_svar_alias_extern_timeseries); - - - /// check if goal dependents are defined - // 1. get union of previous global vars and current model vars - Set allVars = new HashSet(); - allVars.addAll(td.cumulative_global_complete.dvSet); allVars.addAll(model_dataset.dvSet); - allVars.addAll(td.cumulative_global_complete.svSet); allVars.addAll(model_dataset.svSet); - allVars.addAll(td.cumulative_global_complete.tsSet); allVars.addAll(model_dataset.tsSet); - allVars.addAll(td.cumulative_global_complete.exSet); allVars.addAll(model_dataset.exSet); - allVars.addAll(td.cumulative_global_complete.asSet); allVars.addAll(model_dataset.asSet); - - // 2. find undefined - for (String key: model_dataset.gSet){ - - Set goal_dependents_undefined = new HashSet(); - goal_dependents_undefined.addAll(model_dataset.gMap.get(key).expressionDependants); - goal_dependents_undefined.removeAll(allVars); - goal_dependents_undefined.removeAll(Param.reservedSet); - - if (goal_dependents_undefined.size()>0) { - LogUtils.errMsg(model_dataset.gMap.get(key).fromWresl +" variable names used before definition: "+goal_dependents_undefined+" in Goal named ["+key+"]"); - } - } - - /// check if weight var is defined in dvar set - // 1. get union of previous global dvar and current model dvar - Set allDvars = new HashSet(); - allDvars.addAll(td.cumulative_global_complete.dvSet); - allDvars.addAll(model_dataset.dvSet); - // 2. find undefined - Set weightElement_undefined = new HashSet(); - weightElement_undefined.addAll(model_dataset.wtSet); - - weightElement_undefined.removeAll(allDvars); - if (weightElement_undefined.size()>0) LogUtils.errMsg("Weight var not found in dvar: "+ weightElement_undefined); - - - - - model_dataset_map.put(modelName, model_dataset); - - td.cumulative_global_adhocs.overwrittenWith_set(sc.modelDataMap.get(modelName).getGlobalVars_set()); - td.cumulative_global_complete.overwrittenWith_set(model_dataset.getGlobalVars_set()); - - td.cumulative_global_adhocs.lousyConvert(); - td.cumulative_global_complete.lousyConvert(); - } - - /// check if alias is used in goal's constraint expression. - // if yes, then move that alias to dvar and add additional goal - if(send_all_alias_to_dvar) { - LogUtils.importantMsg("Converting all aliases into dvars and constraints...."); - } else { - LogUtils.importantMsg("Converting some aliases into dvars and constraints...."); - } - - for (String key : model_dataset_map.keySet()){ - SimulationDataSet ds = model_dataset_map.get(key); - - Set newGoals = checkAliasInGoalExpression(ds, new HashSet(ds.gSet)); - - // check for alias embedded in another alias - while (newGoals.size()>0){ - newGoals = checkAliasInGoalExpression(ds, newGoals); - } - - if(send_all_alias_to_dvar) { - convertRestAliasInGoalExpression(ds); - } - - - /// check if var size > 100 - Set allVar = new HashSet(); - allVar.addAll(ds.dvSet); - allVar.addAll(ds.asSet); - allVar.addAll(ds.svSet); - allVar.addAll(ds.gSet); - allVar.addAll(ds.exSet); - - for (String e: allVar) { if (e.length()>99) LogUtils.errMsg("Variable name is longer than 99 chars: "+ e);}; - - } - - LogUtils.importantMsg("Finished converting aliases."); - LogUtils.criticalMsg("============================================"); - LogUtils.criticalMsg("Wresl Parsing complete. "); - if (total_warnings>0) LogUtils.criticalMsg("Total warnings in the study: "+ total_warnings); - if (total_errors>0) LogUtils.criticalMsg("Total errors in the study: "+ total_errors); - LogUtils.criticalMsg("============================================"); - - return model_dataset_map; - } - - - public static void analyzeVarNeededFromCycles(StudyConfig sc, StudyDataSet sd) { - - Map mdsm = sd.getModelDataSetMap(); - cycleVarTypeMap = new HashMap>(); - allValidCycleNames = mdsm.keySet(); - String SvarClassName = new Svar().getClass().getName(); - String AliasClassName = new Alias().getClass().getName(); - String DvarClassName = new Dvar().getClass().getName(); - - // create map for valid var name and var type - - for (String key: mdsm.keySet()){ - - ModelDataSet ds = mdsm.get(key); - - /// create map for var and varType - Map varTypeMap = new HashMap(); - - for (String v: ds.svList){ - varTypeMap.put(v, SvarClassName); - } - for (String v: ds.asList){ - varTypeMap.put(v, AliasClassName); - } - for (String v: ds.dvList){ - varTypeMap.put(v, DvarClassName); - } - cycleVarTypeMap.put(key, varTypeMap); - } - - - for (Integer iSequence : sc.sequenceOrder) { - - String cycleKey = sc.sequenceMap.get(iSequence).modelName; - - ModelDataSet ds = mdsm.get(cycleKey); - - // / 1. check needVarFromEarlierCycle in goal, svar and alias; - // / 2. create space in td.varCycleValueMap - // / 3. set usedInLaterCycle for dvar, svar and alias; - - for (String varName : ds.gList) { - - Goal someVar = ds.gMap.get(varName); - - boolean needVarFromEarlierCycle = someVar.needVarFromEarlierCycle; - Set neededVarInCycle = someVar.neededVarInCycleSet; - String fromWresl = someVar.fromWresl; - - if (needVarFromEarlierCycle) { - analyzeVarNeededFromCycle_subfunction(varName, neededVarInCycle, fromWresl, sd); - - } - } - - for (String varName : ds.svList) { - - Svar someVar = ds.svMap.get(varName); - - boolean needVarFromEarlierCycle = someVar.needVarFromEarlierCycle; - Set neededVarInCycle = someVar.neededVarInCycleSet; - String fromWresl = someVar.fromWresl; - - if (needVarFromEarlierCycle) { - analyzeVarNeededFromCycle_subfunction(varName, neededVarInCycle, fromWresl, sd); - - } - } - - for (String varName : ds.asList) { - - Alias someVar = ds.asMap.get(varName); - - boolean needVarFromEarlierCycle = someVar.needVarFromEarlierCycle; - Set neededVarInCycle = someVar.neededVarInCycleSet; - String fromWresl = someVar.fromWresl; - - if (needVarFromEarlierCycle) { - analyzeVarNeededFromCycle_subfunction(varName, neededVarInCycle, fromWresl, sd); - - } - } - } - - - for (String cycleName : allValidCycleNames ){ - - ModelDataSet md = mdsm.get(cycleName); - - md.svarUsedByLaterCycle = new HashSet(md.varUsedByLaterCycle); - md.svarUsedByLaterCycle.retainAll(md.svList); - - md.dvarUsedByLaterCycle = new HashSet(md.varUsedByLaterCycle); - md.dvarUsedByLaterCycle.retainAll(md.dvList); - - md.aliasUsedByLaterCycle = new HashSet(md.varUsedByLaterCycle); - md.aliasUsedByLaterCycle.retainAll(md.asList); - - } - - - LogUtils.importantMsg("=================================================="); - LogUtils.importantMsg("VariableName[CycleName] checking complete. "); - LogUtils.importantMsg("Total errors in the study: "+ total_errors); - LogUtils.importantMsg("=================================================="); - - } - - - private static void analyzeVarNeededFromCycle_subfunction(String varName, Set neededVarInCycle, String fromWresl, StudyDataSet sd) { - - Map> neededCycleVarMap = Tools.getCycleVarMap(neededVarInCycle); - - Map mdsm = sd.getModelDataSetMap(); - - for (String neededCycle : neededCycleVarMap.keySet()) { - - Set neededVarSet = neededCycleVarMap.get(neededCycle); - - if (!allValidCycleNames.contains(neededCycle)) { - - for (String s : neededVarSet) { - LogUtils.errMsg("In file: " + fromWresl + "\n" + "Variable [" + varName + "] has an item with undefined cycle: "+ s + "[" + neededCycle + "]"); - } - continue; - - } else if ( cycleNameConditionMap.get(neededCycle).length()>0 && !cycleNameConditionMap.get(neededCycle).equalsIgnoreCase("always")){ - - for (String s : neededVarSet) { - //LogUtils.warningMsg("In file: " + fromWresl + "\n" + "Variable [" + varName + "] has an item " + s + "[" + neededCycle + "]"+" depending on cycle condition: "+ cycleNameConditionMap.get(neededCycle)); - //LogUtils.warningMsg("Variable [" + varName + "] has an item " + s + "[" + neededCycle + "]"+" depending on cycle condition: "+ cycleNameConditionMap.get(neededCycle)); - } - } - - for (String neededVar : neededVarSet) { - - // / check if exist - Set validVarNames = cycleVarTypeMap.get(neededCycle).keySet(); - - if (!validVarNames.contains(neededVar)) { - - if (sd.getModelDataSetMap().get(neededCycle.toLowerCase()).tsList.contains(neededVar.toLowerCase())){ - - LogUtils.errMsg( fromWresl + " "+neededVar + "[" + neededCycle + "] cannot be of Timeseries type." ); - - } else { - - LogUtils.errMsg( fromWresl + " variable named [" + varName + "] has an undefined variable: "+ neededVar + "[" + neededCycle + "]"); - } - - continue; - } - - // / create space in varCycleValue map - Map> vcv = sd.getVarCycleValueMap(); - - // / create space in varCycleValue map where cycles contains neededCycle and past cycles - - ArrayList cycleListBase = new ArrayList(sd.getModelList()); - ArrayList cycleList = new ArrayList(sd.getModelList()); - - int indexOfNeededCycle = cycleListBase.indexOf(neededCycle); - - -// for (int i=1 ; i <= n_buffer; i++){ -// cycleList.add(0, cycleListBase.get(cycleListBase.size()-i)); -// } -// indexOfNeededCycle = indexOfNeededCycle + n_buffer ; - - int beginIndex = Math.max( indexOfNeededCycle-n_buffer, 0); - - for (int i= beginIndex ; i <= indexOfNeededCycle; i++){ - String cycleN = cycleList.get(i); - - //=================== - if (vcv.keySet().contains(neededVar)) { - vcv.get(neededVar).put(cycleN, null); - } else { - Map t = new HashMap(); - t.put(cycleN, null); - vcv.put(neededVar, t); - } - - // / add to set varUsedByLaterCycle - mdsm.get(cycleN).varUsedByLaterCycle.add(neededVar); - //=================== - } - - } - } - - } - - private static void checkUsedBeforeDefined(SimulationDataSet ds, ArrayList ordered_list_sv_as_ex, Set previous_global_sv_as_ex_ts) { - - Set dep; - - for (int i=0; i< ds.svList.size(); i++ ){ - - String svName = ds.svList.get(i); - // TODO: serious bug. Map object is not reinitialized - dep = new HashSet(ds.svMap.get(svName).dependants); - //dep = ds.svMap.get(svName).dependants; // this will cause problem in shallow copy - dep.removeAll(ds.tsSet); - dep.removeAll(previous_global_sv_as_ex_ts); - - - //dep.removeAll(ds.svList.subList(0, i)); - if (ordered_list_sv_as_ex.contains(svName)) { - int index_sv = ordered_list_sv_as_ex.indexOf(svName); - dep.removeAll(ordered_list_sv_as_ex.subList(0, index_sv)); - } - - if (dep.size()>0){ - - //Set undefinedVar = new HashSet(dep); - //undefinedVar.removeAll(ds.asSet); - - //allows recursive svar definition for future array - LogUtils.warningMsg(ds.svMap.get(svName).fromWresl + " variable names used before definition: "+dep+" in Svar named ["+svName+"]" ); - //LogUtils.errMsg(ds.svMap.get(svName).fromWresl + " variable names used before definition: "+dep+" in Svar named ["+svName+"]" ); - - } - } - - for (int i=0; i< ds.asList.size(); i++ ){ - - String asName = ds.asList.get(i); - - dep = new HashSet(ds.asMap.get(asName).dependants); - - dep.removeAll(ds.tsSet); - dep.removeAll(previous_global_sv_as_ex_ts); - - //dep.removeAll(ds.asList.subList(0, i)); - if (ordered_list_sv_as_ex.contains(asName)) { - int index_as = ordered_list_sv_as_ex.indexOf(asName); - dep.removeAll(ordered_list_sv_as_ex.subList(0, index_as)); - } - - if (dep.size()>0){ - - LogUtils.errMsg( ds.asMap.get(asName).fromWresl + " variable names used before definition: " + dep + " in Alias named ["+asName +"]" ); - - } - } - } - - private static void convertRestAliasInGoalExpression(SimulationDataSet ds) { - - Set asS = new LinkedHashSet(ds.asSet); - - for (String e : asS) { - - String goalName = e+"__alias"; - convertAlias(ds, e, goalName); - - } - } - - private static Set checkAliasInGoalExpression(SimulationDataSet ds, Set goalSetToCheck) { - - Set out_newGoalSet = new LinkedHashSet(); - ArrayList dep; - Set asSet = new LinkedHashSet(ds.asSet); - - for (String gName: goalSetToCheck) { - - dep = new ArrayList(ds.gMap.get(gName).expressionDependants); - - dep.removeAll(ds.tsSet); - dep.removeAll(ds.svSet); - dep.removeAll(ds.dvSet); - - Collections.sort(dep); - for (String e : dep) { - - if ( asSet.contains(e) ){ - - String goalName = e+"__alias"; - convertAlias(ds, e, goalName); - - out_newGoalSet.add(goalName); - } - } - } - return out_newGoalSet; - } - -private static Map getNewDataSet(Set adhoc_incFileSet, Set fileDataMap_wholeStudy_keySet) throws RecognitionException, IOException - { - Map fileDataMap_new = new HashMap(); - - for (String f : adhoc_incFileSet) - { - if (fileDataMap_wholeStudy_keySet.contains(f)) - { - continue; - } - - Map each = FileParser.processNestedFileExceptFor(f, fileDataMap_wholeStudy_keySet); - fileDataMap_new.putAll(each); - } - - return fileDataMap_new; - } - - private static Map copyDataSetToThisModel(Set incFileSet, Map fileDataMap_wholeStudy) - { - Map fileDataMap_thisModel = new HashMap(); - - for (String f : incFileSet) - { - fileDataMap_thisModel.putAll(Tools.putDataFileMapFromWholeStudy(f, fileDataMap_wholeStudy)); - } - - return fileDataMap_thisModel; - } - - private static SimulationDataSet correctScopeAndPrioritize(String modelName, SimulationDataSet adhoc, String absMainFilePath, Map fileDataMap_thisModel, Map fileDataMap_wholeStudy, Map> t1Map_wholeStudy, Map fileScopeMap_wholeStudy) - throws RecognitionException, IOException - { - Map fileScopeMap = new HashMap(fileScopeMap_wholeStudy); - fileScopeMap.putAll(Tools.getScopeMap(adhoc.incFileSet, adhoc.incFileSet_local)); - - Map> t1Map = new HashMap>(t1Map_wholeStudy); - t1Map.put(absMainFilePath, adhoc.incFileSet); - Map> t1ReverseMap = Tools.getReverseMap(t1Map); - - Map fileDataMap_corrected = new HashMap(fileDataMap_thisModel); - SimulationDataSet ds; - for (String f : fileDataMap_thisModel.keySet()) - { - ds = Tools.correctDataScope_deep(f, fileDataMap_thisModel.get(f), fileScopeMap, t1ReverseMap); - fileDataMap_corrected.put(f, ds); - } - - SimulationDataSet model_dataset = new SimulationDataSet(); - - for (String f : adhoc.incFileList) - { - SimulationDataSet temp = new SimulationDataSet(); - - temp.addChildren(f, t1Map, fileDataMap_corrected); - - temp.overwrittenWith_set(fileDataMap_corrected.get(f)); - - model_dataset.overwrittenWith_set(temp); - } - - model_dataset.overwrittenWith_set(adhoc); - - return model_dataset; - } - - private static boolean sortDependency(SimulationDataSet model_dataset, boolean rewrite_list_based_on_dependency) { - boolean OK = true; - - - // sort Svar + Alias - Sort sort_Sv_As = new Sort(model_dataset.svMap, model_dataset.asMap, model_dataset.dvSet, model_dataset.tsSet, model_dataset.exSet); - //model_dataset.exSet); - - ArrayList sortedSvAsList = new ArrayList(); - - Set var_with_unknown = sort_Sv_As.sort(sortedSvAsList); - if (var_with_unknown.size() > 0) OK = false; - - ArrayList sortedSvList = new ArrayList(sortedSvAsList); - ArrayList sortedAsList = new ArrayList(sortedSvAsList); - - sortedAsList.retainAll(model_dataset.asSet); - sortedSvList.retainAll(model_dataset.svSet); - - model_dataset.asSet_unknown = new HashSet(var_with_unknown); - model_dataset.asSet_unknown.retainAll(model_dataset.asSet); - - model_dataset.svSet_unknown = new HashSet(var_with_unknown); - model_dataset.svSet_unknown.retainAll(model_dataset.svSet); - - if (rewrite_list_based_on_dependency) { - model_dataset.asList = sortedAsList; - model_dataset.asList.addAll(model_dataset.asSet_unknown); - model_dataset.asSet = new LinkedHashSet(model_dataset.asList); - - model_dataset.svList = sortedSvList; - model_dataset.svList.addAll(model_dataset.svSet_unknown); - model_dataset.svSet = new LinkedHashSet(model_dataset.svList); - } - - return OK; - } - - private static ArrayList getOrderedList(Map fileDataMap_thisModel, SimulationDataSet adhoc) - { - Map> orderListMap = new HashMap>(); - - ArrayList complete_ordered_list = new ArrayList(); - - Sort sortFile = new Sort(fileDataMap_thisModel); - - ArrayList sortedFileList = new ArrayList(); - - sortFile.sort(sortedFileList); - - //------------------------------------------------ - // initialize - for (String f: sortedFileList){ - ArrayList toBeAdded = new ArrayList(fileDataMap_thisModel.get(f).ordered_list_including_files); - orderListMap.put(f, toBeAdded); - } - - // iterate - - for (String f : sortedFileList) { - SimulationDataSet ds = fileDataMap_thisModel.get(f); - - ArrayList new_ordered_list = new ArrayList(ds.ordered_list_including_files); - - // System.out.println(" new ordered_list_include_files: " + - // new_ordered_list); - - for (String inf : ds.incFileList) { - ArrayList toBeAdded = orderListMap.get(inf); - - // System.out.println(" new ordered_list before: " + - // new_ordered_list); - // System.out.println(" toBeAdded: " + toBeAdded); - - int pos = new_ordered_list.indexOf(inf); - new_ordered_list.addAll(pos, toBeAdded); - new_ordered_list.remove(inf); - } - orderListMap.put(f, new_ordered_list); - //System.out.println(" order list Map: " + orderListMap); - } - - - - //-------------------------------------------------- - - complete_ordered_list = new ArrayList(adhoc.ordered_list_including_files); - - for (String inf : adhoc.incFileList) - { - ArrayList toBeAdded = orderListMap.get(inf); - - int pos = complete_ordered_list.indexOf(inf); - complete_ordered_list.addAll(pos, toBeAdded); - complete_ordered_list.remove(inf); - } - return complete_ordered_list; - } - - private static void convertAlias(SimulationDataSet ds, String aliasName, String goalName) { - - Alias as = ds.asMap.get(aliasName); - - // add e into dvar - Dvar dv = new Dvar(); - - dv.kind = as.kind; - dv.units = as.units; - dv.lowerBound = Param.lower_unbounded; - dv.upperBound = Param.upper_unbounded; - dv.fromWresl = as.fromWresl; - dv.expression = as.expression; - dv.dependants = as.dependants; - dv.timeArraySize = as.timeArraySize; - - ds.dvMap.put(aliasName, dv); - ds.dvList.add(aliasName); - ds.dvSet.add(aliasName); - - if (as.scope.equalsIgnoreCase(Param.global)) { - ds.dvList_global.add(aliasName); - ds.dvSet_global.add(aliasName); - } - else if (as.scope.equalsIgnoreCase(Param.local)) { - ds.dvList_local.add(aliasName); - ds.dvSet_local.add(aliasName); - } - else { - LogUtils.errMsg("Scope error when converting alias to dvar: " + aliasName, as.fromWresl); - } - - // add additional goal - - Goal gl = new Goal(); - gl.caseCondition.add(Param.always); - gl.caseName.add(Param.defaultCaseName); - if (as.timeArraySize.equals("0")){ - gl.caseExpression.add(aliasName + "=" + as.expression); - }else{ - gl.caseExpression.add(aliasName + "($m)=" + as.expression); - } - gl.expressionDependants = as.dependants; - gl.fromWresl = as.fromWresl; - gl.timeArraySize=as.timeArraySize; - gl.needVarFromEarlierCycle = as.needVarFromEarlierCycle; - gl.neededVarInCycleSet = new HashSet(as.neededVarInCycleSet); - - - ds.gMap.put(goalName, gl); - ds.gList.add(goalName); - ds.gSet.add(goalName); - - if (as.scope.equalsIgnoreCase(Param.global)) { - ds.gList_global.add(goalName); - ds.gSet_global.add(goalName); - } - else if (as.scope.equalsIgnoreCase(Param.local)) { - ds.gList_local.add(goalName); - ds.gSet_local.add(goalName); - } - else { - LogUtils.errMsg("Scope error when adding constraint for alias: " + aliasName, as.fromWresl); - } - - // remove e from alias - ds.asList.remove(aliasName); - ds.asList_global.remove(aliasName); - ds.asList_local.remove(aliasName); - ds.asSet.remove(aliasName); - ds.asSet_global.remove(aliasName); - ds.asSet_local.remove(aliasName); - ds.asMap.remove(aliasName); - - } +package wrimsv2.wreslparser.elements; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import org.antlr.runtime.RecognitionException; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.Goal; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.commondata.wresldata.Timeseries; +import wrimsv2.components.ControlData; +import wrimsv2.components.IntDouble; +import wrimsv2.wreslparser.grammar.WreslTreeWalker; +import wrimsv2.wreslplus.elements.VarCycleIndex; + +public class StudyParser{ + + public static int total_errors = 0; + public static ArrayList error_summary = new ArrayList(); + public static int total_warnings = 0; + private static Map> cycleVarTypeMap; + private static Set allValidCycleNames; + private static Map cycleNameConditionMap; + private static Map cycleNameTimeStepMap; + private static int n_buffer = 3; + + + public static void reset(){ + total_errors = 0; + error_summary = new ArrayList(); + total_warnings = 0; + cycleVarTypeMap = null; + allValidCycleNames = null; + cycleNameConditionMap = null; + cycleNameTimeStepMap = null; + } + + public static StudyDataSet writeWreslData(StudyConfig sc, TempData td){ + StudyDataSet studyDataSet = new StudyDataSet(); + + studyDataSet.setModelList(sc.modelList); + studyDataSet.setModelConditionList(sc.modelConditionList); + studyDataSet.setModelTimeStepList(sc.modelTimeStepList); + + Map modelDataSetMap = new HashMap(); + Map timeseriesMap = new HashMap(); + Map> timeseriesTimeStepMap = new HashMap>(); + + for (String modelName : studyDataSet.getModelList()) + { + SimulationDataSet ds = (SimulationDataSet)td.model_dataset_map.get(modelName); + ModelDataSet thisModelDataSet = new ModelDataSet(); + + thisModelDataSet.dvList = ds.dvList; + Collections.sort(thisModelDataSet.dvList,String.CASE_INSENSITIVE_ORDER); + thisModelDataSet.dvList_global = ds.dvList_global; + thisModelDataSet.dvList_local = ds.dvList_local; + + for (String d: ds.dvList){ + if (ds.dvMap.get(d).condition.equalsIgnoreCase(Param.conditional)){ + thisModelDataSet.dvSlackSurplusList.add(d); + thisModelDataSet.dvSlackSurplusMap.put(d, ds.dvMap.get(d)); + ds.dvMap.remove(d); + } + } + + thisModelDataSet.dvList.removeAll(thisModelDataSet.dvSlackSurplusList); + thisModelDataSet.dvList_global.removeAll(thisModelDataSet.dvSlackSurplusList); + thisModelDataSet.dvList_local.removeAll(thisModelDataSet.dvSlackSurplusList); + thisModelDataSet.dvMap = ds.dvMap; + + thisModelDataSet.tsList = ds.tsList; + thisModelDataSet.tsList_global = ds.tsList_global; + thisModelDataSet.tsList_local = ds.tsList_local; + thisModelDataSet.tsMap = ds.tsMap; + + thisModelDataSet.svSet_unknown = ds.svSet_unknown; + thisModelDataSet.svList = ds.svList; + thisModelDataSet.svList_global = ds.svList_global; + thisModelDataSet.svList_local = ds.svList_local; + thisModelDataSet.svMap = ds.svMap; + + thisModelDataSet.gList = ds.gList; + Collections.sort(thisModelDataSet.gList,String.CASE_INSENSITIVE_ORDER); + thisModelDataSet.gList_global = ds.gList_global; + thisModelDataSet.gList_local = ds.gList_local; + thisModelDataSet.gMap = ds.gMap; + + thisModelDataSet.asSet_unknown = ds.asSet_unknown; + thisModelDataSet.asList = ds.asList; + thisModelDataSet.asList_global = ds.asList_global; + thisModelDataSet.asList_local = ds.asList_local; + thisModelDataSet.asMap = ds.asMap; + + thisModelDataSet.exList = ds.exList; + thisModelDataSet.exList_global = ds.exList_global; + thisModelDataSet.exList_local = ds.exList_local; + thisModelDataSet.exMap = ds.exMap; + + + thisModelDataSet.wtList = ds.wtList; + Collections.sort(thisModelDataSet.wtList,String.CASE_INSENSITIVE_ORDER); + + for (String w: ds.wtList){ + if (ds.wtMap.get(w).condition.equalsIgnoreCase(Param.conditional)){ + thisModelDataSet.wtSlackSurplusList.add(w); + thisModelDataSet.wtSlackSurplusMap.put(w, ds.wtMap.get(w)); + ds.wtMap.remove(w); + } + } + + thisModelDataSet.wtList.removeAll(thisModelDataSet.wtSlackSurplusList); + //System.out.println("thisModelDataSet.wtList : "+thisModelDataSet.wtList); + thisModelDataSet.wtMap = ds.wtMap; + + + + + thisModelDataSet.incFileList = ds.incFileList; + thisModelDataSet.incFileList_global = ds.incFileList_global; + thisModelDataSet.incFileList_local = ds.incFileList_local; + + modelDataSetMap.put(modelName, thisModelDataSet); + timeseriesMap.putAll(ds.tsMap); + int modelIndex=studyDataSet.getModelList().indexOf(modelName); + String timeStep=sc.modelTimeStepList.get(modelIndex); + String definedTimeStep; + if (timeStep.equals(Param.undefined)){ + definedTimeStep=ControlData.defaultTimeStep; + }else{ + definedTimeStep=timeStep; + } + for (String timeseriesName:ds.tsMap.keySet()){ + if (timeseriesTimeStepMap.containsKey(timeseriesName)){ + ArrayList timeStepList=timeseriesTimeStepMap.get(timeseriesName); + if (!timeStepList.contains(definedTimeStep)){ + timeStepList.add(definedTimeStep); + } + }else{ + timeseriesTimeStepMap.put(timeseriesName, new ArrayList(Arrays.asList(definedTimeStep))); + } + } + } + + studyDataSet.setModelDataSetMap(modelDataSetMap); + studyDataSet.setTimeseriesMap(timeseriesMap); + studyDataSet.setTimeseriesTimeStepMap(timeseriesTimeStepMap); + studyDataSet.setVarCycleIndexList(VarCycleIndex.varCycleIndexList); + + return studyDataSet; + } + + public static StudyConfig processMainFileIntoStudyConfig(String relativeMainFilePath) throws RecognitionException, IOException { + /// reset total errors + total_errors = 0; + return processMainFileIntoStudyConfig(relativeMainFilePath, false); + } + + public static StudyConfig processMainFileIntoStudyConfig(String relativeMainFilePath, boolean showTree) throws RecognitionException, IOException + { + File absMainFile = new File(relativeMainFilePath).getAbsoluteFile(); + String absMainFilePath = absMainFile.getCanonicalPath().toLowerCase(); + + LogUtils.importantMsg("Parsing study main file: " + absMainFilePath); + + WreslTreeWalker walker = FileParser.parseMainFile(absMainFilePath, showTree); + + StudyConfig sc = new StudyConfig(); + + sc.sequenceMap = walker.thisFileDataSet.seqMap; + + /// Sort sequence order + + for ( Integer i : sc.sequenceMap.keySet()){ sc.sequenceOrder.add(i); } + Collections.sort(sc.sequenceOrder); + + cycleNameConditionMap = new HashMap(); + cycleNameTimeStepMap = new HashMap(); + + for (Integer i : sc.sequenceOrder) { + sc.sequenceList.add(sc.sequenceMap.get(i).sequenceName); + sc.modelList.add(sc.sequenceMap.get(i).modelName); + + sc.modelConditionList.add(sc.sequenceMap.get(i).condition); + sc.modelTimeStepList.add(sc.sequenceMap.get(i).timeStep); + cycleNameConditionMap.put(sc.sequenceMap.get(i).modelName, sc.sequenceMap.get(i).condition ); + cycleNameTimeStepMap.put(sc.sequenceMap.get(i).modelName, sc.sequenceMap.get(i).timeStep ); + } + + sc.absMainFilePath = absMainFilePath; + sc.modelDataMap = walker.modelDataMap; + + for (Integer i : sc.sequenceOrder) { + LogUtils.importantMsg("Sequence: " + i + " : " + ((Sequence)sc.sequenceMap.get(i)).sequenceName + " Model: " + ((Sequence)sc.sequenceMap.get(i)).modelName); + } + + return sc; + } + + public static Map parseModels(StudyConfig sc, TempData td) throws RecognitionException, IOException + { + return parseModels(sc, td, false, false); + } + + public static Map parseModels(StudyConfig sc, TempData td, boolean rewrite_list_based_on_dependency, boolean send_all_alias_to_dvar) throws RecognitionException, IOException + { + Map model_dataset_map = new HashMap(); + + for (Integer iSequence : sc.sequenceOrder) + { + String modelName = sc.sequenceMap.get(iSequence).modelName; + + LogUtils.importantMsg("Processing sequence: " + iSequence + ", model: " + modelName); + + SimulationDataSet adhoc = sc.modelDataMap.get(modelName); + + Map fileDataMap_new = getNewDataSet(adhoc.incFileSet, td.fileDataMap_wholeStudy.keySet()); + + td.fileDataMap_wholeStudy.putAll(fileDataMap_new); + + td.t1Map_wholeStudy.putAll(Tools.getType1Map(fileDataMap_new)); + td.fileScopeMap_wholeStudy.putAll(Tools.getFileScopeMap(fileDataMap_new)); + + Map fileDataMap_thisModel = copyDataSetToThisModel(adhoc.incFileSet, td.fileDataMap_wholeStudy); + + ArrayList ordered_list_for_all_vars = getOrderedList(fileDataMap_thisModel, adhoc); + + + Set duplicates = Tools.removeDuplicates(ordered_list_for_all_vars); + + + if (duplicates.size() > 0) { + LogUtils.errMsg("Variables redefined in model " + modelName + ": " + duplicates); + } + + + SimulationDataSet model_dataset = correctScopeAndPrioritize(modelName, + adhoc, + sc.absMainFilePath, + fileDataMap_thisModel, + td.fileDataMap_wholeStudy, + td.t1Map_wholeStudy, + td.fileScopeMap_wholeStudy); + + model_dataset.svSet = Tools.restoreOrder(model_dataset.svList, ordered_list_for_all_vars, model_dataset.svSet); + model_dataset.asSet = Tools.restoreOrder(model_dataset.asList, ordered_list_for_all_vars, model_dataset.asSet); + + td.t1Map_wholeStudy.put(sc.absMainFilePath, adhoc.incFileSet); + @SuppressWarnings("unused") + Map> t1ReverseMap_wholeStudy = Tools.getReverseMap(td.t1Map_wholeStudy); + + + ///////// add previous globals + //LogUtils.importantMsg("Adding previous global vars into model: "+modelName); + + /// check for redefined weight // TODO: what to do? + Set redefined_globals_wt = new LinkedHashSet(td.cumulative_global_complete.wtSet); + redefined_globals_wt.retainAll(model_dataset.wtSet_global); + if (redefined_globals_wt.size()>0) LogUtils.errMsg("Global weights redefined: "+ redefined_globals_wt); + + /// check for redefined file + Set redefined_global_file = new LinkedHashSet(td.cumulative_global_complete.incFileSet); + redefined_global_file.retainAll(model_dataset.incFileSet_global); + if (redefined_global_file.size()>0) LogUtils.errMsg("Global include files redefined: "+ redefined_global_file); + + /// check for redefined globals + Set redefined_globals = new LinkedHashSet(td.cumulative_global_complete.getAllVarsSet_except_file_and_weight()); + Set redefined_globals_as_locals = new LinkedHashSet(td.cumulative_global_complete.getAllVarsSet_except_file_and_weight()); + + + redefined_globals.retainAll(model_dataset.getAllGlobalVarsSet_except_file_and_weight()); + + redefined_globals_as_locals.retainAll(model_dataset.getAllLocalVarsSet_except_file_and_weight()); + + if (redefined_globals.size()>0) LogUtils.errMsg("Global variables redefined: "+ redefined_globals); + if (redefined_globals_as_locals.size()>0) LogUtils.warningMsg("Global variables redefined as local: "+ redefined_globals_as_locals); + + + + /// add previous globals + + + +// // option 1 : remove redefined +// SimulationDataSet cumulative_global_remove_redefined = new SimulationDataSet(td.cumulative_global_complete); +// cumulative_global_remove_redefined.remove_set(redefined_globals); +// cumulative_global_remove_redefined.remove_set(redefined_globals_as_locals); + + + // option 2 : replace redefined + SimulationDataSet cumulative_global_replace_redefined = new SimulationDataSet(td.cumulative_global_complete); + + + // comment out. redefining globals is not allowed + // cumulative_global_replace_redefined.replaceGlobalWithDuplicateGlobal(redefined_globals,model_dataset ); + + + + try { + cumulative_global_replace_redefined.replaceGlobalWithDuplicateLocal(redefined_globals_as_locals,model_dataset); + } + catch (TypeRedefinedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + // put all previous global vars into current cycle + model_dataset.overwrite_set(cumulative_global_replace_redefined); + + //LogUtils.importantMsg("Finish adding previous global vars into model: "+modelName); + /// finish adding globals + + + model_dataset.lousyConvert(); + + + // check if dependency is unknown TODO: sorted list will not have the same sequence as user's define in wresl + sortDependency(model_dataset, rewrite_list_based_on_dependency); + + //// check if vars are used before being defined + Set svar_alias_extern_set = new HashSet(); + svar_alias_extern_set.addAll(model_dataset.svSet); + svar_alias_extern_set.addAll(model_dataset.asSet); + svar_alias_extern_set.addAll(model_dataset.exSet); + + ArrayList ordered_list_svar_alias_extern = new ArrayList(ordered_list_for_all_vars); + ordered_list_svar_alias_extern.retainAll(svar_alias_extern_set); + + Set previous_global_svar_alias_extern_timeseries = new LinkedHashSet(td.cumulative_global_complete.getSvarAliasExternTimeseries()); + + checkUsedBeforeDefined(new SimulationDataSet(model_dataset), ordered_list_svar_alias_extern, previous_global_svar_alias_extern_timeseries); + + + /// check if goal dependents are defined + // 1. get union of previous global vars and current model vars + Set allVars = new HashSet(); + allVars.addAll(td.cumulative_global_complete.dvSet); allVars.addAll(model_dataset.dvSet); + allVars.addAll(td.cumulative_global_complete.svSet); allVars.addAll(model_dataset.svSet); + allVars.addAll(td.cumulative_global_complete.tsSet); allVars.addAll(model_dataset.tsSet); + allVars.addAll(td.cumulative_global_complete.exSet); allVars.addAll(model_dataset.exSet); + allVars.addAll(td.cumulative_global_complete.asSet); allVars.addAll(model_dataset.asSet); + + // 2. find undefined + for (String key: model_dataset.gSet){ + + Set goal_dependents_undefined = new HashSet(); + goal_dependents_undefined.addAll(model_dataset.gMap.get(key).expressionDependants); + goal_dependents_undefined.removeAll(allVars); + goal_dependents_undefined.removeAll(Param.reservedSet); + + if (goal_dependents_undefined.size()>0) { + LogUtils.errMsg(model_dataset.gMap.get(key).fromWresl +" variable names used before definition: "+goal_dependents_undefined+" in Goal named ["+key+"]"); + } + } + + /// check if weight var is defined in dvar set + // 1. get union of previous global dvar and current model dvar + Set allDvars = new HashSet(); + allDvars.addAll(td.cumulative_global_complete.dvSet); + allDvars.addAll(model_dataset.dvSet); + // 2. find undefined + Set weightElement_undefined = new HashSet(); + weightElement_undefined.addAll(model_dataset.wtSet); + + weightElement_undefined.removeAll(allDvars); + if (weightElement_undefined.size()>0) LogUtils.errMsg("Weight var not found in dvar: "+ weightElement_undefined); + + + + + model_dataset_map.put(modelName, model_dataset); + + td.cumulative_global_adhocs.overwrittenWith_set(sc.modelDataMap.get(modelName).getGlobalVars_set()); + td.cumulative_global_complete.overwrittenWith_set(model_dataset.getGlobalVars_set()); + + td.cumulative_global_adhocs.lousyConvert(); + td.cumulative_global_complete.lousyConvert(); + } + + /// check if alias is used in goal's constraint expression. + // if yes, then move that alias to dvar and add additional goal + if(send_all_alias_to_dvar) { + LogUtils.importantMsg("Converting all aliases into dvars and constraints...."); + } else { + LogUtils.importantMsg("Converting some aliases into dvars and constraints...."); + } + + for (String key : model_dataset_map.keySet()){ + SimulationDataSet ds = model_dataset_map.get(key); + + Set newGoals = checkAliasInGoalExpression(ds, new HashSet(ds.gSet)); + + // check for alias embedded in another alias + while (newGoals.size()>0){ + newGoals = checkAliasInGoalExpression(ds, newGoals); + } + + if(send_all_alias_to_dvar) { + convertRestAliasInGoalExpression(ds); + } + + + /// check if var size > 100 + Set allVar = new HashSet(); + allVar.addAll(ds.dvSet); + allVar.addAll(ds.asSet); + allVar.addAll(ds.svSet); + allVar.addAll(ds.gSet); + allVar.addAll(ds.exSet); + + for (String e: allVar) { if (e.length()>99) LogUtils.errMsg("Variable name is longer than 99 chars: "+ e);}; + + } + + LogUtils.importantMsg("Finished converting aliases."); + LogUtils.criticalMsg("============================================"); + LogUtils.criticalMsg("Wresl Parsing complete. "); + if (total_warnings>0) LogUtils.criticalMsg("Total warnings in the study: "+ total_warnings); + if (total_errors>0) LogUtils.criticalMsg("Total errors in the study: "+ total_errors); + LogUtils.criticalMsg("============================================"); + + return model_dataset_map; + } + + + public static void analyzeVarNeededFromCycles(StudyConfig sc, StudyDataSet sd) { + + Map mdsm = sd.getModelDataSetMap(); + cycleVarTypeMap = new HashMap>(); + allValidCycleNames = mdsm.keySet(); + String SvarClassName = new Svar().getClass().getName(); + String AliasClassName = new Alias().getClass().getName(); + String DvarClassName = new Dvar().getClass().getName(); + + // create map for valid var name and var type + + for (String key: mdsm.keySet()){ + + ModelDataSet ds = mdsm.get(key); + + /// create map for var and varType + Map varTypeMap = new HashMap(); + + for (String v: ds.svList){ + varTypeMap.put(v, SvarClassName); + } + for (String v: ds.asList){ + varTypeMap.put(v, AliasClassName); + } + for (String v: ds.dvList){ + varTypeMap.put(v, DvarClassName); + } + cycleVarTypeMap.put(key, varTypeMap); + } + + + for (Integer iSequence : sc.sequenceOrder) { + + String cycleKey = sc.sequenceMap.get(iSequence).modelName; + + ModelDataSet ds = mdsm.get(cycleKey); + + // / 1. check needVarFromEarlierCycle in goal, svar and alias; + // / 2. create space in td.varCycleValueMap + // / 3. set usedInLaterCycle for dvar, svar and alias; + + for (String varName : ds.gList) { + + Goal someVar = ds.gMap.get(varName); + + boolean needVarFromEarlierCycle = someVar.needVarFromEarlierCycle; + Set neededVarInCycle = someVar.neededVarInCycleSet; + String fromWresl = someVar.fromWresl; + + if (needVarFromEarlierCycle) { + analyzeVarNeededFromCycle_subfunction(varName, neededVarInCycle, fromWresl, sd); + + } + } + + for (String varName : ds.svList) { + + Svar someVar = ds.svMap.get(varName); + + boolean needVarFromEarlierCycle = someVar.needVarFromEarlierCycle; + Set neededVarInCycle = someVar.neededVarInCycleSet; + String fromWresl = someVar.fromWresl; + + if (needVarFromEarlierCycle) { + analyzeVarNeededFromCycle_subfunction(varName, neededVarInCycle, fromWresl, sd); + + } + } + + for (String varName : ds.asList) { + + Alias someVar = ds.asMap.get(varName); + + boolean needVarFromEarlierCycle = someVar.needVarFromEarlierCycle; + Set neededVarInCycle = someVar.neededVarInCycleSet; + String fromWresl = someVar.fromWresl; + + if (needVarFromEarlierCycle) { + analyzeVarNeededFromCycle_subfunction(varName, neededVarInCycle, fromWresl, sd); + + } + } + } + + + for (String cycleName : allValidCycleNames ){ + + ModelDataSet md = mdsm.get(cycleName); + + md.svarUsedByLaterCycle = new HashSet(md.varUsedByLaterCycle); + md.svarUsedByLaterCycle.retainAll(md.svList); + + md.dvarUsedByLaterCycle = new HashSet(md.varUsedByLaterCycle); + md.dvarUsedByLaterCycle.retainAll(md.dvList); + + md.aliasUsedByLaterCycle = new HashSet(md.varUsedByLaterCycle); + md.aliasUsedByLaterCycle.retainAll(md.asList); + + } + + + LogUtils.importantMsg("=================================================="); + LogUtils.importantMsg("VariableName[CycleName] checking complete. "); + LogUtils.importantMsg("Total errors in the study: "+ total_errors); + LogUtils.importantMsg("=================================================="); + + } + + + private static void analyzeVarNeededFromCycle_subfunction(String varName, Set neededVarInCycle, String fromWresl, StudyDataSet sd) { + + Map> neededCycleVarMap = Tools.getCycleVarMap(neededVarInCycle); + + Map mdsm = sd.getModelDataSetMap(); + + for (String neededCycle : neededCycleVarMap.keySet()) { + + Set neededVarSet = neededCycleVarMap.get(neededCycle); + + if (!allValidCycleNames.contains(neededCycle)) { + + for (String s : neededVarSet) { + LogUtils.errMsg("In file: " + fromWresl + "\n" + "Variable [" + varName + "] has an item with undefined cycle: "+ s + "[" + neededCycle + "]"); + } + continue; + + } else if ( cycleNameConditionMap.get(neededCycle).length()>0 && !cycleNameConditionMap.get(neededCycle).equalsIgnoreCase("always")){ + + for (String s : neededVarSet) { + //LogUtils.warningMsg("In file: " + fromWresl + "\n" + "Variable [" + varName + "] has an item " + s + "[" + neededCycle + "]"+" depending on cycle condition: "+ cycleNameConditionMap.get(neededCycle)); + //LogUtils.warningMsg("Variable [" + varName + "] has an item " + s + "[" + neededCycle + "]"+" depending on cycle condition: "+ cycleNameConditionMap.get(neededCycle)); + } + } + + for (String neededVar : neededVarSet) { + + // / check if exist + Set validVarNames = cycleVarTypeMap.get(neededCycle).keySet(); + + if (!validVarNames.contains(neededVar)) { + + if (sd.getModelDataSetMap().get(neededCycle.toLowerCase()).tsList.contains(neededVar.toLowerCase())){ + + LogUtils.errMsg( fromWresl + " "+neededVar + "[" + neededCycle + "] cannot be of Timeseries type." ); + + } else { + + LogUtils.errMsg( fromWresl + " variable named [" + varName + "] has an undefined variable: "+ neededVar + "[" + neededCycle + "]"); + } + + continue; + } + + // / create space in varCycleValue map + Map> vcv = sd.getVarCycleValueMap(); + + // / create space in varCycleValue map where cycles contains neededCycle and past cycles + + ArrayList cycleListBase = new ArrayList(sd.getModelList()); + ArrayList cycleList = new ArrayList(sd.getModelList()); + + int indexOfNeededCycle = cycleListBase.indexOf(neededCycle); + + +// for (int i=1 ; i <= n_buffer; i++){ +// cycleList.add(0, cycleListBase.get(cycleListBase.size()-i)); +// } +// indexOfNeededCycle = indexOfNeededCycle + n_buffer ; + + int beginIndex = Math.max( indexOfNeededCycle-n_buffer, 0); + + for (int i= beginIndex ; i <= indexOfNeededCycle; i++){ + String cycleN = cycleList.get(i); + + //=================== + if (vcv.keySet().contains(neededVar)) { + vcv.get(neededVar).put(cycleN, null); + } else { + Map t = new HashMap(); + t.put(cycleN, null); + vcv.put(neededVar, t); + } + + // / add to set varUsedByLaterCycle + mdsm.get(cycleN).varUsedByLaterCycle.add(neededVar); + //=================== + } + + } + } + + } + + private static void checkUsedBeforeDefined(SimulationDataSet ds, ArrayList ordered_list_sv_as_ex, Set previous_global_sv_as_ex_ts) { + + Set dep; + + for (int i=0; i< ds.svList.size(); i++ ){ + + String svName = ds.svList.get(i); + // TODO: serious bug. Map object is not reinitialized + dep = new HashSet(ds.svMap.get(svName).dependants); + //dep = ds.svMap.get(svName).dependants; // this will cause problem in shallow copy + dep.removeAll(ds.tsSet); + dep.removeAll(previous_global_sv_as_ex_ts); + + + //dep.removeAll(ds.svList.subList(0, i)); + if (ordered_list_sv_as_ex.contains(svName)) { + int index_sv = ordered_list_sv_as_ex.indexOf(svName); + dep.removeAll(ordered_list_sv_as_ex.subList(0, index_sv)); + } + + if (dep.size()>0){ + + //Set undefinedVar = new HashSet(dep); + //undefinedVar.removeAll(ds.asSet); + + //allows recursive svar definition for future array + LogUtils.warningMsg(ds.svMap.get(svName).fromWresl + " variable names used before definition: "+dep+" in Svar named ["+svName+"]" ); + //LogUtils.errMsg(ds.svMap.get(svName).fromWresl + " variable names used before definition: "+dep+" in Svar named ["+svName+"]" ); + + } + } + + for (int i=0; i< ds.asList.size(); i++ ){ + + String asName = ds.asList.get(i); + + dep = new HashSet(ds.asMap.get(asName).dependants); + + dep.removeAll(ds.tsSet); + dep.removeAll(previous_global_sv_as_ex_ts); + + //dep.removeAll(ds.asList.subList(0, i)); + if (ordered_list_sv_as_ex.contains(asName)) { + int index_as = ordered_list_sv_as_ex.indexOf(asName); + dep.removeAll(ordered_list_sv_as_ex.subList(0, index_as)); + } + + if (dep.size()>0){ + + LogUtils.errMsg( ds.asMap.get(asName).fromWresl + " variable names used before definition: " + dep + " in Alias named ["+asName +"]" ); + + } + } + } + + private static void convertRestAliasInGoalExpression(SimulationDataSet ds) { + + Set asS = new LinkedHashSet(ds.asSet); + + for (String e : asS) { + + String goalName = e+"__alias"; + convertAlias(ds, e, goalName); + + } + } + + private static Set checkAliasInGoalExpression(SimulationDataSet ds, Set goalSetToCheck) { + + Set out_newGoalSet = new LinkedHashSet(); + ArrayList dep; + Set asSet = new LinkedHashSet(ds.asSet); + + for (String gName: goalSetToCheck) { + + dep = new ArrayList(ds.gMap.get(gName).expressionDependants); + + dep.removeAll(ds.tsSet); + dep.removeAll(ds.svSet); + dep.removeAll(ds.dvSet); + + Collections.sort(dep); + for (String e : dep) { + + if ( asSet.contains(e) ){ + + String goalName = e+"__alias"; + convertAlias(ds, e, goalName); + + out_newGoalSet.add(goalName); + } + } + } + return out_newGoalSet; + } + +private static Map getNewDataSet(Set adhoc_incFileSet, Set fileDataMap_wholeStudy_keySet) throws RecognitionException, IOException + { + Map fileDataMap_new = new HashMap(); + + for (String f : adhoc_incFileSet) + { + if (fileDataMap_wholeStudy_keySet.contains(f)) + { + continue; + } + + Map each = FileParser.processNestedFileExceptFor(f, fileDataMap_wholeStudy_keySet); + fileDataMap_new.putAll(each); + } + + return fileDataMap_new; + } + + private static Map copyDataSetToThisModel(Set incFileSet, Map fileDataMap_wholeStudy) + { + Map fileDataMap_thisModel = new HashMap(); + + for (String f : incFileSet) + { + fileDataMap_thisModel.putAll(Tools.putDataFileMapFromWholeStudy(f, fileDataMap_wholeStudy)); + } + + return fileDataMap_thisModel; + } + + private static SimulationDataSet correctScopeAndPrioritize(String modelName, SimulationDataSet adhoc, String absMainFilePath, Map fileDataMap_thisModel, Map fileDataMap_wholeStudy, Map> t1Map_wholeStudy, Map fileScopeMap_wholeStudy) + throws RecognitionException, IOException + { + Map fileScopeMap = new HashMap(fileScopeMap_wholeStudy); + fileScopeMap.putAll(Tools.getScopeMap(adhoc.incFileSet, adhoc.incFileSet_local)); + + Map> t1Map = new HashMap>(t1Map_wholeStudy); + t1Map.put(absMainFilePath, adhoc.incFileSet); + Map> t1ReverseMap = Tools.getReverseMap(t1Map); + + Map fileDataMap_corrected = new HashMap(fileDataMap_thisModel); + SimulationDataSet ds; + for (String f : fileDataMap_thisModel.keySet()) + { + ds = Tools.correctDataScope_deep(f, fileDataMap_thisModel.get(f), fileScopeMap, t1ReverseMap); + fileDataMap_corrected.put(f, ds); + } + + SimulationDataSet model_dataset = new SimulationDataSet(); + + for (String f : adhoc.incFileList) + { + SimulationDataSet temp = new SimulationDataSet(); + + temp.addChildren(f, t1Map, fileDataMap_corrected); + + temp.overwrittenWith_set(fileDataMap_corrected.get(f)); + + model_dataset.overwrittenWith_set(temp); + } + + model_dataset.overwrittenWith_set(adhoc); + + return model_dataset; + } + + private static boolean sortDependency(SimulationDataSet model_dataset, boolean rewrite_list_based_on_dependency) { + boolean OK = true; + + + // sort Svar + Alias + Sort sort_Sv_As = new Sort(model_dataset.svMap, model_dataset.asMap, model_dataset.dvSet, model_dataset.tsSet, model_dataset.exSet); + //model_dataset.exSet); + + ArrayList sortedSvAsList = new ArrayList(); + + Set var_with_unknown = sort_Sv_As.sort(sortedSvAsList); + if (var_with_unknown.size() > 0) OK = false; + + ArrayList sortedSvList = new ArrayList(sortedSvAsList); + ArrayList sortedAsList = new ArrayList(sortedSvAsList); + + sortedAsList.retainAll(model_dataset.asSet); + sortedSvList.retainAll(model_dataset.svSet); + + model_dataset.asSet_unknown = new HashSet(var_with_unknown); + model_dataset.asSet_unknown.retainAll(model_dataset.asSet); + + model_dataset.svSet_unknown = new HashSet(var_with_unknown); + model_dataset.svSet_unknown.retainAll(model_dataset.svSet); + + if (rewrite_list_based_on_dependency) { + model_dataset.asList = sortedAsList; + model_dataset.asList.addAll(model_dataset.asSet_unknown); + model_dataset.asSet = new LinkedHashSet(model_dataset.asList); + + model_dataset.svList = sortedSvList; + model_dataset.svList.addAll(model_dataset.svSet_unknown); + model_dataset.svSet = new LinkedHashSet(model_dataset.svList); + } + + return OK; + } + + private static ArrayList getOrderedList(Map fileDataMap_thisModel, SimulationDataSet adhoc) + { + Map> orderListMap = new HashMap>(); + + ArrayList complete_ordered_list = new ArrayList(); + + Sort sortFile = new Sort(fileDataMap_thisModel); + + ArrayList sortedFileList = new ArrayList(); + + sortFile.sort(sortedFileList); + + //------------------------------------------------ + // initialize + for (String f: sortedFileList){ + ArrayList toBeAdded = new ArrayList(fileDataMap_thisModel.get(f).ordered_list_including_files); + orderListMap.put(f, toBeAdded); + } + + // iterate + + for (String f : sortedFileList) { + SimulationDataSet ds = fileDataMap_thisModel.get(f); + + ArrayList new_ordered_list = new ArrayList(ds.ordered_list_including_files); + + // System.out.println(" new ordered_list_include_files: " + + // new_ordered_list); + + for (String inf : ds.incFileList) { + ArrayList toBeAdded = orderListMap.get(inf); + + // System.out.println(" new ordered_list before: " + + // new_ordered_list); + // System.out.println(" toBeAdded: " + toBeAdded); + + int pos = new_ordered_list.indexOf(inf); + new_ordered_list.addAll(pos, toBeAdded); + new_ordered_list.remove(inf); + } + orderListMap.put(f, new_ordered_list); + //System.out.println(" order list Map: " + orderListMap); + } + + + + //-------------------------------------------------- + + complete_ordered_list = new ArrayList(adhoc.ordered_list_including_files); + + for (String inf : adhoc.incFileList) + { + ArrayList toBeAdded = orderListMap.get(inf); + + int pos = complete_ordered_list.indexOf(inf); + complete_ordered_list.addAll(pos, toBeAdded); + complete_ordered_list.remove(inf); + } + return complete_ordered_list; + } + + private static void convertAlias(SimulationDataSet ds, String aliasName, String goalName) { + + Alias as = ds.asMap.get(aliasName); + + // add e into dvar + Dvar dv = new Dvar(); + + dv.kind = as.kind; + dv.units = as.units; + dv.lowerBound = Param.lower_unbounded; + dv.upperBound = Param.upper_unbounded; + dv.fromWresl = as.fromWresl; + dv.expression = as.expression; + dv.dependants = as.dependants; + dv.timeArraySize = as.timeArraySize; + + ds.dvMap.put(aliasName, dv); + ds.dvList.add(aliasName); + ds.dvSet.add(aliasName); + + if (as.scope.equalsIgnoreCase(Param.global)) { + ds.dvList_global.add(aliasName); + ds.dvSet_global.add(aliasName); + } + else if (as.scope.equalsIgnoreCase(Param.local)) { + ds.dvList_local.add(aliasName); + ds.dvSet_local.add(aliasName); + } + else { + LogUtils.errMsg("Scope error when converting alias to dvar: " + aliasName, as.fromWresl); + } + + // add additional goal + + Goal gl = new Goal(); + gl.caseCondition.add(Param.always); + gl.caseName.add(Param.defaultCaseName); + if (as.timeArraySize.equals("0")){ + gl.caseExpression.add(aliasName + "=" + as.expression); + }else{ + gl.caseExpression.add(aliasName + "($m)=" + as.expression); + } + gl.expressionDependants = as.dependants; + gl.fromWresl = as.fromWresl; + gl.timeArraySize=as.timeArraySize; + gl.needVarFromEarlierCycle = as.needVarFromEarlierCycle; + gl.neededVarInCycleSet = new HashSet(as.neededVarInCycleSet); + + + ds.gMap.put(goalName, gl); + ds.gList.add(goalName); + ds.gSet.add(goalName); + + if (as.scope.equalsIgnoreCase(Param.global)) { + ds.gList_global.add(goalName); + ds.gSet_global.add(goalName); + } + else if (as.scope.equalsIgnoreCase(Param.local)) { + ds.gList_local.add(goalName); + ds.gSet_local.add(goalName); + } + else { + LogUtils.errMsg("Scope error when adding constraint for alias: " + aliasName, as.fromWresl); + } + + // remove e from alias + ds.asList.remove(aliasName); + ds.asList_global.remove(aliasName); + ds.asList_local.remove(aliasName); + ds.asSet.remove(aliasName); + ds.asSet_global.remove(aliasName); + ds.asSet_local.remove(aliasName); + ds.asMap.remove(aliasName); + + } } \ No newline at end of file diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StudyUtils.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/StudyUtils.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StudyUtils.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/StudyUtils.java index 2eb0b6df3..a0b23054c 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/StudyUtils.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/StudyUtils.java @@ -1,357 +1,357 @@ -package wrimsv2.wreslparser.elements; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.Date; -import java.util.Properties; - -import org.antlr.runtime.RecognitionException; -import org.apache.commons.io.FilenameUtils; -//import org.codehaus.jackson.JsonGenerationException; -//import org.codehaus.jackson.JsonParseException; -//import org.codehaus.jackson.map.JsonMappingException; -//import org.codehaus.jackson.map.ObjectMapper; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.io.Input; -import com.esotericsoftware.kryo.io.Output; - -import wrimsv2.commondata.wresldata.*; -import wrimsv2.components.BuildProps; -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; -import wrimsv2.evaluator.WeightEval; -import wrimsv2.solver.mpmodel.MPModel; -import wrimsv2.sql.socket.FileEvent; -import wrimsv2.tools.Warmstart; -import wrimsv2.wreslplus.elements.*; -import wrimsv2.wreslplus.elements.procedures.ToWreslData; - - -public class StudyUtils { - - public static int config_errors = 0; - public static int total_errors = 0; - public static boolean loadParserData=false; - public static boolean compileOnly=false; - - public static String parserDataPath = ""; - public static String configFilePath = ""; - public static String configFileCanonicalPath = ""; - public static String configDir = ""; - public static String configFileName = "default"; - public static boolean useWreslPlus = false; - public static boolean parserCheckVarUndefined = true; - public static boolean showCompileLog = false; - - private StudyUtils() { - - } - - public static void reset() { - - StudyParser.reset(); - total_errors = 0; - config_errors = 0; - } - - public static StudyDataSet compileStudy(String inMainWreslPath) throws IOException { - - StudyUtils.compileOnly = true; - StudyDataSet sds = checkStudy(inMainWreslPath); - WeightEval.procWt(sds); - return sds; - } - - public static StudyDataSet checkStudy(String inMainWreslPath) throws IOException { - - // TODO: clean up this mess. simplify these checkStudy methods. - if (FilePaths.mainFile.length()<1) FilePaths.mainFile = FilenameUtils.getName(inMainWreslPath); - - String mainFileName = FilenameUtils.removeExtension(FilePaths.mainFile); - - String csvFolderName = "=WreslCheck_"+mainFileName+"="; - String logFileName = "=WreslCheck_"+mainFileName+"=.log"; - - if (!ControlData.outputWreslCSV) { - csvFolderName = ""; // disable csv output - } - - return checkStudy(inMainWreslPath, logFileName, csvFolderName, ControlData.sendAliasToDvar); - - } - - public static StudyDataSet checkStudy(String inMainWreslPath, String csvFolderName, boolean sendAliasToDvar) throws IOException { - - String mainFileName = FilenameUtils.removeExtension(FilePaths.mainFile); - - String logFileName = "=WreslCheck_"+mainFileName+"=.log"; - - return checkStudy(inMainWreslPath, logFileName, csvFolderName, sendAliasToDvar); - - } - - public static StudyDataSet checkStudy(String inMainWreslPath, String logFileName, String csvFolderName, - boolean sendAliasToDvar) throws IOException { - - StudyDataSet sds = null; - - File mainWreslFile = sanityCheck(inMainWreslPath); - - LogUtils.setLogFile(mainWreslFile.getParentFile().getCanonicalPath(), logFileName); - - LogUtils.titleMsg(Param.wreslChekerName + new BuildProps().getVN()); - - - try { - - if (useWreslPlus) { - sds = parseWreslPlus(mainWreslFile); - total_errors = StudyParser.total_errors; - } else { - sds = parseWresl(mainWreslFile, sendAliasToDvar); - } - - } - catch (RecognitionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - if (csvFolderName != null && csvFolderName.length() > 0) { - String csvFolderPath = mainWreslFile.getParentFile() + File.separator + csvFolderName; - WriteCSV.study(sds, csvFolderPath); - } - - if (StudyUtils.compileOnly) { - - if (StudyUtils.total_errors ==0) { - StudyUtils.compileObject(FilePaths.fullMainPath, sds); - //System.exit(0); - } else { - LogUtils.errMsg("Compilation unsuccessful."); - //System.exit(1); - } - - } - - LogUtils.closeLogFile(); - - if (total_errors==0){ - if (ControlData.useCbcWarmStart || ControlData.cbcCheckIntErr || ControlData.cbc_debug_routeCbc || ControlData.cbc_debug_routeXA){ - if (ControlData.solverName.equalsIgnoreCase("Cbc") || ControlData.solverName.equalsIgnoreCase("Cbc1")){ - - Warmstart.collectIntegerDV_2(sds); - - } - } - } - return sds; - - } - - public static void compileObject(String inMainWreslPath, StudyDataSet sds) { - - StringBuilder b = new StringBuilder(inMainWreslPath); - b.replace(inMainWreslPath.lastIndexOf("."), inMainWreslPath.length(), ".par"); - String objFilePath = b.toString(); - - StringBuilder b2 = new StringBuilder(FilePaths.mainFile); - b2.replace(FilePaths.mainFile.lastIndexOf("."), FilePaths.mainFile.length(), ".par"); - String objFileName = b2.toString(); - - LogUtils.importantMsg("Writing parser data...."); - writeObj(sds, objFilePath); - LogUtils.importantMsg("Wresl files are compiled into a binary file: "+objFileName ); - - } - - public static StudyDataSet loadObject(String objFilePath) { - - System.out.println("Loading precompiled parser data: "+objFilePath); - - return readObj(objFilePath); - - } - - private static File sanityCheck(String inMainWreslPath) throws IOException { - - String m = inMainWreslPath; - File validatedAbsFile = null; - - if (m.length() < 7) { - - throw new IOException("Invalid wresl file: " + m); } - - String extension = m.substring(m.length() - 5); - - if (!extension.equalsIgnoreCase("wresl")) { throw new IOException("Invalid wresl file: " + m); } - - validatedAbsFile = new File(inMainWreslPath).getAbsoluteFile(); - - if (!validatedAbsFile.exists()) { throw new IOException("File not found: " + inMainWreslPath); } - - return validatedAbsFile; - - } - - private static StudyDataSet parseWresl(File validatedMainWreslFile, boolean sendAliasToDvar) - throws RecognitionException, IOException { - - try { - - TempData td = new TempData(); - StudyParser.reset(); - VarCycleIndex.clearVarCycleIndexList(); - StudyConfig sc = StudyParser.processMainFileIntoStudyConfig(validatedMainWreslFile.getCanonicalPath()); - - // td.model_dataset_map=StudyParser.parseModels(sc,td); - td.model_dataset_map = StudyParser.parseModels(sc, td, false, sendAliasToDvar); - - StudyDataSet sd = StudyParser.writeWreslData(sc, td); - - StudyParser.analyzeVarNeededFromCycles(sc, sd); - - total_errors = StudyParser.total_errors; - - return sd; - - } - catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - private static StudyDataSet parseWreslPlus(File validatedMainWreslFile) - throws RecognitionException, IOException { - - StudyUtils.reset(); - - try { - - - //total_errors = StudyParser.total_errors; - StudyTemp st = null; - if (showCompileLog) { - st = Workflow.checkStudy_compileLog(validatedMainWreslFile.getCanonicalPath()); - } else { - st = Workflow.checkStudy(validatedMainWreslFile.getCanonicalPath()); - } - - StudyDataSet sd = ToWreslData.convertStudy(st); - - st = null; - System.gc(); - - return sd; - - } - catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - public static void writeObj(StudyDataSet sds, String objFilePath) { - - Kryo kryo = new Kryo(); - registerClasses(kryo); - try { - Output output = new Output(new FileOutputStream(objFilePath)); - kryo.writeObject(output, sds); - output.close(); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - /* - ObjectMapper objectMapper = new ObjectMapper(); - try { - objectMapper.writeValue(new File(objFilePath), sds); - } catch (JsonGenerationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (JsonMappingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - */ - } - - private static StudyDataSet readObj(String objFilePath) { - - StudyDataSet sds=new StudyDataSet(); - Kryo kryo = new Kryo(); - registerClasses(kryo); - try { - Input input = new Input(new FileInputStream(objFilePath)); - sds = kryo.readObject(input, StudyDataSet.class); - input.close(); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - /* - ObjectMapper objectMapper = new ObjectMapper(); - StudyDataSet sds=new StudyDataSet(); - try { - sds = objectMapper.readValue(new File(objFilePath), StudyDataSet.class); - } catch (JsonParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (JsonMappingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - */ - return sds; - - } - - public static void registerClasses(Kryo kryo){ - kryo.register(Alias.class); - kryo.register(Dvar.class); - kryo.register(External.class); - kryo.register(Goal.class); - kryo.register(ModelDataSet.class); - kryo.register(StudyDataSet.class); - kryo.register(Svar.class); - kryo.register(Timeseries.class); - kryo.register(WeightElement.class); - kryo.register(MPModel.class); - kryo.register(FileEvent.class); - kryo.register(AliasTemp.class); - kryo.register(DvarTemp.class); - kryo.register(ExternalTemp.class); - kryo.register(GoalCase.class); - kryo.register(GoalHS.class); - kryo.register(GoalTemp.class); - kryo.register(IfIncItemGroup.class); - kryo.register(IncFileTemp.class); - kryo.register(ModelTemp.class); - kryo.register(ParamTemp.class); - kryo.register(SequenceTemp.class); - kryo.register(StudyTemp.class); - kryo.register(SvarTemp.class); - kryo.register(TimeseriesTemp.class); - kryo.register(WeightSubgroup.class); - kryo.register(WeightTable.class); - kryo.register(WeightTemp.class); - } +package wrimsv2.wreslparser.elements; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Date; +import java.util.Properties; + +import org.antlr.runtime.RecognitionException; +import org.apache.commons.io.FilenameUtils; +//import org.codehaus.jackson.JsonGenerationException; +//import org.codehaus.jackson.JsonParseException; +//import org.codehaus.jackson.map.JsonMappingException; +//import org.codehaus.jackson.map.ObjectMapper; + +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; + +import wrimsv2.commondata.wresldata.*; +import wrimsv2.components.BuildProps; +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; +import wrimsv2.evaluator.WeightEval; +import wrimsv2.solver.mpmodel.MPModel; +import wrimsv2.sql.socket.FileEvent; +import wrimsv2.tools.Warmstart; +import wrimsv2.wreslplus.elements.*; +import wrimsv2.wreslplus.elements.procedures.ToWreslData; + + +public class StudyUtils { + + public static int config_errors = 0; + public static int total_errors = 0; + public static boolean loadParserData=false; + public static boolean compileOnly=false; + + public static String parserDataPath = ""; + public static String configFilePath = ""; + public static String configFileCanonicalPath = ""; + public static String configDir = ""; + public static String configFileName = "default"; + public static boolean useWreslPlus = false; + public static boolean parserCheckVarUndefined = true; + public static boolean showCompileLog = false; + + private StudyUtils() { + + } + + public static void reset() { + + StudyParser.reset(); + total_errors = 0; + config_errors = 0; + } + + public static StudyDataSet compileStudy(String inMainWreslPath) throws IOException { + + StudyUtils.compileOnly = true; + StudyDataSet sds = checkStudy(inMainWreslPath); + WeightEval.procWt(sds); + return sds; + } + + public static StudyDataSet checkStudy(String inMainWreslPath) throws IOException { + + // TODO: clean up this mess. simplify these checkStudy methods. + if (FilePaths.mainFile.length()<1) FilePaths.mainFile = FilenameUtils.getName(inMainWreslPath); + + String mainFileName = FilenameUtils.removeExtension(FilePaths.mainFile); + + String csvFolderName = "=WreslCheck_"+mainFileName+"="; + String logFileName = "=WreslCheck_"+mainFileName+"=.log"; + + if (!ControlData.outputWreslCSV) { + csvFolderName = ""; // disable csv output + } + + return checkStudy(inMainWreslPath, logFileName, csvFolderName, ControlData.sendAliasToDvar); + + } + + public static StudyDataSet checkStudy(String inMainWreslPath, String csvFolderName, boolean sendAliasToDvar) throws IOException { + + String mainFileName = FilenameUtils.removeExtension(FilePaths.mainFile); + + String logFileName = "=WreslCheck_"+mainFileName+"=.log"; + + return checkStudy(inMainWreslPath, logFileName, csvFolderName, sendAliasToDvar); + + } + + public static StudyDataSet checkStudy(String inMainWreslPath, String logFileName, String csvFolderName, + boolean sendAliasToDvar) throws IOException { + + StudyDataSet sds = null; + + File mainWreslFile = sanityCheck(inMainWreslPath); + + LogUtils.setLogFile(mainWreslFile.getParentFile().getCanonicalPath(), logFileName); + + LogUtils.titleMsg(Param.wreslChekerName + new BuildProps().getVN()); + + + try { + + if (useWreslPlus) { + sds = parseWreslPlus(mainWreslFile); + total_errors = StudyParser.total_errors; + } else { + sds = parseWresl(mainWreslFile, sendAliasToDvar); + } + + } + catch (RecognitionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + if (csvFolderName != null && csvFolderName.length() > 0) { + String csvFolderPath = mainWreslFile.getParentFile() + File.separator + csvFolderName; + WriteCSV.study(sds, csvFolderPath); + } + + if (StudyUtils.compileOnly) { + + if (StudyUtils.total_errors ==0) { + StudyUtils.compileObject(FilePaths.fullMainPath, sds); + //System.exit(0); + } else { + LogUtils.errMsg("Compilation unsuccessful."); + //System.exit(1); + } + + } + + LogUtils.closeLogFile(); + + if (total_errors==0){ + if (ControlData.useCbcWarmStart || ControlData.cbcCheckIntErr || ControlData.cbc_debug_routeCbc || ControlData.cbc_debug_routeXA){ + if (ControlData.solverName.equalsIgnoreCase("Cbc") || ControlData.solverName.equalsIgnoreCase("Cbc1")){ + + Warmstart.collectIntegerDV_2(sds); + + } + } + } + return sds; + + } + + public static void compileObject(String inMainWreslPath, StudyDataSet sds) { + + StringBuilder b = new StringBuilder(inMainWreslPath); + b.replace(inMainWreslPath.lastIndexOf("."), inMainWreslPath.length(), ".par"); + String objFilePath = b.toString(); + + StringBuilder b2 = new StringBuilder(FilePaths.mainFile); + b2.replace(FilePaths.mainFile.lastIndexOf("."), FilePaths.mainFile.length(), ".par"); + String objFileName = b2.toString(); + + LogUtils.importantMsg("Writing parser data...."); + writeObj(sds, objFilePath); + LogUtils.importantMsg("Wresl files are compiled into a binary file: "+objFileName ); + + } + + public static StudyDataSet loadObject(String objFilePath) { + + System.out.println("Loading precompiled parser data: "+objFilePath); + + return readObj(objFilePath); + + } + + private static File sanityCheck(String inMainWreslPath) throws IOException { + + String m = inMainWreslPath; + File validatedAbsFile = null; + + if (m.length() < 7) { + + throw new IOException("Invalid wresl file: " + m); } + + String extension = m.substring(m.length() - 5); + + if (!extension.equalsIgnoreCase("wresl")) { throw new IOException("Invalid wresl file: " + m); } + + validatedAbsFile = new File(inMainWreslPath).getAbsoluteFile(); + + if (!validatedAbsFile.exists()) { throw new IOException("File not found: " + inMainWreslPath); } + + return validatedAbsFile; + + } + + private static StudyDataSet parseWresl(File validatedMainWreslFile, boolean sendAliasToDvar) + throws RecognitionException, IOException { + + try { + + TempData td = new TempData(); + StudyParser.reset(); + VarCycleIndex.clearVarCycleIndexList(); + StudyConfig sc = StudyParser.processMainFileIntoStudyConfig(validatedMainWreslFile.getCanonicalPath()); + + // td.model_dataset_map=StudyParser.parseModels(sc,td); + td.model_dataset_map = StudyParser.parseModels(sc, td, false, sendAliasToDvar); + + StudyDataSet sd = StudyParser.writeWreslData(sc, td); + + StudyParser.analyzeVarNeededFromCycles(sc, sd); + + total_errors = StudyParser.total_errors; + + return sd; + + } + catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + private static StudyDataSet parseWreslPlus(File validatedMainWreslFile) + throws RecognitionException, IOException { + + StudyUtils.reset(); + + try { + + + //total_errors = StudyParser.total_errors; + StudyTemp st = null; + if (showCompileLog) { + st = Workflow.checkStudy_compileLog(validatedMainWreslFile.getCanonicalPath()); + } else { + st = Workflow.checkStudy(validatedMainWreslFile.getCanonicalPath()); + } + + StudyDataSet sd = ToWreslData.convertStudy(st); + + st = null; + System.gc(); + + return sd; + + } + catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + public static void writeObj(StudyDataSet sds, String objFilePath) { + + Kryo kryo = new Kryo(); + registerClasses(kryo); + try { + Output output = new Output(new FileOutputStream(objFilePath)); + kryo.writeObject(output, sds); + output.close(); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + /* + ObjectMapper objectMapper = new ObjectMapper(); + try { + objectMapper.writeValue(new File(objFilePath), sds); + } catch (JsonGenerationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + */ + } + + private static StudyDataSet readObj(String objFilePath) { + + StudyDataSet sds=new StudyDataSet(); + Kryo kryo = new Kryo(); + registerClasses(kryo); + try { + Input input = new Input(new FileInputStream(objFilePath)); + sds = kryo.readObject(input, StudyDataSet.class); + input.close(); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + /* + ObjectMapper objectMapper = new ObjectMapper(); + StudyDataSet sds=new StudyDataSet(); + try { + sds = objectMapper.readValue(new File(objFilePath), StudyDataSet.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + */ + return sds; + + } + + public static void registerClasses(Kryo kryo){ + kryo.register(Alias.class); + kryo.register(Dvar.class); + kryo.register(External.class); + kryo.register(Goal.class); + kryo.register(ModelDataSet.class); + kryo.register(StudyDataSet.class); + kryo.register(Svar.class); + kryo.register(Timeseries.class); + kryo.register(WeightElement.class); + kryo.register(MPModel.class); + kryo.register(FileEvent.class); + kryo.register(AliasTemp.class); + kryo.register(DvarTemp.class); + kryo.register(ExternalTemp.class); + kryo.register(GoalCase.class); + kryo.register(GoalHS.class); + kryo.register(GoalTemp.class); + kryo.register(IfIncItemGroup.class); + kryo.register(IncFileTemp.class); + kryo.register(ModelTemp.class); + kryo.register(ParamTemp.class); + kryo.register(SequenceTemp.class); + kryo.register(StudyTemp.class); + kryo.register(SvarTemp.class); + kryo.register(TimeseriesTemp.class); + kryo.register(WeightSubgroup.class); + kryo.register(WeightTable.class); + kryo.register(WeightTemp.class); + } } \ No newline at end of file diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/TempData.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/TempData.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/TempData.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/TempData.java index 9ead92195..e1a8340d3 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/TempData.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/TempData.java @@ -1,49 +1,49 @@ -package wrimsv2.wreslparser.elements; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - - -public class TempData { - - public Map fileDataMap_wholeStudy ; - public Map> t1Map_wholeStudy; - public Map fileScopeMap_wholeStudy; - - /// this map will collect detailed info for models - public Map model_dataset_map; - - /// map of model's global adhocs - public Map model_global_adhoc_map; - - /// cumulative global vars and include files - public SimulationDataSet cumulative_global_adhocs; - public SimulationDataSet cumulative_global_complete; - - public TempData(){ - - fileDataMap_wholeStudy = new HashMap(); - t1Map_wholeStudy = new HashMap>(); - fileScopeMap_wholeStudy = new HashMap(); - - /// this map will collect detailed info for models - model_dataset_map = new HashMap(); - - /// map of model's global adhocs - model_global_adhoc_map = new HashMap(); - - /// cumulative global vars and include files - cumulative_global_adhocs = new SimulationDataSet(); - - cumulative_global_complete = new SimulationDataSet(); - -// /// this map contains value of vars needed for WRESL syntax: varName[cycleName] -// /// < VarName, < CycleName, Value >> -// varCycleValueMap = new HashMap>(); - - } - - -} - +package wrimsv2.wreslparser.elements; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + + +public class TempData { + + public Map fileDataMap_wholeStudy ; + public Map> t1Map_wholeStudy; + public Map fileScopeMap_wholeStudy; + + /// this map will collect detailed info for models + public Map model_dataset_map; + + /// map of model's global adhocs + public Map model_global_adhoc_map; + + /// cumulative global vars and include files + public SimulationDataSet cumulative_global_adhocs; + public SimulationDataSet cumulative_global_complete; + + public TempData(){ + + fileDataMap_wholeStudy = new HashMap(); + t1Map_wholeStudy = new HashMap>(); + fileScopeMap_wholeStudy = new HashMap(); + + /// this map will collect detailed info for models + model_dataset_map = new HashMap(); + + /// map of model's global adhocs + model_global_adhoc_map = new HashMap(); + + /// cumulative global vars and include files + cumulative_global_adhocs = new SimulationDataSet(); + + cumulative_global_complete = new SimulationDataSet(); + +// /// this map contains value of vars needed for WRESL syntax: varName[cycleName] +// /// < VarName, < CycleName, Value >> +// varCycleValueMap = new HashMap>(); + + } + + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Tools.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/Tools.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Tools.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/Tools.java index c9592187c..db9b9f4a9 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/Tools.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/Tools.java @@ -1,601 +1,601 @@ -package wrimsv2.wreslparser.elements; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.io.Reader; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; - -import wrimsv2.commondata.wresldata.Param; - -public class Tools { - public static String strip(String s) { - if (s==null) return null; - return s.substring(1, s.length() - 1); - } - public static String replace_regex(String s) { - if (s==null) return null; - s=s.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)"); - s=s.replaceAll("\\.", "\\\\."); - s=s.replaceAll("\\*", "\\\\*"); - s=s.replaceAll("\\|", "\\\\|"); - s=s.replaceAll("\\+", "\\\\+"); - s=s.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]"); - s=s.replaceAll("##", ".+"); - return s; - } - public static String remove_nulls(String s) { - if (s==null) return null; - s=s.replaceAll("null", ""); - s=s.replaceAll("\\s+", " "); - return s; - } - public static String replace_ignoreChar(String s) { - if (s==null) return null; - s=s.replaceAll("\n+", "").replaceAll("\r+", ""); - s=s.replaceAll("\t+", ""); - s=s.replaceAll("\\s+", ""); - return s; - } - public static String add_space_between_logical(String s) { - if (s==null) return null; - - s = replace_ignoreChar(s); - s = replace_seperator(s); - - s=s.replaceAll("\\.AND\\.", " \\.and\\. "); - s=s.replaceAll("\\.OR\\.", " \\.or\\. "); - s=s.replaceAll("\\.and\\.", " \\.and\\. "); - s=s.replaceAll("\\.or\\.", " \\.or\\. "); - - return s; - } - public static String replace_seperator(String s) { - if (s==null) return null; - s=s.replaceAll(Param.arg_seperator,Param.new_seperator); - return s; - } - public static String replace_pathseperator(String s) { - if (s==null) return null; - s=s.replace(Param.windows_pathseperator,File.separator); - s=s.replace(Param.linux_pathseperator,File.separator); - return s; - } - public static Map readFilesFromDirAsMap(String dir) - throws IOException { - File folder = new File(dir); - File[] listOfFiles = folder.listFiles(); - Map map = new HashMap(); - - for (File file : listOfFiles) { - - if (!file.getName().contains(".svn")) { - - String filePath = file.getPath(); - String fileName = file.getName(); - map.put(fileName, readFileAsString(filePath)); - } - } - - return map; - - } - - public static String readFileAsString(String filePath) { - byte[] buffer = new byte[(int) new File(filePath).length()]; - BufferedInputStream f = null; - try { - f = new BufferedInputStream(new FileInputStream(filePath)); - f.read(buffer); - } catch ( IOException e){ - - LogUtils.errMsg("File not found: "+ filePath); - - //System.exit(1); - - } finally { - if (f != null) - try { - f.close(); - } catch (IOException ignored) { - } - } - return new String(buffer); - } - - - public static String readFileAsString(String file, String csName) throws IOException { - Charset cs = Charset.forName(csName); - // Thanks to Jon Skeet - // No real need to close the BufferedReader/InputStreamReader - // as they're only wrapping the stream - FileInputStream stream = new FileInputStream(file); - try { - Reader reader = new BufferedReader(new InputStreamReader(stream, cs)); - StringBuilder builder = new StringBuilder(); - char[] buffer = new char[8192]; - int read; - while ((read = reader.read(buffer, 0, buffer.length)) > 0) { - builder.append(buffer, 0, read); - } - return builder.toString(); - } - finally { - // Potential issue here: if this throws an IOException, - // it will mask any others. Normally I'd use a utility - // method which would log exceptions and swallow them - stream.close(); - } - } - - public static String readFileLine(String filePath) throws IOException { - - File input = new File(filePath); - BufferedReader in = new BufferedReader(new FileReader(input)); - return in.readLine(); - } - - public static PrintWriter openFile(String filePath) throws IOException { - - File f = new File(filePath); - File dir = new File(f.getParent()); - dir.mkdirs(); - f.createNewFile(); - - return new PrintWriter(new BufferedWriter(new FileWriter(f))); - } - - public static PrintWriter openFile(String dirPath, String fileName, boolean isAppend) throws IOException { - - File f = new File(dirPath, fileName); - File dir = new File(f.getParent()); - dir.mkdirs(); - f.createNewFile(); - - return new PrintWriter(new BufferedWriter(new FileWriter(f,isAppend))); - } - - public static PrintWriter openFile(String dirPath, String fileName) throws IOException { - - File f = new File(dirPath, fileName); - File dir = new File(f.getParent()); - dir.mkdirs(); - f.createNewFile(); - - return new PrintWriter(new BufferedWriter(new FileWriter(f))); - } - - public static PrintWriter setOutputString(String dirPath, String fileName) throws IOException { - - File f = new File(dirPath, fileName); - File dir = new File(f.getParent()); - dir.mkdirs(); - f.createNewFile(); - - return new PrintWriter(new BufferedWriter(new FileWriter(f))); - } - - public static boolean deleteDir(String dirString) { - File dir = new File(dirString); - if (dir.isDirectory()) { - String[] children = dir.list(); - for (int i = 0; i < children.length; i++) { - boolean success = deleteDir(new File(dir, children[i]) - .getPath()); - if (!success) { - return false; - } - } - } - return dir.delete(); - } - - public static Map convertSimulationDataSetMapToLocal(Map s) { - - Map out = new HashMap(); - - for (String key : s.keySet()){ - - out.put(key, convertSimulationDataSetToLocal(s.get(key))); - - } - - return out; - - } - - public static SimulationDataSet convertSimulationDataSetToLocal(SimulationDataSet s) { - - SimulationDataSet out = new SimulationDataSet(); - - if (!s.wtList.isEmpty()) { - out.wtList.addAll(s.wtList); - out.wtList_local.addAll(s.wtList); - out.wtMap.putAll(s.wtMap); - } - - if (!s.incFileList.isEmpty()) { - out.incFileList.addAll(s.incFileList); - out.incFileList_local.addAll(s.incFileList); - out.incFileMap.putAll(s.incFileMap); - } - - if (!s.exList.isEmpty()) { - out.exList.addAll(s.exList); - out.exList_local.addAll(s.exList); - out.exMap.putAll(s.exMap); - } - - if (!s.svList.isEmpty()) { - out.svList.addAll(s.svList); - out.svList_local.addAll(s.svList); - out.svMap.putAll(s.svMap); - } - - if (!s.dvList.isEmpty()) { - out.dvList.addAll(s.dvList); - out.dvList_local.addAll(s.dvList); - out.dvMap.putAll(s.dvMap); - } - if (!s.asList.isEmpty()) { - out.asList.addAll(s.asList); - out.asList_local.addAll(s.asList); - out.asMap.putAll(s.asMap); - } - - if (!s.gList.isEmpty()) { - out.gList.addAll(s.gList); - out.gList_local.addAll(s.gList); - out.gMap.putAll(s.gMap); - } - - if (!s.model_list.isEmpty()) { - out.model_list.addAll(s.model_list); - } - - return out; - } - - - - - - public static ArrayList getScopeList(ArrayList fileList, ArrayList localList) { - - ArrayList scopeList = new ArrayList(); - - for (String f : fileList) { - if (localList.contains(f)) { - scopeList.add("local"); - } - else { - scopeList.add("global"); - } - } - return scopeList; - - } - - public static Map getScopeMap(Set fileSet, Set localSet) { - - Map scopeMap = new HashMap(); - - for (String f : fileSet) { - if (localSet.contains(f)) { - scopeMap.put(f,Param.local); - } - else { - scopeMap.put(f,Param.global); - } - } - return scopeMap; - - } - - /// type 1 map is the shallow included files, e.g., map( f1, [f7,f9]) - public static Map> getType1Map(Map dataMap) { - - Map> out = new HashMap>(); - - for (String f : dataMap.keySet()){ - - SimulationDataSet data = dataMap.get(f); - - Set fileSet = new HashSet(); - fileSet.addAll(data.incFileSet); - - out.put(f, fileSet); - } - return out; - } - - /// type 1 map is the shallow included files, e.g., map( f1, [f7,f9]) - public static Map> getReverseMap(Map> t1Map) { - - Map> out = new HashMap>(); - - for (String f : t1Map.keySet()) { - - for (String c : t1Map.get(f)) { - - if (out.get(c) == null) { - Set s = new HashSet(); - s.add(f); - out.put(c, s); - } - else { - out.get(c).add(f); - } - - } - - } - return out; - } - - /// type 1 map is the shallow included files, e.g., map( f1, [f7,f9]) - public static Map> getReverseMap_arrayList(Map> t1Map) { - - Map> out = new HashMap>(); - - for (String f : t1Map.keySet()){ - - for (String c : t1Map.get(f)){ - - ArrayList s; - if (out.get(c)==null) { s = new ArrayList(); s.add(f);} - else { s= out.get(c); s.add(f);} - - out.put(c, s); - - } - - } - return out; - } - - public static Map getFileScopeMap(Map dataMap) { - - Map out = new HashMap(); - //getScopeMap(adhoc.incFileList, adhoc.incFileList_local); - - - for (String f : dataMap.keySet()){ - - SimulationDataSet data = dataMap.get(f); - out.putAll(getScopeMap(data.incFileSet, data.incFileSet_local)); - - } - return out; - } - - /// type 1 map is the scope list for the shallow included files, e.g., map( f1, [f7 scope ,f9 scope]) - public static Map> getType1MapScope(Map dataMap) { - - Map> out = new HashMap>(); - - for (String f : dataMap.keySet()){ - - SimulationDataSet data = dataMap.get(f); - - ArrayList scopeList = new ArrayList(); - - for (String i : data.incFileList){ - if (data.incFileList_local.contains(i)){scopeList.add("local");} - else {scopeList.add("global");} - - } - - out.put(f, scopeList); - } - return out; - } - - public static SimulationDataSet correctDataScope_shallow(String f, SimulationDataSet ds, Map fileScopeMap, - Map> t1ReverseMap ) { - - - if (fileScopeMap.get(f) == Param.local) { - - ds.convertToLocal_set(); - - } - else { - - for (String upperFile : t1ReverseMap.get(f)) { - - if (fileScopeMap.get(upperFile) == Param.local) { - - //LogUtils.normalMsg("...Convert this file data to local: " + f ); - //LogUtils.normalMsg(" due to [local] specification for its parent file: " + upperFile + "\n"); - - ds.convertToLocal_set(); - - break; - } - } - } - return ds; - } - - - public static SimulationDataSet correctDataScope_deep(String f, SimulationDataSet ds, Map fileScopeMap, - Map> t1ReverseMap ) { - - - if (fileScopeMap.get(f) == Param.local) { - - ds.convertToLocal_set(); - return ds; - - } - - - if (!t1ReverseMap.keySet().contains(f)) return ds; - - for (String upperFile : t1ReverseMap.get(f)) { - - // LogUtils.errMsg(" ===========: "+f); - // LogUtils.errMsg(" $$$$$$$$$$$: files in reverseMap: "+upperFile); - - if (fileScopeMap.get(upperFile) == Param.local) { - - // LogUtils.normalMsg("...Convert this file data to local: " + f - // ); - // LogUtils.normalMsg(" due to [local] specification for its parent file: " - // + upperFile + "\n"); - - ds.convertToLocal_set(); - - break; - } - else { - - ds = correctDataScope_deep(upperFile, ds, fileScopeMap, t1ReverseMap); - - } - } - - return ds; - } - - public static Map getAllOffSprings(String nodeFile, Map> t1Map, Map fileDataMap ) { - Map out = new HashMap(); - - for (String child : t1Map.get(nodeFile)){ - - if (t1Map.get(child)!=null) out.putAll(getAllOffSprings(child,t1Map,fileDataMap)); - - out.put(child, fileDataMap.get(child)); - } - - return out; - - } - - public static Map putDataFileMapFromWholeStudy(String file, Map fileDataMap) { - - - Map out = new HashMap(); - - out.put(file, fileDataMap.get(file)); - - if (! fileDataMap.get(file).incFileList.isEmpty()){ - - for (String child : fileDataMap.get(file).incFileList){ - out.putAll(putDataFileMapFromWholeStudy(child,fileDataMap)); - } - } - - return out; - - } - public static Set mapRemoveAll (Map map, Set set){ - - Set removedKeys = new LinkedHashSet(); - - for (String key: set){ - - if (map.remove(key)!=null) removedKeys.add(key); - } - return removedKeys; - } - public static Set mapRemoveAll (Map map, ArrayList list){ - - return mapRemoveAll (map, new LinkedHashSet(list)); - } - - public static SimulationDataSet overwrite_set(SimulationDataSet main, SimulationDataSet s) { - - SimulationDataSet a = new SimulationDataSet(); a.add(main); - SimulationDataSet b = new SimulationDataSet(); b.add(s); - b.overwrittenWith_set(a); - - return b; - } - - public static Set convertStrToSet(String inStr){ - - Set out = new HashSet(); - StringTokenizer st = new StringTokenizer(inStr); - - while (st.hasMoreTokens()) { - out.add(st.nextToken()); - } - out.remove("null"); - - return out; - } - - public static Set restoreOrder(ArrayList toBeRestored, ArrayList referenceOrder, - Set member) { - - ArrayList orderedList = new ArrayList(referenceOrder); - - Set nonMember = new HashSet(referenceOrder); - nonMember.removeAll(member); - - orderedList.removeAll(nonMember); - - toBeRestored = orderedList; - - return new LinkedHashSet(orderedList); - } - - public static Set removeDuplicates(ArrayList list) - { - Set s = new LinkedHashSet(list); - - ArrayList duplicatesList = new ArrayList(list); - - for (String x : s) { - duplicatesList.remove(x); - } - - list.clear(); - list.addAll(s); - - return new LinkedHashSet(duplicatesList); - } - - public static Map> getCycleVarMap(Set setVarCycle) - { - Map> out = new HashMap>(); - - for (String x : setVarCycle) { - - int posStart = x.indexOf("["); - int posEnd = x.indexOf("]"); - - String varName = x.substring(0,posStart); - String cycleName = x.substring(posStart+1, posEnd); - - if (out.keySet().contains(cycleName)){ - - out.get(cycleName).add(varName); - } - else{ - - Set setVarName = new HashSet(); - setVarName.add(varName); - out.put(cycleName, setVarName); - } - } - - return out; - } -} +package wrimsv2.wreslparser.elements; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.io.Reader; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; + +import wrimsv2.commondata.wresldata.Param; + +public class Tools { + public static String strip(String s) { + if (s==null) return null; + return s.substring(1, s.length() - 1); + } + public static String replace_regex(String s) { + if (s==null) return null; + s=s.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)"); + s=s.replaceAll("\\.", "\\\\."); + s=s.replaceAll("\\*", "\\\\*"); + s=s.replaceAll("\\|", "\\\\|"); + s=s.replaceAll("\\+", "\\\\+"); + s=s.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]"); + s=s.replaceAll("##", ".+"); + return s; + } + public static String remove_nulls(String s) { + if (s==null) return null; + s=s.replaceAll("null", ""); + s=s.replaceAll("\\s+", " "); + return s; + } + public static String replace_ignoreChar(String s) { + if (s==null) return null; + s=s.replaceAll("\n+", "").replaceAll("\r+", ""); + s=s.replaceAll("\t+", ""); + s=s.replaceAll("\\s+", ""); + return s; + } + public static String add_space_between_logical(String s) { + if (s==null) return null; + + s = replace_ignoreChar(s); + s = replace_seperator(s); + + s=s.replaceAll("\\.AND\\.", " \\.and\\. "); + s=s.replaceAll("\\.OR\\.", " \\.or\\. "); + s=s.replaceAll("\\.and\\.", " \\.and\\. "); + s=s.replaceAll("\\.or\\.", " \\.or\\. "); + + return s; + } + public static String replace_seperator(String s) { + if (s==null) return null; + s=s.replaceAll(Param.arg_seperator,Param.new_seperator); + return s; + } + public static String replace_pathseperator(String s) { + if (s==null) return null; + s=s.replace(Param.windows_pathseperator,File.separator); + s=s.replace(Param.linux_pathseperator,File.separator); + return s; + } + public static Map readFilesFromDirAsMap(String dir) + throws IOException { + File folder = new File(dir); + File[] listOfFiles = folder.listFiles(); + Map map = new HashMap(); + + for (File file : listOfFiles) { + + if (!file.getName().contains(".svn")) { + + String filePath = file.getPath(); + String fileName = file.getName(); + map.put(fileName, readFileAsString(filePath)); + } + } + + return map; + + } + + public static String readFileAsString(String filePath) { + byte[] buffer = new byte[(int) new File(filePath).length()]; + BufferedInputStream f = null; + try { + f = new BufferedInputStream(new FileInputStream(filePath)); + f.read(buffer); + } catch ( IOException e){ + + LogUtils.errMsg("File not found: "+ filePath); + + //System.exit(1); + + } finally { + if (f != null) + try { + f.close(); + } catch (IOException ignored) { + } + } + return new String(buffer); + } + + + public static String readFileAsString(String file, String csName) throws IOException { + Charset cs = Charset.forName(csName); + // Thanks to Jon Skeet + // No real need to close the BufferedReader/InputStreamReader + // as they're only wrapping the stream + FileInputStream stream = new FileInputStream(file); + try { + Reader reader = new BufferedReader(new InputStreamReader(stream, cs)); + StringBuilder builder = new StringBuilder(); + char[] buffer = new char[8192]; + int read; + while ((read = reader.read(buffer, 0, buffer.length)) > 0) { + builder.append(buffer, 0, read); + } + return builder.toString(); + } + finally { + // Potential issue here: if this throws an IOException, + // it will mask any others. Normally I'd use a utility + // method which would log exceptions and swallow them + stream.close(); + } + } + + public static String readFileLine(String filePath) throws IOException { + + File input = new File(filePath); + BufferedReader in = new BufferedReader(new FileReader(input)); + return in.readLine(); + } + + public static PrintWriter openFile(String filePath) throws IOException { + + File f = new File(filePath); + File dir = new File(f.getParent()); + dir.mkdirs(); + f.createNewFile(); + + return new PrintWriter(new BufferedWriter(new FileWriter(f))); + } + + public static PrintWriter openFile(String dirPath, String fileName, boolean isAppend) throws IOException { + + File f = new File(dirPath, fileName); + File dir = new File(f.getParent()); + dir.mkdirs(); + f.createNewFile(); + + return new PrintWriter(new BufferedWriter(new FileWriter(f,isAppend))); + } + + public static PrintWriter openFile(String dirPath, String fileName) throws IOException { + + File f = new File(dirPath, fileName); + File dir = new File(f.getParent()); + dir.mkdirs(); + f.createNewFile(); + + return new PrintWriter(new BufferedWriter(new FileWriter(f))); + } + + public static PrintWriter setOutputString(String dirPath, String fileName) throws IOException { + + File f = new File(dirPath, fileName); + File dir = new File(f.getParent()); + dir.mkdirs(); + f.createNewFile(); + + return new PrintWriter(new BufferedWriter(new FileWriter(f))); + } + + public static boolean deleteDir(String dirString) { + File dir = new File(dirString); + if (dir.isDirectory()) { + String[] children = dir.list(); + for (int i = 0; i < children.length; i++) { + boolean success = deleteDir(new File(dir, children[i]) + .getPath()); + if (!success) { + return false; + } + } + } + return dir.delete(); + } + + public static Map convertSimulationDataSetMapToLocal(Map s) { + + Map out = new HashMap(); + + for (String key : s.keySet()){ + + out.put(key, convertSimulationDataSetToLocal(s.get(key))); + + } + + return out; + + } + + public static SimulationDataSet convertSimulationDataSetToLocal(SimulationDataSet s) { + + SimulationDataSet out = new SimulationDataSet(); + + if (!s.wtList.isEmpty()) { + out.wtList.addAll(s.wtList); + out.wtList_local.addAll(s.wtList); + out.wtMap.putAll(s.wtMap); + } + + if (!s.incFileList.isEmpty()) { + out.incFileList.addAll(s.incFileList); + out.incFileList_local.addAll(s.incFileList); + out.incFileMap.putAll(s.incFileMap); + } + + if (!s.exList.isEmpty()) { + out.exList.addAll(s.exList); + out.exList_local.addAll(s.exList); + out.exMap.putAll(s.exMap); + } + + if (!s.svList.isEmpty()) { + out.svList.addAll(s.svList); + out.svList_local.addAll(s.svList); + out.svMap.putAll(s.svMap); + } + + if (!s.dvList.isEmpty()) { + out.dvList.addAll(s.dvList); + out.dvList_local.addAll(s.dvList); + out.dvMap.putAll(s.dvMap); + } + if (!s.asList.isEmpty()) { + out.asList.addAll(s.asList); + out.asList_local.addAll(s.asList); + out.asMap.putAll(s.asMap); + } + + if (!s.gList.isEmpty()) { + out.gList.addAll(s.gList); + out.gList_local.addAll(s.gList); + out.gMap.putAll(s.gMap); + } + + if (!s.model_list.isEmpty()) { + out.model_list.addAll(s.model_list); + } + + return out; + } + + + + + + public static ArrayList getScopeList(ArrayList fileList, ArrayList localList) { + + ArrayList scopeList = new ArrayList(); + + for (String f : fileList) { + if (localList.contains(f)) { + scopeList.add("local"); + } + else { + scopeList.add("global"); + } + } + return scopeList; + + } + + public static Map getScopeMap(Set fileSet, Set localSet) { + + Map scopeMap = new HashMap(); + + for (String f : fileSet) { + if (localSet.contains(f)) { + scopeMap.put(f,Param.local); + } + else { + scopeMap.put(f,Param.global); + } + } + return scopeMap; + + } + + /// type 1 map is the shallow included files, e.g., map( f1, [f7,f9]) + public static Map> getType1Map(Map dataMap) { + + Map> out = new HashMap>(); + + for (String f : dataMap.keySet()){ + + SimulationDataSet data = dataMap.get(f); + + Set fileSet = new HashSet(); + fileSet.addAll(data.incFileSet); + + out.put(f, fileSet); + } + return out; + } + + /// type 1 map is the shallow included files, e.g., map( f1, [f7,f9]) + public static Map> getReverseMap(Map> t1Map) { + + Map> out = new HashMap>(); + + for (String f : t1Map.keySet()) { + + for (String c : t1Map.get(f)) { + + if (out.get(c) == null) { + Set s = new HashSet(); + s.add(f); + out.put(c, s); + } + else { + out.get(c).add(f); + } + + } + + } + return out; + } + + /// type 1 map is the shallow included files, e.g., map( f1, [f7,f9]) + public static Map> getReverseMap_arrayList(Map> t1Map) { + + Map> out = new HashMap>(); + + for (String f : t1Map.keySet()){ + + for (String c : t1Map.get(f)){ + + ArrayList s; + if (out.get(c)==null) { s = new ArrayList(); s.add(f);} + else { s= out.get(c); s.add(f);} + + out.put(c, s); + + } + + } + return out; + } + + public static Map getFileScopeMap(Map dataMap) { + + Map out = new HashMap(); + //getScopeMap(adhoc.incFileList, adhoc.incFileList_local); + + + for (String f : dataMap.keySet()){ + + SimulationDataSet data = dataMap.get(f); + out.putAll(getScopeMap(data.incFileSet, data.incFileSet_local)); + + } + return out; + } + + /// type 1 map is the scope list for the shallow included files, e.g., map( f1, [f7 scope ,f9 scope]) + public static Map> getType1MapScope(Map dataMap) { + + Map> out = new HashMap>(); + + for (String f : dataMap.keySet()){ + + SimulationDataSet data = dataMap.get(f); + + ArrayList scopeList = new ArrayList(); + + for (String i : data.incFileList){ + if (data.incFileList_local.contains(i)){scopeList.add("local");} + else {scopeList.add("global");} + + } + + out.put(f, scopeList); + } + return out; + } + + public static SimulationDataSet correctDataScope_shallow(String f, SimulationDataSet ds, Map fileScopeMap, + Map> t1ReverseMap ) { + + + if (fileScopeMap.get(f) == Param.local) { + + ds.convertToLocal_set(); + + } + else { + + for (String upperFile : t1ReverseMap.get(f)) { + + if (fileScopeMap.get(upperFile) == Param.local) { + + //LogUtils.normalMsg("...Convert this file data to local: " + f ); + //LogUtils.normalMsg(" due to [local] specification for its parent file: " + upperFile + "\n"); + + ds.convertToLocal_set(); + + break; + } + } + } + return ds; + } + + + public static SimulationDataSet correctDataScope_deep(String f, SimulationDataSet ds, Map fileScopeMap, + Map> t1ReverseMap ) { + + + if (fileScopeMap.get(f) == Param.local) { + + ds.convertToLocal_set(); + return ds; + + } + + + if (!t1ReverseMap.keySet().contains(f)) return ds; + + for (String upperFile : t1ReverseMap.get(f)) { + + // LogUtils.errMsg(" ===========: "+f); + // LogUtils.errMsg(" $$$$$$$$$$$: files in reverseMap: "+upperFile); + + if (fileScopeMap.get(upperFile) == Param.local) { + + // LogUtils.normalMsg("...Convert this file data to local: " + f + // ); + // LogUtils.normalMsg(" due to [local] specification for its parent file: " + // + upperFile + "\n"); + + ds.convertToLocal_set(); + + break; + } + else { + + ds = correctDataScope_deep(upperFile, ds, fileScopeMap, t1ReverseMap); + + } + } + + return ds; + } + + public static Map getAllOffSprings(String nodeFile, Map> t1Map, Map fileDataMap ) { + Map out = new HashMap(); + + for (String child : t1Map.get(nodeFile)){ + + if (t1Map.get(child)!=null) out.putAll(getAllOffSprings(child,t1Map,fileDataMap)); + + out.put(child, fileDataMap.get(child)); + } + + return out; + + } + + public static Map putDataFileMapFromWholeStudy(String file, Map fileDataMap) { + + + Map out = new HashMap(); + + out.put(file, fileDataMap.get(file)); + + if (! fileDataMap.get(file).incFileList.isEmpty()){ + + for (String child : fileDataMap.get(file).incFileList){ + out.putAll(putDataFileMapFromWholeStudy(child,fileDataMap)); + } + } + + return out; + + } + public static Set mapRemoveAll (Map map, Set set){ + + Set removedKeys = new LinkedHashSet(); + + for (String key: set){ + + if (map.remove(key)!=null) removedKeys.add(key); + } + return removedKeys; + } + public static Set mapRemoveAll (Map map, ArrayList list){ + + return mapRemoveAll (map, new LinkedHashSet(list)); + } + + public static SimulationDataSet overwrite_set(SimulationDataSet main, SimulationDataSet s) { + + SimulationDataSet a = new SimulationDataSet(); a.add(main); + SimulationDataSet b = new SimulationDataSet(); b.add(s); + b.overwrittenWith_set(a); + + return b; + } + + public static Set convertStrToSet(String inStr){ + + Set out = new HashSet(); + StringTokenizer st = new StringTokenizer(inStr); + + while (st.hasMoreTokens()) { + out.add(st.nextToken()); + } + out.remove("null"); + + return out; + } + + public static Set restoreOrder(ArrayList toBeRestored, ArrayList referenceOrder, + Set member) { + + ArrayList orderedList = new ArrayList(referenceOrder); + + Set nonMember = new HashSet(referenceOrder); + nonMember.removeAll(member); + + orderedList.removeAll(nonMember); + + toBeRestored = orderedList; + + return new LinkedHashSet(orderedList); + } + + public static Set removeDuplicates(ArrayList list) + { + Set s = new LinkedHashSet(list); + + ArrayList duplicatesList = new ArrayList(list); + + for (String x : s) { + duplicatesList.remove(x); + } + + list.clear(); + list.addAll(s); + + return new LinkedHashSet(duplicatesList); + } + + public static Map> getCycleVarMap(Set setVarCycle) + { + Map> out = new HashMap>(); + + for (String x : setVarCycle) { + + int posStart = x.indexOf("["); + int posEnd = x.indexOf("]"); + + String varName = x.substring(0,posStart); + String cycleName = x.substring(posStart+1, posEnd); + + if (out.keySet().contains(cycleName)){ + + out.get(cycleName).add(varName); + } + else{ + + Set setVarName = new HashSet(); + setVarName.add(varName); + out.put(cycleName, setVarName); + } + } + + return out; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/TypeRedefinedException.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/TypeRedefinedException.java similarity index 91% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/TypeRedefinedException.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/TypeRedefinedException.java index a8d482918..17fe33780 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/TypeRedefinedException.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/TypeRedefinedException.java @@ -1,17 +1,17 @@ -package wrimsv2.wreslparser.elements; - - - -public class TypeRedefinedException extends FatalErrorException{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - - - - -} - +package wrimsv2.wreslparser.elements; + + + +public class TypeRedefinedException extends FatalErrorException{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + + + + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/WriteCSV.java b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/WriteCSV.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/WriteCSV.java rename to wrims-core/src/main/java/wrimsv2/wreslparser/elements/WriteCSV.java index e23dd4343..e281ebefc 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslparser/elements/WriteCSV.java +++ b/wrims-core/src/main/java/wrimsv2/wreslparser/elements/WriteCSV.java @@ -1,676 +1,676 @@ -package wrimsv2.wreslparser.elements; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Set; - -import java.util.Map; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.External; -import wrimsv2.commondata.wresldata.Goal; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.commondata.wresldata.Timeseries; -import wrimsv2.commondata.wresldata.WeightElement; - - -public class WriteCSV { - - //static Map> mapStringList = new HashMap>(); - //private static PrintWriter out; - - public static String sequence_header ="CYCLE,CONDITION,TIMESTEP"; - public static String weight_header ="DVAR,TIME_ARRAY_SIZE,CONDITION,WEIGHT"; - public static String external_header ="FUNCTION,FILE,FROM_WRESL_FILE"; - public static String svar_header ="NAME,TIME_ARRAY_SIZE,CASE,ORDER,CONDITION,EXPRESSION,DEPENDANT,FROM_WRESL_FILE,NEED_VAR_FROM_CYCLE,USED_IN_LATER_CYCLE"; - public static String timeseries_header ="NAME,B_PART,TYPE,UNITS,CONVERT_TO_UNITS,FROM_WRESL_FILE"; - public static String timeseries_timestep_header ="NAME,B_PART,TIMESTEP"; - public static String dvar_header ="NAME,TIME_ARRAY_SIZE,CONDITION,LOWER_BOUND,UPPER_BOUND,INTEGER,UNITS,TYPE,FROM_WRESL_FILE,USED_IN_LATER_CYCLE"; - public static String alias_header ="NAME,TIME_ARRAY_SIZE,TYPE,UNITS,EXPRESSION,DEPENDANT,FROM_WRESL_FILE,NEED_VAR_FROM_CYCLE,USED_IN_LATER_CYCLE"; - public static String goal_header = "NAME,TIME_ARRAY_SIZE,CASE,ORDER,CONDITION,EXPRESSION,DEPENDANT,FROM_WRESL_FILE,NEED_VAR_FROM_CYCLE,"; - private static ModelDataSet currentModelDataSet; - - - public static void study(StudyDataSet sd, String outParent) { - - if (sd==null) return; - - Map modelDataSetMap = sd.getModelDataSetMap(); - - output(modelDataSetMap,outParent); - - try { - PrintWriter out_seq = Tools.openFile(outParent, "SEQUENCE.csv"); - out_seq.print(WriteCSV.sequence_header + "\n"); - sequence(sd.getModelList(), sd.getModelConditionList(), out_seq); - out_seq.close(); - - if (sd.getTimeseriesMap().keySet().size()>0) { - PrintWriter out_timeseries_wholeStudy = Tools.openFile(outParent, "TIMESERIES.csv"); - out_timeseries_wholeStudy.print(WriteCSV.timeseries_header + "\n"); - timeseries_wholeStudy( sd.getTimeseriesMap(), out_timeseries_wholeStudy); - out_timeseries_wholeStudy.close(); - - - PrintWriter out_timeseriesTimeStep = Tools.openFile(outParent, "TIMESERIES_TIMESTEP.csv"); - out_timeseriesTimeStep.print(WriteCSV.timeseries_timestep_header + "\n"); - timeseriesTimeStep( sd, out_timeseriesTimeStep); - out_timeseriesTimeStep.close(); - } - - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - - public static void study(StudyConfig sc, Map modelDataMap, String outParent) { - - Tools.deleteDir(outParent); - - output(modelDataMap,outParent); - - try { - PrintWriter out_seq = Tools.openFile(outParent, "SEQUENCE.csv"); - out_seq.print(WriteCSV.sequence_header + "\n"); - sequence(sc.sequenceMap, sc.sequenceOrder, out_seq); - out_seq.close(); - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - - public static void output(Map modelDataMap, String outParent) { - - for (String model : modelDataMap.keySet()) { - - String outFolder = outParent + File.separator + model; - - try { - dataset(modelDataMap.get(model), outFolder); - } - catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } - - public static void dataset(ModelDataSet ds, String outFolder) throws IOException { - - PrintWriter out_ex; - PrintWriter out_svTs; - PrintWriter out_sv; - PrintWriter out_sv_unknown; - PrintWriter out_dv; - PrintWriter out_goal; - PrintWriter out_alias; - PrintWriter out_alias_unknown; - PrintWriter out_wt; - PrintWriter out_incFile; - - currentModelDataSet = ds; - - - //outFolder = System.getProperty("user.dir")+"//"+outFolder; - - if(ds.incFileList.size()>0){ - out_incFile = Tools.openFile(outFolder, "include_file.csv"); - //out_incFile.print(WriteCSV.incFile_header + "\n"); - incFile(ds.incFileList, out_incFile); - out_incFile.close(); - } - if(ds.incFileList_global.size()>0){ - out_incFile = Tools.openFile(outFolder, "include_file_global.csv"); - //out_incFile.print(WriteCSV.incFile_header + "\n"); - incFile(ds.incFileList_global, out_incFile); - out_incFile.close(); - } - if(ds.exList.size()>0){ - out_ex = Tools.openFile(outFolder, "external.csv"); - out_ex.print(WriteCSV.external_header + "\n"); - external(ds.exMap, ds.exList, out_ex); - out_ex.close(); - } - if(ds.tsList.size()>0){ - out_svTs = Tools.openFile(outFolder, "timeseries.csv"); - out_svTs.print(WriteCSV.timeseries_header + "\n"); - timeseries_model(ds.tsMap, ds.tsList, out_svTs); - out_svTs.close(); - } - if(ds.svList.size()>0){ - out_sv = Tools.openFile(outFolder, "svar.csv"); - out_sv.print(WriteCSV.svar_header + "\n"); - svar(ds.svMap, ds.svList, out_sv); - out_sv.close(); - } - if(ds.svSet_unknown.size()>0){ - out_sv_unknown = Tools.openFile(outFolder, "svar_unknown.csv"); - out_sv_unknown.print(WriteCSV.svar_header + "\n"); - svar(ds.svMap, new ArrayList(ds.svSet_unknown), out_sv_unknown); - out_sv_unknown.close(); - } - if((ds.dvList.size()+ds.dvSlackSurplusList.size())>0){ - out_dv = Tools.openFile(outFolder, "dvar.csv"); - out_dv.print(WriteCSV.dvar_header + "\n"); - ArrayList allDvList = new ArrayList(ds.dvList); - allDvList.addAll(ds.dvSlackSurplusList); - Map allDvMap = new HashMap(ds.dvMap); - allDvMap.putAll(ds.dvSlackSurplusMap); - dvar(allDvMap, allDvList, out_dv); - out_dv.close(); - } - if(ds.gList.size()>0){ - out_goal = Tools.openFile(outFolder, "constraint.csv"); - out_goal.print(WriteCSV.goal_header + "\n"); - goal(ds.gMap, ds.gList, out_goal); - out_goal.close(); - } - if(ds.exList.size()>0){ - out_ex = Tools.openFile(outFolder, "external.csv"); - out_ex.print(WriteCSV.external_header + "\n"); - external(ds.exMap, ds.exList, out_ex); - out_ex.close(); - } - if((ds.wtList.size()+ds.wtSlackSurplusList.size())>0){ - out_wt = Tools.openFile(outFolder, "weight.csv"); - out_wt.print(WriteCSV.weight_header + "\n"); - ArrayList allWtList = new ArrayList(ds.wtList); - allWtList.addAll(ds.wtSlackSurplusList); - Map allWtMap = new HashMap(ds.wtMap); - allWtMap.putAll(ds.wtSlackSurplusMap); - weight(allWtMap, allWtList, out_wt); - out_wt.close(); - } - if(ds.asList.size()>0){ - out_alias = Tools.openFile(outFolder, "alias.csv"); - out_alias.print(WriteCSV.alias_header + "\n"); - alias(ds.asMap, ds.asList, out_alias); - out_alias.close(); - } - if(ds.asSet_unknown.size()>0){ - out_alias_unknown = Tools.openFile(outFolder, "alias_unknown.csv"); - out_alias_unknown.print(WriteCSV.alias_header + "\n"); - alias_unknown(ds.asMap, ds.dvMap, new ArrayList(ds.asSet_unknown), out_alias_unknown); - out_alias_unknown.close(); - } - - - - }; - - public static void timeseries_model(Map sTsMap, ArrayList list ,PrintWriter out) { - - List keys = new ArrayList(list); - Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); - - for (String k: keys ){ - - Timeseries s = sTsMap.get(k); - - out.print(k); // for SVAR NAME - out.print(Param.csv_seperator+s.dssBPart); //for DSS B Part - out.print(Param.csv_seperator+s.kind); //for KIND - out.print(Param.csv_seperator+s.units); //for UNITS - out.print(Param.csv_seperator+s.convertToUnits); //for CONVERT - out.print(",n"); //for OUTPUT - - out.print(Param.csv_seperator+s.fromWresl); - out.print("\n"); - - } - }; - - public static void svar(Map sMap, ArrayList list ,PrintWriter out) { - - List keys = new ArrayList(list); - //Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); - - for (String k: keys ){ - - //out.print(k); - Svar s = sMap.get(k); - - for (int i=0; i dep = new ArrayList(s.dependants); - Collections.sort(dep,String.CASE_INSENSITIVE_ORDER); - - for (String d: dep){ - out.print(d+";"); //for dependants - } - } - - out.print(Param.csv_seperator+s.fromWresl); - - out.print(Param.csv_seperator); - - if (s.neededVarInCycleSet!=null){ - - List varInCycle = new ArrayList(s.neededVarInCycleSet); - Collections.sort(varInCycle,String.CASE_INSENSITIVE_ORDER); - - for (String d: varInCycle){ - out.print(d+";"); //for dependantName[cycleName] - } - } - - out.print(Param.csv_seperator); - - boolean usedByLaterCycle = false; - if (currentModelDataSet.svarUsedByLaterCycle.contains(k)) usedByLaterCycle = true; - - out.print( usedByLaterCycle); - - out.print(Param.csv_seperator); - - out.print("\n"); - } - } - }; - - public static void sequence(ArrayList modelList, ArrayList modelConditionList ,PrintWriter out) { - - for (int i = 0; i< modelList.size(); i++ ){ - - out.print(modelList.get(i)); - out.print(Param.csv_seperator+modelConditionList.get(i)); - out.print("\n"); - - } - }; - - public static void sequence(Map seqMap, ArrayList list ,PrintWriter out) { - - List keys = list; - Collections.sort(keys); - - for (Integer k: keys ){ - - out.print(seqMap.get(k).modelName); - out.print(Param.csv_seperator+seqMap.get(k).condition+Param.csv_seperator+seqMap.get(k).timeStep); - out.print("\n"); - - } - }; - - - public static void timeseries_wholeStudy(Map tsMap, PrintWriter out) { - - Set kSet = tsMap.keySet(); - - List keys = new ArrayList(kSet); - - Collections.sort(keys); - - for (String k: keys ){ - - Timeseries s = tsMap.get(k); - - out.print(k); // for SVAR NAME - out.print(Param.csv_seperator+s.dssBPart); //for DSS B Part - out.print(Param.csv_seperator+s.kind); //for KIND - out.print(Param.csv_seperator+s.units); //for UNITS - out.print(Param.csv_seperator+s.convertToUnits); //for CONVERT - out.print(",n"); //for OUTPUT - - out.print(Param.csv_seperator+s.fromWresl); - out.print("\n"); - - } - }; - - public static void timeseriesTimeStep(StudyDataSet sd, PrintWriter out) { - - Map tsMap = sd.getTimeseriesMap(); - - Set kSet = tsMap.keySet(); - - List keys = new ArrayList(kSet); - - Collections.sort(keys); - - for (String k: keys ){ - - Timeseries s = tsMap.get(k); - - out.print(k); // for TIMESERIES NAME - out.print(Param.csv_seperator+s.dssBPart); //for DSS B Part - out.print(Param.csv_seperator); - - for (String step:sd.getTimeseriesTimeStepMap().get(k)){ - - out.print(step+";"); - - } - - out.print("\n"); - - } - }; - - public static void incFile(ArrayList list ,PrintWriter out) { - - List keys = new ArrayList(list); - Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); - - for (String k: keys ){ - - //out.print(k); - - - out.print(k); // - - out.print("\n"); - - } - }; - - public static void external(Map exMap, ArrayList list ,PrintWriter out) { - - List keys = new ArrayList(list); - Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); - - for (String k: keys ){ - - //out.print(k); - External s = exMap.get(k); - - - out.print(k); // - out.print(Param.csv_seperator+s.type); - - out.print(Param.csv_seperator+s.fromWresl); - out.print("\n"); - - } - }; - - - public static void weight(Map wtMap, ArrayList list ,PrintWriter out) { - - List keys = new ArrayList(list); - Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); - - for (String k: keys ){ - - - if (! wtMap.containsKey(k)) System.out.println("##### not exist in wtMap:"+k); - - - //out.print(k); - WeightElement w = wtMap.get(k); - - - out.print(k); // for DVAR NAME - - out.print(Param.csv_seperator+w.timeArraySize); //for TIME ARRAY SIZE - - out.print(Param.csv_seperator+w.condition); - - out.print(Param.csv_seperator+w.weight); - - out.print("\n"); - - } - }; - - public static void dvar(Map dMap, ArrayList list ,PrintWriter out) { - - List keys = new ArrayList(list); - Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); - - for (String k: keys ){ - - Dvar d = dMap.get(k); - - out.print(k); // for DVAR NAME - out.print(Param.csv_seperator+d.timeArraySize); //for TIME ARRAY SIZE - out.print(Param.csv_seperator+d.condition); // for DVAR CONDITION - out.print(Param.csv_seperator+d.lowerBound); //for UNITS - out.print(Param.csv_seperator+d.upperBound); //for UNITS - out.print(Param.csv_seperator+d.integer); //for KIND - out.print(Param.csv_seperator+d.units); //for UNITS - out.print(Param.csv_seperator+d.kind); //for KIND - - out.print(Param.csv_seperator+d.fromWresl); - - out.print(Param.csv_seperator); - - boolean usedByLaterCycle = false; - if (currentModelDataSet.dvarUsedByLaterCycle.contains(k)) usedByLaterCycle = true; - - out.print( usedByLaterCycle); - - out.print(Param.csv_seperator); - - out.print("\n"); - } - }; - - public static void alias_unknown(Map asMap, Map dvMap, ArrayList list ,PrintWriter out) { - - List keys = new ArrayList(list); - Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); - - for (String k : keys) { - - if (asMap.keySet().contains(k)) { - - Alias a = asMap.get(k); - - out.print(k); // for DVAR NAME - out.print(Param.csv_seperator + a.timeArraySize); //for TIME ARRAY SIZE - out.print(Param.csv_seperator + a.kind); // for KIND - out.print(Param.csv_seperator + a.units); // for UNITS - out.print(Param.csv_seperator + a.expression); // for expression - - out.print(Param.csv_seperator); - - if (a.dependants != null) { - for (String d : a.dependants) { - out.print(d + ";"); // for dependants - } - } - - out.print(Param.csv_seperator + a.fromWresl); - out.print("\n"); - } - else { // converted to dv - - Dvar a = dvMap.get(k); - - out.print(k); // for DVAR NAME - - out.print(Param.csv_seperator + a.kind); // for KIND - out.print(Param.csv_seperator + a.units); // for UNITS - out.print(Param.csv_seperator + a.expression); // for expression - - out.print(Param.csv_seperator); - - if (a.dependants != null) { - for (String d : a.dependants) { - out.print(d + ";"); // for dependants - } - } - - out.print(Param.csv_seperator + a.fromWresl); - out.print("\n"); - - } - } - }; - - public static void alias(Map asMap, ArrayList list ,PrintWriter out) { - - List keys = new ArrayList(list); - Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); - - for (String k: keys ){ - - Alias a = asMap.get(k); - - out.print(k); // for DVAR NAME - out.print(Param.csv_seperator+a.timeArraySize); //for TIME ARRAY SIZE - out.print(Param.csv_seperator+a.kind); //for KIND - out.print(Param.csv_seperator+a.units); //for UNITS - out.print(Param.csv_seperator+a.expression); //for expression - - out.print(Param.csv_seperator); - - if (a.dependants!=null){ - - List dep = new ArrayList(a.dependants); - Collections.sort(dep,String.CASE_INSENSITIVE_ORDER); - - for (String d: dep){ - out.print(d+";"); //for dependants - } - } - - out.print(Param.csv_seperator+a.fromWresl); - - out.print(Param.csv_seperator); - - if (a.neededVarInCycleSet!=null){ - - List varInCycle = new ArrayList(a.neededVarInCycleSet); - Collections.sort(varInCycle,String.CASE_INSENSITIVE_ORDER); - - for (String d: varInCycle){ - out.print(d+";"); //for dependantName[cycleName] - } - } - - out.print(Param.csv_seperator); - - boolean usedByLaterCycle = false; - if (currentModelDataSet.aliasUsedByLaterCycle.contains(k)) usedByLaterCycle = true; - - out.print( usedByLaterCycle); - - out.print("\n"); - } - }; - - public static void goal(Map gMap, ArrayList list ,PrintWriter out) { - - List keys = new ArrayList(list); - Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); - - for (String k: keys ){ - - //out.print(k); - Goal g = gMap.get(k); - - for (int i=0; i dep = new ArrayList(g.expressionDependants); - Collections.sort(dep,String.CASE_INSENSITIVE_ORDER); - - for (String d: dep){ - out.print(d+";"); //for dependants - } - } - -// out.print(Param.csv_seperator+g.case_lhs_gt_rhs.get(i)); // -// out.print(Param.csv_seperator+g.case_lhs_lt_rhs.get(i)); //for EXPRESSION - - - out.print(Param.csv_seperator+g.fromWresl); - out.print(Param.csv_seperator); - - if (g.neededVarInCycleSet!=null){ - - List varInCycle = new ArrayList(g.neededVarInCycleSet); - Collections.sort(varInCycle,String.CASE_INSENSITIVE_ORDER); - - for (String d: varInCycle){ - out.print(d+";"); //for dependantName[cycleName] - } - } - out.print("\n"); - } - } - }; - - public static void mapStringListMerged(Object obj, PrintWriter out) { - - @SuppressWarnings("unchecked") - List>> listMapStringList = (List>>) obj; - Map> mapAll = new HashMap>(); - - ArrayList keys = new ArrayList(); - - for (Map> m : listMapStringList){ - - mapAll.putAll(m); - } - - Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); - - for (String k: keys ){ - out.print(k); - - for(String i : mapAll.get(k)){ - out.print(Param.csv_seperator+i);} - out.print("\n"); - } - }; - - -} +package wrimsv2.wreslparser.elements; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Set; + +import java.util.Map; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.External; +import wrimsv2.commondata.wresldata.Goal; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.commondata.wresldata.Timeseries; +import wrimsv2.commondata.wresldata.WeightElement; + + +public class WriteCSV { + + //static Map> mapStringList = new HashMap>(); + //private static PrintWriter out; + + public static String sequence_header ="CYCLE,CONDITION,TIMESTEP"; + public static String weight_header ="DVAR,TIME_ARRAY_SIZE,CONDITION,WEIGHT"; + public static String external_header ="FUNCTION,FILE,FROM_WRESL_FILE"; + public static String svar_header ="NAME,TIME_ARRAY_SIZE,CASE,ORDER,CONDITION,EXPRESSION,DEPENDANT,FROM_WRESL_FILE,NEED_VAR_FROM_CYCLE,USED_IN_LATER_CYCLE"; + public static String timeseries_header ="NAME,B_PART,TYPE,UNITS,CONVERT_TO_UNITS,FROM_WRESL_FILE"; + public static String timeseries_timestep_header ="NAME,B_PART,TIMESTEP"; + public static String dvar_header ="NAME,TIME_ARRAY_SIZE,CONDITION,LOWER_BOUND,UPPER_BOUND,INTEGER,UNITS,TYPE,FROM_WRESL_FILE,USED_IN_LATER_CYCLE"; + public static String alias_header ="NAME,TIME_ARRAY_SIZE,TYPE,UNITS,EXPRESSION,DEPENDANT,FROM_WRESL_FILE,NEED_VAR_FROM_CYCLE,USED_IN_LATER_CYCLE"; + public static String goal_header = "NAME,TIME_ARRAY_SIZE,CASE,ORDER,CONDITION,EXPRESSION,DEPENDANT,FROM_WRESL_FILE,NEED_VAR_FROM_CYCLE,"; + private static ModelDataSet currentModelDataSet; + + + public static void study(StudyDataSet sd, String outParent) { + + if (sd==null) return; + + Map modelDataSetMap = sd.getModelDataSetMap(); + + output(modelDataSetMap,outParent); + + try { + PrintWriter out_seq = Tools.openFile(outParent, "SEQUENCE.csv"); + out_seq.print(WriteCSV.sequence_header + "\n"); + sequence(sd.getModelList(), sd.getModelConditionList(), out_seq); + out_seq.close(); + + if (sd.getTimeseriesMap().keySet().size()>0) { + PrintWriter out_timeseries_wholeStudy = Tools.openFile(outParent, "TIMESERIES.csv"); + out_timeseries_wholeStudy.print(WriteCSV.timeseries_header + "\n"); + timeseries_wholeStudy( sd.getTimeseriesMap(), out_timeseries_wholeStudy); + out_timeseries_wholeStudy.close(); + + + PrintWriter out_timeseriesTimeStep = Tools.openFile(outParent, "TIMESERIES_TIMESTEP.csv"); + out_timeseriesTimeStep.print(WriteCSV.timeseries_timestep_header + "\n"); + timeseriesTimeStep( sd, out_timeseriesTimeStep); + out_timeseriesTimeStep.close(); + } + + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + public static void study(StudyConfig sc, Map modelDataMap, String outParent) { + + Tools.deleteDir(outParent); + + output(modelDataMap,outParent); + + try { + PrintWriter out_seq = Tools.openFile(outParent, "SEQUENCE.csv"); + out_seq.print(WriteCSV.sequence_header + "\n"); + sequence(sc.sequenceMap, sc.sequenceOrder, out_seq); + out_seq.close(); + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + public static void output(Map modelDataMap, String outParent) { + + for (String model : modelDataMap.keySet()) { + + String outFolder = outParent + File.separator + model; + + try { + dataset(modelDataMap.get(model), outFolder); + } + catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + } + + public static void dataset(ModelDataSet ds, String outFolder) throws IOException { + + PrintWriter out_ex; + PrintWriter out_svTs; + PrintWriter out_sv; + PrintWriter out_sv_unknown; + PrintWriter out_dv; + PrintWriter out_goal; + PrintWriter out_alias; + PrintWriter out_alias_unknown; + PrintWriter out_wt; + PrintWriter out_incFile; + + currentModelDataSet = ds; + + + //outFolder = System.getProperty("user.dir")+"//"+outFolder; + + if(ds.incFileList.size()>0){ + out_incFile = Tools.openFile(outFolder, "include_file.csv"); + //out_incFile.print(WriteCSV.incFile_header + "\n"); + incFile(ds.incFileList, out_incFile); + out_incFile.close(); + } + if(ds.incFileList_global.size()>0){ + out_incFile = Tools.openFile(outFolder, "include_file_global.csv"); + //out_incFile.print(WriteCSV.incFile_header + "\n"); + incFile(ds.incFileList_global, out_incFile); + out_incFile.close(); + } + if(ds.exList.size()>0){ + out_ex = Tools.openFile(outFolder, "external.csv"); + out_ex.print(WriteCSV.external_header + "\n"); + external(ds.exMap, ds.exList, out_ex); + out_ex.close(); + } + if(ds.tsList.size()>0){ + out_svTs = Tools.openFile(outFolder, "timeseries.csv"); + out_svTs.print(WriteCSV.timeseries_header + "\n"); + timeseries_model(ds.tsMap, ds.tsList, out_svTs); + out_svTs.close(); + } + if(ds.svList.size()>0){ + out_sv = Tools.openFile(outFolder, "svar.csv"); + out_sv.print(WriteCSV.svar_header + "\n"); + svar(ds.svMap, ds.svList, out_sv); + out_sv.close(); + } + if(ds.svSet_unknown.size()>0){ + out_sv_unknown = Tools.openFile(outFolder, "svar_unknown.csv"); + out_sv_unknown.print(WriteCSV.svar_header + "\n"); + svar(ds.svMap, new ArrayList(ds.svSet_unknown), out_sv_unknown); + out_sv_unknown.close(); + } + if((ds.dvList.size()+ds.dvSlackSurplusList.size())>0){ + out_dv = Tools.openFile(outFolder, "dvar.csv"); + out_dv.print(WriteCSV.dvar_header + "\n"); + ArrayList allDvList = new ArrayList(ds.dvList); + allDvList.addAll(ds.dvSlackSurplusList); + Map allDvMap = new HashMap(ds.dvMap); + allDvMap.putAll(ds.dvSlackSurplusMap); + dvar(allDvMap, allDvList, out_dv); + out_dv.close(); + } + if(ds.gList.size()>0){ + out_goal = Tools.openFile(outFolder, "constraint.csv"); + out_goal.print(WriteCSV.goal_header + "\n"); + goal(ds.gMap, ds.gList, out_goal); + out_goal.close(); + } + if(ds.exList.size()>0){ + out_ex = Tools.openFile(outFolder, "external.csv"); + out_ex.print(WriteCSV.external_header + "\n"); + external(ds.exMap, ds.exList, out_ex); + out_ex.close(); + } + if((ds.wtList.size()+ds.wtSlackSurplusList.size())>0){ + out_wt = Tools.openFile(outFolder, "weight.csv"); + out_wt.print(WriteCSV.weight_header + "\n"); + ArrayList allWtList = new ArrayList(ds.wtList); + allWtList.addAll(ds.wtSlackSurplusList); + Map allWtMap = new HashMap(ds.wtMap); + allWtMap.putAll(ds.wtSlackSurplusMap); + weight(allWtMap, allWtList, out_wt); + out_wt.close(); + } + if(ds.asList.size()>0){ + out_alias = Tools.openFile(outFolder, "alias.csv"); + out_alias.print(WriteCSV.alias_header + "\n"); + alias(ds.asMap, ds.asList, out_alias); + out_alias.close(); + } + if(ds.asSet_unknown.size()>0){ + out_alias_unknown = Tools.openFile(outFolder, "alias_unknown.csv"); + out_alias_unknown.print(WriteCSV.alias_header + "\n"); + alias_unknown(ds.asMap, ds.dvMap, new ArrayList(ds.asSet_unknown), out_alias_unknown); + out_alias_unknown.close(); + } + + + + }; + + public static void timeseries_model(Map sTsMap, ArrayList list ,PrintWriter out) { + + List keys = new ArrayList(list); + Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); + + for (String k: keys ){ + + Timeseries s = sTsMap.get(k); + + out.print(k); // for SVAR NAME + out.print(Param.csv_seperator+s.dssBPart); //for DSS B Part + out.print(Param.csv_seperator+s.kind); //for KIND + out.print(Param.csv_seperator+s.units); //for UNITS + out.print(Param.csv_seperator+s.convertToUnits); //for CONVERT + out.print(",n"); //for OUTPUT + + out.print(Param.csv_seperator+s.fromWresl); + out.print("\n"); + + } + }; + + public static void svar(Map sMap, ArrayList list ,PrintWriter out) { + + List keys = new ArrayList(list); + //Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); + + for (String k: keys ){ + + //out.print(k); + Svar s = sMap.get(k); + + for (int i=0; i dep = new ArrayList(s.dependants); + Collections.sort(dep,String.CASE_INSENSITIVE_ORDER); + + for (String d: dep){ + out.print(d+";"); //for dependants + } + } + + out.print(Param.csv_seperator+s.fromWresl); + + out.print(Param.csv_seperator); + + if (s.neededVarInCycleSet!=null){ + + List varInCycle = new ArrayList(s.neededVarInCycleSet); + Collections.sort(varInCycle,String.CASE_INSENSITIVE_ORDER); + + for (String d: varInCycle){ + out.print(d+";"); //for dependantName[cycleName] + } + } + + out.print(Param.csv_seperator); + + boolean usedByLaterCycle = false; + if (currentModelDataSet.svarUsedByLaterCycle.contains(k)) usedByLaterCycle = true; + + out.print( usedByLaterCycle); + + out.print(Param.csv_seperator); + + out.print("\n"); + } + } + }; + + public static void sequence(ArrayList modelList, ArrayList modelConditionList ,PrintWriter out) { + + for (int i = 0; i< modelList.size(); i++ ){ + + out.print(modelList.get(i)); + out.print(Param.csv_seperator+modelConditionList.get(i)); + out.print("\n"); + + } + }; + + public static void sequence(Map seqMap, ArrayList list ,PrintWriter out) { + + List keys = list; + Collections.sort(keys); + + for (Integer k: keys ){ + + out.print(seqMap.get(k).modelName); + out.print(Param.csv_seperator+seqMap.get(k).condition+Param.csv_seperator+seqMap.get(k).timeStep); + out.print("\n"); + + } + }; + + + public static void timeseries_wholeStudy(Map tsMap, PrintWriter out) { + + Set kSet = tsMap.keySet(); + + List keys = new ArrayList(kSet); + + Collections.sort(keys); + + for (String k: keys ){ + + Timeseries s = tsMap.get(k); + + out.print(k); // for SVAR NAME + out.print(Param.csv_seperator+s.dssBPart); //for DSS B Part + out.print(Param.csv_seperator+s.kind); //for KIND + out.print(Param.csv_seperator+s.units); //for UNITS + out.print(Param.csv_seperator+s.convertToUnits); //for CONVERT + out.print(",n"); //for OUTPUT + + out.print(Param.csv_seperator+s.fromWresl); + out.print("\n"); + + } + }; + + public static void timeseriesTimeStep(StudyDataSet sd, PrintWriter out) { + + Map tsMap = sd.getTimeseriesMap(); + + Set kSet = tsMap.keySet(); + + List keys = new ArrayList(kSet); + + Collections.sort(keys); + + for (String k: keys ){ + + Timeseries s = tsMap.get(k); + + out.print(k); // for TIMESERIES NAME + out.print(Param.csv_seperator+s.dssBPart); //for DSS B Part + out.print(Param.csv_seperator); + + for (String step:sd.getTimeseriesTimeStepMap().get(k)){ + + out.print(step+";"); + + } + + out.print("\n"); + + } + }; + + public static void incFile(ArrayList list ,PrintWriter out) { + + List keys = new ArrayList(list); + Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); + + for (String k: keys ){ + + //out.print(k); + + + out.print(k); // + + out.print("\n"); + + } + }; + + public static void external(Map exMap, ArrayList list ,PrintWriter out) { + + List keys = new ArrayList(list); + Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); + + for (String k: keys ){ + + //out.print(k); + External s = exMap.get(k); + + + out.print(k); // + out.print(Param.csv_seperator+s.type); + + out.print(Param.csv_seperator+s.fromWresl); + out.print("\n"); + + } + }; + + + public static void weight(Map wtMap, ArrayList list ,PrintWriter out) { + + List keys = new ArrayList(list); + Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); + + for (String k: keys ){ + + + if (! wtMap.containsKey(k)) System.out.println("##### not exist in wtMap:"+k); + + + //out.print(k); + WeightElement w = wtMap.get(k); + + + out.print(k); // for DVAR NAME + + out.print(Param.csv_seperator+w.timeArraySize); //for TIME ARRAY SIZE + + out.print(Param.csv_seperator+w.condition); + + out.print(Param.csv_seperator+w.weight); + + out.print("\n"); + + } + }; + + public static void dvar(Map dMap, ArrayList list ,PrintWriter out) { + + List keys = new ArrayList(list); + Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); + + for (String k: keys ){ + + Dvar d = dMap.get(k); + + out.print(k); // for DVAR NAME + out.print(Param.csv_seperator+d.timeArraySize); //for TIME ARRAY SIZE + out.print(Param.csv_seperator+d.condition); // for DVAR CONDITION + out.print(Param.csv_seperator+d.lowerBound); //for UNITS + out.print(Param.csv_seperator+d.upperBound); //for UNITS + out.print(Param.csv_seperator+d.integer); //for KIND + out.print(Param.csv_seperator+d.units); //for UNITS + out.print(Param.csv_seperator+d.kind); //for KIND + + out.print(Param.csv_seperator+d.fromWresl); + + out.print(Param.csv_seperator); + + boolean usedByLaterCycle = false; + if (currentModelDataSet.dvarUsedByLaterCycle.contains(k)) usedByLaterCycle = true; + + out.print( usedByLaterCycle); + + out.print(Param.csv_seperator); + + out.print("\n"); + } + }; + + public static void alias_unknown(Map asMap, Map dvMap, ArrayList list ,PrintWriter out) { + + List keys = new ArrayList(list); + Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); + + for (String k : keys) { + + if (asMap.keySet().contains(k)) { + + Alias a = asMap.get(k); + + out.print(k); // for DVAR NAME + out.print(Param.csv_seperator + a.timeArraySize); //for TIME ARRAY SIZE + out.print(Param.csv_seperator + a.kind); // for KIND + out.print(Param.csv_seperator + a.units); // for UNITS + out.print(Param.csv_seperator + a.expression); // for expression + + out.print(Param.csv_seperator); + + if (a.dependants != null) { + for (String d : a.dependants) { + out.print(d + ";"); // for dependants + } + } + + out.print(Param.csv_seperator + a.fromWresl); + out.print("\n"); + } + else { // converted to dv + + Dvar a = dvMap.get(k); + + out.print(k); // for DVAR NAME + + out.print(Param.csv_seperator + a.kind); // for KIND + out.print(Param.csv_seperator + a.units); // for UNITS + out.print(Param.csv_seperator + a.expression); // for expression + + out.print(Param.csv_seperator); + + if (a.dependants != null) { + for (String d : a.dependants) { + out.print(d + ";"); // for dependants + } + } + + out.print(Param.csv_seperator + a.fromWresl); + out.print("\n"); + + } + } + }; + + public static void alias(Map asMap, ArrayList list ,PrintWriter out) { + + List keys = new ArrayList(list); + Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); + + for (String k: keys ){ + + Alias a = asMap.get(k); + + out.print(k); // for DVAR NAME + out.print(Param.csv_seperator+a.timeArraySize); //for TIME ARRAY SIZE + out.print(Param.csv_seperator+a.kind); //for KIND + out.print(Param.csv_seperator+a.units); //for UNITS + out.print(Param.csv_seperator+a.expression); //for expression + + out.print(Param.csv_seperator); + + if (a.dependants!=null){ + + List dep = new ArrayList(a.dependants); + Collections.sort(dep,String.CASE_INSENSITIVE_ORDER); + + for (String d: dep){ + out.print(d+";"); //for dependants + } + } + + out.print(Param.csv_seperator+a.fromWresl); + + out.print(Param.csv_seperator); + + if (a.neededVarInCycleSet!=null){ + + List varInCycle = new ArrayList(a.neededVarInCycleSet); + Collections.sort(varInCycle,String.CASE_INSENSITIVE_ORDER); + + for (String d: varInCycle){ + out.print(d+";"); //for dependantName[cycleName] + } + } + + out.print(Param.csv_seperator); + + boolean usedByLaterCycle = false; + if (currentModelDataSet.aliasUsedByLaterCycle.contains(k)) usedByLaterCycle = true; + + out.print( usedByLaterCycle); + + out.print("\n"); + } + }; + + public static void goal(Map gMap, ArrayList list ,PrintWriter out) { + + List keys = new ArrayList(list); + Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); + + for (String k: keys ){ + + //out.print(k); + Goal g = gMap.get(k); + + for (int i=0; i dep = new ArrayList(g.expressionDependants); + Collections.sort(dep,String.CASE_INSENSITIVE_ORDER); + + for (String d: dep){ + out.print(d+";"); //for dependants + } + } + +// out.print(Param.csv_seperator+g.case_lhs_gt_rhs.get(i)); // +// out.print(Param.csv_seperator+g.case_lhs_lt_rhs.get(i)); //for EXPRESSION + + + out.print(Param.csv_seperator+g.fromWresl); + out.print(Param.csv_seperator); + + if (g.neededVarInCycleSet!=null){ + + List varInCycle = new ArrayList(g.neededVarInCycleSet); + Collections.sort(varInCycle,String.CASE_INSENSITIVE_ORDER); + + for (String d: varInCycle){ + out.print(d+";"); //for dependantName[cycleName] + } + } + out.print("\n"); + } + } + }; + + public static void mapStringListMerged(Object obj, PrintWriter out) { + + @SuppressWarnings("unchecked") + List>> listMapStringList = (List>>) obj; + Map> mapAll = new HashMap>(); + + ArrayList keys = new ArrayList(); + + for (Map> m : listMapStringList){ + + mapAll.putAll(m); + } + + Collections.sort(keys,String.CASE_INSENSITIVE_ORDER); + + for (String k: keys ){ + out.print(k); + + for(String i : mapAll.get(k)){ + out.print(Param.csv_seperator+i);} + out.print("\n"); + } + }; + + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/AliasTemp.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/AliasTemp.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/AliasTemp.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/AliasTemp.java index e8a68362f..9eef2ae3f 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/AliasTemp.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/AliasTemp.java @@ -1,66 +1,66 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.evaluator.ValueEvaluatorTreeWalker; - - - -public class AliasTemp implements Serializable { - - private static final long serialVersionUID = 1L; - - public String fromWresl; // for test only - public int line=1; - public String id; - public String kind; - public String units; - public String condition; - public String expression; - public Set dependants; - public Set dependants_timeseries; - public Set dependants_dvar; - public Set dependants_svar; - public Set dependants_alias; - public Set dependants_parameter; - public Set dependants_unknown; - public Set neededVarInCycleSet; - public boolean needVarFromEarlierCycle; - public boolean isMovedToDvar; - public boolean isProcessed; - public boolean noSolver; - - // default is 0 - public String timeArraySize; - public String arraySize; - - public AliasTemp(){ - - kind=Param.undefined; - units=Param.undefined; - condition = Param.always; - expression=Param.undefined; - dependants = new LinkedHashSet(); -// dependants_timeseries = new LinkedHashSet(); -// dependants_dvar = new LinkedHashSet(); -// dependants_svar = new LinkedHashSet(); -// dependants_alias = new LinkedHashSet(); - neededVarInCycleSet = new LinkedHashSet(); - needVarFromEarlierCycle = false; - isMovedToDvar = false; - isProcessed = false; - noSolver = false; - - timeArraySize="0"; - arraySize="0"; - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.evaluator.ValueEvaluatorTreeWalker; + + + +public class AliasTemp implements Serializable { + + private static final long serialVersionUID = 1L; + + public String fromWresl; // for test only + public int line=1; + public String id; + public String kind; + public String units; + public String condition; + public String expression; + public Set dependants; + public Set dependants_timeseries; + public Set dependants_dvar; + public Set dependants_svar; + public Set dependants_alias; + public Set dependants_parameter; + public Set dependants_unknown; + public Set neededVarInCycleSet; + public boolean needVarFromEarlierCycle; + public boolean isMovedToDvar; + public boolean isProcessed; + public boolean noSolver; + + // default is 0 + public String timeArraySize; + public String arraySize; + + public AliasTemp(){ + + kind=Param.undefined; + units=Param.undefined; + condition = Param.always; + expression=Param.undefined; + dependants = new LinkedHashSet(); +// dependants_timeseries = new LinkedHashSet(); +// dependants_dvar = new LinkedHashSet(); +// dependants_svar = new LinkedHashSet(); +// dependants_alias = new LinkedHashSet(); + neededVarInCycleSet = new LinkedHashSet(); + needVarFromEarlierCycle = false; + isMovedToDvar = false; + isProcessed = false; + noSolver = false; + + timeArraySize="0"; + arraySize="0"; + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/CompileLog.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/CompileLog.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/CompileLog.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/CompileLog.java index 811e5e977..8e5e7b93e 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/CompileLog.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/CompileLog.java @@ -1,319 +1,319 @@ -package wrimsv2.wreslplus.elements; - -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Set; - -import org.apache.commons.io.FilenameUtils; - -import wrimsv2.commondata.wresldata.Param; - -public class CompileLog { - - private CompileLog(){} - - public static String createMainWreslLog( StudyTemp st, LinkedHashMap fileMap_reverse) { - - String r = ""; - r=r+doSequence(st); - r=r+doIncModel(st); - - r=r+doModels(st, fileMap_reverse); - - return r; - } - public static String writeLog( String r, String canonicalFilePath) { - - String f = FilenameUtils.removeExtension(canonicalFilePath) + ".de"; - PrintWriter p = null; - try { - p = new PrintWriter(new BufferedWriter(new FileWriter(f))); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - p.print(r); - p.flush(); - p.close(); - return r; - } - - - public static String createWreslFileLog( ModelTemp mt, Set deps) { - - String r = ""; - - r=r+doModel(mt, deps); - - return r; - } - - private static String doModel( ModelTemp mt, Set deps) { - - // use symbol instead of full file path - - - - String r=""; - - r=r+doTimeseries(mt); - r=r+doDv(mt); - - - r=r+doAlias(mt, deps); - r=r+"------------------\n"; - - - r=r+doSvIncFileModel(mt); - r=r+doGoal(mt, deps); - - Set varsInModel = new HashSet(); - - varsInModel.addAll(Tools.allToLowerCase(mt.svList)); - varsInModel.addAll(Tools.allToLowerCase(mt.tsList)); - varsInModel.addAll(Tools.allToLowerCase(mt.asList)); - varsInModel.addAll(Tools.allToLowerCase(mt.dvList)); - - deps.removeAll(varsInModel); - - return r; - - } - private static String doModels( StudyTemp st, LinkedHashMap fileMap_reverse) { - - // use symbol instead of full file path - - - - String r=""; - r=r+"model{\n"; - - //LinkedHashMap fileMap_reverse = new LinkedHashMap(); - - for (String m: st.modelList){ - ModelTemp mt = st.modelMap.get(m); - r=r+"\t"+m.toLowerCase()+"{\n"; - - r=r+doTimeseries(mt); - r=r+doDv(mt); - - r=r+doAlias(mt,null); - r=r+"------------------\n"; - - - r=r+doSvIncFileModel(mt,fileMap_reverse); - r=r+doGoal(mt,null); - - r=r+"\t}\n"; //+m.toLowerCase()+"\n"; - } - - r=r+"}\n"; - return r; - - } - private static String doSvIncFileModel(ModelTemp mt) { - - String r=""; - for (int i=0; i fileMap_reverse) { - - String r=""; - for (int i=0; i deps) { - String r=""; - for (String d : mt.asList) { - AliasTemp dt = mt.asMap.get(d); - r=r+"\t\t@a:" + d; - r=r+"\te:" + dt.expression.toLowerCase(); - if (dt.kind!=Param.undefined) r=r+"\tk:" + dt.kind.toLowerCase(); - if (dt.units!=Param.undefined) r=r+"\tu:" + dt.units.toLowerCase(); - r=r+"\n"; - - // collect dependents - if (deps != null) { - Set dependents = Tools.allToLowerCase(new HashSet(dt.dependants)); - dependents.removeAll(Param.reservedSet); - deps.addAll(dependents); - } - } - return r; - } - - private static String doGoal(ModelTemp mt, Set deps) { - String r=""; - for (String d : mt.glList) { - GoalTemp dt = mt.glMap.get(d); - - if (!dt.hasLhs){ - // simple - r=r+"@gs:" + d; - r=r+"\te:" + dt.caseExpression.get(0).toLowerCase(); - r=r+"\n"; - - } else if (!dt.hasCase){ - // no case - r=r+"@gnc:" + d; - r=r+"\tl:" + dt.lhs.toLowerCase(); - GoalCase gc = dt.caseMap.get(dt.caseName.get(0)); - r=r+"\tr:" + gc.rhs.toLowerCase(); - if (!gc.lhs_gt_rhs.equalsIgnoreCase(Param.constrain)) r=r+"\tlhs>rhs:" + gc.lhs_gt_rhs.toLowerCase(); - if (!gc.lhs_lt_rhs.equalsIgnoreCase(Param.constrain)) r=r+"\tlhsrhs:" + gc.lhs_gt_rhs.toLowerCase(); - if (!gc.lhs_lt_rhs.equalsIgnoreCase(Param.constrain)) r=r+"\tlhs dependents = Tools.allToLowerCase(new HashSet(dt.dependants)); - dependents.removeAll(Param.reservedSet); - deps.addAll(dependents); - } - - } - return r; - } - - private static String doSv(SvarTemp svT) { - String r = ""; - for (int i=0; i includedModels = new LinkedHashSet(); - - r=r+"includeModel{\n"; - for (String s: st.modelList){ - includedModels.addAll(st.modelMap.get(s).incModelList); - } - - for (String s: includedModels){ - r=r+"\t"+s.toLowerCase()+"\n"; - } - - - r=r+"}\n"; - - return r; - - } - - private static String doSequence( StudyTemp st) { - String r=""; - r=r+"sequence{\n"; - for (String s: st.seqList){ - - r=r+"\t"+st.seqMap.get(s).model.toLowerCase(); - r=r+"\ts:"+s.toLowerCase(); - if (!st.seqMap.get(s).condition.toLowerCase().equals(Param.always)) r=r+"\tc:"+st.seqMap.get(s).condition.toLowerCase(); - r=r+"\to:"+st.seqMap.get(s).order; - if (st.seqMap.get(s).timeStep!=Param.undefined) r=r+"\tt:"+st.seqMap.get(s).timeStep.toLowerCase(); - r=r+"\n"; - } - r=r+"}\n"; - return r; - - } -} +package wrimsv2.wreslplus.elements; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Set; + +import org.apache.commons.io.FilenameUtils; + +import wrimsv2.commondata.wresldata.Param; + +public class CompileLog { + + private CompileLog(){} + + public static String createMainWreslLog( StudyTemp st, LinkedHashMap fileMap_reverse) { + + String r = ""; + r=r+doSequence(st); + r=r+doIncModel(st); + + r=r+doModels(st, fileMap_reverse); + + return r; + } + public static String writeLog( String r, String canonicalFilePath) { + + String f = FilenameUtils.removeExtension(canonicalFilePath) + ".de"; + PrintWriter p = null; + try { + p = new PrintWriter(new BufferedWriter(new FileWriter(f))); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + p.print(r); + p.flush(); + p.close(); + return r; + } + + + public static String createWreslFileLog( ModelTemp mt, Set deps) { + + String r = ""; + + r=r+doModel(mt, deps); + + return r; + } + + private static String doModel( ModelTemp mt, Set deps) { + + // use symbol instead of full file path + + + + String r=""; + + r=r+doTimeseries(mt); + r=r+doDv(mt); + + + r=r+doAlias(mt, deps); + r=r+"------------------\n"; + + + r=r+doSvIncFileModel(mt); + r=r+doGoal(mt, deps); + + Set varsInModel = new HashSet(); + + varsInModel.addAll(Tools.allToLowerCase(mt.svList)); + varsInModel.addAll(Tools.allToLowerCase(mt.tsList)); + varsInModel.addAll(Tools.allToLowerCase(mt.asList)); + varsInModel.addAll(Tools.allToLowerCase(mt.dvList)); + + deps.removeAll(varsInModel); + + return r; + + } + private static String doModels( StudyTemp st, LinkedHashMap fileMap_reverse) { + + // use symbol instead of full file path + + + + String r=""; + r=r+"model{\n"; + + //LinkedHashMap fileMap_reverse = new LinkedHashMap(); + + for (String m: st.modelList){ + ModelTemp mt = st.modelMap.get(m); + r=r+"\t"+m.toLowerCase()+"{\n"; + + r=r+doTimeseries(mt); + r=r+doDv(mt); + + r=r+doAlias(mt,null); + r=r+"------------------\n"; + + + r=r+doSvIncFileModel(mt,fileMap_reverse); + r=r+doGoal(mt,null); + + r=r+"\t}\n"; //+m.toLowerCase()+"\n"; + } + + r=r+"}\n"; + return r; + + } + private static String doSvIncFileModel(ModelTemp mt) { + + String r=""; + for (int i=0; i fileMap_reverse) { + + String r=""; + for (int i=0; i deps) { + String r=""; + for (String d : mt.asList) { + AliasTemp dt = mt.asMap.get(d); + r=r+"\t\t@a:" + d; + r=r+"\te:" + dt.expression.toLowerCase(); + if (dt.kind!=Param.undefined) r=r+"\tk:" + dt.kind.toLowerCase(); + if (dt.units!=Param.undefined) r=r+"\tu:" + dt.units.toLowerCase(); + r=r+"\n"; + + // collect dependents + if (deps != null) { + Set dependents = Tools.allToLowerCase(new HashSet(dt.dependants)); + dependents.removeAll(Param.reservedSet); + deps.addAll(dependents); + } + } + return r; + } + + private static String doGoal(ModelTemp mt, Set deps) { + String r=""; + for (String d : mt.glList) { + GoalTemp dt = mt.glMap.get(d); + + if (!dt.hasLhs){ + // simple + r=r+"@gs:" + d; + r=r+"\te:" + dt.caseExpression.get(0).toLowerCase(); + r=r+"\n"; + + } else if (!dt.hasCase){ + // no case + r=r+"@gnc:" + d; + r=r+"\tl:" + dt.lhs.toLowerCase(); + GoalCase gc = dt.caseMap.get(dt.caseName.get(0)); + r=r+"\tr:" + gc.rhs.toLowerCase(); + if (!gc.lhs_gt_rhs.equalsIgnoreCase(Param.constrain)) r=r+"\tlhs>rhs:" + gc.lhs_gt_rhs.toLowerCase(); + if (!gc.lhs_lt_rhs.equalsIgnoreCase(Param.constrain)) r=r+"\tlhsrhs:" + gc.lhs_gt_rhs.toLowerCase(); + if (!gc.lhs_lt_rhs.equalsIgnoreCase(Param.constrain)) r=r+"\tlhs dependents = Tools.allToLowerCase(new HashSet(dt.dependants)); + dependents.removeAll(Param.reservedSet); + deps.addAll(dependents); + } + + } + return r; + } + + private static String doSv(SvarTemp svT) { + String r = ""; + for (int i=0; i includedModels = new LinkedHashSet(); + + r=r+"includeModel{\n"; + for (String s: st.modelList){ + includedModels.addAll(st.modelMap.get(s).incModelList); + } + + for (String s: includedModels){ + r=r+"\t"+s.toLowerCase()+"\n"; + } + + + r=r+"}\n"; + + return r; + + } + + private static String doSequence( StudyTemp st) { + String r=""; + r=r+"sequence{\n"; + for (String s: st.seqList){ + + r=r+"\t"+st.seqMap.get(s).model.toLowerCase(); + r=r+"\ts:"+s.toLowerCase(); + if (!st.seqMap.get(s).condition.toLowerCase().equals(Param.always)) r=r+"\tc:"+st.seqMap.get(s).condition.toLowerCase(); + r=r+"\to:"+st.seqMap.get(s).order; + if (st.seqMap.get(s).timeStep!=Param.undefined) r=r+"\tt:"+st.seqMap.get(s).timeStep.toLowerCase(); + r=r+"\n"; + } + r=r+"}\n"; + return r; + + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/DvarTemp.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/DvarTemp.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/DvarTemp.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/DvarTemp.java index aeb2b4b1a..ced15cb5c 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/DvarTemp.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/DvarTemp.java @@ -1,51 +1,51 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; - - - -public class DvarTemp implements Serializable { - - private static final long serialVersionUID = 1L; - - public String fromWresl; // for test only - public int line=1; - public String id; - public boolean isInteger; - public String format; - public String kind; - public String units; - public String lowerBound; - public String upperBound; - public String condition; - public String expression; - public Set dependants; - public boolean isFromAlias; - - // default is 0 - public String timeArraySize; - public String arraySize; - - public DvarTemp(){ - - isInteger=false; - isFromAlias=false; - format=Param.undefined; - kind=Param.undefined; - units=Param.undefined; - lowerBound=Param.dv_std_lowerBound; - upperBound=Param.dv_std_upperBound; - condition = Param.always; - expression=Param.undefined; - dependants = new HashSet(); - - timeArraySize="0"; - arraySize="0"; - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; + + + +public class DvarTemp implements Serializable { + + private static final long serialVersionUID = 1L; + + public String fromWresl; // for test only + public int line=1; + public String id; + public boolean isInteger; + public String format; + public String kind; + public String units; + public String lowerBound; + public String upperBound; + public String condition; + public String expression; + public Set dependants; + public boolean isFromAlias; + + // default is 0 + public String timeArraySize; + public String arraySize; + + public DvarTemp(){ + + isInteger=false; + isFromAlias=false; + format=Param.undefined; + kind=Param.undefined; + units=Param.undefined; + lowerBound=Param.dv_std_lowerBound; + upperBound=Param.dv_std_upperBound; + condition = Param.always; + expression=Param.undefined; + dependants = new HashSet(); + + timeArraySize="0"; + arraySize="0"; + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ExternalTemp.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/ExternalTemp.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ExternalTemp.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/ExternalTemp.java index e49d175b4..fcb96dcf9 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ExternalTemp.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/ExternalTemp.java @@ -1,28 +1,28 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; - - - -public class ExternalTemp implements Serializable { - - private static final long serialVersionUID = 1L; - - public String fromWresl; // for test only - public int line=1; - public String id; - public String fileName; - - public ExternalTemp(){ - - fileName=Param.undefined; - fromWresl=Param.undefined; - - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; + + + +public class ExternalTemp implements Serializable { + + private static final long serialVersionUID = 1L; + + public String fromWresl; // for test only + public int line=1; + public String id; + public String fileName; + + public ExternalTemp(){ + + fileName=Param.undefined; + fromWresl=Param.undefined; + + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GlobalData.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/GlobalData.java similarity index 92% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GlobalData.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/GlobalData.java index cbd72697b..30c05a83b 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GlobalData.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/GlobalData.java @@ -1,9 +1,9 @@ -package wrimsv2.wreslplus.elements; - - -public class GlobalData { - public static String runDir = null; - - -} - +package wrimsv2.wreslplus.elements; + + +public class GlobalData { + public static String runDir = null; + + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GoalCase.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/GoalCase.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GoalCase.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/GoalCase.java index db957116b..2a7c68ded 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GoalCase.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/GoalCase.java @@ -1,38 +1,38 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.EvaluatorParser; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.evaluator.ValueEvaluatorTreeWalker; - - -public class GoalCase implements Serializable { - - private static final long serialVersionUID = 1L; - - public String id; - public String condition; - public String rhs; - public String lhs_gt_rhs; - public String lhs_lt_rhs; - //public Set dependants; - - public GoalCase(){ - - //id=Param.undefined; - condition = Param.always; - //dependants = new LinkedHashSet(); - lhs_gt_rhs = Param.constrain; - lhs_lt_rhs = Param.constrain; - - } -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.EvaluatorParser; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.evaluator.ValueEvaluatorTreeWalker; + + +public class GoalCase implements Serializable { + + private static final long serialVersionUID = 1L; + + public String id; + public String condition; + public String rhs; + public String lhs_gt_rhs; + public String lhs_lt_rhs; + //public Set dependants; + + public GoalCase(){ + + //id=Param.undefined; + condition = Param.always; + //dependants = new LinkedHashSet(); + lhs_gt_rhs = Param.constrain; + lhs_lt_rhs = Param.constrain; + + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GoalHS.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/GoalHS.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GoalHS.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/GoalHS.java index 2c328ddbd..323bf40f5 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GoalHS.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/GoalHS.java @@ -1,45 +1,45 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.EvaluatorParser; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.evaluator.ValueEvaluatorTreeWalker; - - -public class GoalHS implements Serializable { - - private static final long serialVersionUID = 1L; - - public String fromWresl; // for test only - public int line=1; - public String id; - public String condition; - public String lhs; - - public Set dependants; - public Set neededVarInCycleSet; - public boolean needVarFromEarlierCycle; - - public ArrayList caseName; - public Map caseMap; - - public GoalHS(){ - - condition = Param.always; - dependants = new LinkedHashSet(); - neededVarInCycleSet = new LinkedHashSet(); - needVarFromEarlierCycle = false; - caseName=new ArrayList(); - caseMap=new LinkedHashMap(); - } -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.EvaluatorParser; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.evaluator.ValueEvaluatorTreeWalker; + + +public class GoalHS implements Serializable { + + private static final long serialVersionUID = 1L; + + public String fromWresl; // for test only + public int line=1; + public String id; + public String condition; + public String lhs; + + public Set dependants; + public Set neededVarInCycleSet; + public boolean needVarFromEarlierCycle; + + public ArrayList caseName; + public Map caseMap; + + public GoalHS(){ + + condition = Param.always; + dependants = new LinkedHashSet(); + neededVarInCycleSet = new LinkedHashSet(); + needVarFromEarlierCycle = false; + caseName=new ArrayList(); + caseMap=new LinkedHashMap(); + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GoalTemp.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/GoalTemp.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GoalTemp.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/GoalTemp.java index 0d04323a2..01b6cc322 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/GoalTemp.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/GoalTemp.java @@ -1,88 +1,88 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.EvaluatorParser; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.evaluator.ValueEvaluatorTreeWalker; - - -public class GoalTemp implements Serializable { - - private static final long serialVersionUID = 1L; - - public String fromWresl; // for test only - public int line=1; - public String id; - public String condition; - public String lhs; - - public Set dependants; - public Set dependants_timeseries; - public Set dependants_svar; - public Set dependants_dvar; - public Set dependants_alias; - public Set dependants_external; - public Set dependants_parameter; - public Set dependants_unknown; - public Set neededVarInCycleSet; - public boolean needVarFromEarlierCycle; - - public boolean hasCase; - public boolean hasLhs; - public boolean isFromAlias; - public boolean isProcessed; - public ArrayList caseName; - public Map caseMap; - public ArrayList caseCondition; - public ArrayList caseExpression; - // ArrayList< Map< dvarName, Weight > > index is case number - public ArrayList> dvarWeightMapList; - public ArrayList> dvarSlackSurplusList; - public ArrayList slackList; - public ArrayList surplusList; - - // default is 0 - public String timeArraySize; - public String arraySize; - - public GoalTemp(){ - - lhs=null; - hasCase=false; - hasLhs=false; - isFromAlias=false; - isProcessed=false; - condition = Param.always; - dependants = new LinkedHashSet(); -// dependants_timeseries = new LinkedHashSet(); -// dependants_svar = new LinkedHashSet(); -// dependants_dvar = new LinkedHashSet(); -// dependants_alias = new LinkedHashSet(); -// dependants_external = new LinkedHashSet(); -// dependants_unknown = new LinkedHashSet(); - neededVarInCycleSet = new LinkedHashSet(); - needVarFromEarlierCycle = false; - caseName=new ArrayList(); - caseMap=new LinkedHashMap(); - caseCondition=new ArrayList(); - caseExpression=new ArrayList(); - dvarWeightMapList = new ArrayList>(); - dvarSlackSurplusList = new ArrayList>(); - slackList=new ArrayList(); - surplusList=new ArrayList(); - - timeArraySize="0"; - arraySize="0"; - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.EvaluatorParser; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.evaluator.ValueEvaluatorTreeWalker; + + +public class GoalTemp implements Serializable { + + private static final long serialVersionUID = 1L; + + public String fromWresl; // for test only + public int line=1; + public String id; + public String condition; + public String lhs; + + public Set dependants; + public Set dependants_timeseries; + public Set dependants_svar; + public Set dependants_dvar; + public Set dependants_alias; + public Set dependants_external; + public Set dependants_parameter; + public Set dependants_unknown; + public Set neededVarInCycleSet; + public boolean needVarFromEarlierCycle; + + public boolean hasCase; + public boolean hasLhs; + public boolean isFromAlias; + public boolean isProcessed; + public ArrayList caseName; + public Map caseMap; + public ArrayList caseCondition; + public ArrayList caseExpression; + // ArrayList< Map< dvarName, Weight > > index is case number + public ArrayList> dvarWeightMapList; + public ArrayList> dvarSlackSurplusList; + public ArrayList slackList; + public ArrayList surplusList; + + // default is 0 + public String timeArraySize; + public String arraySize; + + public GoalTemp(){ + + lhs=null; + hasCase=false; + hasLhs=false; + isFromAlias=false; + isProcessed=false; + condition = Param.always; + dependants = new LinkedHashSet(); +// dependants_timeseries = new LinkedHashSet(); +// dependants_svar = new LinkedHashSet(); +// dependants_dvar = new LinkedHashSet(); +// dependants_alias = new LinkedHashSet(); +// dependants_external = new LinkedHashSet(); +// dependants_unknown = new LinkedHashSet(); + neededVarInCycleSet = new LinkedHashSet(); + needVarFromEarlierCycle = false; + caseName=new ArrayList(); + caseMap=new LinkedHashMap(); + caseCondition=new ArrayList(); + caseExpression=new ArrayList(); + dvarWeightMapList = new ArrayList>(); + dvarSlackSurplusList = new ArrayList>(); + slackList=new ArrayList(); + surplusList=new ArrayList(); + + timeArraySize="0"; + arraySize="0"; + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/IfIncItemGroup.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/IfIncItemGroup.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/IfIncItemGroup.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/IfIncItemGroup.java index ebeacb80e..a58d6cce2 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/IfIncItemGroup.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/IfIncItemGroup.java @@ -1,48 +1,48 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Set; - -public class IfIncItemGroup implements Serializable { - - private static final long serialVersionUID = 1L; - public String id; - public String fromWresl; - public int line=1; - - public ArrayList> inc_item_list; - public ArrayList> inc_files_map_list; - public ArrayList> inc_svar_map_list; - public ArrayList> inc_dvar_map_list; - public ArrayList> inc_alias_map_list; - public ArrayList> inc_timeseries_map_list; - public ArrayList> inc_goalSimple_map_list; - public ArrayList> inc_goalComplex_map_list; - public ArrayList> inc_weightTable_map_list; - public ArrayList conditionList; - public ArrayList conditionValueList; - public Set dependants; - - public IfIncItemGroup(){ - - inc_item_list = new ArrayList>(); - inc_files_map_list = new ArrayList>(); - inc_svar_map_list = new ArrayList>(); - inc_dvar_map_list = new ArrayList>(); - inc_alias_map_list = new ArrayList>(); - inc_timeseries_map_list = new ArrayList>(); - inc_goalSimple_map_list = new ArrayList>(); - inc_goalComplex_map_list = new ArrayList>(); - inc_weightTable_map_list = new ArrayList>(); - conditionList = new ArrayList(); - dependants = new LinkedHashSet(); - - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Set; + +public class IfIncItemGroup implements Serializable { + + private static final long serialVersionUID = 1L; + public String id; + public String fromWresl; + public int line=1; + + public ArrayList> inc_item_list; + public ArrayList> inc_files_map_list; + public ArrayList> inc_svar_map_list; + public ArrayList> inc_dvar_map_list; + public ArrayList> inc_alias_map_list; + public ArrayList> inc_timeseries_map_list; + public ArrayList> inc_goalSimple_map_list; + public ArrayList> inc_goalComplex_map_list; + public ArrayList> inc_weightTable_map_list; + public ArrayList conditionList; + public ArrayList conditionValueList; + public Set dependants; + + public IfIncItemGroup(){ + + inc_item_list = new ArrayList>(); + inc_files_map_list = new ArrayList>(); + inc_svar_map_list = new ArrayList>(); + inc_dvar_map_list = new ArrayList>(); + inc_alias_map_list = new ArrayList>(); + inc_timeseries_map_list = new ArrayList>(); + inc_goalSimple_map_list = new ArrayList>(); + inc_goalComplex_map_list = new ArrayList>(); + inc_weightTable_map_list = new ArrayList>(); + conditionList = new ArrayList(); + dependants = new LinkedHashSet(); + + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/IncFileSimple.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/IncFileSimple.java similarity index 93% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/IncFileSimple.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/IncFileSimple.java index e54ab72c7..5f4528d80 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/IncFileSimple.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/IncFileSimple.java @@ -1,17 +1,17 @@ -package wrimsv2.wreslplus.elements; - -public class IncFileSimple { - - public String fromWresl; - public int line=1; - public String absPath; - - public IncFileSimple(){ - } - - public IncFileSimple(String absPath){ - this.absPath=absPath; - } - -} - +package wrimsv2.wreslplus.elements; + +public class IncFileSimple { + + public String fromWresl; + public int line=1; + public String absPath; + + public IncFileSimple(){ + } + + public IncFileSimple(String absPath){ + this.absPath=absPath; + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/IncFileTemp.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/IncFileTemp.java similarity index 93% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/IncFileTemp.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/IncFileTemp.java index 9c5ac74db..1637d4661 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/IncFileTemp.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/IncFileTemp.java @@ -1,20 +1,20 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; - -public class IncFileTemp implements Serializable { - - private static final long serialVersionUID = 1L; - public String id; - public String rawPath; - public String pathRelativeToRunDir; - public String absPath; - - - public IncFileTemp(){ - - - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; + +public class IncFileTemp implements Serializable { + + private static final long serialVersionUID = 1L; + public String id; + public String rawPath; + public String pathRelativeToRunDir; + public String absPath; + + + public IncFileTemp(){ + + + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/LookupTableSimple.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/LookupTableSimple.java similarity index 93% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/LookupTableSimple.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/LookupTableSimple.java index 4244f3fbc..ceb7fd462 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/LookupTableSimple.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/LookupTableSimple.java @@ -1,17 +1,17 @@ -package wrimsv2.wreslplus.elements; - -public class LookupTableSimple { - - public String fromWresl; - public int line=1; - public String tableName; - - public LookupTableSimple(){ - } - - public LookupTableSimple(String tableName){ - this.tableName=tableName; - } - -} - +package wrimsv2.wreslplus.elements; + +public class LookupTableSimple { + + public String fromWresl; + public int line=1; + public String tableName; + + public LookupTableSimple(){ + } + + public LookupTableSimple(String tableName){ + this.tableName=tableName; + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ModelTemp.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/ModelTemp.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ModelTemp.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/ModelTemp.java index 404370d71..9e7889f4c 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ModelTemp.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/ModelTemp.java @@ -1,160 +1,160 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -import org.javatuples.Triplet; - -public class ModelTemp implements Serializable { - - private static final long serialVersionUID = 1L; - - public String id; - public String absPath; - public String parentAbsPath; - public String pathRelativeToRunDir; //processed - - public ArrayList itemList; - public ArrayList itemTypeList; - public ArrayList svIncFileList; // processed - public ArrayList svIncFileList_post; // post processed - - public ArrayList asIncFileList; // processed - public ArrayList asIncFileList_post; // post processed - - public ArrayList exIncFileList; // processed - public ArrayList exIncFileList_post; // post processed - - public ArrayList dvIncFileList; // processed - public ArrayList dvIncFileList_post; // post processed - - public ArrayList glIncFileList; // processed - public ArrayList glIncFileList_post; // post processed - - // - //public ArrayList> t_svList; // processed - //public ArrayList> t_svList_post; // post processed - - //TODO: use more compact storage. i.e., Map - // then converts to Map - - public ArrayList incFileIDList; - public ArrayList incFileRelativePathList; // processed - public ArrayList incFileRelativePathList_post; // post processed - public ArrayList incFileAbsPathList; // processed - public ArrayList incFileAbsPathList_post; // post processed - public Map incFileMap; - - public ArrayList ifIncItemGroupIDList; - public Map ifIncItemGroupMap; - - public ArrayList incModelList; - - public ArrayList wvList_post; // added after processed - public ArrayList wTableObjList; // raw data - public ArrayList asList_backup; // backup raw lowercased - public ArrayList asList; - //public ArrayList asList_reduced; // added after processed - public LinkedHashMap asMap; - public ArrayList svList; - public Map svMap; - public ArrayList dvList; - public Map dvMap; - public ArrayList dvList_fromAlias; // processed - public ArrayList dvList_deviationSlackSurplus; // give warning or error if greater than a tolerance - public Map deviationSlackSurplus_toleranceMap; // < deviationSS, tolerance> - public ArrayList tsList; - public Map tsMap; - public ArrayList exList; - public Map exMap; - public ArrayList glList_backup; - public ArrayList glList; - public Map glMap; - public ArrayList gl2List; - public ArrayList glList_fromAlias; // processed - public ArrayList ssList_hasCase; // processed - public Map ssMap_hasCase; // processed - public Map ssWeightMap_hasCase; // processed - public ArrayList ssList_noCase; // processed - public Map ssMap_noCase; // processed - public Map ssWeightMap_noCase; // processed - - public Map groupWeightMap; // processed - - public Map> neededCycleVarMap; - -// public Set varUsedByLaterCycle; -// public Set dvarUsedByLaterCycle; -// public Set svarUsedByLaterCycle; -// public Set aliasUsedByLaterCycle; - - public ModelTemp(){ - - //t_svList = new ArrayList>(); - //t_svList_post = new ArrayList>(); - itemList = new ArrayList(); - itemTypeList = new ArrayList(); - //svIncFileList = new ArrayList(); - svIncFileList_post = new ArrayList(); - asIncFileList_post = new ArrayList(); - exIncFileList_post = new ArrayList(); - dvIncFileList_post = new ArrayList(); - glIncFileList_post = new ArrayList(); - incFileIDList = new ArrayList(); - incFileRelativePathList = new ArrayList(); - incFileRelativePathList_post = new ArrayList(); - incFileAbsPathList = new ArrayList(); - incFileAbsPathList_post = new ArrayList(); - - incFileMap= new LinkedHashMap(); - - - ifIncItemGroupIDList = new ArrayList(); - ifIncItemGroupMap = new HashMap(); - - incModelList = new ArrayList(); - - wvList_post = new ArrayList(); // type obj - wTableObjList = new ArrayList(); - svList = new ArrayList(); //raw data - svMap = new HashMap(); // includes processed data - asList = new ArrayList(); - //asList_reduced = new ArrayList(); - asMap = new LinkedHashMap(); - dvList = new ArrayList(); - dvMap = new HashMap(); - dvList_fromAlias = new ArrayList(); - dvList_deviationSlackSurplus = new ArrayList(); - deviationSlackSurplus_toleranceMap = new HashMap(); - tsList = new ArrayList(); - tsMap = new HashMap(); - exList = new ArrayList(); - exMap = new HashMap(); - glList = new ArrayList(); - glMap = new HashMap(); - gl2List = new ArrayList(); - glList_fromAlias = new ArrayList(); - ssList_hasCase = new ArrayList(); - ssMap_hasCase = new LinkedHashMap(); - ssWeightMap_hasCase = new LinkedHashMap(); - ssList_noCase = new ArrayList(); - ssMap_noCase = new LinkedHashMap(); - ssWeightMap_noCase = new LinkedHashMap(); - - groupWeightMap = new HashMap(); - - neededCycleVarMap = new HashMap>(); - -// varUsedByLaterCycle = new HashSet(); -// dvarUsedByLaterCycle = new HashSet(); -// svarUsedByLaterCycle = new HashSet(); -// aliasUsedByLaterCycle = new HashSet(); - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import org.javatuples.Triplet; + +public class ModelTemp implements Serializable { + + private static final long serialVersionUID = 1L; + + public String id; + public String absPath; + public String parentAbsPath; + public String pathRelativeToRunDir; //processed + + public ArrayList itemList; + public ArrayList itemTypeList; + public ArrayList svIncFileList; // processed + public ArrayList svIncFileList_post; // post processed + + public ArrayList asIncFileList; // processed + public ArrayList asIncFileList_post; // post processed + + public ArrayList exIncFileList; // processed + public ArrayList exIncFileList_post; // post processed + + public ArrayList dvIncFileList; // processed + public ArrayList dvIncFileList_post; // post processed + + public ArrayList glIncFileList; // processed + public ArrayList glIncFileList_post; // post processed + + // + //public ArrayList> t_svList; // processed + //public ArrayList> t_svList_post; // post processed + + //TODO: use more compact storage. i.e., Map + // then converts to Map + + public ArrayList incFileIDList; + public ArrayList incFileRelativePathList; // processed + public ArrayList incFileRelativePathList_post; // post processed + public ArrayList incFileAbsPathList; // processed + public ArrayList incFileAbsPathList_post; // post processed + public Map incFileMap; + + public ArrayList ifIncItemGroupIDList; + public Map ifIncItemGroupMap; + + public ArrayList incModelList; + + public ArrayList wvList_post; // added after processed + public ArrayList wTableObjList; // raw data + public ArrayList asList_backup; // backup raw lowercased + public ArrayList asList; + //public ArrayList asList_reduced; // added after processed + public LinkedHashMap asMap; + public ArrayList svList; + public Map svMap; + public ArrayList dvList; + public Map dvMap; + public ArrayList dvList_fromAlias; // processed + public ArrayList dvList_deviationSlackSurplus; // give warning or error if greater than a tolerance + public Map deviationSlackSurplus_toleranceMap; // < deviationSS, tolerance> + public ArrayList tsList; + public Map tsMap; + public ArrayList exList; + public Map exMap; + public ArrayList glList_backup; + public ArrayList glList; + public Map glMap; + public ArrayList gl2List; + public ArrayList glList_fromAlias; // processed + public ArrayList ssList_hasCase; // processed + public Map ssMap_hasCase; // processed + public Map ssWeightMap_hasCase; // processed + public ArrayList ssList_noCase; // processed + public Map ssMap_noCase; // processed + public Map ssWeightMap_noCase; // processed + + public Map groupWeightMap; // processed + + public Map> neededCycleVarMap; + +// public Set varUsedByLaterCycle; +// public Set dvarUsedByLaterCycle; +// public Set svarUsedByLaterCycle; +// public Set aliasUsedByLaterCycle; + + public ModelTemp(){ + + //t_svList = new ArrayList>(); + //t_svList_post = new ArrayList>(); + itemList = new ArrayList(); + itemTypeList = new ArrayList(); + //svIncFileList = new ArrayList(); + svIncFileList_post = new ArrayList(); + asIncFileList_post = new ArrayList(); + exIncFileList_post = new ArrayList(); + dvIncFileList_post = new ArrayList(); + glIncFileList_post = new ArrayList(); + incFileIDList = new ArrayList(); + incFileRelativePathList = new ArrayList(); + incFileRelativePathList_post = new ArrayList(); + incFileAbsPathList = new ArrayList(); + incFileAbsPathList_post = new ArrayList(); + + incFileMap= new LinkedHashMap(); + + + ifIncItemGroupIDList = new ArrayList(); + ifIncItemGroupMap = new HashMap(); + + incModelList = new ArrayList(); + + wvList_post = new ArrayList(); // type obj + wTableObjList = new ArrayList(); + svList = new ArrayList(); //raw data + svMap = new HashMap(); // includes processed data + asList = new ArrayList(); + //asList_reduced = new ArrayList(); + asMap = new LinkedHashMap(); + dvList = new ArrayList(); + dvMap = new HashMap(); + dvList_fromAlias = new ArrayList(); + dvList_deviationSlackSurplus = new ArrayList(); + deviationSlackSurplus_toleranceMap = new HashMap(); + tsList = new ArrayList(); + tsMap = new HashMap(); + exList = new ArrayList(); + exMap = new HashMap(); + glList = new ArrayList(); + glMap = new HashMap(); + gl2List = new ArrayList(); + glList_fromAlias = new ArrayList(); + ssList_hasCase = new ArrayList(); + ssMap_hasCase = new LinkedHashMap(); + ssWeightMap_hasCase = new LinkedHashMap(); + ssList_noCase = new ArrayList(); + ssMap_noCase = new LinkedHashMap(); + ssWeightMap_noCase = new LinkedHashMap(); + + groupWeightMap = new HashMap(); + + neededCycleVarMap = new HashMap>(); + +// varUsedByLaterCycle = new HashSet(); +// dvarUsedByLaterCycle = new HashSet(); +// svarUsedByLaterCycle = new HashSet(); +// aliasUsedByLaterCycle = new HashSet(); + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/OutputUtils.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/OutputUtils.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/OutputUtils.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/OutputUtils.java index bb9bbe367..3a31fb9db 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/OutputUtils.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/OutputUtils.java @@ -1,42 +1,42 @@ -package wrimsv2.wreslplus.elements; - -import java.io.IOException; -import java.io.PrintWriter; - -public class OutputUtils { - - private static PrintWriter _outputFile; - - - public static void closeLogFile(){ - - _outputFile.close(); - } - - public static PrintWriter setLogFile(String parentDir, String logFileName){ - - try { - _outputFile = Tools.openFile(parentDir, logFileName); - - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - return _outputFile; - } - - public static PrintWriter setLogFile(String logFileName){ - - try { - _outputFile = Tools.openFile(System.getProperty("user.dir"), logFileName); - - } - catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - return _outputFile; - } -} - +package wrimsv2.wreslplus.elements; + +import java.io.IOException; +import java.io.PrintWriter; + +public class OutputUtils { + + private static PrintWriter _outputFile; + + + public static void closeLogFile(){ + + _outputFile.close(); + } + + public static PrintWriter setLogFile(String parentDir, String logFileName){ + + try { + _outputFile = Tools.openFile(parentDir, logFileName); + + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + return _outputFile; + } + + public static PrintWriter setLogFile(String logFileName){ + + try { + _outputFile = Tools.openFile(System.getProperty("user.dir"), logFileName); + + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + return _outputFile; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ParamTemp.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/ParamTemp.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ParamTemp.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/ParamTemp.java index c0c840c56..fd7e0dc5a 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ParamTemp.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/ParamTemp.java @@ -1,30 +1,30 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.LinkedHashSet; -import java.util.Set; - - - -public class ParamTemp implements Serializable { - - private static final long serialVersionUID = 1L; - - public String fromWresl; // for test only - public int line=1; - public String id; - public Set dependants; - public Set dependants_unknown; - - public String expression; - - - public ParamTemp(){ - - dependants = new LinkedHashSet(); - expression = ""; - - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.LinkedHashSet; +import java.util.Set; + + + +public class ParamTemp implements Serializable { + + private static final long serialVersionUID = 1L; + + public String fromWresl; // for test only + public int line=1; + public String id; + public Set dependants; + public Set dependants_unknown; + + public String expression; + + + public ParamTemp(){ + + dependants = new LinkedHashSet(); + expression = ""; + + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ParserUtils.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/ParserUtils.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ParserUtils.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/ParserUtils.java index d4868ddf9..91fe9927d 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/ParserUtils.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/ParserUtils.java @@ -1,189 +1,189 @@ -package wrimsv2.wreslplus.elements; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import org.antlr.runtime.ANTLRFileStream; -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CharStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; - -import wrimsv2.components.ControlData; -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslplus.elements.procedures.ErrorCheck; -import wrimsv2.wreslplus.elements.procedures.ProcIfIncItemGroup; -import wrimsv2.wreslplus.elements.procedures.ProcIncFile; -import wrimsv2.wreslplus.elements.procedures.ProcVarIncFileList; -import wrimsv2.wreslplus.elements.procedures.ToLowerCase; -import wrimsv2.wreslplus.grammar.WreslPlusLexer; -import wrimsv2.wreslplus.grammar.WreslPlusParser; - -public class ParserUtils { - - - - private ParserUtils(){} - - - public static WreslPlusParser initParser(String inputFilePath) throws RecognitionException { - - // inputFilePath should be checked and converted to CanonicalPath before this method - - CharStream stream; - - try { - stream = new ANTLRFileStream(inputFilePath, "UTF8"); - } - catch(Exception e) { - //e.printStackTrace(); - LogUtils.errMsg("File not found: "+ inputFilePath); - LogUtils.closeLogFile(); - return null; - } - - WreslPlusLexer lexer = new WreslPlusLexer(stream); - - TokenStream tokenStream = new CommonTokenStream(lexer); - - WreslPlusParser parser = new WreslPlusParser(tokenStream); - - //parser.currentAbsolutePath = new File(inputFilePath).getAbsolutePath(); - //parser.currentAbsoluteParent = new File(inputFilePath).getAbsoluteFile().getParent(); - - // TODO: lowercase conversion is used to ignore the mismatched include wresl file path and the actual path of the study. - - try { - parser.currentAbsolutePath = new File(inputFilePath).getCanonicalPath().toLowerCase(); - parser.currentAbsoluteParent = new File(inputFilePath).getCanonicalFile().getParent().toLowerCase(); - } - catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - parser.pathRelativeToRunDir = ResourceUtils.getRelativePath(parser.currentAbsolutePath, GlobalData.runDir, File.separator); - - if (ControlData.isParseStudy) LogUtils.importantMsg("Parsing file: "+parser.currentAbsolutePath); - - return parser; - - } - - - public static StudyTemp parseWreslMain(String inputFilePath) { - - - WreslPlusParser parser = null; - - try { - parser = initParser(inputFilePath); - parser.wreslMain(); - } - catch (RecognitionException e) { - - e.printStackTrace(); - } - - parser.styObj.absPath = parser.currentAbsolutePath; - parser.styObj.relativePath = parser.pathRelativeToRunDir; - parser.styObj.runDir = parser.currentAbsoluteParent; - - return parser.styObj; - - } - - - public static ModelTemp parseWreslFile(String inputFilePath) { - - - WreslPlusParser parser = null; - - try { - parser = initParser(inputFilePath); - parser.wreslFile(); - if (parser.number_of_errors>0) return null; - } - catch (RecognitionException e) { - - e.printStackTrace(); - } - - return parser.mObj; - - } - - - public static void parseAllIncFile(ArrayList relativePathList , StudyTemp st) { - - for (String relativePath: relativePathList){ - - //ModelTemp fm = null; - - if (!st.fileModelNameMap.keySet().contains(relativePath)){ - - String absPath = Tools.getCanonicalLowCasePath(new File(st.runDir, relativePath).getAbsolutePath()); - ModelTemp fm = parseWreslFile(absPath); - - if (fm==null) continue; - - ToLowerCase.convert(fm); - - ErrorCheck.checkVarRedefined(fm, st); - - // check unknown dependants in if statement - ErrorCheck.checkIfStatementHasUnknownDependants(fm, st.parameterMap.keySet()); - - // process "if include file group" - ProcIfIncItemGroup.process(fm); - - - ProcIncFile.processPath(fm); - ProcVarIncFileList.replaceIncFile(fm,null); - Procedures.processDependants(fm); - -// SerialXml.writeModelTemp(fm, absPath+".x"); -// ModelTemp fm = SerialXml.readModelTemp(absPath+".x"); - - // TODO: allow multiple models in a file - String modelName = fm.id.toLowerCase(); - //System.out.println("err: modelName: "+fm.id); - ArrayList modelNameList = new ArrayList(); - modelNameList.add(modelName); - - st.fileModelNameMap.put(relativePath, modelNameList); - - st.fileModelDataTable.put(relativePath, modelName, fm); - - // parse all included files within files - parseAllIncFile(fm.incFileRelativePathList, st); - - } - - } - - } - - - public static void setRunDir(String runDir){ - - GlobalData.runDir = Tools.getCanonicalLowCasePath(runDir);; - } - - - public static WreslPlusParser initParserSimple(String text) throws RecognitionException { - - ANTLRStringStream stream = new ANTLRStringStream(text); - WreslPlusLexer lexer = new WreslPlusLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - WreslPlusParser parser = new WreslPlusParser(tokenStream); - - return parser; - - } - - - -} - +package wrimsv2.wreslplus.elements; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import org.antlr.runtime.ANTLRFileStream; +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CharStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.TokenStream; + +import wrimsv2.components.ControlData; +import wrimsv2.wreslparser.elements.LogUtils; +import wrimsv2.wreslplus.elements.procedures.ErrorCheck; +import wrimsv2.wreslplus.elements.procedures.ProcIfIncItemGroup; +import wrimsv2.wreslplus.elements.procedures.ProcIncFile; +import wrimsv2.wreslplus.elements.procedures.ProcVarIncFileList; +import wrimsv2.wreslplus.elements.procedures.ToLowerCase; +import wrimsv2.wreslplus.grammar.WreslPlusLexer; +import wrimsv2.wreslplus.grammar.WreslPlusParser; + +public class ParserUtils { + + + + private ParserUtils(){} + + + public static WreslPlusParser initParser(String inputFilePath) throws RecognitionException { + + // inputFilePath should be checked and converted to CanonicalPath before this method + + CharStream stream; + + try { + stream = new ANTLRFileStream(inputFilePath, "UTF8"); + } + catch(Exception e) { + //e.printStackTrace(); + LogUtils.errMsg("File not found: "+ inputFilePath); + LogUtils.closeLogFile(); + return null; + } + + WreslPlusLexer lexer = new WreslPlusLexer(stream); + + TokenStream tokenStream = new CommonTokenStream(lexer); + + WreslPlusParser parser = new WreslPlusParser(tokenStream); + + //parser.currentAbsolutePath = new File(inputFilePath).getAbsolutePath(); + //parser.currentAbsoluteParent = new File(inputFilePath).getAbsoluteFile().getParent(); + + // TODO: lowercase conversion is used to ignore the mismatched include wresl file path and the actual path of the study. + + try { + parser.currentAbsolutePath = new File(inputFilePath).getCanonicalPath().toLowerCase(); + parser.currentAbsoluteParent = new File(inputFilePath).getCanonicalFile().getParent().toLowerCase(); + } + catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + parser.pathRelativeToRunDir = ResourceUtils.getRelativePath(parser.currentAbsolutePath, GlobalData.runDir, File.separator); + + if (ControlData.isParseStudy) LogUtils.importantMsg("Parsing file: "+parser.currentAbsolutePath); + + return parser; + + } + + + public static StudyTemp parseWreslMain(String inputFilePath) { + + + WreslPlusParser parser = null; + + try { + parser = initParser(inputFilePath); + parser.wreslMain(); + } + catch (RecognitionException e) { + + e.printStackTrace(); + } + + parser.styObj.absPath = parser.currentAbsolutePath; + parser.styObj.relativePath = parser.pathRelativeToRunDir; + parser.styObj.runDir = parser.currentAbsoluteParent; + + return parser.styObj; + + } + + + public static ModelTemp parseWreslFile(String inputFilePath) { + + + WreslPlusParser parser = null; + + try { + parser = initParser(inputFilePath); + parser.wreslFile(); + if (parser.number_of_errors>0) return null; + } + catch (RecognitionException e) { + + e.printStackTrace(); + } + + return parser.mObj; + + } + + + public static void parseAllIncFile(ArrayList relativePathList , StudyTemp st) { + + for (String relativePath: relativePathList){ + + //ModelTemp fm = null; + + if (!st.fileModelNameMap.keySet().contains(relativePath)){ + + String absPath = Tools.getCanonicalLowCasePath(new File(st.runDir, relativePath).getAbsolutePath()); + ModelTemp fm = parseWreslFile(absPath); + + if (fm==null) continue; + + ToLowerCase.convert(fm); + + ErrorCheck.checkVarRedefined(fm, st); + + // check unknown dependants in if statement + ErrorCheck.checkIfStatementHasUnknownDependants(fm, st.parameterMap.keySet()); + + // process "if include file group" + ProcIfIncItemGroup.process(fm); + + + ProcIncFile.processPath(fm); + ProcVarIncFileList.replaceIncFile(fm,null); + Procedures.processDependants(fm); + +// SerialXml.writeModelTemp(fm, absPath+".x"); +// ModelTemp fm = SerialXml.readModelTemp(absPath+".x"); + + // TODO: allow multiple models in a file + String modelName = fm.id.toLowerCase(); + //System.out.println("err: modelName: "+fm.id); + ArrayList modelNameList = new ArrayList(); + modelNameList.add(modelName); + + st.fileModelNameMap.put(relativePath, modelNameList); + + st.fileModelDataTable.put(relativePath, modelName, fm); + + // parse all included files within files + parseAllIncFile(fm.incFileRelativePathList, st); + + } + + } + + } + + + public static void setRunDir(String runDir){ + + GlobalData.runDir = Tools.getCanonicalLowCasePath(runDir);; + } + + + public static WreslPlusParser initParserSimple(String text) throws RecognitionException { + + ANTLRStringStream stream = new ANTLRStringStream(text); + WreslPlusLexer lexer = new WreslPlusLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + WreslPlusParser parser = new WreslPlusParser(tokenStream); + + return parser; + + } + + + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/Procedures.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/Procedures.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/Procedures.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/Procedures.java index 26a547756..f53ae77e3 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/Procedures.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/Procedures.java @@ -1,968 +1,968 @@ -package wrimsv2.wreslplus.elements; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.components.ControlData; -import wrimsv2.components.IntDouble; -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslplus.elements.procedures.ErrorCheck; - -public class Procedures { - - private Procedures() { - } - - public static void processDependants(StudyTemp s) { - - for (String m : s.modelList_effective) { - - ModelTemp mObj = s.modelMap.get(m); - - processDependants(mObj); - - } - - for (String m : s.incModelList_effective) { - - ModelTemp mObj = s.modelMap.get(m); - - processDependants(mObj); - - } - - } - - public static void processDependants(ModelTemp mObj) { - - for (String key : mObj.svMap.keySet()) { - - SvarTemp svObj = mObj.svMap.get(key); - - svObj.dependants.removeAll(Param.reservedSet); - } - - for (String key : mObj.glMap.keySet()) { - - GoalTemp svObj = mObj.glMap.get(key); - - svObj.dependants.removeAll(Param.reservedSet); - - } - - for (String key : mObj.asMap.keySet()) { - - AliasTemp asObj = mObj.asMap.get(key); - - asObj.dependants.removeAll(Param.reservedSet); - - } - - } - - public static boolean copyModelVarMapToSequenceVarMap(StudyTemp st) { - - boolean hasError = false; - - - for (String seqName : st.seqList) { - - SequenceTemp seqObj = st.seqMap.get(seqName); - ModelTemp seqModelObj = st.modelMap.get(seqObj.model); - - seqObj.svIncFileList_post = seqModelObj.svIncFileList_post; - seqObj.asIncFileList_post = seqModelObj.asIncFileList_post; - seqObj.exIncFileList_post = seqModelObj.exIncFileList_post; - seqObj.dvIncFileList_post = seqModelObj.dvIncFileList_post; - seqObj.glIncFileList_post = seqModelObj.glIncFileList_post; - seqObj.incFileAbsPathList_post = seqModelObj.incFileAbsPathList_post; - seqObj.incFileRelativePathList_post = seqModelObj.incFileRelativePathList_post; - - if (st.allOffspringMap_incModel.keySet().contains(seqObj.model)) { - for (String f: st.allOffspringMap_incModel.get(seqObj.model)) { - - ModelTemp incModel = st.modelMap.get(f); - - - if(copyModelVarMapToSequenceVarMap(incModel, seqObj)) return true; - - - } - } - - - for (String f: seqModelObj.incFileRelativePathList_post){ - - ModelTemp incModel = st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)); - - if (copyModelVarMapToSequenceVarMap(incModel, seqObj)) return true; - - } - - if (copyModelVarMapToSequenceVarMap(seqModelObj, seqObj)) return true; - - - // check redefinition of Goal - if (ErrorCheck.findDuplicatesIgnoreCase(seqObj.glList).size()>0){ - - String glName = ErrorCheck.findDuplicatesIgnoreCase(seqObj.glList).get(0); - GoalTemp glObj_seq = seqObj.glMap.get(glName); - String msg = "Goal ["+glName+"] is redefined in Cycle ["+ seqObj.id +"]"; - LogUtils.errMsgLocation(glObj_seq.fromWresl, glObj_seq.line, msg); - - hasError = true; - //return hasError; - - } - - // check redefinition of Svar - if (ErrorCheck.findDuplicatesIgnoreCase(seqObj.svIncFileList_post).size()>0){ - - String svName = ErrorCheck.findDuplicatesIgnoreCase(seqObj.svIncFileList_post).get(0); - SvarTemp svObj_seq = seqObj.svMap.get(svName); - String msg = "Svar ["+svName+"] is redefined in Cycle ["+ seqObj.id +"]"; - LogUtils.errMsgLocation(svObj_seq.fromWresl, svObj_seq.line, msg); - - hasError = true; - //return hasError; - - } - - // check redefinition of Dvar - if (ErrorCheck.findDuplicatesIgnoreCase(seqObj.dvList).size()>0){ - - String dvName = ErrorCheck.findDuplicatesIgnoreCase(seqObj.dvList).get(0); - DvarTemp dvObj_seq = seqObj.dvMap.get(dvName); - String msg = "Dvar ["+dvName+"] is redefined in Cycle ["+ seqObj.id +"]"; - LogUtils.errMsgLocation(dvObj_seq.fromWresl, dvObj_seq.line, msg); - - hasError = true; - //return hasError; - - } - - // check redefinition of Alias - if (ErrorCheck.findDuplicatesIgnoreCase(seqObj.asList).size()>0){ - - String asName = ErrorCheck.findDuplicatesIgnoreCase(seqObj.asList).get(0); - AliasTemp asObj_seq = seqObj.asMap.get(asName); - String msg = "Alias ["+asName+"] is redefined in Cycle ["+ seqObj.id +"]"; - LogUtils.errMsgLocation(asObj_seq.fromWresl, asObj_seq.line, msg); - - hasError = true; - //return hasError; - - } - - // check redefinition of Timeseries - if (ErrorCheck.findDuplicatesIgnoreCase(seqObj.tsList).size()>0){ - - String tsName = ErrorCheck.findDuplicatesIgnoreCase(seqObj.tsList).get(0); - TimeseriesTemp tsObj_seq = seqObj.tsMap.get(tsName); - String msg = "Timeseries ["+tsName+"] is redefined in Cycle ["+ seqObj.id +"]"; - LogUtils.errMsgLocation(tsObj_seq.fromWresl, tsObj_seq.line, msg); - - hasError = true; - //return hasError; - - } - - // check redefinition of vars - if (!hasError) { - - ArrayList allVars = new ArrayList(); - allVars.addAll(seqObj.glList); - allVars.addAll(seqObj.svIncFileList_post); - allVars.addAll(seqObj.dvList); - allVars.addAll(seqObj.asList); - allVars.addAll(seqObj.tsList); - - if (ErrorCheck.findDuplicatesIgnoreCase(allVars).size() > 0) { - - String name = ErrorCheck.findDuplicatesIgnoreCase(allVars).get(0); - String msg = "Dvar, Svar, Timeseries, Alias, or Goal label [" + name + "] is redefined in Cycle [" + seqObj.id + "]"; - LogUtils.errMsg(msg); - - hasError = true; - // return hasError; - - } - - } - } - - - return hasError; - } - - public static boolean copyModelVarMapToSequenceVarMap(ModelTemp mt, SequenceTemp seq) { - - boolean hasError = false; - - for (String cycleName: mt.neededCycleVarMap.keySet()){ - - if (seq.neededCycleVarMap.containsKey(cycleName)){ - - seq.neededCycleVarMap.get(cycleName).addAll(mt.neededCycleVarMap.get(cycleName)); - } - else { - seq.neededCycleVarMap.put(cycleName, mt.neededCycleVarMap.get(cycleName)); - } - } - - seq.wvList.addAll(mt.wvList_post); - seq.wTableObjList.addAll(mt.wTableObjList); - seq.exList.addAll(mt.exList); - seq.dvList.addAll(mt.dvList); - seq.dvList_deviationSlackSurplus.addAll(mt.dvList_deviationSlackSurplus); - seq.deviationSlackSurplus_toleranceMap.putAll(mt.deviationSlackSurplus_toleranceMap); - - seq.asList.addAll(mt.asList); - seq.glList.addAll(mt.glList); - - // check redefined goal - // TODO: provide option to turn on or off - if (false) { - if (ErrorCheck.findDuplicatesIgnoreCase(seq.glList).size() > 0) { - - String glName = ErrorCheck.findDuplicatesIgnoreCase(seq.glList).get(0); - GoalTemp glObj_mt = mt.glMap.get(glName); - String msg = "Goal [" + glName + "] is redefined in Cycle [" + seq.id + "]"; - LogUtils.errMsgLocation(glObj_mt.fromWresl, glObj_mt.line, msg); - - GoalTemp glObj_seq = seq.glMap.get(glName); - LogUtils.errMsgLocation(glObj_seq.fromWresl, glObj_seq.line, msg); - - hasError = true; - return hasError; - - } - } - - seq.gl2List.addAll(mt.gl2List); - seq.tsList.addAll(mt.tsList); - - seq.ssList_hasCase.addAll(mt.ssList_hasCase); - seq.ssList_noCase.addAll(mt.ssList_noCase); - - - seq.svMap.putAll(mt.svMap); - seq.dvMap.putAll(mt.dvMap); - seq.asMap.putAll(mt.asMap); - seq.glMap.putAll(mt.glMap); - seq.exMap.putAll(mt.exMap); - seq.tsMap.putAll(mt.tsMap); - - - seq.ssMap_hasCase.putAll(mt.ssMap_hasCase); - seq.ssWeightMap_hasCase.putAll(mt.ssWeightMap_hasCase); - seq.ssMap_noCase.putAll(mt.ssMap_noCase); - seq.ssWeightMap_noCase.putAll(mt.ssWeightMap_noCase); - - seq.groupWeightMap.putAll(mt.groupWeightMap); - - return hasError; - } - - public static void convertAliasToGoal(StudyTemp s) { - - - for (String se : s.seqList){ - - SequenceTemp seqObj = s.seqMap.get(se); - - convertAliasToGoal(seqObj); - - } - - } - - public static void convertAliasToGoal(SequenceTemp seqObj) { - - Set allDepInGoals = new HashSet(); - - // add all dep from Goal - for (String key : seqObj.glMap.keySet()) { - - GoalTemp g = seqObj.glMap.get(key); - allDepInGoals.addAll(g.dependants); - allDepInGoals.retainAll(seqObj.asList); - } - - // TODO: slow algorithm. need to improve. - - boolean hasNewItem = true; - HashSet t; - - while (hasNewItem) { - - t = new HashSet(); - - for (String key : allDepInGoals) { - - AliasTemp a = seqObj.asMap.get(key); - - t.addAll(a.dependants); - } - - t.removeAll(allDepInGoals); - t.retainAll(seqObj.asList); - allDepInGoals.addAll(t); - - hasNewItem = t.size()>0 ; - } - - // TODO: provide option for sending all alias to goal and dvar - // so that non-unique solution analysis can work with alias vars - for (String aKey : seqObj.asMap.keySet()) { - - if (allDepInGoals.contains(aKey)) { - - AliasTemp a = seqObj.asMap.get(aKey); - //System.out.println(aKey+":"+a.noSolver); - if (!a.noSolver){ - - a.isMovedToDvar = true; - - // add to dvar - DvarTemp d = new DvarTemp(); - d.id = a.id; - d.upperBound = Param.upper_unbounded; - d.lowerBound = Param.lower_unbounded; - d.kind = a.kind; - d.units = a.units; - d.fromWresl = a.fromWresl; - d.condition = a.condition; - d.isFromAlias = true; - d.timeArraySize = a.timeArraySize; - d.line=a.line; - - seqObj.asList.remove(aKey); - seqObj.asIncFileList_post.remove(aKey); - seqObj.dvList_fromAlias.add(aKey); - //seqObj.dvList.add(aKey); - seqObj.dvMap.put(aKey, d); - - // add goal - GoalTemp g = new GoalTemp(); - g.isFromAlias=true; - g.fromWresl = a.fromWresl; - g.id = a.id + "__alias"; - // String e = a.id.toLowerCase() + "=" + a.expression; - if (a.timeArraySize.equals("0")){ - g.caseExpression.add(a.id.toLowerCase() + "=" + a.expression); - }else{ - g.caseExpression.add(a.id.toLowerCase()+"($m)" + "=" + a.expression); - } - g.condition = a.condition; - g.caseName.add(Param.defaultCaseName); - g.caseCondition.add(Param.always); - g.dependants = a.dependants; - g.timeArraySize = a.timeArraySize; - g.line=a.line; - - seqObj.glList_fromAlias.add(g.id.toLowerCase()); - //seqObj.glList.add(g.id.toLowerCase()); - seqObj.glMap.put(g.id.toLowerCase(), g); - } - - } - - } - - } - - - public static void postProcessIncFileList(StudyTemp st) { - - // use the fileGroupOrder - for (HashSet fgroup: st.fileGroupOrder){ - - for ( String f : fgroup){ - - if (!st.allOffspringMap.keySet().contains(f)) continue; // TODO: the whole first round can be skipped - - - //Pair p = new Pair(f, st.fileModelNameMap.get(f).get(0)); - - //ModelTemp m = st.fileModelDataMap.get(p); - ModelTemp m = st.fileModelDataTable.get(f,st.fileModelNameMap.get(f).get(0)); - ArrayList list_post1 = m.incFileAbsPathList_post; - ArrayList list_post2 = m.incFileRelativePathList_post; - final ArrayList checkList = new ArrayList(m.incFileRelativePathList_post); - - - for( String includedFile: st.allOffspringMap.get(f)){ - int index =checkList.indexOf(includedFile); - - - //Pair p2 = new Pair(includedFile, st.fileModelNameMap.get(includedFile).get(0)); - - //ModelTemp includedModel = st.fileModelDataMap.get(p2); - if (index>-1) { - ModelTemp includedModel = st.fileModelDataTable.get(includedFile, st.fileModelNameMap.get(includedFile).get(0)); - - - list_post1.addAll(index+1, includedModel.incFileAbsPathList_post); - list_post2.addAll(index+1, includedModel.incFileRelativePathList_post); - } - } - } - } - - // process the main file includes - // TODO: replace effective list with seq. - for (String fi : st.modelList_effective){ - - ModelTemp m = st.modelMap.get(fi); - - for (String includedFile: m.incFileRelativePathList ){ - - int index = m.incFileRelativePathList.indexOf(includedFile); - - //Pair p2 = new Pair(includedFile, st.fileModelNameMap.get(includedFile).get(0)); - - //ModelTemp includedModel = st.fileModelDataMap.get(p2); - - ModelTemp includedModel = st.fileModelDataTable.get(includedFile, st.fileModelNameMap.get(includedFile).get(0)); - - m.incFileRelativePathList_post.addAll(index+1, includedModel.incFileRelativePathList_post); - m.incFileAbsPathList_post.addAll(index+1, includedModel.incFileAbsPathList_post); - - - } - } - } - - public static void findKidMap(StudyTemp st) { - - for (String f: st.fileModelNameMap.keySet()){ - - String modelName = st.fileModelNameMap.get(f).get(0); - - ArrayList kids = st.fileModelDataTable.get(f,modelName).incFileRelativePathList; - - if (kids==null){ - st.noKid.add(f); - } else if (kids.isEmpty()){ - st.noKid.add(f); - } else { - //st.kidssMap.put(f, modelName, new HashSet(kids)); - st.kidMap.put(f, new HashSet(kids)); - } - - } - - } - - public static void findAllOffSpring(StudyTemp st) { - - - for (String f: st.kidMap.keySet()) { - - HashSet a = Tools.findAllOffspring(f, st.kidMap); - - st.allOffspringMap.put(f, a); - - } - - } - - public static void findFileGroupOrder(StudyTemp st) { - - Map> toBeSorted = new HashMap>(st.allOffspringMap); - - ///// skip mainFile - toBeSorted.remove(st.relativePath); - - //System.out.println("st.noKid"+st.noKid); - st.fileGroupOrder.add(st.noKid); - - - Tools.findFileHierarchy(st.fileGroupOrder, toBeSorted); - - } - - - // replace file with vars - public static void postProcessVarListinIncFile(StudyTemp st) { - - // use the fileGroupOrder - for (HashSet fgroup: st.fileGroupOrder){ - - for ( String f : fgroup){ - - if (!st.allOffspringMap.keySet().contains(f)) continue; // TODO: the whole first round can be skipped - - String modelName = st.fileModelNameMap.get(f).get(0); - - ModelTemp m = st.fileModelDataTable.get(f,modelName); - - for( String includedFile: st.allOffspringMap.get(f)){ - - int index =m.svIncFileList_post.indexOf(includedFile); - - if (index>-1) { - m.svIncFileList_post.remove(index); - - //Pair p2 = new Pair(includedFile, st.fileModelNameMap.get(includedFile).get(0)); - - ModelTemp includedModel = st.fileModelDataTable.get(includedFile,st.fileModelNameMap.get(includedFile).get(0)); - m.svIncFileList_post.addAll(index, includedModel.svIncFileList_post); - //m.dvList.addAll(includedModel.dvList); - m.ssList_noCase.addAll(includedModel.ssList_noCase); - m.ssList_hasCase.addAll(includedModel.ssList_hasCase); - - } - - // process alias - index =m.asIncFileList_post.indexOf(includedFile); - - if (index > -1) { - - m.asIncFileList_post.remove(index); - ModelTemp includedModel = st.fileModelDataTable.get(includedFile, - st.fileModelNameMap.get(includedFile).get(0)); - m.asIncFileList_post.addAll(index, includedModel.asIncFileList_post); - - } - - // process external - index =m.exIncFileList_post.indexOf(includedFile); - - if (index > -1) { - - m.exIncFileList_post.remove(index); - ModelTemp includedModel = st.fileModelDataTable.get(includedFile, - st.fileModelNameMap.get(includedFile).get(0)); - m.exIncFileList_post.addAll(index, includedModel.exIncFileList_post); - - } - - // process dv - index =m.dvIncFileList_post.indexOf(includedFile); - - if (index > -1) { - - m.dvIncFileList_post.remove(index); - ModelTemp includedModel = st.fileModelDataTable.get(includedFile, - st.fileModelNameMap.get(includedFile).get(0)); - m.dvIncFileList_post.addAll(index, includedModel.dvIncFileList_post); - - } - - // process gl - index =m.glIncFileList_post.indexOf(includedFile); - - if (index > -1) { - - m.glIncFileList_post.remove(index); - ModelTemp includedModel = st.fileModelDataTable.get(includedFile, - st.fileModelNameMap.get(includedFile).get(0)); - m.glIncFileList_post.addAll(index, includedModel.glIncFileList_post); - - } - - } - } - } - - // process the main file except the first model includes - ArrayList ttt = new ArrayList(st.modelList_effective); - - for (String modelNameOfMain : ttt){ - - ModelTemp m = st.modelMap.get(modelNameOfMain); - - - for (String includedFile: m.incFileRelativePathList ){ - - int index = m.svIncFileList_post.indexOf(includedFile); - - - if (index>-1) { - - String modelName = st.fileModelNameMap.get(includedFile).get(0); - - //Pair p = new Pair(includedFile, modelName); - - ModelTemp includedModel = st.fileModelDataTable.get(includedFile,modelName); - - - - m.svIncFileList_post.remove(index); - - m.svIncFileList_post.addAll(index, includedModel.svIncFileList_post); - //m.dvList.addAll(includedModel.dvList); - m.ssList_noCase.addAll(includedModel.ssList_noCase); - m.ssList_hasCase.addAll(includedModel.ssList_hasCase); - } - - // process alias - index = m.asIncFileList_post.indexOf(includedFile); - - if (index > -1) { - - String modelName = st.fileModelNameMap.get(includedFile).get(0); - - ModelTemp includedModel = st.fileModelDataTable.get(includedFile, modelName); - m.asIncFileList_post.remove(index); - m.asIncFileList_post.addAll(index, includedModel.asIncFileList_post); - } - - // process external - index = m.exIncFileList_post.indexOf(includedFile); - - if (index > -1) { - - String modelName = st.fileModelNameMap.get(includedFile).get(0); - - ModelTemp includedModel = st.fileModelDataTable.get(includedFile, modelName); - m.exIncFileList_post.remove(index); - m.exIncFileList_post.addAll(index, includedModel.exIncFileList_post); - } - - // process dv - index = m.dvIncFileList_post.indexOf(includedFile); - - if (index > -1) { - - String modelName = st.fileModelNameMap.get(includedFile).get(0); - - ModelTemp includedModel = st.fileModelDataTable.get(includedFile, modelName); - m.dvIncFileList_post.remove(index); - m.dvIncFileList_post.addAll(index, includedModel.dvIncFileList_post); - } - - // process gl - index = m.glIncFileList_post.indexOf(includedFile); - - if (index > -1) { - - String modelName = st.fileModelNameMap.get(includedFile).get(0); - - ModelTemp includedModel = st.fileModelDataTable.get(includedFile, modelName); - m.glIncFileList_post.remove(index); - m.glIncFileList_post.addAll(index, includedModel.glIncFileList_post); - } - } - } - } - - // TODO: this process alias only. need to expand to other types - public static void classifyDependants(StudyTemp s) { - - for (String se : s.seqList){ - - SequenceTemp seqObj = s.seqMap.get(se); - - //ModelTemp mObj = s.modelMap.get(m); - - classifyDependants(seqObj, s.parameterList); - } - } - public static void classifyDependants(SequenceTemp seqObj, ArrayList parameterList) { - - for (String key : seqObj.asMap.keySet()) { - - AliasTemp asObj = seqObj.asMap.get(key); - - //if (asObj.isProcessed) continue; - - Set temp = new HashSet(asObj.dependants); - - asObj.dependants_timeseries = new LinkedHashSet(asObj.dependants); - asObj.dependants_timeseries.retainAll(seqObj.tsList); - temp.removeAll(asObj.dependants_timeseries); - - - asObj.dependants_dvar = new LinkedHashSet(temp); - asObj.dependants_dvar.retainAll(seqObj.dvList); - temp.removeAll(asObj.dependants_dvar); - - asObj.dependants_svar = new LinkedHashSet(temp); - asObj.dependants_svar.retainAll(seqObj.svMap.keySet()); - temp.removeAll(asObj.dependants_svar); - - asObj.dependants_alias = new LinkedHashSet(temp); - asObj.dependants_alias.retainAll(seqObj.asMap.keySet()); - temp.removeAll(asObj.dependants_alias); - - asObj.dependants_parameter = new LinkedHashSet(temp); - asObj.dependants_parameter.retainAll(parameterList); - temp.removeAll(asObj.dependants_parameter); - -// asObj.dependants_unknown = temp; -// asObj.dependants_unknown.removeAll(asObj.dependants_timeseries); -// asObj.dependants_unknown.removeAll(asObj.dependants_dvar); -// asObj.dependants_unknown.removeAll(asObj.dependants_svar); -// asObj.dependants_unknown.removeAll(asObj.dependants_alias); -// asObj.dependants_unknown.removeAll(asObj.dependants_parameter); - - - // TODO: this is to match legacy wresl parser - asObj.dependants.removeAll(asObj.dependants_timeseries); - asObj.dependants.removeAll(asObj.dependants_dvar); - - //asObj.isProcessed = true; - } - - for (String key : seqObj.svMap.keySet()) { - - SvarTemp svObj = seqObj.svMap.get(key); - - //if (svObj.isProcessed) continue; - - Set temp = new HashSet(svObj.dependants); - - svObj.dependants_timeseries = new LinkedHashSet(svObj.dependants); - svObj.dependants_timeseries.retainAll(seqObj.tsList); - temp.removeAll(svObj.dependants_timeseries); - - svObj.dependants_alias = new LinkedHashSet(temp); - svObj.dependants_alias.retainAll(seqObj.asMap.keySet()); - temp.removeAll(svObj.dependants_alias); - - svObj.dependants_dvar = new LinkedHashSet(temp); - svObj.dependants_dvar.retainAll(seqObj.dvList); - temp.removeAll(svObj.dependants_dvar); - - svObj.dependants_svar = new LinkedHashSet(temp); - svObj.dependants_svar.retainAll(seqObj.svMap.keySet()); - temp.removeAll(svObj.dependants_svar); - - svObj.dependants_external = new LinkedHashSet(temp); - svObj.dependants_external.retainAll(seqObj.exList); - temp.removeAll(svObj.dependants_external); - - svObj.dependants_parameter = new LinkedHashSet(temp); - svObj.dependants_parameter.retainAll(parameterList); - temp.removeAll(svObj.dependants_parameter); - -// svObj.dependants_unknown = temp; -// svObj.dependants_unknown.removeAll(svObj.dependants_timeseries); -// svObj.dependants_unknown.removeAll(svObj.dependants_alias); -// svObj.dependants_unknown.removeAll(svObj.dependants_dvar); -// svObj.dependants_unknown.removeAll(svObj.dependants_svar); -// svObj.dependants_unknown.removeAll(svObj.dependants_external); -// svObj.dependants_unknown.removeAll(svObj.dependants_parameter); - - // TODO: this is to match legacy wresl parser - svObj.dependants.removeAll(svObj.dependants_timeseries); - svObj.dependants.removeAll(seqObj.dvList); - - //svObj.isProcessed = true; - } - - for (String key : seqObj.glMap.keySet()) { - - GoalTemp svObj = seqObj.glMap.get(key); - - //if (svObj.isProcessed) continue; - - //svObj.dependants.removeAll(seqObj.tsList); - //svObj.dependants.removeAll(seqObj.dvList); - - Set temp = new HashSet(svObj.dependants); - - svObj.dependants_timeseries = new LinkedHashSet(svObj.dependants); - svObj.dependants_timeseries.retainAll(seqObj.tsList); - temp.removeAll(svObj.dependants_timeseries); - - svObj.dependants_svar = new LinkedHashSet(temp); - svObj.dependants_svar.retainAll(seqObj.svMap.keySet()); - temp.removeAll(svObj.dependants_svar); - - svObj.dependants_dvar = new LinkedHashSet(temp); - svObj.dependants_dvar.retainAll(seqObj.dvList); - temp.removeAll(svObj.dependants_dvar); - - svObj.dependants_alias = new LinkedHashSet(temp); - svObj.dependants_alias.retainAll(seqObj.asMap.keySet()); - temp.removeAll(svObj.dependants_alias); - - svObj.dependants_external = new LinkedHashSet(temp); - svObj.dependants_external.retainAll(seqObj.exMap.keySet()); - temp.removeAll(svObj.dependants_external); - - svObj.dependants_parameter = new LinkedHashSet(temp); - svObj.dependants_parameter.retainAll(parameterList); - temp.removeAll(svObj.dependants_parameter); - -// svObj.dependants_unknown = temp; -// svObj.dependants_unknown.removeAll(svObj.dependants_timeseries); -// svObj.dependants_unknown.removeAll(svObj.dependants_svar); -// svObj.dependants_unknown.removeAll(svObj.dependants_dvar); -// svObj.dependants_unknown.removeAll(svObj.dependants_alias); -// svObj.dependants_unknown.removeAll(svObj.dependants_external); -// svObj.dependants_unknown.removeAll(svObj.dependants_parameter); - - //svObj.isProcessed = true; - - } - } - - - public static void analyzeVarNeededFromCycle(StudyTemp s){ - - for (String se : s.seqList){ - - SequenceTemp q = s.seqMap.get(se); - ArrayList others = new ArrayList(s.seqList); - others.remove(se); - - for (String o : others){ - - SequenceTemp otherSeq = s.seqMap.get(o); - - Set varSet = otherSeq.neededCycleVarMap.get(q.model); - - if (varSet != null) { - - q.varUsedByLaterCycle.addAll(varSet); - - for (String e : varSet) { - - if (q.asIncFileList_post.contains(e)) { - - q.aliasUsedByLaterCycle.add(e); - } - else if (q.dvList.contains(e)) { - - q.dvarUsedByLaterCycle.add(e); - } - else if (q.dvList_fromAlias.contains(e)) { - - q.dvarUsedByLaterCycle.add(e); - } - else if (q.svIncFileList_post.contains(e)) { - - q.svarUsedByLaterCycle.add(e); - } - else { - - // TODO: this variable is in a IF statement where condition is not satisfied therefore not exists in previous cycle - - //LogUtils.errMsg(" Unknown type of variable ["+ e +"] in ["+ se+": "+q.model +"] is used in ["+o+": "+otherSeq.model+"]"); - - } - } - } - - - } - - } - - } - - public static void createSpaceInVarCycleValueMap(StudyTemp s){ - - Map> vcv = s.varCycleValueMap; - - for (String seqName : s.seqList){ - - SequenceTemp q = s.seqMap.get(seqName); - - String modelName = q.model; - - for (String e : q.varUsedByLaterCycle) { - - // / create space in varCycleValue map - if (vcv.keySet().contains(e)) { - vcv.get(e).put(modelName, null); - } else { - Map t = new HashMap(); - t.put(modelName, null); - vcv.put(e, t); - } - } - - - - } - } - - public static void collectTimeStep(StudyTemp st) { - - for (String se : st.seqList){ - - SequenceTemp q = st.seqMap.get(se); - - // TODO: warning!!! need test - st.seqTimeStepList.add(q.timeStep); - - String timeStep=q.timeStep; - String definedTimeStep; - - if (timeStep.equals(Param.undefined)){ - definedTimeStep=ControlData.defaultTimeStep; - }else{ - definedTimeStep=timeStep; - } - - for (String timeseriesName : q.tsList) { - - if (st.timeseriesTimeStepMap.containsKey(timeseriesName)) { - - ArrayList timeStepList = st.timeseriesTimeStepMap.get(timeseriesName); - if (!timeStepList.contains(definedTimeStep)) { - timeStepList.add(definedTimeStep); - } - } - else { - st.timeseriesTimeStepMap.put(timeseriesName, new ArrayList(Arrays.asList(definedTimeStep))); - } - } - - } - - } - - public static int findWarmStart(int preStop, int nCyc) { - - for (int i=preStop+1; iParam.cbcMinIntNumber){ - return i; - } - } - return nCyc+1; - } - - - public static int findWarmStart(int preStop, int nCyc, StudyDataSet sd) { - - for (int i=preStop+1; iParam.cbcMinIntNumber){ - return i; - } - } - return nCyc+1; - } - - public static int findWarmStop(int start, int nCyc) { - for (int i=start; i0){ + + String glName = ErrorCheck.findDuplicatesIgnoreCase(seqObj.glList).get(0); + GoalTemp glObj_seq = seqObj.glMap.get(glName); + String msg = "Goal ["+glName+"] is redefined in Cycle ["+ seqObj.id +"]"; + LogUtils.errMsgLocation(glObj_seq.fromWresl, glObj_seq.line, msg); + + hasError = true; + //return hasError; + + } + + // check redefinition of Svar + if (ErrorCheck.findDuplicatesIgnoreCase(seqObj.svIncFileList_post).size()>0){ + + String svName = ErrorCheck.findDuplicatesIgnoreCase(seqObj.svIncFileList_post).get(0); + SvarTemp svObj_seq = seqObj.svMap.get(svName); + String msg = "Svar ["+svName+"] is redefined in Cycle ["+ seqObj.id +"]"; + LogUtils.errMsgLocation(svObj_seq.fromWresl, svObj_seq.line, msg); + + hasError = true; + //return hasError; + + } + + // check redefinition of Dvar + if (ErrorCheck.findDuplicatesIgnoreCase(seqObj.dvList).size()>0){ + + String dvName = ErrorCheck.findDuplicatesIgnoreCase(seqObj.dvList).get(0); + DvarTemp dvObj_seq = seqObj.dvMap.get(dvName); + String msg = "Dvar ["+dvName+"] is redefined in Cycle ["+ seqObj.id +"]"; + LogUtils.errMsgLocation(dvObj_seq.fromWresl, dvObj_seq.line, msg); + + hasError = true; + //return hasError; + + } + + // check redefinition of Alias + if (ErrorCheck.findDuplicatesIgnoreCase(seqObj.asList).size()>0){ + + String asName = ErrorCheck.findDuplicatesIgnoreCase(seqObj.asList).get(0); + AliasTemp asObj_seq = seqObj.asMap.get(asName); + String msg = "Alias ["+asName+"] is redefined in Cycle ["+ seqObj.id +"]"; + LogUtils.errMsgLocation(asObj_seq.fromWresl, asObj_seq.line, msg); + + hasError = true; + //return hasError; + + } + + // check redefinition of Timeseries + if (ErrorCheck.findDuplicatesIgnoreCase(seqObj.tsList).size()>0){ + + String tsName = ErrorCheck.findDuplicatesIgnoreCase(seqObj.tsList).get(0); + TimeseriesTemp tsObj_seq = seqObj.tsMap.get(tsName); + String msg = "Timeseries ["+tsName+"] is redefined in Cycle ["+ seqObj.id +"]"; + LogUtils.errMsgLocation(tsObj_seq.fromWresl, tsObj_seq.line, msg); + + hasError = true; + //return hasError; + + } + + // check redefinition of vars + if (!hasError) { + + ArrayList allVars = new ArrayList(); + allVars.addAll(seqObj.glList); + allVars.addAll(seqObj.svIncFileList_post); + allVars.addAll(seqObj.dvList); + allVars.addAll(seqObj.asList); + allVars.addAll(seqObj.tsList); + + if (ErrorCheck.findDuplicatesIgnoreCase(allVars).size() > 0) { + + String name = ErrorCheck.findDuplicatesIgnoreCase(allVars).get(0); + String msg = "Dvar, Svar, Timeseries, Alias, or Goal label [" + name + "] is redefined in Cycle [" + seqObj.id + "]"; + LogUtils.errMsg(msg); + + hasError = true; + // return hasError; + + } + + } + } + + + return hasError; + } + + public static boolean copyModelVarMapToSequenceVarMap(ModelTemp mt, SequenceTemp seq) { + + boolean hasError = false; + + for (String cycleName: mt.neededCycleVarMap.keySet()){ + + if (seq.neededCycleVarMap.containsKey(cycleName)){ + + seq.neededCycleVarMap.get(cycleName).addAll(mt.neededCycleVarMap.get(cycleName)); + } + else { + seq.neededCycleVarMap.put(cycleName, mt.neededCycleVarMap.get(cycleName)); + } + } + + seq.wvList.addAll(mt.wvList_post); + seq.wTableObjList.addAll(mt.wTableObjList); + seq.exList.addAll(mt.exList); + seq.dvList.addAll(mt.dvList); + seq.dvList_deviationSlackSurplus.addAll(mt.dvList_deviationSlackSurplus); + seq.deviationSlackSurplus_toleranceMap.putAll(mt.deviationSlackSurplus_toleranceMap); + + seq.asList.addAll(mt.asList); + seq.glList.addAll(mt.glList); + + // check redefined goal + // TODO: provide option to turn on or off + if (false) { + if (ErrorCheck.findDuplicatesIgnoreCase(seq.glList).size() > 0) { + + String glName = ErrorCheck.findDuplicatesIgnoreCase(seq.glList).get(0); + GoalTemp glObj_mt = mt.glMap.get(glName); + String msg = "Goal [" + glName + "] is redefined in Cycle [" + seq.id + "]"; + LogUtils.errMsgLocation(glObj_mt.fromWresl, glObj_mt.line, msg); + + GoalTemp glObj_seq = seq.glMap.get(glName); + LogUtils.errMsgLocation(glObj_seq.fromWresl, glObj_seq.line, msg); + + hasError = true; + return hasError; + + } + } + + seq.gl2List.addAll(mt.gl2List); + seq.tsList.addAll(mt.tsList); + + seq.ssList_hasCase.addAll(mt.ssList_hasCase); + seq.ssList_noCase.addAll(mt.ssList_noCase); + + + seq.svMap.putAll(mt.svMap); + seq.dvMap.putAll(mt.dvMap); + seq.asMap.putAll(mt.asMap); + seq.glMap.putAll(mt.glMap); + seq.exMap.putAll(mt.exMap); + seq.tsMap.putAll(mt.tsMap); + + + seq.ssMap_hasCase.putAll(mt.ssMap_hasCase); + seq.ssWeightMap_hasCase.putAll(mt.ssWeightMap_hasCase); + seq.ssMap_noCase.putAll(mt.ssMap_noCase); + seq.ssWeightMap_noCase.putAll(mt.ssWeightMap_noCase); + + seq.groupWeightMap.putAll(mt.groupWeightMap); + + return hasError; + } + + public static void convertAliasToGoal(StudyTemp s) { + + + for (String se : s.seqList){ + + SequenceTemp seqObj = s.seqMap.get(se); + + convertAliasToGoal(seqObj); + + } + + } + + public static void convertAliasToGoal(SequenceTemp seqObj) { + + Set allDepInGoals = new HashSet(); + + // add all dep from Goal + for (String key : seqObj.glMap.keySet()) { + + GoalTemp g = seqObj.glMap.get(key); + allDepInGoals.addAll(g.dependants); + allDepInGoals.retainAll(seqObj.asList); + } + + // TODO: slow algorithm. need to improve. + + boolean hasNewItem = true; + HashSet t; + + while (hasNewItem) { + + t = new HashSet(); + + for (String key : allDepInGoals) { + + AliasTemp a = seqObj.asMap.get(key); + + t.addAll(a.dependants); + } + + t.removeAll(allDepInGoals); + t.retainAll(seqObj.asList); + allDepInGoals.addAll(t); + + hasNewItem = t.size()>0 ; + } + + // TODO: provide option for sending all alias to goal and dvar + // so that non-unique solution analysis can work with alias vars + for (String aKey : seqObj.asMap.keySet()) { + + if (allDepInGoals.contains(aKey)) { + + AliasTemp a = seqObj.asMap.get(aKey); + //System.out.println(aKey+":"+a.noSolver); + if (!a.noSolver){ + + a.isMovedToDvar = true; + + // add to dvar + DvarTemp d = new DvarTemp(); + d.id = a.id; + d.upperBound = Param.upper_unbounded; + d.lowerBound = Param.lower_unbounded; + d.kind = a.kind; + d.units = a.units; + d.fromWresl = a.fromWresl; + d.condition = a.condition; + d.isFromAlias = true; + d.timeArraySize = a.timeArraySize; + d.line=a.line; + + seqObj.asList.remove(aKey); + seqObj.asIncFileList_post.remove(aKey); + seqObj.dvList_fromAlias.add(aKey); + //seqObj.dvList.add(aKey); + seqObj.dvMap.put(aKey, d); + + // add goal + GoalTemp g = new GoalTemp(); + g.isFromAlias=true; + g.fromWresl = a.fromWresl; + g.id = a.id + "__alias"; + // String e = a.id.toLowerCase() + "=" + a.expression; + if (a.timeArraySize.equals("0")){ + g.caseExpression.add(a.id.toLowerCase() + "=" + a.expression); + }else{ + g.caseExpression.add(a.id.toLowerCase()+"($m)" + "=" + a.expression); + } + g.condition = a.condition; + g.caseName.add(Param.defaultCaseName); + g.caseCondition.add(Param.always); + g.dependants = a.dependants; + g.timeArraySize = a.timeArraySize; + g.line=a.line; + + seqObj.glList_fromAlias.add(g.id.toLowerCase()); + //seqObj.glList.add(g.id.toLowerCase()); + seqObj.glMap.put(g.id.toLowerCase(), g); + } + + } + + } + + } + + + public static void postProcessIncFileList(StudyTemp st) { + + // use the fileGroupOrder + for (HashSet fgroup: st.fileGroupOrder){ + + for ( String f : fgroup){ + + if (!st.allOffspringMap.keySet().contains(f)) continue; // TODO: the whole first round can be skipped + + + //Pair p = new Pair(f, st.fileModelNameMap.get(f).get(0)); + + //ModelTemp m = st.fileModelDataMap.get(p); + ModelTemp m = st.fileModelDataTable.get(f,st.fileModelNameMap.get(f).get(0)); + ArrayList list_post1 = m.incFileAbsPathList_post; + ArrayList list_post2 = m.incFileRelativePathList_post; + final ArrayList checkList = new ArrayList(m.incFileRelativePathList_post); + + + for( String includedFile: st.allOffspringMap.get(f)){ + int index =checkList.indexOf(includedFile); + + + //Pair p2 = new Pair(includedFile, st.fileModelNameMap.get(includedFile).get(0)); + + //ModelTemp includedModel = st.fileModelDataMap.get(p2); + if (index>-1) { + ModelTemp includedModel = st.fileModelDataTable.get(includedFile, st.fileModelNameMap.get(includedFile).get(0)); + + + list_post1.addAll(index+1, includedModel.incFileAbsPathList_post); + list_post2.addAll(index+1, includedModel.incFileRelativePathList_post); + } + } + } + } + + // process the main file includes + // TODO: replace effective list with seq. + for (String fi : st.modelList_effective){ + + ModelTemp m = st.modelMap.get(fi); + + for (String includedFile: m.incFileRelativePathList ){ + + int index = m.incFileRelativePathList.indexOf(includedFile); + + //Pair p2 = new Pair(includedFile, st.fileModelNameMap.get(includedFile).get(0)); + + //ModelTemp includedModel = st.fileModelDataMap.get(p2); + + ModelTemp includedModel = st.fileModelDataTable.get(includedFile, st.fileModelNameMap.get(includedFile).get(0)); + + m.incFileRelativePathList_post.addAll(index+1, includedModel.incFileRelativePathList_post); + m.incFileAbsPathList_post.addAll(index+1, includedModel.incFileAbsPathList_post); + + + } + } + } + + public static void findKidMap(StudyTemp st) { + + for (String f: st.fileModelNameMap.keySet()){ + + String modelName = st.fileModelNameMap.get(f).get(0); + + ArrayList kids = st.fileModelDataTable.get(f,modelName).incFileRelativePathList; + + if (kids==null){ + st.noKid.add(f); + } else if (kids.isEmpty()){ + st.noKid.add(f); + } else { + //st.kidssMap.put(f, modelName, new HashSet(kids)); + st.kidMap.put(f, new HashSet(kids)); + } + + } + + } + + public static void findAllOffSpring(StudyTemp st) { + + + for (String f: st.kidMap.keySet()) { + + HashSet a = Tools.findAllOffspring(f, st.kidMap); + + st.allOffspringMap.put(f, a); + + } + + } + + public static void findFileGroupOrder(StudyTemp st) { + + Map> toBeSorted = new HashMap>(st.allOffspringMap); + + ///// skip mainFile + toBeSorted.remove(st.relativePath); + + //System.out.println("st.noKid"+st.noKid); + st.fileGroupOrder.add(st.noKid); + + + Tools.findFileHierarchy(st.fileGroupOrder, toBeSorted); + + } + + + // replace file with vars + public static void postProcessVarListinIncFile(StudyTemp st) { + + // use the fileGroupOrder + for (HashSet fgroup: st.fileGroupOrder){ + + for ( String f : fgroup){ + + if (!st.allOffspringMap.keySet().contains(f)) continue; // TODO: the whole first round can be skipped + + String modelName = st.fileModelNameMap.get(f).get(0); + + ModelTemp m = st.fileModelDataTable.get(f,modelName); + + for( String includedFile: st.allOffspringMap.get(f)){ + + int index =m.svIncFileList_post.indexOf(includedFile); + + if (index>-1) { + m.svIncFileList_post.remove(index); + + //Pair p2 = new Pair(includedFile, st.fileModelNameMap.get(includedFile).get(0)); + + ModelTemp includedModel = st.fileModelDataTable.get(includedFile,st.fileModelNameMap.get(includedFile).get(0)); + m.svIncFileList_post.addAll(index, includedModel.svIncFileList_post); + //m.dvList.addAll(includedModel.dvList); + m.ssList_noCase.addAll(includedModel.ssList_noCase); + m.ssList_hasCase.addAll(includedModel.ssList_hasCase); + + } + + // process alias + index =m.asIncFileList_post.indexOf(includedFile); + + if (index > -1) { + + m.asIncFileList_post.remove(index); + ModelTemp includedModel = st.fileModelDataTable.get(includedFile, + st.fileModelNameMap.get(includedFile).get(0)); + m.asIncFileList_post.addAll(index, includedModel.asIncFileList_post); + + } + + // process external + index =m.exIncFileList_post.indexOf(includedFile); + + if (index > -1) { + + m.exIncFileList_post.remove(index); + ModelTemp includedModel = st.fileModelDataTable.get(includedFile, + st.fileModelNameMap.get(includedFile).get(0)); + m.exIncFileList_post.addAll(index, includedModel.exIncFileList_post); + + } + + // process dv + index =m.dvIncFileList_post.indexOf(includedFile); + + if (index > -1) { + + m.dvIncFileList_post.remove(index); + ModelTemp includedModel = st.fileModelDataTable.get(includedFile, + st.fileModelNameMap.get(includedFile).get(0)); + m.dvIncFileList_post.addAll(index, includedModel.dvIncFileList_post); + + } + + // process gl + index =m.glIncFileList_post.indexOf(includedFile); + + if (index > -1) { + + m.glIncFileList_post.remove(index); + ModelTemp includedModel = st.fileModelDataTable.get(includedFile, + st.fileModelNameMap.get(includedFile).get(0)); + m.glIncFileList_post.addAll(index, includedModel.glIncFileList_post); + + } + + } + } + } + + // process the main file except the first model includes + ArrayList ttt = new ArrayList(st.modelList_effective); + + for (String modelNameOfMain : ttt){ + + ModelTemp m = st.modelMap.get(modelNameOfMain); + + + for (String includedFile: m.incFileRelativePathList ){ + + int index = m.svIncFileList_post.indexOf(includedFile); + + + if (index>-1) { + + String modelName = st.fileModelNameMap.get(includedFile).get(0); + + //Pair p = new Pair(includedFile, modelName); + + ModelTemp includedModel = st.fileModelDataTable.get(includedFile,modelName); + + + + m.svIncFileList_post.remove(index); + + m.svIncFileList_post.addAll(index, includedModel.svIncFileList_post); + //m.dvList.addAll(includedModel.dvList); + m.ssList_noCase.addAll(includedModel.ssList_noCase); + m.ssList_hasCase.addAll(includedModel.ssList_hasCase); + } + + // process alias + index = m.asIncFileList_post.indexOf(includedFile); + + if (index > -1) { + + String modelName = st.fileModelNameMap.get(includedFile).get(0); + + ModelTemp includedModel = st.fileModelDataTable.get(includedFile, modelName); + m.asIncFileList_post.remove(index); + m.asIncFileList_post.addAll(index, includedModel.asIncFileList_post); + } + + // process external + index = m.exIncFileList_post.indexOf(includedFile); + + if (index > -1) { + + String modelName = st.fileModelNameMap.get(includedFile).get(0); + + ModelTemp includedModel = st.fileModelDataTable.get(includedFile, modelName); + m.exIncFileList_post.remove(index); + m.exIncFileList_post.addAll(index, includedModel.exIncFileList_post); + } + + // process dv + index = m.dvIncFileList_post.indexOf(includedFile); + + if (index > -1) { + + String modelName = st.fileModelNameMap.get(includedFile).get(0); + + ModelTemp includedModel = st.fileModelDataTable.get(includedFile, modelName); + m.dvIncFileList_post.remove(index); + m.dvIncFileList_post.addAll(index, includedModel.dvIncFileList_post); + } + + // process gl + index = m.glIncFileList_post.indexOf(includedFile); + + if (index > -1) { + + String modelName = st.fileModelNameMap.get(includedFile).get(0); + + ModelTemp includedModel = st.fileModelDataTable.get(includedFile, modelName); + m.glIncFileList_post.remove(index); + m.glIncFileList_post.addAll(index, includedModel.glIncFileList_post); + } + } + } + } + + // TODO: this process alias only. need to expand to other types + public static void classifyDependants(StudyTemp s) { + + for (String se : s.seqList){ + + SequenceTemp seqObj = s.seqMap.get(se); + + //ModelTemp mObj = s.modelMap.get(m); + + classifyDependants(seqObj, s.parameterList); + } + } + public static void classifyDependants(SequenceTemp seqObj, ArrayList parameterList) { + + for (String key : seqObj.asMap.keySet()) { + + AliasTemp asObj = seqObj.asMap.get(key); + + //if (asObj.isProcessed) continue; + + Set temp = new HashSet(asObj.dependants); + + asObj.dependants_timeseries = new LinkedHashSet(asObj.dependants); + asObj.dependants_timeseries.retainAll(seqObj.tsList); + temp.removeAll(asObj.dependants_timeseries); + + + asObj.dependants_dvar = new LinkedHashSet(temp); + asObj.dependants_dvar.retainAll(seqObj.dvList); + temp.removeAll(asObj.dependants_dvar); + + asObj.dependants_svar = new LinkedHashSet(temp); + asObj.dependants_svar.retainAll(seqObj.svMap.keySet()); + temp.removeAll(asObj.dependants_svar); + + asObj.dependants_alias = new LinkedHashSet(temp); + asObj.dependants_alias.retainAll(seqObj.asMap.keySet()); + temp.removeAll(asObj.dependants_alias); + + asObj.dependants_parameter = new LinkedHashSet(temp); + asObj.dependants_parameter.retainAll(parameterList); + temp.removeAll(asObj.dependants_parameter); + +// asObj.dependants_unknown = temp; +// asObj.dependants_unknown.removeAll(asObj.dependants_timeseries); +// asObj.dependants_unknown.removeAll(asObj.dependants_dvar); +// asObj.dependants_unknown.removeAll(asObj.dependants_svar); +// asObj.dependants_unknown.removeAll(asObj.dependants_alias); +// asObj.dependants_unknown.removeAll(asObj.dependants_parameter); + + + // TODO: this is to match legacy wresl parser + asObj.dependants.removeAll(asObj.dependants_timeseries); + asObj.dependants.removeAll(asObj.dependants_dvar); + + //asObj.isProcessed = true; + } + + for (String key : seqObj.svMap.keySet()) { + + SvarTemp svObj = seqObj.svMap.get(key); + + //if (svObj.isProcessed) continue; + + Set temp = new HashSet(svObj.dependants); + + svObj.dependants_timeseries = new LinkedHashSet(svObj.dependants); + svObj.dependants_timeseries.retainAll(seqObj.tsList); + temp.removeAll(svObj.dependants_timeseries); + + svObj.dependants_alias = new LinkedHashSet(temp); + svObj.dependants_alias.retainAll(seqObj.asMap.keySet()); + temp.removeAll(svObj.dependants_alias); + + svObj.dependants_dvar = new LinkedHashSet(temp); + svObj.dependants_dvar.retainAll(seqObj.dvList); + temp.removeAll(svObj.dependants_dvar); + + svObj.dependants_svar = new LinkedHashSet(temp); + svObj.dependants_svar.retainAll(seqObj.svMap.keySet()); + temp.removeAll(svObj.dependants_svar); + + svObj.dependants_external = new LinkedHashSet(temp); + svObj.dependants_external.retainAll(seqObj.exList); + temp.removeAll(svObj.dependants_external); + + svObj.dependants_parameter = new LinkedHashSet(temp); + svObj.dependants_parameter.retainAll(parameterList); + temp.removeAll(svObj.dependants_parameter); + +// svObj.dependants_unknown = temp; +// svObj.dependants_unknown.removeAll(svObj.dependants_timeseries); +// svObj.dependants_unknown.removeAll(svObj.dependants_alias); +// svObj.dependants_unknown.removeAll(svObj.dependants_dvar); +// svObj.dependants_unknown.removeAll(svObj.dependants_svar); +// svObj.dependants_unknown.removeAll(svObj.dependants_external); +// svObj.dependants_unknown.removeAll(svObj.dependants_parameter); + + // TODO: this is to match legacy wresl parser + svObj.dependants.removeAll(svObj.dependants_timeseries); + svObj.dependants.removeAll(seqObj.dvList); + + //svObj.isProcessed = true; + } + + for (String key : seqObj.glMap.keySet()) { + + GoalTemp svObj = seqObj.glMap.get(key); + + //if (svObj.isProcessed) continue; + + //svObj.dependants.removeAll(seqObj.tsList); + //svObj.dependants.removeAll(seqObj.dvList); + + Set temp = new HashSet(svObj.dependants); + + svObj.dependants_timeseries = new LinkedHashSet(svObj.dependants); + svObj.dependants_timeseries.retainAll(seqObj.tsList); + temp.removeAll(svObj.dependants_timeseries); + + svObj.dependants_svar = new LinkedHashSet(temp); + svObj.dependants_svar.retainAll(seqObj.svMap.keySet()); + temp.removeAll(svObj.dependants_svar); + + svObj.dependants_dvar = new LinkedHashSet(temp); + svObj.dependants_dvar.retainAll(seqObj.dvList); + temp.removeAll(svObj.dependants_dvar); + + svObj.dependants_alias = new LinkedHashSet(temp); + svObj.dependants_alias.retainAll(seqObj.asMap.keySet()); + temp.removeAll(svObj.dependants_alias); + + svObj.dependants_external = new LinkedHashSet(temp); + svObj.dependants_external.retainAll(seqObj.exMap.keySet()); + temp.removeAll(svObj.dependants_external); + + svObj.dependants_parameter = new LinkedHashSet(temp); + svObj.dependants_parameter.retainAll(parameterList); + temp.removeAll(svObj.dependants_parameter); + +// svObj.dependants_unknown = temp; +// svObj.dependants_unknown.removeAll(svObj.dependants_timeseries); +// svObj.dependants_unknown.removeAll(svObj.dependants_svar); +// svObj.dependants_unknown.removeAll(svObj.dependants_dvar); +// svObj.dependants_unknown.removeAll(svObj.dependants_alias); +// svObj.dependants_unknown.removeAll(svObj.dependants_external); +// svObj.dependants_unknown.removeAll(svObj.dependants_parameter); + + //svObj.isProcessed = true; + + } + } + + + public static void analyzeVarNeededFromCycle(StudyTemp s){ + + for (String se : s.seqList){ + + SequenceTemp q = s.seqMap.get(se); + ArrayList others = new ArrayList(s.seqList); + others.remove(se); + + for (String o : others){ + + SequenceTemp otherSeq = s.seqMap.get(o); + + Set varSet = otherSeq.neededCycleVarMap.get(q.model); + + if (varSet != null) { + + q.varUsedByLaterCycle.addAll(varSet); + + for (String e : varSet) { + + if (q.asIncFileList_post.contains(e)) { + + q.aliasUsedByLaterCycle.add(e); + } + else if (q.dvList.contains(e)) { + + q.dvarUsedByLaterCycle.add(e); + } + else if (q.dvList_fromAlias.contains(e)) { + + q.dvarUsedByLaterCycle.add(e); + } + else if (q.svIncFileList_post.contains(e)) { + + q.svarUsedByLaterCycle.add(e); + } + else { + + // TODO: this variable is in a IF statement where condition is not satisfied therefore not exists in previous cycle + + //LogUtils.errMsg(" Unknown type of variable ["+ e +"] in ["+ se+": "+q.model +"] is used in ["+o+": "+otherSeq.model+"]"); + + } + } + } + + + } + + } + + } + + public static void createSpaceInVarCycleValueMap(StudyTemp s){ + + Map> vcv = s.varCycleValueMap; + + for (String seqName : s.seqList){ + + SequenceTemp q = s.seqMap.get(seqName); + + String modelName = q.model; + + for (String e : q.varUsedByLaterCycle) { + + // / create space in varCycleValue map + if (vcv.keySet().contains(e)) { + vcv.get(e).put(modelName, null); + } else { + Map t = new HashMap(); + t.put(modelName, null); + vcv.put(e, t); + } + } + + + + } + } + + public static void collectTimeStep(StudyTemp st) { + + for (String se : st.seqList){ + + SequenceTemp q = st.seqMap.get(se); + + // TODO: warning!!! need test + st.seqTimeStepList.add(q.timeStep); + + String timeStep=q.timeStep; + String definedTimeStep; + + if (timeStep.equals(Param.undefined)){ + definedTimeStep=ControlData.defaultTimeStep; + }else{ + definedTimeStep=timeStep; + } + + for (String timeseriesName : q.tsList) { + + if (st.timeseriesTimeStepMap.containsKey(timeseriesName)) { + + ArrayList timeStepList = st.timeseriesTimeStepMap.get(timeseriesName); + if (!timeStepList.contains(definedTimeStep)) { + timeStepList.add(definedTimeStep); + } + } + else { + st.timeseriesTimeStepMap.put(timeseriesName, new ArrayList(Arrays.asList(definedTimeStep))); + } + } + + } + + } + + public static int findWarmStart(int preStop, int nCyc) { + + for (int i=preStop+1; iParam.cbcMinIntNumber){ + return i; + } + } + return nCyc+1; + } + + + public static int findWarmStart(int preStop, int nCyc, StudyDataSet sd) { + + for (int i=preStop+1; iParam.cbcMinIntNumber){ + return i; + } + } + return nCyc+1; + } + + public static int findWarmStop(int start, int nCyc) { + for (int i=start; i dependants; - - public ArrayList svIncFileList_post; // copied from included model - public ArrayList asIncFileList_post; // copied from included model - public ArrayList exIncFileList_post; // copied from included model - public ArrayList dvIncFileList_post; // copied from included model - public ArrayList glIncFileList_post; // copied from included model - public ArrayList incFileAbsPathList_post; // copied from included model - public ArrayList incFileRelativePathList_post; // copied from included model - // does not reflect user's input order - public ArrayList exList; - public ArrayList dvList; - public ArrayList dvList_fromAlias; - public ArrayList dvList_deviationSlackSurplus; - public Map deviationSlackSurplus_toleranceMap; // < deviationSS, tolerance> - public ArrayList asList; - public ArrayList glList; - public ArrayList gl2List; - public ArrayList glList_fromAlias; - public ArrayList ssList_hasCase; - public ArrayList ssList_noCase; - - public ArrayList tsList; - public Map tsMap; - - public Map svMap; - public Map dvMap; - public LinkedHashMap asMap; - public LinkedHashMap glMap; - public Map exMap; - - - public Map ssMap_hasCase; // processed - public Map ssWeightMap_hasCase; // processed - - public Map ssMap_noCase; // processed - public Map ssWeightMap_noCase; // processed - - public Map groupWeightMap; // copid from model - - public ArrayList wvList; - public ArrayList wTableObjList; - - public Map> neededCycleVarMap; - - public Set varUsedByLaterCycle; - public Set dvarUsedByLaterCycle; - public Set svarUsedByLaterCycle; - public Set aliasUsedByLaterCycle; - - - public SequenceTemp(){ - - fromWresl =""; - dependants = new LinkedHashSet(); - - condition = Param.always; - timeStep = Param.undefined; - //svIncFileList_post = new ArrayList(); - exList = new ArrayList(); - dvList = new ArrayList(); - dvList_fromAlias = new ArrayList(); - dvList_deviationSlackSurplus = new ArrayList(); - deviationSlackSurplus_toleranceMap = new HashMap(); - asList = new ArrayList(); - glList = new ArrayList(); - gl2List = new ArrayList(); - glList_fromAlias = new ArrayList(); - tsList = new ArrayList(); - ssList_hasCase = new ArrayList(); - ssList_noCase = new ArrayList(); - - tsMap = new HashMap(); - svMap = new HashMap(); - dvMap = new HashMap(); - asMap = new LinkedHashMap(); - glMap = new LinkedHashMap(); - exMap = new HashMap(); - - ssMap_hasCase = new HashMap(); - ssWeightMap_hasCase = new HashMap(); - - ssMap_noCase = new HashMap(); - ssWeightMap_noCase = new HashMap(); - - groupWeightMap = new HashMap(); - - wvList = new ArrayList(); - wTableObjList = new ArrayList(); - - neededCycleVarMap = new HashMap>(); - - varUsedByLaterCycle = new HashSet(); - dvarUsedByLaterCycle = new HashSet(); - svarUsedByLaterCycle = new HashSet(); - aliasUsedByLaterCycle = new HashSet(); - - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; + +public class SequenceTemp implements Serializable { + + private static final long serialVersionUID = 1L; + + public String id; + public String fromWresl; + public int line=1; + public String model; + public String condition; + public String order; + public String timeStep; + + public Set dependants; + + public ArrayList svIncFileList_post; // copied from included model + public ArrayList asIncFileList_post; // copied from included model + public ArrayList exIncFileList_post; // copied from included model + public ArrayList dvIncFileList_post; // copied from included model + public ArrayList glIncFileList_post; // copied from included model + public ArrayList incFileAbsPathList_post; // copied from included model + public ArrayList incFileRelativePathList_post; // copied from included model + // does not reflect user's input order + public ArrayList exList; + public ArrayList dvList; + public ArrayList dvList_fromAlias; + public ArrayList dvList_deviationSlackSurplus; + public Map deviationSlackSurplus_toleranceMap; // < deviationSS, tolerance> + public ArrayList asList; + public ArrayList glList; + public ArrayList gl2List; + public ArrayList glList_fromAlias; + public ArrayList ssList_hasCase; + public ArrayList ssList_noCase; + + public ArrayList tsList; + public Map tsMap; + + public Map svMap; + public Map dvMap; + public LinkedHashMap asMap; + public LinkedHashMap glMap; + public Map exMap; + + + public Map ssMap_hasCase; // processed + public Map ssWeightMap_hasCase; // processed + + public Map ssMap_noCase; // processed + public Map ssWeightMap_noCase; // processed + + public Map groupWeightMap; // copid from model + + public ArrayList wvList; + public ArrayList wTableObjList; + + public Map> neededCycleVarMap; + + public Set varUsedByLaterCycle; + public Set dvarUsedByLaterCycle; + public Set svarUsedByLaterCycle; + public Set aliasUsedByLaterCycle; + + + public SequenceTemp(){ + + fromWresl =""; + dependants = new LinkedHashSet(); + + condition = Param.always; + timeStep = Param.undefined; + //svIncFileList_post = new ArrayList(); + exList = new ArrayList(); + dvList = new ArrayList(); + dvList_fromAlias = new ArrayList(); + dvList_deviationSlackSurplus = new ArrayList(); + deviationSlackSurplus_toleranceMap = new HashMap(); + asList = new ArrayList(); + glList = new ArrayList(); + gl2List = new ArrayList(); + glList_fromAlias = new ArrayList(); + tsList = new ArrayList(); + ssList_hasCase = new ArrayList(); + ssList_noCase = new ArrayList(); + + tsMap = new HashMap(); + svMap = new HashMap(); + dvMap = new HashMap(); + asMap = new LinkedHashMap(); + glMap = new LinkedHashMap(); + exMap = new HashMap(); + + ssMap_hasCase = new HashMap(); + ssWeightMap_hasCase = new HashMap(); + + ssMap_noCase = new HashMap(); + ssWeightMap_noCase = new HashMap(); + + groupWeightMap = new HashMap(); + + wvList = new ArrayList(); + wTableObjList = new ArrayList(); + + neededCycleVarMap = new HashMap>(); + + varUsedByLaterCycle = new HashSet(); + dvarUsedByLaterCycle = new HashSet(); + svarUsedByLaterCycle = new HashSet(); + aliasUsedByLaterCycle = new HashSet(); + + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/StudyTemp.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/StudyTemp.java similarity index 97% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/StudyTemp.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/StudyTemp.java index a7ee2f023..a77438b1c 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/StudyTemp.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/StudyTemp.java @@ -1,96 +1,96 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; - -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.components.IntDouble; - -import com.google.common.collect.HashBasedTable; - -public class StudyTemp implements Serializable { - - private static final long serialVersionUID = 1L; - //public boolean isSort = true; - public String runDir = null; - public String absPath = null; - public String relativePath = null; - - public ArrayList parameterList; - public ArrayList parameterConstList; // subset of parameterList - //public Map parameterMap; - public LinkedHashMap parameterMap; - public LinkedHashMap controlDataParameterMap; - - public ArrayList seqList; - public ArrayList seqTimeStepList; - public Map seqMap; - public ArrayList modelList_effective; //processed // defined in sequence - public ArrayList incModelList_effective; //processed // models included in models - public ArrayList modelList; - public Map modelMap; - public Map> fileModelNameMap; - public HashBasedTable fileModelDataTable; // - - // include models - public Map>kidMap_incModel; // processed - public HashSet noKid_incModel; // processed - public Map>allOffspringMap_incModel; // all offspring map. processed - public ArrayList>fileGroupOrder_incModel; // processed after kidMap and AOMap - - // files - public Map>kidMap; // processed - public HashSet noKid; // processed - public Map>allOffspringMap; // all offspring map. processed - public ArrayList>fileGroupOrder; // processed after kidMap and AOMap - - //public String objectiveType="obj"; - - /// this map contains value of vars needed for WRESL syntax: varName[cycleName] - /// < VarName, < CycleName, Value >> - public Map> varCycleValueMap; - - /// < timeseries name, time steps > - public Map> timeseriesTimeStepMap; - - - public StudyTemp(){ - - parameterList = new ArrayList(); - parameterConstList = new ArrayList(); - parameterMap = new LinkedHashMap(); - controlDataParameterMap = new LinkedHashMap(); - - seqTimeStepList = new ArrayList(); - modelList = new ArrayList(); - modelList_effective = new ArrayList(); - incModelList_effective = new ArrayList(); - modelMap = new HashMap(); - seqList = new ArrayList(); - seqMap = new HashMap(); - fileModelNameMap = new LinkedHashMap>(); - fileModelDataTable = HashBasedTable.create(); - - kidMap_incModel = new HashMap>(); - noKid_incModel = new HashSet(); - allOffspringMap_incModel = new HashMap>(); - fileGroupOrder_incModel = new ArrayList>(); - - kidMap = new HashMap>(); - //kidssMap = HashBasedTable.create(); - noKid = new HashSet(); - allOffspringMap = new HashMap>(); - fileGroupOrder = new ArrayList>(); - - varCycleValueMap = new HashMap>(); - - timeseriesTimeStepMap = new HashMap>(); - - - } - -} +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; + +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.components.IntDouble; + +import com.google.common.collect.HashBasedTable; + +public class StudyTemp implements Serializable { + + private static final long serialVersionUID = 1L; + //public boolean isSort = true; + public String runDir = null; + public String absPath = null; + public String relativePath = null; + + public ArrayList parameterList; + public ArrayList parameterConstList; // subset of parameterList + //public Map parameterMap; + public LinkedHashMap parameterMap; + public LinkedHashMap controlDataParameterMap; + + public ArrayList seqList; + public ArrayList seqTimeStepList; + public Map seqMap; + public ArrayList modelList_effective; //processed // defined in sequence + public ArrayList incModelList_effective; //processed // models included in models + public ArrayList modelList; + public Map modelMap; + public Map> fileModelNameMap; + public HashBasedTable fileModelDataTable; // + + // include models + public Map>kidMap_incModel; // processed + public HashSet noKid_incModel; // processed + public Map>allOffspringMap_incModel; // all offspring map. processed + public ArrayList>fileGroupOrder_incModel; // processed after kidMap and AOMap + + // files + public Map>kidMap; // processed + public HashSet noKid; // processed + public Map>allOffspringMap; // all offspring map. processed + public ArrayList>fileGroupOrder; // processed after kidMap and AOMap + + //public String objectiveType="obj"; + + /// this map contains value of vars needed for WRESL syntax: varName[cycleName] + /// < VarName, < CycleName, Value >> + public Map> varCycleValueMap; + + /// < timeseries name, time steps > + public Map> timeseriesTimeStepMap; + + + public StudyTemp(){ + + parameterList = new ArrayList(); + parameterConstList = new ArrayList(); + parameterMap = new LinkedHashMap(); + controlDataParameterMap = new LinkedHashMap(); + + seqTimeStepList = new ArrayList(); + modelList = new ArrayList(); + modelList_effective = new ArrayList(); + incModelList_effective = new ArrayList(); + modelMap = new HashMap(); + seqList = new ArrayList(); + seqMap = new HashMap(); + fileModelNameMap = new LinkedHashMap>(); + fileModelDataTable = HashBasedTable.create(); + + kidMap_incModel = new HashMap>(); + noKid_incModel = new HashSet(); + allOffspringMap_incModel = new HashMap>(); + fileGroupOrder_incModel = new ArrayList>(); + + kidMap = new HashMap>(); + //kidssMap = HashBasedTable.create(); + noKid = new HashSet(); + allOffspringMap = new HashMap>(); + fileGroupOrder = new ArrayList>(); + + varCycleValueMap = new HashMap>(); + + timeseriesTimeStepMap = new HashMap>(); + + + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/SvarTemp.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/SvarTemp.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/SvarTemp.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/SvarTemp.java index ed5e55165..3bab2ff01 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/SvarTemp.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/SvarTemp.java @@ -1,76 +1,76 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.components.IntDouble; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.evaluator.ValueEvaluatorTreeWalker; - - - -public class SvarTemp implements Serializable { - - private static final long serialVersionUID = 1L; - - public String fromWresl; // for test only - public int line=1; - public String id; - public String kind; - public String units; - public String condition; - //public String expression; - public Set dependants; - public Set dependants_timeseries; - public Set dependants_external; - public Set dependants_parameter; - public Set dependants_alias; - public Set dependants_dvar; - public Set dependants_svar; - public Set dependants_unknown; - public Set dependants_notAllowed; - public Set neededVarInCycleSet; - public boolean needVarFromEarlierCycle; - public boolean isProcessed; - - - - public ArrayList caseName; - public ArrayList caseCondition; - public ArrayList caseExpression; - - - // default is 0 - public String timeArraySize; - public String arraySize; - - public SvarTemp(){ - - fromWresl =""; - kind=Param.undefined; - units=Param.undefined; - condition = Param.always; - //expression=Param.undefined; - dependants = new LinkedHashSet(); - dependants_notAllowed = new LinkedHashSet(); -// dependants_timeseries = new LinkedHashSet(); -// dependants_external = new LinkedHashSet(); - //dependants_svar = new LinkedHashSet(); - neededVarInCycleSet = new LinkedHashSet(); - needVarFromEarlierCycle = false; - isProcessed = false; - - timeArraySize="0"; - arraySize="0"; - - caseName=new ArrayList(); - caseCondition=new ArrayList(); - caseExpression=new ArrayList(); - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.components.IntDouble; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.evaluator.ValueEvaluatorTreeWalker; + + + +public class SvarTemp implements Serializable { + + private static final long serialVersionUID = 1L; + + public String fromWresl; // for test only + public int line=1; + public String id; + public String kind; + public String units; + public String condition; + //public String expression; + public Set dependants; + public Set dependants_timeseries; + public Set dependants_external; + public Set dependants_parameter; + public Set dependants_alias; + public Set dependants_dvar; + public Set dependants_svar; + public Set dependants_unknown; + public Set dependants_notAllowed; + public Set neededVarInCycleSet; + public boolean needVarFromEarlierCycle; + public boolean isProcessed; + + + + public ArrayList caseName; + public ArrayList caseCondition; + public ArrayList caseExpression; + + + // default is 0 + public String timeArraySize; + public String arraySize; + + public SvarTemp(){ + + fromWresl =""; + kind=Param.undefined; + units=Param.undefined; + condition = Param.always; + //expression=Param.undefined; + dependants = new LinkedHashSet(); + dependants_notAllowed = new LinkedHashSet(); +// dependants_timeseries = new LinkedHashSet(); +// dependants_external = new LinkedHashSet(); + //dependants_svar = new LinkedHashSet(); + neededVarInCycleSet = new LinkedHashSet(); + needVarFromEarlierCycle = false; + isProcessed = false; + + timeArraySize="0"; + arraySize="0"; + + caseName=new ArrayList(); + caseCondition=new ArrayList(); + caseExpression=new ArrayList(); + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/TimeseriesTemp.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/TimeseriesTemp.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/TimeseriesTemp.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/TimeseriesTemp.java index b8427bec3..cb4a2b4e6 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/TimeseriesTemp.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/TimeseriesTemp.java @@ -1,34 +1,34 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.components.IntDouble; - - - -public class TimeseriesTemp implements Serializable { - - private static final long serialVersionUID = 1L; - - public String id; - public String dssBPart; - public String kind; - public String units; - public String convertToUnits; - public String fromWresl; - public int line=1; - - public TimeseriesTemp(){ - - dssBPart=Param.undefined; - kind=Param.undefined; - units=Param.undefined; - convertToUnits =Param.undefined; - fromWresl = Param.undefined; - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.components.IntDouble; + + + +public class TimeseriesTemp implements Serializable { + + private static final long serialVersionUID = 1L; + + public String id; + public String dssBPart; + public String kind; + public String units; + public String convertToUnits; + public String fromWresl; + public int line=1; + + public TimeseriesTemp(){ + + dssBPart=Param.undefined; + kind=Param.undefined; + units=Param.undefined; + convertToUnits =Param.undefined; + fromWresl = Param.undefined; + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/Tools.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/Tools.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/Tools.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/Tools.java index 765821529..36d45377c 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/Tools.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/Tools.java @@ -1,596 +1,596 @@ -package wrimsv2.wreslplus.elements; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.io.Reader; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; - -import com.google.common.collect.HashBasedTable; - -import wrimsv2.commondata.wresldata.Goal; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslparser.elements.StudyUtils; - - -public class Tools { - public static String strip(String s) { - if (s==null) return null; - return s.substring(1, s.length() - 1); - } - - public static String getCanonicalLowCasePath(String filePath) { - - String canonicalPath_lowercase=null; - - try { - - canonicalPath_lowercase = new File(filePath).getCanonicalPath().toLowerCase(); - - } catch (IOException e) { - - e.printStackTrace(); - LogUtils.errMsg("IOException: " + filePath); - } - - return canonicalPath_lowercase; - - } - - public static HashSet findAllOffspring (String fileName, final Map> kidMap){ - - HashSet out = new HashSet(); - - if (!kidMap.keySet().contains(fileName)) return out; - - out.addAll(kidMap.get(fileName)); - - for (String kid : kidMap.get(fileName)) { - - out.addAll(findAllOffspring(kid, kidMap)); - - } - return out; - } - - // TODO: move to Tools - // be careful, the map is modified in this function - public static void findFileHierarchy(ArrayList> hierarchySetList, Map> toBeSorted) { - - //System.out.println("hierarchySetList"+hierarchySetList); - - if (!toBeSorted.isEmpty()) { - - HashSet c = new HashSet(); - Set toBeSorted_keySet = new HashSet(toBeSorted.keySet()); - for (String s : toBeSorted_keySet){ - - //System.out.println("%%% s: "+s); - - // TODO: inefficient. needs rewrite - HashSet ttt = new HashSet(); - for (HashSet ss : hierarchySetList){ ttt.addAll(ss); } - if ( ttt.containsAll(toBeSorted.get(s))) { - c.add(s); - toBeSorted.remove(s); - } - } - hierarchySetList.add(c); - findFileHierarchy(hierarchySetList, toBeSorted); - - } - - } - - //TODO: this can be optimized for memory - public static ArrayList allToUpperCase(ArrayList inArrayList){ - - ArrayList out = new ArrayList(); - - for (String s: inArrayList){ - out.add(s.toUpperCase()); - } - - return out; - } - //TODO: this can be optimized for memory - public static ArrayList allToLowerCase(ArrayList inArrayList){ - - ArrayList out = new ArrayList(); - - for (String s: inArrayList){ - out.add(s.toLowerCase()); - } - - return out; - } - public static ArrayList> allToLowerCase2(ArrayList> inArrayList){ - - ArrayList> out = new ArrayList>(); - - for (ArrayList s: inArrayList){ - out.add(allToLowerCase(s)); - } - - return out; - } - //TODO: this can be optimized for memory - public static Map allToLowerCase_string(Map inMap){ - - Map out = new LinkedHashMap(); - - for (String s: inMap.keySet()){ - out.put(s.toLowerCase(),inMap.get(s).toLowerCase()); - } - - return out; - } - public static Map> allToLowerCase_string_set(Map> inMap){ - - Map> out = new LinkedHashMap>(); - - for (String s: inMap.keySet()){ - out.put(s.toLowerCase(), (HashSet)allToLowerCase(inMap.get(s))); - } - - return out; - } - public static Map allToLowerCaseString(Map inMap){ - - Map out = new LinkedHashMap(); - - for (String s: inMap.keySet()){ - out.put(s.toLowerCase(),inMap.get(s)); - } - - return out; - } - public static LinkedHashMap allToLowerCase_weightSubgroup(Map inMap){ - - LinkedHashMap out = new LinkedHashMap(); - - for (String s: inMap.keySet()){ - out.put(s.toLowerCase(),allToLowerCase(inMap.get(s))); - } - - return out; - } - public static WeightSubgroup allToLowerCase(WeightSubgroup wsg){ - - WeightSubgroup out = new WeightSubgroup(); - - out.deviationPenalty = wsg.deviationPenalty.toLowerCase(); - out.deviationTolerance = wsg.deviationTolerance.toLowerCase(); - out.id = wsg.id; - out.varList = allToLowerCase(wsg.varList); - - return out; - } - public static Set allToLowerCase(Set inSet){ - - Set out = new LinkedHashSet(); - - for (String s: inSet){ - out.add(s.toLowerCase()); - } - - return out; - } - public static String replace_regex(String s) { - if (s==null) return null; - s=s.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)"); - s=s.replaceAll("\\.", "\\\\."); - s=s.replaceAll("\\*", "\\\\*"); - s=s.replaceAll("\\|", "\\\\|"); - s=s.replaceAll("\\+", "\\\\+"); - s=s.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]"); - s=s.replaceAll("##", ".+"); - return s; - } - public static String remove_nulls(String s) { - if (s==null) return null; - s=s.replaceAll("null", ""); - s=s.replaceAll("\\s+", " "); - return s; - } - public static ArrayList replace_with_space(ArrayList s) { - if (s==null) return null; - ArrayList o = new ArrayList(); - for (String e : s){ - o.add(replace_with_space(e)); - } - return o; - } - public static String replace_with_space(String s) { - if (s==null) return null; - s=s.replaceAll("\n+", " ").replaceAll("\r+", " "); - s=s.replaceAll("\t+", " "); - s=s.replaceAll("\\s+", " "); - return s; - } - public static ArrayList replace_ignoreChar(ArrayList s) { - if (s==null) return null; - ArrayList o = new ArrayList(); - for (String e : s){ - o.add(replace_ignoreChar(e)); - } - return o; - } - public static String replace_ignoreChar(String s) { - if (s==null) return null; - s=s.replaceAll("\n+", "").replaceAll("\r+", ""); - s=s.replaceAll("\t+", ""); - s=s.replaceAll("\\s+", ""); - return s; - } - public static ArrayList add_space_between_logical(ArrayList s) { - if (s==null) return s; - ArrayList o = new ArrayList(); - for (String e : s){ - o.add(add_space_between_logical(e)); - } - return o; - } - public static String add_space_between_logical(String s) { - if (s==null) return null; - - //s = replace_ignoreChar(s); - //s = replace_seperator(s); - - s=s.replaceAll("\\.AND\\.", " \\.and\\. "); - s=s.replaceAll("\\.OR\\.", " \\.or\\. "); - s=s.replaceAll("\\.and\\.", " \\.and\\. "); - s=s.replaceAll("\\.or\\.", " \\.or\\. "); - - return s; - } - public static ArrayList replace_seperator(ArrayList s) { - if (s.size()<1) return null; - ArrayList o = new ArrayList(); - for (String e: s){ - o.add(Tools.replace_seperator(e)); - } - return o; - } - public static String replace_seperator(String s) { - if (s==null) return null; - s=s.replaceAll(Param.arg_seperator,Param.new_seperator); - return s; - } - public static Map readFilesFromDirAsMap(String dir) - throws IOException { - File folder = new File(dir); - File[] listOfFiles = folder.listFiles(); - Map map = new HashMap(); - - for (File file : listOfFiles) { - - if (!file.getName().contains(".svn")) { - - String filePath = file.getPath(); - String fileName = file.getName(); - map.put(fileName, readFileAsString(filePath)); - } - } - - return map; - - } - - public static String readFileAsString(String filePath) { - byte[] buffer = new byte[(int) new File(filePath).length()]; - BufferedInputStream f = null; - try { - f = new BufferedInputStream(new FileInputStream(filePath)); - f.read(buffer); - } catch ( IOException e){ - - LogUtils.errMsg("File not found: "+ filePath); - - System.exit(1); - - } finally { - if (f != null) - try { - f.close(); - } catch (IOException ignored) { - } - } - return new String(buffer); - } - - - public static String readFileAsString(String file, String csName) throws IOException { - Charset cs = Charset.forName(csName); - // Thanks to Jon Skeet - // No real need to close the BufferedReader/InputStreamReader - // as they're only wrapping the stream - FileInputStream stream = new FileInputStream(file); - try { - Reader reader = new BufferedReader(new InputStreamReader(stream, cs)); - StringBuilder builder = new StringBuilder(); - char[] buffer = new char[8192]; - int read; - while ((read = reader.read(buffer, 0, buffer.length)) > 0) { - builder.append(buffer, 0, read); - } - return builder.toString(); - } - finally { - // Potential issue here: if this throws an IOException, - // it will mask any others. Normally I'd use a utility - // method which would log exceptions and swallow them - stream.close(); - } - } - - public static String readFileLine(String filePath) throws IOException { - - File input = new File(filePath); - BufferedReader in = new BufferedReader(new FileReader(input)); - return in.readLine(); - } - - public static PrintWriter openFile(String dirPath, String fileName, boolean isAppend) throws IOException { - - File f = new File(dirPath, fileName); - File dir = new File(f.getParent()); - dir.mkdirs(); - f.createNewFile(); - - return new PrintWriter(new BufferedWriter(new FileWriter(f, isAppend))); - - } - - public static PrintWriter openFile(String dirPath, String fileName) throws IOException { - - return openFile(dirPath, fileName, false); - - } - - public static boolean deleteDir(String dirString) { - File dir = new File(dirString); - if (dir.isDirectory()) { - String[] children = dir.list(); - for (int i = 0; i < children.length; i++) { - boolean success = deleteDir(new File(dir, children[i]) - .getPath()); - if (!success) { - return false; - } - } - } - return dir.delete(); - } - - public static ArrayList getScopeList(ArrayList fileList, ArrayList localList) { - - ArrayList scopeList = new ArrayList(); - - for (String f : fileList) { - if (localList.contains(f)) { - scopeList.add("local"); - } - else { - scopeList.add("global"); - } - } - return scopeList; - - } - - public static Map getScopeMap(Set fileSet, Set localSet) { - - Map scopeMap = new HashMap(); - - for (String f : fileSet) { - if (localSet.contains(f)) { - scopeMap.put(f,Param.local); - } - else { - scopeMap.put(f,Param.global); - } - } - return scopeMap; - - } - - /// type 1 map is the shallow included files, e.g., map( f1, [f7,f9]) - public static Map> getReverseMap(Map> t1Map) { - - Map> out = new HashMap>(); - - for (String f : t1Map.keySet()) { - - for (String c : t1Map.get(f)) { - - if (out.get(c) == null) { - Set s = new HashSet(); - s.add(f); - out.put(c, s); - } - else { - out.get(c).add(f); - } - - } - - } - return out; - } - - /// type 1 map is the shallow included files, e.g., map( f1, [f7,f9]) - public static Map> getReverseMap_arrayList(Map> t1Map) { - - Map> out = new HashMap>(); - - for (String f : t1Map.keySet()){ - - for (String c : t1Map.get(f)){ - - ArrayList s; - if (out.get(c)==null) { s = new ArrayList(); s.add(f);} - else { s= out.get(c); s.add(f);} - - out.put(c, s); - - } - - } - return out; - } - - public static void mapRetainAll (Map map, ArrayList retainKeys){ - - Set mapKeys = new HashSet(map.keySet()); - Set removeKeys = new HashSet(mapKeys); - removeKeys.removeAll(retainKeys); - - for (String rkey: removeKeys){ - - map.remove(rkey); - } - - } - - public static Set mapRemoveAll (Map map, Set set){ - - Set removedKeys = new LinkedHashSet(); - - for (String key: set){ - - if (map.remove(key)!=null) removedKeys.add(key); - } - return removedKeys; - } - public static Set mapRemoveAll (Map map, ArrayList list){ - - return mapRemoveAll (map, new LinkedHashSet(list)); - } - - public static Set convertStrToSet(String inStr){ - - Set out = new HashSet(); - StringTokenizer st = new StringTokenizer(inStr); - - while (st.hasMoreTokens()) { - out.add(st.nextToken()); - } - out.remove("null"); - - return out; - } - - public static Set restoreOrder(ArrayList toBeRestored, ArrayList referenceOrder, - Set member) { - - ArrayList orderedList = new ArrayList(referenceOrder); - - Set nonMember = new HashSet(referenceOrder); - nonMember.removeAll(member); - - orderedList.removeAll(nonMember); - - toBeRestored = orderedList; - - return new LinkedHashSet(orderedList); - } - - public static Set removeDuplicates(ArrayList list) - { - Set s = new LinkedHashSet(list); - - ArrayList duplicatesList = new ArrayList(list); - - for (String x : s) { - duplicatesList.remove(x); - } - - list.clear(); - list.addAll(s); - - return new LinkedHashSet(duplicatesList); - } - - public static Map> getCycleVarMap(Set setVarCycle) - { - Map> out = new HashMap>(); - - for (String x : setVarCycle) { - - int posStart = x.indexOf("["); - int posEnd = x.indexOf("]"); - - String varName = x.substring(0,posStart); - String cycleName = x.substring(posStart+1, posEnd); - - if (out.keySet().contains(cycleName)){ - - out.get(cycleName).add(varName); - } - else{ - - Set setVarName = new HashSet(); - setVarName.add(varName); - out.put(cycleName, setVarName); - } - } - - return out; - } - public static void quickLog(String fn, String x, boolean isAppend) { - - File ilpRootDir = new File(FilePaths.mainDirectory, "=ILP="); - File ilpDir = new File(ilpRootDir, StudyUtils.configFileName); - - try { - PrintWriter quickLogFile = Tools.openFile(ilpDir.getAbsolutePath(), fn, isAppend); - quickLogFile.println(x); - quickLogFile.close(); - } catch (IOException e) { - System.err.println("Error: " + e.getMessage()); - } - - } - - public static void quickLog(String fn, String x) { - quickLog(fn, x, false); - } - - public static String noZerofmt(double d) - { - if(d == (long) d) - return String.format("%d",(long)d); - else - return String.format("%s",d); - } - - public static String findGoalLocation(String goalName){ - ModelDataSet mds = ControlData.currModelDataSet; - String sourceLocation = ""; - if (mds.gMap.containsKey(goalName)){ - Goal goal=mds.gMap.get(goalName); - sourceLocation="("+goal.fromWresl+":"+goal.line+")"; - } - return sourceLocation; - } -} +package wrimsv2.wreslplus.elements; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.io.Reader; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; + +import com.google.common.collect.HashBasedTable; + +import wrimsv2.commondata.wresldata.Goal; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; +import wrimsv2.wreslparser.elements.LogUtils; +import wrimsv2.wreslparser.elements.StudyUtils; + + +public class Tools { + public static String strip(String s) { + if (s==null) return null; + return s.substring(1, s.length() - 1); + } + + public static String getCanonicalLowCasePath(String filePath) { + + String canonicalPath_lowercase=null; + + try { + + canonicalPath_lowercase = new File(filePath).getCanonicalPath().toLowerCase(); + + } catch (IOException e) { + + e.printStackTrace(); + LogUtils.errMsg("IOException: " + filePath); + } + + return canonicalPath_lowercase; + + } + + public static HashSet findAllOffspring (String fileName, final Map> kidMap){ + + HashSet out = new HashSet(); + + if (!kidMap.keySet().contains(fileName)) return out; + + out.addAll(kidMap.get(fileName)); + + for (String kid : kidMap.get(fileName)) { + + out.addAll(findAllOffspring(kid, kidMap)); + + } + return out; + } + + // TODO: move to Tools + // be careful, the map is modified in this function + public static void findFileHierarchy(ArrayList> hierarchySetList, Map> toBeSorted) { + + //System.out.println("hierarchySetList"+hierarchySetList); + + if (!toBeSorted.isEmpty()) { + + HashSet c = new HashSet(); + Set toBeSorted_keySet = new HashSet(toBeSorted.keySet()); + for (String s : toBeSorted_keySet){ + + //System.out.println("%%% s: "+s); + + // TODO: inefficient. needs rewrite + HashSet ttt = new HashSet(); + for (HashSet ss : hierarchySetList){ ttt.addAll(ss); } + if ( ttt.containsAll(toBeSorted.get(s))) { + c.add(s); + toBeSorted.remove(s); + } + } + hierarchySetList.add(c); + findFileHierarchy(hierarchySetList, toBeSorted); + + } + + } + + //TODO: this can be optimized for memory + public static ArrayList allToUpperCase(ArrayList inArrayList){ + + ArrayList out = new ArrayList(); + + for (String s: inArrayList){ + out.add(s.toUpperCase()); + } + + return out; + } + //TODO: this can be optimized for memory + public static ArrayList allToLowerCase(ArrayList inArrayList){ + + ArrayList out = new ArrayList(); + + for (String s: inArrayList){ + out.add(s.toLowerCase()); + } + + return out; + } + public static ArrayList> allToLowerCase2(ArrayList> inArrayList){ + + ArrayList> out = new ArrayList>(); + + for (ArrayList s: inArrayList){ + out.add(allToLowerCase(s)); + } + + return out; + } + //TODO: this can be optimized for memory + public static Map allToLowerCase_string(Map inMap){ + + Map out = new LinkedHashMap(); + + for (String s: inMap.keySet()){ + out.put(s.toLowerCase(),inMap.get(s).toLowerCase()); + } + + return out; + } + public static Map> allToLowerCase_string_set(Map> inMap){ + + Map> out = new LinkedHashMap>(); + + for (String s: inMap.keySet()){ + out.put(s.toLowerCase(), (HashSet)allToLowerCase(inMap.get(s))); + } + + return out; + } + public static Map allToLowerCaseString(Map inMap){ + + Map out = new LinkedHashMap(); + + for (String s: inMap.keySet()){ + out.put(s.toLowerCase(),inMap.get(s)); + } + + return out; + } + public static LinkedHashMap allToLowerCase_weightSubgroup(Map inMap){ + + LinkedHashMap out = new LinkedHashMap(); + + for (String s: inMap.keySet()){ + out.put(s.toLowerCase(),allToLowerCase(inMap.get(s))); + } + + return out; + } + public static WeightSubgroup allToLowerCase(WeightSubgroup wsg){ + + WeightSubgroup out = new WeightSubgroup(); + + out.deviationPenalty = wsg.deviationPenalty.toLowerCase(); + out.deviationTolerance = wsg.deviationTolerance.toLowerCase(); + out.id = wsg.id; + out.varList = allToLowerCase(wsg.varList); + + return out; + } + public static Set allToLowerCase(Set inSet){ + + Set out = new LinkedHashSet(); + + for (String s: inSet){ + out.add(s.toLowerCase()); + } + + return out; + } + public static String replace_regex(String s) { + if (s==null) return null; + s=s.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)"); + s=s.replaceAll("\\.", "\\\\."); + s=s.replaceAll("\\*", "\\\\*"); + s=s.replaceAll("\\|", "\\\\|"); + s=s.replaceAll("\\+", "\\\\+"); + s=s.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]"); + s=s.replaceAll("##", ".+"); + return s; + } + public static String remove_nulls(String s) { + if (s==null) return null; + s=s.replaceAll("null", ""); + s=s.replaceAll("\\s+", " "); + return s; + } + public static ArrayList replace_with_space(ArrayList s) { + if (s==null) return null; + ArrayList o = new ArrayList(); + for (String e : s){ + o.add(replace_with_space(e)); + } + return o; + } + public static String replace_with_space(String s) { + if (s==null) return null; + s=s.replaceAll("\n+", " ").replaceAll("\r+", " "); + s=s.replaceAll("\t+", " "); + s=s.replaceAll("\\s+", " "); + return s; + } + public static ArrayList replace_ignoreChar(ArrayList s) { + if (s==null) return null; + ArrayList o = new ArrayList(); + for (String e : s){ + o.add(replace_ignoreChar(e)); + } + return o; + } + public static String replace_ignoreChar(String s) { + if (s==null) return null; + s=s.replaceAll("\n+", "").replaceAll("\r+", ""); + s=s.replaceAll("\t+", ""); + s=s.replaceAll("\\s+", ""); + return s; + } + public static ArrayList add_space_between_logical(ArrayList s) { + if (s==null) return s; + ArrayList o = new ArrayList(); + for (String e : s){ + o.add(add_space_between_logical(e)); + } + return o; + } + public static String add_space_between_logical(String s) { + if (s==null) return null; + + //s = replace_ignoreChar(s); + //s = replace_seperator(s); + + s=s.replaceAll("\\.AND\\.", " \\.and\\. "); + s=s.replaceAll("\\.OR\\.", " \\.or\\. "); + s=s.replaceAll("\\.and\\.", " \\.and\\. "); + s=s.replaceAll("\\.or\\.", " \\.or\\. "); + + return s; + } + public static ArrayList replace_seperator(ArrayList s) { + if (s.size()<1) return null; + ArrayList o = new ArrayList(); + for (String e: s){ + o.add(Tools.replace_seperator(e)); + } + return o; + } + public static String replace_seperator(String s) { + if (s==null) return null; + s=s.replaceAll(Param.arg_seperator,Param.new_seperator); + return s; + } + public static Map readFilesFromDirAsMap(String dir) + throws IOException { + File folder = new File(dir); + File[] listOfFiles = folder.listFiles(); + Map map = new HashMap(); + + for (File file : listOfFiles) { + + if (!file.getName().contains(".svn")) { + + String filePath = file.getPath(); + String fileName = file.getName(); + map.put(fileName, readFileAsString(filePath)); + } + } + + return map; + + } + + public static String readFileAsString(String filePath) { + byte[] buffer = new byte[(int) new File(filePath).length()]; + BufferedInputStream f = null; + try { + f = new BufferedInputStream(new FileInputStream(filePath)); + f.read(buffer); + } catch ( IOException e){ + + LogUtils.errMsg("File not found: "+ filePath); + + System.exit(1); + + } finally { + if (f != null) + try { + f.close(); + } catch (IOException ignored) { + } + } + return new String(buffer); + } + + + public static String readFileAsString(String file, String csName) throws IOException { + Charset cs = Charset.forName(csName); + // Thanks to Jon Skeet + // No real need to close the BufferedReader/InputStreamReader + // as they're only wrapping the stream + FileInputStream stream = new FileInputStream(file); + try { + Reader reader = new BufferedReader(new InputStreamReader(stream, cs)); + StringBuilder builder = new StringBuilder(); + char[] buffer = new char[8192]; + int read; + while ((read = reader.read(buffer, 0, buffer.length)) > 0) { + builder.append(buffer, 0, read); + } + return builder.toString(); + } + finally { + // Potential issue here: if this throws an IOException, + // it will mask any others. Normally I'd use a utility + // method which would log exceptions and swallow them + stream.close(); + } + } + + public static String readFileLine(String filePath) throws IOException { + + File input = new File(filePath); + BufferedReader in = new BufferedReader(new FileReader(input)); + return in.readLine(); + } + + public static PrintWriter openFile(String dirPath, String fileName, boolean isAppend) throws IOException { + + File f = new File(dirPath, fileName); + File dir = new File(f.getParent()); + dir.mkdirs(); + f.createNewFile(); + + return new PrintWriter(new BufferedWriter(new FileWriter(f, isAppend))); + + } + + public static PrintWriter openFile(String dirPath, String fileName) throws IOException { + + return openFile(dirPath, fileName, false); + + } + + public static boolean deleteDir(String dirString) { + File dir = new File(dirString); + if (dir.isDirectory()) { + String[] children = dir.list(); + for (int i = 0; i < children.length; i++) { + boolean success = deleteDir(new File(dir, children[i]) + .getPath()); + if (!success) { + return false; + } + } + } + return dir.delete(); + } + + public static ArrayList getScopeList(ArrayList fileList, ArrayList localList) { + + ArrayList scopeList = new ArrayList(); + + for (String f : fileList) { + if (localList.contains(f)) { + scopeList.add("local"); + } + else { + scopeList.add("global"); + } + } + return scopeList; + + } + + public static Map getScopeMap(Set fileSet, Set localSet) { + + Map scopeMap = new HashMap(); + + for (String f : fileSet) { + if (localSet.contains(f)) { + scopeMap.put(f,Param.local); + } + else { + scopeMap.put(f,Param.global); + } + } + return scopeMap; + + } + + /// type 1 map is the shallow included files, e.g., map( f1, [f7,f9]) + public static Map> getReverseMap(Map> t1Map) { + + Map> out = new HashMap>(); + + for (String f : t1Map.keySet()) { + + for (String c : t1Map.get(f)) { + + if (out.get(c) == null) { + Set s = new HashSet(); + s.add(f); + out.put(c, s); + } + else { + out.get(c).add(f); + } + + } + + } + return out; + } + + /// type 1 map is the shallow included files, e.g., map( f1, [f7,f9]) + public static Map> getReverseMap_arrayList(Map> t1Map) { + + Map> out = new HashMap>(); + + for (String f : t1Map.keySet()){ + + for (String c : t1Map.get(f)){ + + ArrayList s; + if (out.get(c)==null) { s = new ArrayList(); s.add(f);} + else { s= out.get(c); s.add(f);} + + out.put(c, s); + + } + + } + return out; + } + + public static void mapRetainAll (Map map, ArrayList retainKeys){ + + Set mapKeys = new HashSet(map.keySet()); + Set removeKeys = new HashSet(mapKeys); + removeKeys.removeAll(retainKeys); + + for (String rkey: removeKeys){ + + map.remove(rkey); + } + + } + + public static Set mapRemoveAll (Map map, Set set){ + + Set removedKeys = new LinkedHashSet(); + + for (String key: set){ + + if (map.remove(key)!=null) removedKeys.add(key); + } + return removedKeys; + } + public static Set mapRemoveAll (Map map, ArrayList list){ + + return mapRemoveAll (map, new LinkedHashSet(list)); + } + + public static Set convertStrToSet(String inStr){ + + Set out = new HashSet(); + StringTokenizer st = new StringTokenizer(inStr); + + while (st.hasMoreTokens()) { + out.add(st.nextToken()); + } + out.remove("null"); + + return out; + } + + public static Set restoreOrder(ArrayList toBeRestored, ArrayList referenceOrder, + Set member) { + + ArrayList orderedList = new ArrayList(referenceOrder); + + Set nonMember = new HashSet(referenceOrder); + nonMember.removeAll(member); + + orderedList.removeAll(nonMember); + + toBeRestored = orderedList; + + return new LinkedHashSet(orderedList); + } + + public static Set removeDuplicates(ArrayList list) + { + Set s = new LinkedHashSet(list); + + ArrayList duplicatesList = new ArrayList(list); + + for (String x : s) { + duplicatesList.remove(x); + } + + list.clear(); + list.addAll(s); + + return new LinkedHashSet(duplicatesList); + } + + public static Map> getCycleVarMap(Set setVarCycle) + { + Map> out = new HashMap>(); + + for (String x : setVarCycle) { + + int posStart = x.indexOf("["); + int posEnd = x.indexOf("]"); + + String varName = x.substring(0,posStart); + String cycleName = x.substring(posStart+1, posEnd); + + if (out.keySet().contains(cycleName)){ + + out.get(cycleName).add(varName); + } + else{ + + Set setVarName = new HashSet(); + setVarName.add(varName); + out.put(cycleName, setVarName); + } + } + + return out; + } + public static void quickLog(String fn, String x, boolean isAppend) { + + File ilpRootDir = new File(FilePaths.mainDirectory, "=ILP="); + File ilpDir = new File(ilpRootDir, StudyUtils.configFileName); + + try { + PrintWriter quickLogFile = Tools.openFile(ilpDir.getAbsolutePath(), fn, isAppend); + quickLogFile.println(x); + quickLogFile.close(); + } catch (IOException e) { + System.err.println("Error: " + e.getMessage()); + } + + } + + public static void quickLog(String fn, String x) { + quickLog(fn, x, false); + } + + public static String noZerofmt(double d) + { + if(d == (long) d) + return String.format("%d",(long)d); + else + return String.format("%s",d); + } + + public static String findGoalLocation(String goalName){ + ModelDataSet mds = ControlData.currModelDataSet; + String sourceLocation = ""; + if (mds.gMap.containsKey(goalName)){ + Goal goal=mds.gMap.get(goalName); + sourceLocation="("+goal.fromWresl+":"+goal.line+")"; + } + return sourceLocation; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/VarCycleIndex.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/VarCycleIndex.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/VarCycleIndex.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/VarCycleIndex.java index b33d6a655..c64c61e6c 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/VarCycleIndex.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/VarCycleIndex.java @@ -1,11 +1,11 @@ -package wrimsv2.wreslplus.elements; - -import java.util.ArrayList; - -public class VarCycleIndex { - public static ArrayList varCycleIndexList= new ArrayList(); - - public static void clearVarCycleIndexList(){ - varCycleIndexList = new ArrayList(); - } -} +package wrimsv2.wreslplus.elements; + +import java.util.ArrayList; + +public class VarCycleIndex { + public static ArrayList varCycleIndexList= new ArrayList(); + + public static void clearVarCycleIndexList(){ + varCycleIndexList = new ArrayList(); + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/WeightSubgroup.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/WeightSubgroup.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/WeightSubgroup.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/WeightSubgroup.java index a1b734b64..8d75509a6 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/WeightSubgroup.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/WeightSubgroup.java @@ -1,26 +1,26 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.ArrayList; - -import wrimsv2.commondata.wresldata.Param; - -public class WeightSubgroup implements Serializable { - - private static final long serialVersionUID = 1L; - public String id; - public ArrayList varList; - public String deviationPenalty; - public String deviationTolerance; - //public ArrayList subgroup; - - public WeightSubgroup(){ - varList = new ArrayList(); - deviationPenalty = Param.zero; // default is zero - deviationTolerance = Param.zero; - //subgroup = new ArrayList(); - - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.ArrayList; + +import wrimsv2.commondata.wresldata.Param; + +public class WeightSubgroup implements Serializable { + + private static final long serialVersionUID = 1L; + public String id; + public ArrayList varList; + public String deviationPenalty; + public String deviationTolerance; + //public ArrayList subgroup; + + public WeightSubgroup(){ + varList = new ArrayList(); + deviationPenalty = Param.zero; // default is zero + deviationTolerance = Param.zero; + //subgroup = new ArrayList(); + + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/WeightTable.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/WeightTable.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/WeightTable.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/WeightTable.java index b6e57717b..f199a9d1d 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/WeightTable.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/WeightTable.java @@ -1,55 +1,55 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; - -public class WeightTable implements Serializable { - - private static final long serialVersionUID = 1L; - public String id_lowcase; - public String id_raw; - public boolean isWeightGroup; - public String condition; - public String fromWresl; - public int line; - public Set dependants; - public ArrayList varList; - public Map varWeightMap; - public Map varLineMap; - public String commonWeight; - public String deviationPenalty; - public String deviationTolerance; - //public ArrayList subgroup; - public Map subgroupMap; - //public ArrayList weightGroupList; - //public Map> varDependantMap; - public Map varTimeArraySizeMap; - - - public WeightTable(){ - isWeightGroup = false; - condition = Param.always; - fromWresl = Param.undefined; - dependants = new LinkedHashSet(); - varList = new ArrayList(); - varWeightMap = new LinkedHashMap(); - varLineMap = new LinkedHashMap(); - commonWeight = Param.undefined; - deviationPenalty = Param.zero; - deviationTolerance = Param.zero; - //subgroup = new ArrayList(); - subgroupMap = new LinkedHashMap(); - //weightGroupList = new ArrayList(); - //varDependantMap = new LinkedHashMap>(); - varTimeArraySizeMap = new LinkedHashMap(); - - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; + +public class WeightTable implements Serializable { + + private static final long serialVersionUID = 1L; + public String id_lowcase; + public String id_raw; + public boolean isWeightGroup; + public String condition; + public String fromWresl; + public int line; + public Set dependants; + public ArrayList varList; + public Map varWeightMap; + public Map varLineMap; + public String commonWeight; + public String deviationPenalty; + public String deviationTolerance; + //public ArrayList subgroup; + public Map subgroupMap; + //public ArrayList weightGroupList; + //public Map> varDependantMap; + public Map varTimeArraySizeMap; + + + public WeightTable(){ + isWeightGroup = false; + condition = Param.always; + fromWresl = Param.undefined; + dependants = new LinkedHashSet(); + varList = new ArrayList(); + varWeightMap = new LinkedHashMap(); + varLineMap = new LinkedHashMap(); + commonWeight = Param.undefined; + deviationPenalty = Param.zero; + deviationTolerance = Param.zero; + //subgroup = new ArrayList(); + subgroupMap = new LinkedHashMap(); + //weightGroupList = new ArrayList(); + //varDependantMap = new LinkedHashMap>(); + varTimeArraySizeMap = new LinkedHashMap(); + + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/WeightTemp.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/WeightTemp.java similarity index 94% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/WeightTemp.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/WeightTemp.java index 312f198df..6c63eae12 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/WeightTemp.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/WeightTemp.java @@ -1,30 +1,30 @@ -package wrimsv2.wreslplus.elements; - -import java.io.Serializable; - -import wrimsv2.commondata.wresldata.Param; - -public class WeightTemp implements Serializable { - - private static final long serialVersionUID = 1L; - public String id; - public String weight; - public String condition; - public String fromWresl; - public int line=1; - - public String timeArraySize; - public String arraySize; - - public WeightTemp(){ - weight = Param.undefined; - condition = Param.always; - fromWresl = Param.undefined; - - timeArraySize="0"; - arraySize="0"; - - } - -} - +package wrimsv2.wreslplus.elements; + +import java.io.Serializable; + +import wrimsv2.commondata.wresldata.Param; + +public class WeightTemp implements Serializable { + + private static final long serialVersionUID = 1L; + public String id; + public String weight; + public String condition; + public String fromWresl; + public int line=1; + + public String timeArraySize; + public String arraySize; + + public WeightTemp(){ + weight = Param.undefined; + condition = Param.always; + fromWresl = Param.undefined; + + timeArraySize="0"; + arraySize="0"; + + } + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/Workflow.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/Workflow.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/Workflow.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/Workflow.java index 72540a0bb..1e920160d 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/Workflow.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/Workflow.java @@ -1,326 +1,326 @@ -package wrimsv2.wreslplus.elements; - -import java.io.File; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.io.FilenameUtils; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.components.ControlData; -import wrimsv2.components.FilePaths; -import wrimsv2.config.ConfigUtils; -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslparser.elements.StudyParser; -import wrimsv2.wreslparser.elements.StudyUtils; -import wrimsv2.wreslplus.elements.procedures.ErrorCheck; -import wrimsv2.wreslplus.elements.procedures.ProcGoal; -import wrimsv2.wreslplus.elements.procedures.ProcIfIncItemGroup; -import wrimsv2.wreslplus.elements.procedures.ProcMainFile; -import wrimsv2.wreslplus.elements.procedures.ProcIncFile; -import wrimsv2.wreslplus.elements.procedures.ProcParameter; -import wrimsv2.wreslplus.elements.procedures.ProcVarIncFileList; -import wrimsv2.wreslplus.elements.procedures.ProcWeight; -import wrimsv2.wreslplus.elements.procedures.ToLowerCase; - -public class Workflow { - - - private Workflow(){} - - - public static StudyTemp checkStudy(String mainFilePath) { - - StudyParser.reset(); - - String canonicalMainFilePath = Tools.getCanonicalLowCasePath(mainFilePath); - - ParserUtils.setRunDir(new File(canonicalMainFilePath).getParent()); - - VarCycleIndex.clearVarCycleIndexList(); - - StudyTemp st = ParserUtils.parseWreslMain(canonicalMainFilePath); - // TODO: need to check sequence error here - // check study - - if (StudyParser.total_errors>0) { - - LogUtils.parsingSummaryMsg("Wresl+ parsing aborted", StudyParser.total_errors); - - return null; - } - - - if (ErrorCheck.checkIncModelNotExistIgnoreCase(st)) return null; - if (ErrorCheck.checkModelRedefinedIgnoreCase(st)>0) return null; - if (ErrorCheck.checkSequenceHasUniqueModel(st)>0) return null; - if (ErrorCheck.checkVarRedefined(st)>0) return null; - - ToLowerCase.convert(st); - - if (ErrorCheck.checkVarRedefined(st)>0) return null; - - // for Error.log header - ControlData.currEvalTypeIndex=8; - - // check config param not declared in wresl main file - if (ErrorCheck.checkInitialVarInConfigNotDeclaredInWresl(st)) return null; - - // overwrite main wresl parameter with config file parameter - if (ConfigUtils.paramMap.size()>0){ - - for (String k: ConfigUtils.paramMap.keySet()){ - ParamTemp pt = ConfigUtils.paramMap.get(k); - SvarTemp svObj = new SvarTemp(); - svObj.id = pt.id; - svObj.caseName.add(Param.defaultCaseName); - svObj.caseCondition.add(Param.always); - svObj.caseExpression.add(pt.expression); - svObj.dependants = pt.dependants; - - LogUtils.importantMsg("Overwrite initial variable ["+ k +"] in main wresl file."); - st.parameterMap.put(k,svObj); - } - - } - - // check param dependents unknown - if (ErrorCheck.checkInitialConst(st)) return null; - if (ErrorCheck.checkParameterHasUnknownDepedants(st)) return null; - - ProcParameter.process(st); - - if (ErrorCheck.checkSeqConditionHasUnknownDepedants(st)) return null; - - // check unknown dependants in if statement - ErrorCheck.checkIfStatementHasUnknownDependants(st); - - // process "if include file group" - ProcIfIncItemGroup.process(st); - - - ProcMainFile.findEffectiveModel(st); - - ProcMainFile.findKidMap_incModel(st); - ProcMainFile.findAllOffSpring_incModel(st); - ProcMainFile.findGroupOrder_incModel(st); - - - ProcMainFile.findEffectiveIncludeModel(st); - - - ProcIncFile.processPath(st); - - - ProcVarIncFileList.replaceIncFile(st); - - - Procedures.processDependants(st); - - - - - /// put effective models into fileModelDataTable - - for (String modelName: st.modelList_effective){ - - ModelTemp mt = st.modelMap.get(modelName); // this is model in main file - - if (st.fileModelNameMap.keySet().contains(mt.pathRelativeToRunDir)) { - - st.fileModelNameMap.get(mt.pathRelativeToRunDir).add(modelName); - - } else { - ArrayList modelNameList = new ArrayList(); - modelNameList.add(modelName); - st.fileModelNameMap.put(mt.pathRelativeToRunDir, modelNameList); - } - - st.fileModelDataTable.put(mt.pathRelativeToRunDir, modelName, mt); - - } - - /// put effective include models into fileModelDataTable - for (String incM: st.incModelList_effective){ - - ModelTemp incMt = st.modelMap.get(incM); // this is model in main file - - if (st.fileModelNameMap.keySet().contains(incMt.pathRelativeToRunDir)) { - - st.fileModelNameMap.get(incMt.pathRelativeToRunDir).add(incM); - - } else { - ArrayList modelNameList = new ArrayList(); - modelNameList.add(incM); - st.fileModelNameMap.put(incMt.pathRelativeToRunDir, modelNameList); - } - - st.fileModelDataTable.put(incMt.pathRelativeToRunDir, incM, incMt); - - } - - // parse modelList_effective all included files - // store results to a map using relativePath as key - for (String se : st.seqList){ - - SequenceTemp seqObj = st.seqMap.get(se); - String m = seqObj.model; - - ModelTemp mt = st.modelMap.get(m); - - ParserUtils.parseAllIncFile(mt.incFileRelativePathList, st); - - } - - // parse incModelList_effective all included files - // store results to a map using relativePath as key - for (String incM : st.incModelList_effective){ - - ModelTemp mt = st.modelMap.get(incM); - - ParserUtils.parseAllIncFile(mt.incFileRelativePathList, st); - - } - - - if (StudyParser.total_errors>0) { - - LogUtils.parsingSummaryMsg("Wresl+ parsing stopped", StudyParser.total_errors); - if (ControlData.showWreslLog) { - for (String e:StudyParser.error_summary){ - System.err.println( e); - } - } - for (String e:StudyParser.error_summary){ - LogUtils._logFile.println(e); - } - LogUtils._logFile.flush(); - - return null; - } - - // find all offspring - // store results to kidMap and AOMap, fileGroupOrder - Procedures.findKidMap(st); - - - Procedures.findAllOffSpring(st); - - - Procedures.findFileGroupOrder(st); - - - Procedures.postProcessIncFileList(st); - - - Procedures.postProcessVarListinIncFile(st); - - ProcGoal.processGoalHS2(st); - - ProcWeight.collectWeightVar(st); - - - // filter weight groups from the weight Object list and then process them - // TODO: need to rewrite - - ProcWeight.processWeightGroup(st); - - if(Procedures.copyModelVarMapToSequenceVarMap(st)) return null; - - - if (ErrorCheck.checkWeightObjList(st)) return null; - - ErrorCheck.checkVarRedefined(st); - - Procedures.classifyDependants(st); // TODO: has bug. need to fix. also a bottleneck. - - if (StudyUtils.parserCheckVarUndefined) { - LogUtils.importantMsg("Check variables used before defined ..."); - ErrorCheck.checkVarUsedBeforeDefined(st); - } - - LogUtils.importantMsg("Convert aliases to goals ..."); - Procedures.convertAliasToGoal(st); // TODO: bottleneck. need to optimize. - - ErrorCheck.checkWeightVarNotInDvar(st); - - Procedures.analyzeVarNeededFromCycle(st); - Procedures.createSpaceInVarCycleValueMap(st); - - - Procedures.collectTimeStep(st); - - - LogUtils.parsingSummaryMsg("Wresl+ parsing completed",StudyParser.total_errors); - - if (StudyParser.total_errors>0) return null; - - return st; - - } - - - public static StudyTemp checkStudy_compileLog(String mainFilePath) { - - StudyParser.reset(); - VarCycleIndex.clearVarCycleIndexList(); - - - String canonicalMainFilePath = Tools.getCanonicalLowCasePath(mainFilePath); - - String runDir = new File(canonicalMainFilePath).getParent(); - String mainFileName = new File(canonicalMainFilePath).getName(); - - ParserUtils.setRunDir(runDir); - - String compileLogDir = "z:\\compileLog\\"+FilenameUtils.getPath(runDir); - - - new File(compileLogDir).mkdirs(); - - StudyTemp st = ParserUtils.parseWreslMain(canonicalMainFilePath); - - LinkedHashMap fileMap_reverse = new LinkedHashMap(); - - String mainString = CompileLog.createMainWreslLog(st, fileMap_reverse); - CompileLog.writeLog(mainString, new File (compileLogDir, mainFileName).getAbsolutePath()); - - - for (String filePath : fileMap_reverse.keySet()) { - - String absFilePath = st.runDir + "\\" + filePath; - - ModelTemp mt = ParserUtils.parseWreslFile(absFilePath); - - - Set deps = new LinkedHashSet(); - String w = CompileLog.createWreslFileLog(mt, deps); - - // write dependents - w= "\n" + w; - for (String d : deps){ w= d +" " + w; } - w = "@dep: "+ w; - - - File f = new File (compileLogDir, filePath); - File dir = f.getParentFile(); - if (! dir.exists()) dir.mkdirs(); - - CompileLog.writeLog(w, f.getAbsolutePath()); - - } - - - - - return st; - - } - - - -} - +package wrimsv2.wreslplus.elements; + +import java.io.File; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.io.FilenameUtils; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.components.ControlData; +import wrimsv2.components.FilePaths; +import wrimsv2.config.ConfigUtils; +import wrimsv2.wreslparser.elements.LogUtils; +import wrimsv2.wreslparser.elements.StudyParser; +import wrimsv2.wreslparser.elements.StudyUtils; +import wrimsv2.wreslplus.elements.procedures.ErrorCheck; +import wrimsv2.wreslplus.elements.procedures.ProcGoal; +import wrimsv2.wreslplus.elements.procedures.ProcIfIncItemGroup; +import wrimsv2.wreslplus.elements.procedures.ProcMainFile; +import wrimsv2.wreslplus.elements.procedures.ProcIncFile; +import wrimsv2.wreslplus.elements.procedures.ProcParameter; +import wrimsv2.wreslplus.elements.procedures.ProcVarIncFileList; +import wrimsv2.wreslplus.elements.procedures.ProcWeight; +import wrimsv2.wreslplus.elements.procedures.ToLowerCase; + +public class Workflow { + + + private Workflow(){} + + + public static StudyTemp checkStudy(String mainFilePath) { + + StudyParser.reset(); + + String canonicalMainFilePath = Tools.getCanonicalLowCasePath(mainFilePath); + + ParserUtils.setRunDir(new File(canonicalMainFilePath).getParent()); + + VarCycleIndex.clearVarCycleIndexList(); + + StudyTemp st = ParserUtils.parseWreslMain(canonicalMainFilePath); + // TODO: need to check sequence error here + // check study + + if (StudyParser.total_errors>0) { + + LogUtils.parsingSummaryMsg("Wresl+ parsing aborted", StudyParser.total_errors); + + return null; + } + + + if (ErrorCheck.checkIncModelNotExistIgnoreCase(st)) return null; + if (ErrorCheck.checkModelRedefinedIgnoreCase(st)>0) return null; + if (ErrorCheck.checkSequenceHasUniqueModel(st)>0) return null; + if (ErrorCheck.checkVarRedefined(st)>0) return null; + + ToLowerCase.convert(st); + + if (ErrorCheck.checkVarRedefined(st)>0) return null; + + // for Error.log header + ControlData.currEvalTypeIndex=8; + + // check config param not declared in wresl main file + if (ErrorCheck.checkInitialVarInConfigNotDeclaredInWresl(st)) return null; + + // overwrite main wresl parameter with config file parameter + if (ConfigUtils.paramMap.size()>0){ + + for (String k: ConfigUtils.paramMap.keySet()){ + ParamTemp pt = ConfigUtils.paramMap.get(k); + SvarTemp svObj = new SvarTemp(); + svObj.id = pt.id; + svObj.caseName.add(Param.defaultCaseName); + svObj.caseCondition.add(Param.always); + svObj.caseExpression.add(pt.expression); + svObj.dependants = pt.dependants; + + LogUtils.importantMsg("Overwrite initial variable ["+ k +"] in main wresl file."); + st.parameterMap.put(k,svObj); + } + + } + + // check param dependents unknown + if (ErrorCheck.checkInitialConst(st)) return null; + if (ErrorCheck.checkParameterHasUnknownDepedants(st)) return null; + + ProcParameter.process(st); + + if (ErrorCheck.checkSeqConditionHasUnknownDepedants(st)) return null; + + // check unknown dependants in if statement + ErrorCheck.checkIfStatementHasUnknownDependants(st); + + // process "if include file group" + ProcIfIncItemGroup.process(st); + + + ProcMainFile.findEffectiveModel(st); + + ProcMainFile.findKidMap_incModel(st); + ProcMainFile.findAllOffSpring_incModel(st); + ProcMainFile.findGroupOrder_incModel(st); + + + ProcMainFile.findEffectiveIncludeModel(st); + + + ProcIncFile.processPath(st); + + + ProcVarIncFileList.replaceIncFile(st); + + + Procedures.processDependants(st); + + + + + /// put effective models into fileModelDataTable + + for (String modelName: st.modelList_effective){ + + ModelTemp mt = st.modelMap.get(modelName); // this is model in main file + + if (st.fileModelNameMap.keySet().contains(mt.pathRelativeToRunDir)) { + + st.fileModelNameMap.get(mt.pathRelativeToRunDir).add(modelName); + + } else { + ArrayList modelNameList = new ArrayList(); + modelNameList.add(modelName); + st.fileModelNameMap.put(mt.pathRelativeToRunDir, modelNameList); + } + + st.fileModelDataTable.put(mt.pathRelativeToRunDir, modelName, mt); + + } + + /// put effective include models into fileModelDataTable + for (String incM: st.incModelList_effective){ + + ModelTemp incMt = st.modelMap.get(incM); // this is model in main file + + if (st.fileModelNameMap.keySet().contains(incMt.pathRelativeToRunDir)) { + + st.fileModelNameMap.get(incMt.pathRelativeToRunDir).add(incM); + + } else { + ArrayList modelNameList = new ArrayList(); + modelNameList.add(incM); + st.fileModelNameMap.put(incMt.pathRelativeToRunDir, modelNameList); + } + + st.fileModelDataTable.put(incMt.pathRelativeToRunDir, incM, incMt); + + } + + // parse modelList_effective all included files + // store results to a map using relativePath as key + for (String se : st.seqList){ + + SequenceTemp seqObj = st.seqMap.get(se); + String m = seqObj.model; + + ModelTemp mt = st.modelMap.get(m); + + ParserUtils.parseAllIncFile(mt.incFileRelativePathList, st); + + } + + // parse incModelList_effective all included files + // store results to a map using relativePath as key + for (String incM : st.incModelList_effective){ + + ModelTemp mt = st.modelMap.get(incM); + + ParserUtils.parseAllIncFile(mt.incFileRelativePathList, st); + + } + + + if (StudyParser.total_errors>0) { + + LogUtils.parsingSummaryMsg("Wresl+ parsing stopped", StudyParser.total_errors); + if (ControlData.showWreslLog) { + for (String e:StudyParser.error_summary){ + System.err.println( e); + } + } + for (String e:StudyParser.error_summary){ + LogUtils._logFile.println(e); + } + LogUtils._logFile.flush(); + + return null; + } + + // find all offspring + // store results to kidMap and AOMap, fileGroupOrder + Procedures.findKidMap(st); + + + Procedures.findAllOffSpring(st); + + + Procedures.findFileGroupOrder(st); + + + Procedures.postProcessIncFileList(st); + + + Procedures.postProcessVarListinIncFile(st); + + ProcGoal.processGoalHS2(st); + + ProcWeight.collectWeightVar(st); + + + // filter weight groups from the weight Object list and then process them + // TODO: need to rewrite + + ProcWeight.processWeightGroup(st); + + if(Procedures.copyModelVarMapToSequenceVarMap(st)) return null; + + + if (ErrorCheck.checkWeightObjList(st)) return null; + + ErrorCheck.checkVarRedefined(st); + + Procedures.classifyDependants(st); // TODO: has bug. need to fix. also a bottleneck. + + if (StudyUtils.parserCheckVarUndefined) { + LogUtils.importantMsg("Check variables used before defined ..."); + ErrorCheck.checkVarUsedBeforeDefined(st); + } + + LogUtils.importantMsg("Convert aliases to goals ..."); + Procedures.convertAliasToGoal(st); // TODO: bottleneck. need to optimize. + + ErrorCheck.checkWeightVarNotInDvar(st); + + Procedures.analyzeVarNeededFromCycle(st); + Procedures.createSpaceInVarCycleValueMap(st); + + + Procedures.collectTimeStep(st); + + + LogUtils.parsingSummaryMsg("Wresl+ parsing completed",StudyParser.total_errors); + + if (StudyParser.total_errors>0) return null; + + return st; + + } + + + public static StudyTemp checkStudy_compileLog(String mainFilePath) { + + StudyParser.reset(); + VarCycleIndex.clearVarCycleIndexList(); + + + String canonicalMainFilePath = Tools.getCanonicalLowCasePath(mainFilePath); + + String runDir = new File(canonicalMainFilePath).getParent(); + String mainFileName = new File(canonicalMainFilePath).getName(); + + ParserUtils.setRunDir(runDir); + + String compileLogDir = "z:\\compileLog\\"+FilenameUtils.getPath(runDir); + + + new File(compileLogDir).mkdirs(); + + StudyTemp st = ParserUtils.parseWreslMain(canonicalMainFilePath); + + LinkedHashMap fileMap_reverse = new LinkedHashMap(); + + String mainString = CompileLog.createMainWreslLog(st, fileMap_reverse); + CompileLog.writeLog(mainString, new File (compileLogDir, mainFileName).getAbsolutePath()); + + + for (String filePath : fileMap_reverse.keySet()) { + + String absFilePath = st.runDir + "\\" + filePath; + + ModelTemp mt = ParserUtils.parseWreslFile(absFilePath); + + + Set deps = new LinkedHashSet(); + String w = CompileLog.createWreslFileLog(mt, deps); + + // write dependents + w= "\n" + w; + for (String d : deps){ w= d +" " + w; } + w = "@dep: "+ w; + + + File f = new File (compileLogDir, filePath); + File dir = f.getParentFile(); + if (! dir.exists()) dir.mkdirs(); + + CompileLog.writeLog(w, f.getAbsolutePath()); + + } + + + + + return st; + + } + + + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ErrorCheck.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ErrorCheck.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ErrorCheck.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ErrorCheck.java index d29320c86..2b8fa3228 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ErrorCheck.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ErrorCheck.java @@ -1,803 +1,803 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.components.ControlData; -import wrimsv2.components.Error; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.config.ConfigUtils; -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslplus.elements.AliasTemp; -import wrimsv2.wreslplus.elements.DvarTemp; -import wrimsv2.wreslplus.elements.GoalTemp; -import wrimsv2.wreslplus.elements.IfIncItemGroup; -import wrimsv2.wreslplus.elements.ModelTemp; -import wrimsv2.wreslplus.elements.ParamTemp; -import wrimsv2.wreslplus.elements.SequenceTemp; -import wrimsv2.wreslplus.elements.StudyTemp; -import wrimsv2.wreslplus.elements.SvarTemp; -import wrimsv2.wreslplus.elements.Tools; -import wrimsv2.wreslplus.elements.WeightSubgroup; -import wrimsv2.wreslplus.elements.WeightTable; - -public class ErrorCheck { - - - private ErrorCheck(){} - -// // these dvars are from slack and surplus of weight group deviation penalty -// public static boolean checkDeviationSlackSurplus(ArrayList dvList_monitored, Map dvMap) { -// -// ArrayList errorList = new ArrayList(); -// -// for (String x : dvList_monitored){ -// -// double v = (Double) dvMap.get(x).getData().getData(); -// -// if (v > Param.deviationSlackSurplusTolerance) { -// -// errorList.add(x); -// -// } -// -// } -// -// if (errorList.size()>0) { -// -// Error.addDeviationError( " Deviation slack and surplus are not zero: "+errorList); -// Error.writeDeviationErrorFile("Error_deviation.txt"); -// return true; -// -// } -// -// return false; -// -// } - - // these dvars are from slack and surplus of weight group deviation penalty - public static boolean checkDeviationSlackSurplus(Map deviationSS_toleranceMap, Map dvMap) { - - ArrayList errorList = new ArrayList(); - - for (String x : deviationSS_toleranceMap.keySet()){ - - double v = (Double) dvMap.get(x).getData().getData(); - - if (v > deviationSS_toleranceMap.get(x)) { - - errorList.add(x); - Error.addDeviationError( "Tolerance of ["+ deviationSS_toleranceMap.get(x) +"] exceeded by deviation slack and surplus: ["+x+"]"); - - } - - } - - if (errorList.size()>0) { - - Error.writeDeviationErrorFile("Error_deviation.txt"); - Error.writeErrorLog(); - return true; - - } - - return false; - - } - - // TODO: this process alias only. need to expand to other types - public static void checkVarUsedBeforeDefined(StudyTemp s) { - - for (String se : s.seqList){ - - SequenceTemp seqObj = s.seqMap.get(se); - - checkVarUsedBeforeDefined(seqObj); - } - } - - public static void checkVarUsedBeforeDefined(SequenceTemp seqObj) { - -/* for (String key : seqObj.asMap.keySet()) { - - AliasTemp asObj = seqObj.asMap.get(key); - - Set temp = new HashSet(asObj.dependants); - temp.removeAll(seqObj.tsList); - temp.removeAll(seqObj.asMap.keySet()); - temp.removeAll(seqObj.dvList); - temp.removeAll(seqObj.svMap.keySet()); - temp.removeAll(asObj.dependants_parameter); - asObj.dependants_unknown = temp; - - if (asObj.dependants_unknown.size()>0){ - String msg = "In model ["+seqObj.model+"] variable(s) not defined before use: "+asObj.dependants_unknown+" in Alias ["+asObj.id+"]"; - LogUtils.errMsgLocation(asObj.fromWresl, asObj.line, msg); - } - - } - - - for (String key : seqObj.glMap.keySet()) { - - GoalTemp glObj = seqObj.glMap.get(key); - - Set temp = new HashSet(glObj.dependants); - temp.removeAll(seqObj.tsList); - temp.removeAll(seqObj.asMap.keySet()); - temp.removeAll(seqObj.dvList); - temp.removeAll(seqObj.svMap.keySet()); - temp.removeAll(seqObj.exList); - temp.removeAll(glObj.dependants_parameter); - glObj.dependants_unknown = temp; - - if (glObj.dependants_unknown.size()>0){ - String msg = "In model ["+seqObj.model+"] variable(s) not defined before use: "+glObj.dependants_unknown+" in Goal ["+glObj.id+"]"; - LogUtils.errMsgLocation(glObj.fromWresl, glObj.line, msg); - } - - } - */ - - for (int i=0; i temp = new HashSet(svObj.dependants); - temp.removeAll(seqObj.tsList); - temp.removeAll(seqObj.asMap.keySet()); - temp.removeAll(seqObj.dvList); - temp.removeAll(seqObj.svMap.keySet()); - temp.removeAll(seqObj.exList); - temp.removeAll(svObj.dependants_parameter); - svObj.dependants_unknown = temp; - - - if (svObj.dependants_unknown.size()>0){ - String msg = "In Sequence: ["+seqObj.id+"] Svar: ["+ svObj.id + "] has unknown variable(s): "+svObj.dependants_unknown; - LogUtils.errMsgLocation(svObj.fromWresl, svObj.line, msg); - - - } else { - - for (String dep: svObj.dependants_svar){ - - if ( seqObj.svIncFileList_post.indexOf(dep)> i){ - String msg = "In Sequence: ["+seqObj.id+"] Svar: ["+ svObj.id + "] has variable(s) not defined before use: "+dep; - LogUtils.errMsgLocation(svObj.fromWresl, svObj.line, msg); - } - - } - - } - - } - - } - - public static boolean checkIncModelNotExistIgnoreCase (StudyTemp s){ - - ArrayList modelList_lowercase = new ArrayList(); - - modelList_lowercase.addAll(Tools.allToLowerCase(s.modelList)); - - //System.out.println("modelList_lowercase:"+modelList_lowercase); - - for (ModelTemp mt: s.modelMap.values()){ - - for ( String incM: mt.incModelList) { - - if ( !modelList_lowercase.contains(incM.toLowerCase())) { - - LogUtils.errMsg("Include model ["+ incM +"] not exist in model ["+mt.id+"]."); - - return true; - } - - } - - } - - return false; - - } - - public static int checkSequenceHasUniqueModel (StudyTemp s){ - - ArrayList modelList = new ArrayList(); - - //modelList_lowercase.addAll(Tools.allToLowerCase(s.modelList)); - - - for (SequenceTemp seq: s.seqMap.values()){ - - modelList.add(seq.model.toLowerCase()); - - } - - ArrayList modelDup = findDuplicatesIgnoreCase(modelList); - - for (String m:modelDup){ - LogUtils.errMsg("Each sequence must define unique model. ["+ m +"] is used in multiple sequences."); - } - return modelDup.size(); - - - - } - - public static int checkModelRedefinedIgnoreCase (StudyTemp s){ - - ArrayList modelDup = findDuplicatesIgnoreCase(s.modelList); - - //System.out.println("modelDup:"+modelDup); - - for (String m:modelDup){ - LogUtils.errMsg("Model ["+ m +"] redefined in main file."); - } - return modelDup.size(); - - } - - public static int checkModelRedefined (StudyTemp s){ - - ArrayList modelDup = findDuplicates(s.modelList); - - //System.out.println("modelDup:"+modelDup); - - for (String m:modelDup){ - LogUtils.errMsg("Model ["+ s.modelMap.get(m).id +"] redefined in main file."); - } - return modelDup.size(); - - } - - public static int checkVarRedefined (StudyTemp s){ - - // check modelList itself - // check item duplicates with model names - - - // - int totalDup=0; - for (String k: s.modelList){ - - ModelTemp m = s.modelMap.get(k); - - totalDup += checkVarRedefined(m, s); - - } - - return totalDup; - - } - - public static int checkVarRedefined (ModelTemp m, StudyTemp st){ - - - // check dvar list duplicates - ArrayList dvDup = findDuplicates(m.dvList); - - if (dvDup.size()>0) { - m.dvList = removeDuplicates(m.dvList); - - for (String s: dvDup){ - DvarTemp dvO = m.dvMap.get(s); - //LogUtils.errMsg("Dvar ["+dvO.id+"] redefined in file ["+ dvO.fromWresl +"]."); - String msg = "Dvar ["+dvO.id+"] redefined"; - LogUtils.errMsgLocation(dvO.fromWresl, dvO.line, msg); - } - } - - // check svar defined in initial statement - - ArrayList svDup_initialStatement = new ArrayList(st.controlDataParameterMap.keySet()); - - svDup_initialStatement.retainAll(m.svList); - - if (svDup_initialStatement.size()>0) { - - for (String s: svDup_initialStatement){ - SvarTemp svO = m.svMap.get(s); - String msg = "Svar ["+svO.id+"] redefined in initial statement and model statement"; - LogUtils.errMsgLocation(svO.fromWresl, svO.line, msg); - } - } - - // check svar list duplicates - ArrayList svDup = findDuplicates(m.svList); - - if (svDup.size()>0) { - m.svList = removeDuplicates(m.svList); - - for (String s: svDup){ - SvarTemp svO = m.svMap.get(s); - //LogUtils.errMsg("Svar ["+svO.id+"] redefined in file ["+ svO.fromWresl +"]."); - String msg = "Svar ["+svO.id+"] redefined"; - LogUtils.errMsgLocation(svO.fromWresl, svO.line, msg); - } - } - - // TODO: check incFile list duplicates - - - // check wTable var duplicates - ArrayList wvDup = findDuplicates(m.wvList_post); - - if (wvDup.size()>0) { - m.wvList_post = removeDuplicates(m.wvList_post); - - for (String s: wvDup){ - LogUtils.errMsg("Weight redefined: "+s+" in file: unknown."); - } - } - - // check item list duplicates - ArrayList itemDup = findDuplicates(m.itemList); - - if (itemDup.size()>0) { - m.itemList = removeDuplicates(m.itemList); - - for (String s: itemDup){ - String item = "Item"; - int line = 0; - if (m.dvList.contains(s)) {line = m.dvMap.get(s).line;item="dvar";} - else if (m.svList.contains(s)) {line = m.svMap.get(s).line;item="svar";} - else if (m.tsList.contains(s)) {line = m.tsMap.get(s).line;item="timeseries";} - else if (m.glList.contains(s)) {line = m.glMap.get(s).line;item="goal";} - else if (m.asList.contains(s)) {line = m.asMap.get(s).line;item="alias";} - else if (m.exList.contains(s)) {line = m.exMap.get(s).line;item="external";} - //else if (m.incFileIDList.contains(s)) {line = -1;item="include file";} - //LogUtils.errMsg("Item ["+s+"] redefined in file ["+ m.absPath +"]."); - String msg = item+" ["+s+"] redefined"; - LogUtils.errMsgLocation(m.absPath, line, msg); - } - } - - return dvDup.size()+svDup.size()+wvDup.size()+itemDup.size(); - - } - - public static ArrayList findDuplicatesIgnoreCase(ArrayList a){ - - ArrayList duplicates = new ArrayList(); - - if (a.size()<1) return duplicates; - - ArrayList a_lowercase = Tools.allToLowerCase(a); - - duplicates.addAll(a_lowercase); - Set varSet = new LinkedHashSet(); - - varSet.addAll(a_lowercase); - - for (String s: varSet) { - duplicates.remove(s); - } - - return duplicates; - } - - public static ArrayList findDuplicates(ArrayList a){ - - ArrayList duplicates = new ArrayList(); - - if (a.size()<1) return duplicates; - - duplicates.addAll(a); - Set varSet = new LinkedHashSet(); - - varSet.addAll(a); - - for (String s: varSet) { - duplicates.remove(s); - } - - return duplicates; - } - - public static ArrayList removeDuplicates(ArrayList a){ - - Set varSet = new LinkedHashSet(); - - varSet.addAll(a); - - return new ArrayList(varSet); - - } - - - - public static boolean checkWeightObjList(StudyTemp st) { - - boolean ret = false; - - for (String seqName : st.seqList) { - - SequenceTemp seqObj = st.seqMap.get(seqName); - - - //// check duplicate weight group (objective) names - ArrayList WeightObjIdList = new ArrayList(); - - for (WeightTable wt: seqObj.wTableObjList){ - - WeightObjIdList.add(wt.id_lowcase); - - } - if (findDuplicates(WeightObjIdList).size()>0) { - - for (String id : findDuplicates(WeightObjIdList)) { - LogUtils.errMsg(" Objective ["+id+"] is redefined in Sequence ["+ seqName +"]"); - - } - - return true; - - } - - //// check deviation penalty and tolerance "Not a number" in weight group - - for (WeightTable wt: seqObj.wTableObjList){ - - if (wt.isWeightGroup) { - - try { - - double p = Double.parseDouble(wt.deviationPenalty); - - if (p<0) { - LogUtils.errMsg(" Deviation Penalty ["+ wt.deviationPenalty +"] in Objective ["+ wt.id_raw +"] must be a nonnegative number." ); - ret = true; - } - - } catch (Exception e) { - - LogUtils.errMsg(" Deviation Penalty ["+ wt.deviationPenalty +"] in Objective ["+ wt.id_raw +"] must be a pure number." ); - - ret = true; - } - - try { - - double p = Double.parseDouble(wt.deviationTolerance); - - if (p<0) { - LogUtils.errMsg(" Deviation Tolerance ["+ wt.deviationTolerance +"] in Objective ["+ wt.id_raw +"] must be a nonnegative number." ); - ret = true; - } - - } catch (Exception e) { - - LogUtils.errMsg(" Deviation Tolerance ["+ wt.deviationTolerance +"] in Objective ["+ wt.id_raw +"] must be a pure number." ); - - ret = true; - } - - for (WeightSubgroup ws: wt.subgroupMap.values()){ - - - try { - - double p = Double.parseDouble(ws.deviationPenalty); - - if (p<0) { - LogUtils.errMsg(" Deviation Penalty ["+ ws.deviationPenalty +"] in Objective ["+ wt.id_raw +"] must be a nonnegative number." ); - ret = true; - } - - } catch (Exception e) { - - LogUtils.errMsg(" Deviation Penalty ["+ ws.deviationPenalty +"] in Objective ["+ wt.id_raw +"] must be a pure number." ); - - ret = true; - } - - try { - - double p = Double.parseDouble(ws.deviationTolerance); - - if (p<0) { - LogUtils.errMsg(" Deviation Tolerance ["+ ws.deviationTolerance +"] in Objective ["+ wt.id_raw +"] must be a nonnegative number." ); - ret = true; - } - - } catch (Exception e) { - - LogUtils.errMsg(" Deviation Tolerance ["+ ws.deviationTolerance +"] in Objective ["+ wt.id_raw +"] must be a pure number." ); - - ret = true; - } - - } - - } - - } - - if (ret) return true; - - - //// check duplicate variables inside the same weight group (objective) - - for (WeightTable wt: seqObj.wTableObjList){ - - ArrayList varList = new ArrayList(); - - if (wt.isWeightGroup) { - varList.addAll(wt.varList); - varList.addAll(wt.subgroupMap.keySet()); - - for (WeightSubgroup ws: wt.subgroupMap.values()){ - - varList.addAll(ws.varList); - - } - - } - else { - varList.addAll(wt.varList); - - } - - if (findDuplicates(varList).size()>0) { - - for (String var : findDuplicates(varList)) { - LogUtils.errMsg(" Weight variable ["+var+"] in Objective ["+ wt.id_raw +"] is redefined in Sequence ["+ seqName +"]"); - } - - ret = true; - } - } - - if (ret) return true; - - //// check duplicates variables inside the sequence - - ArrayList varList = new ArrayList(); - - for (WeightTable wt: seqObj.wTableObjList){ - - if (wt.isWeightGroup) { - varList.addAll(wt.varList); - varList.addAll(wt.subgroupMap.keySet()); - - for (WeightSubgroup ws: wt.subgroupMap.values()){ - - varList.addAll(ws.varList); - - } - - } - else { - varList.addAll(wt.varList); - - } - - } - - if (findDuplicates(varList).size()>0) { - - for (String var : findDuplicates(varList)) { - LogUtils.errMsg(" Weight variable ["+var+"] is redefined in Sequence ["+ seqName +"]"); - } - - ret = true; - } - - if (ret) return true; - - - } - - return false; - - } - - public static void checkWeightVarNotInDvar(StudyTemp s) { - - for (String se : s.seqList){ - - SequenceTemp seqObj = s.seqMap.get(se); - - checkWeightVarNotInDvar(seqObj); - } - } - - public static void checkWeightVarNotInDvar(SequenceTemp seqObj) { - - Set unknowns = new HashSet(); - unknowns.addAll(seqObj.wvList); - unknowns.removeAll(seqObj.dvList); - unknowns.removeAll(seqObj.dvList_fromAlias); - -// System.out.println("### seqObj.wvList:"+seqObj.wvList); -// System.out.println("### seqObj.dvList:"+seqObj.dvList); -// System.out.println("### seqObj.dvList_fromAlias:"+seqObj.dvList_fromAlias); - - if (unknowns.size()>0) { - - LogUtils.errMsg(" Weight variables "+unknowns+" are not defined as Dvar; or are not defined as Alias and show up as terms in Goal."); - - - } - - } - - public static boolean checkInitialVarInConfigNotDeclaredInWresl(StudyTemp st) { - - Set undeclared = new HashSet(); - - undeclared.addAll(ConfigUtils.paramMap.keySet()); - - undeclared.removeAll(st.parameterList); - - if (undeclared.size()>0) { - - Error.addInitialError("Initial variable(s) in Config file not declared in main wresl file: "+undeclared); - - Error.writeErrorLog(); - return true; - } - - return false; - } - - public static boolean checkInitialConst(StudyTemp st) { - - boolean hasError = false; - - for (String k: st.parameterConstList){ - - SvarTemp pt = st.parameterMap.get(k); - String expression = pt.caseExpression.get(0); - try { - - Float.parseFloat(expression); - - } catch (Exception e) { - - String msg = "Variable ["+ k +"] declared as Const type must be a number, but it's either defined or overwritten by Config file as ["+expression+"]"; - - Error.addInitialError(msg); - LogUtils.errMsg(msg); - - hasError = true; - } - - } - - if (hasError) Error.writeErrorLog(); - return hasError; - - } - - public static boolean checkParameterHasUnknownDepedants(StudyTemp st) { - - boolean hasError = false; - - //for (String k : Lists.reverse(parameterList)) - - - for (int i=st.parameterList.size()-1; i>=0; i-- ){ - - String k = st.parameterList.get(i); - - SvarTemp pt = st.parameterMap.get(k); - - pt.dependants_unknown = new HashSet(); - pt.dependants_unknown.addAll(pt.dependants); - - pt.dependants_unknown.removeAll(st.parameterList.subList(0, i)); - - if(pt.dependants_notAllowed.size()>0){ - - String msg = "Initial svar ["+ pt.id +"] has dependent(s) not allowed: "+pt.dependants_notAllowed; - - Error.addInitialError(msg); - //LogUtils.errMsg(msg); - LogUtils.errMsgLocation(pt.fromWresl, pt.line, msg); - - hasError = true; - - } - if (pt.dependants_unknown.size()>0){ - - String msg = "Initial svar ["+ pt.id +"] has unknown dependent(s): "+pt.dependants_unknown; - - Error.addInitialError(msg); - //LogUtils.errMsg(msg); - LogUtils.errMsgLocation(pt.fromWresl, pt.line, msg); - - hasError = true; - - } - - } - - if (hasError) Error.writeErrorLog(); - return hasError; - - } - - public static void checkIfStatementHasUnknownDependants(StudyTemp st) { - - for (String q: st.modelList){ - - ModelTemp m = st.modelMap.get(q); - - checkIfStatementHasUnknownDependants(m, st.parameterMap.keySet()); - - - } - - } - - public static boolean checkIfStatementHasUnknownDependants(ModelTemp m, Set parameters) { - - - for ( String k : m.ifIncItemGroupIDList){ - - IfIncItemGroup iObj = m.ifIncItemGroupMap.get(k); - - Set dependants_unknown = iObj.dependants; - - dependants_unknown.removeAll(parameters); - - if (dependants_unknown.size()>0) { - - String msg = "Conditional include (if, elseif) has dependant(s) not defined in the initial block "+dependants_unknown + " in file: "+iObj.fromWresl; - //LogUtils.errMsg(msg); - Error.addInitialError(msg); - Error.writeErrorLog(); - return true; - - } - - } - - return false; - - } - - public static boolean checkSeqConditionHasUnknownDepedants(StudyTemp st) { - - boolean hasError = false; - - - for (String k: st.seqList){ - - SequenceTemp seqObj = st.seqMap.get(k); - ArrayList unknown_deps = new ArrayList(seqObj.dependants); - - unknown_deps.removeAll(st.controlDataParameterMap.keySet()); - unknown_deps.removeAll(Param.reservedSet); - - - if (unknown_deps.size()>0){ - - String msg = "Sequence ["+ k +"] has unknown dependent(s): "+unknown_deps; - - Error.addInitialError(msg); - LogUtils.errMsgLocation(seqObj.fromWresl, seqObj.line, msg); - - hasError = true; - - } - - } - - if (hasError) Error.writeErrorLog(); - return hasError; - - } - - -} - +package wrimsv2.wreslplus.elements.procedures; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.components.ControlData; +import wrimsv2.components.Error; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.config.ConfigUtils; +import wrimsv2.wreslparser.elements.LogUtils; +import wrimsv2.wreslplus.elements.AliasTemp; +import wrimsv2.wreslplus.elements.DvarTemp; +import wrimsv2.wreslplus.elements.GoalTemp; +import wrimsv2.wreslplus.elements.IfIncItemGroup; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.ParamTemp; +import wrimsv2.wreslplus.elements.SequenceTemp; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.SvarTemp; +import wrimsv2.wreslplus.elements.Tools; +import wrimsv2.wreslplus.elements.WeightSubgroup; +import wrimsv2.wreslplus.elements.WeightTable; + +public class ErrorCheck { + + + private ErrorCheck(){} + +// // these dvars are from slack and surplus of weight group deviation penalty +// public static boolean checkDeviationSlackSurplus(ArrayList dvList_monitored, Map dvMap) { +// +// ArrayList errorList = new ArrayList(); +// +// for (String x : dvList_monitored){ +// +// double v = (Double) dvMap.get(x).getData().getData(); +// +// if (v > Param.deviationSlackSurplusTolerance) { +// +// errorList.add(x); +// +// } +// +// } +// +// if (errorList.size()>0) { +// +// Error.addDeviationError( " Deviation slack and surplus are not zero: "+errorList); +// Error.writeDeviationErrorFile("Error_deviation.txt"); +// return true; +// +// } +// +// return false; +// +// } + + // these dvars are from slack and surplus of weight group deviation penalty + public static boolean checkDeviationSlackSurplus(Map deviationSS_toleranceMap, Map dvMap) { + + ArrayList errorList = new ArrayList(); + + for (String x : deviationSS_toleranceMap.keySet()){ + + double v = (Double) dvMap.get(x).getData().getData(); + + if (v > deviationSS_toleranceMap.get(x)) { + + errorList.add(x); + Error.addDeviationError( "Tolerance of ["+ deviationSS_toleranceMap.get(x) +"] exceeded by deviation slack and surplus: ["+x+"]"); + + } + + } + + if (errorList.size()>0) { + + Error.writeDeviationErrorFile("Error_deviation.txt"); + Error.writeErrorLog(); + return true; + + } + + return false; + + } + + // TODO: this process alias only. need to expand to other types + public static void checkVarUsedBeforeDefined(StudyTemp s) { + + for (String se : s.seqList){ + + SequenceTemp seqObj = s.seqMap.get(se); + + checkVarUsedBeforeDefined(seqObj); + } + } + + public static void checkVarUsedBeforeDefined(SequenceTemp seqObj) { + +/* for (String key : seqObj.asMap.keySet()) { + + AliasTemp asObj = seqObj.asMap.get(key); + + Set temp = new HashSet(asObj.dependants); + temp.removeAll(seqObj.tsList); + temp.removeAll(seqObj.asMap.keySet()); + temp.removeAll(seqObj.dvList); + temp.removeAll(seqObj.svMap.keySet()); + temp.removeAll(asObj.dependants_parameter); + asObj.dependants_unknown = temp; + + if (asObj.dependants_unknown.size()>0){ + String msg = "In model ["+seqObj.model+"] variable(s) not defined before use: "+asObj.dependants_unknown+" in Alias ["+asObj.id+"]"; + LogUtils.errMsgLocation(asObj.fromWresl, asObj.line, msg); + } + + } + + + for (String key : seqObj.glMap.keySet()) { + + GoalTemp glObj = seqObj.glMap.get(key); + + Set temp = new HashSet(glObj.dependants); + temp.removeAll(seqObj.tsList); + temp.removeAll(seqObj.asMap.keySet()); + temp.removeAll(seqObj.dvList); + temp.removeAll(seqObj.svMap.keySet()); + temp.removeAll(seqObj.exList); + temp.removeAll(glObj.dependants_parameter); + glObj.dependants_unknown = temp; + + if (glObj.dependants_unknown.size()>0){ + String msg = "In model ["+seqObj.model+"] variable(s) not defined before use: "+glObj.dependants_unknown+" in Goal ["+glObj.id+"]"; + LogUtils.errMsgLocation(glObj.fromWresl, glObj.line, msg); + } + + } + */ + + for (int i=0; i temp = new HashSet(svObj.dependants); + temp.removeAll(seqObj.tsList); + temp.removeAll(seqObj.asMap.keySet()); + temp.removeAll(seqObj.dvList); + temp.removeAll(seqObj.svMap.keySet()); + temp.removeAll(seqObj.exList); + temp.removeAll(svObj.dependants_parameter); + svObj.dependants_unknown = temp; + + + if (svObj.dependants_unknown.size()>0){ + String msg = "In Sequence: ["+seqObj.id+"] Svar: ["+ svObj.id + "] has unknown variable(s): "+svObj.dependants_unknown; + LogUtils.errMsgLocation(svObj.fromWresl, svObj.line, msg); + + + } else { + + for (String dep: svObj.dependants_svar){ + + if ( seqObj.svIncFileList_post.indexOf(dep)> i){ + String msg = "In Sequence: ["+seqObj.id+"] Svar: ["+ svObj.id + "] has variable(s) not defined before use: "+dep; + LogUtils.errMsgLocation(svObj.fromWresl, svObj.line, msg); + } + + } + + } + + } + + } + + public static boolean checkIncModelNotExistIgnoreCase (StudyTemp s){ + + ArrayList modelList_lowercase = new ArrayList(); + + modelList_lowercase.addAll(Tools.allToLowerCase(s.modelList)); + + //System.out.println("modelList_lowercase:"+modelList_lowercase); + + for (ModelTemp mt: s.modelMap.values()){ + + for ( String incM: mt.incModelList) { + + if ( !modelList_lowercase.contains(incM.toLowerCase())) { + + LogUtils.errMsg("Include model ["+ incM +"] not exist in model ["+mt.id+"]."); + + return true; + } + + } + + } + + return false; + + } + + public static int checkSequenceHasUniqueModel (StudyTemp s){ + + ArrayList modelList = new ArrayList(); + + //modelList_lowercase.addAll(Tools.allToLowerCase(s.modelList)); + + + for (SequenceTemp seq: s.seqMap.values()){ + + modelList.add(seq.model.toLowerCase()); + + } + + ArrayList modelDup = findDuplicatesIgnoreCase(modelList); + + for (String m:modelDup){ + LogUtils.errMsg("Each sequence must define unique model. ["+ m +"] is used in multiple sequences."); + } + return modelDup.size(); + + + + } + + public static int checkModelRedefinedIgnoreCase (StudyTemp s){ + + ArrayList modelDup = findDuplicatesIgnoreCase(s.modelList); + + //System.out.println("modelDup:"+modelDup); + + for (String m:modelDup){ + LogUtils.errMsg("Model ["+ m +"] redefined in main file."); + } + return modelDup.size(); + + } + + public static int checkModelRedefined (StudyTemp s){ + + ArrayList modelDup = findDuplicates(s.modelList); + + //System.out.println("modelDup:"+modelDup); + + for (String m:modelDup){ + LogUtils.errMsg("Model ["+ s.modelMap.get(m).id +"] redefined in main file."); + } + return modelDup.size(); + + } + + public static int checkVarRedefined (StudyTemp s){ + + // check modelList itself + // check item duplicates with model names + + + // + int totalDup=0; + for (String k: s.modelList){ + + ModelTemp m = s.modelMap.get(k); + + totalDup += checkVarRedefined(m, s); + + } + + return totalDup; + + } + + public static int checkVarRedefined (ModelTemp m, StudyTemp st){ + + + // check dvar list duplicates + ArrayList dvDup = findDuplicates(m.dvList); + + if (dvDup.size()>0) { + m.dvList = removeDuplicates(m.dvList); + + for (String s: dvDup){ + DvarTemp dvO = m.dvMap.get(s); + //LogUtils.errMsg("Dvar ["+dvO.id+"] redefined in file ["+ dvO.fromWresl +"]."); + String msg = "Dvar ["+dvO.id+"] redefined"; + LogUtils.errMsgLocation(dvO.fromWresl, dvO.line, msg); + } + } + + // check svar defined in initial statement + + ArrayList svDup_initialStatement = new ArrayList(st.controlDataParameterMap.keySet()); + + svDup_initialStatement.retainAll(m.svList); + + if (svDup_initialStatement.size()>0) { + + for (String s: svDup_initialStatement){ + SvarTemp svO = m.svMap.get(s); + String msg = "Svar ["+svO.id+"] redefined in initial statement and model statement"; + LogUtils.errMsgLocation(svO.fromWresl, svO.line, msg); + } + } + + // check svar list duplicates + ArrayList svDup = findDuplicates(m.svList); + + if (svDup.size()>0) { + m.svList = removeDuplicates(m.svList); + + for (String s: svDup){ + SvarTemp svO = m.svMap.get(s); + //LogUtils.errMsg("Svar ["+svO.id+"] redefined in file ["+ svO.fromWresl +"]."); + String msg = "Svar ["+svO.id+"] redefined"; + LogUtils.errMsgLocation(svO.fromWresl, svO.line, msg); + } + } + + // TODO: check incFile list duplicates + + + // check wTable var duplicates + ArrayList wvDup = findDuplicates(m.wvList_post); + + if (wvDup.size()>0) { + m.wvList_post = removeDuplicates(m.wvList_post); + + for (String s: wvDup){ + LogUtils.errMsg("Weight redefined: "+s+" in file: unknown."); + } + } + + // check item list duplicates + ArrayList itemDup = findDuplicates(m.itemList); + + if (itemDup.size()>0) { + m.itemList = removeDuplicates(m.itemList); + + for (String s: itemDup){ + String item = "Item"; + int line = 0; + if (m.dvList.contains(s)) {line = m.dvMap.get(s).line;item="dvar";} + else if (m.svList.contains(s)) {line = m.svMap.get(s).line;item="svar";} + else if (m.tsList.contains(s)) {line = m.tsMap.get(s).line;item="timeseries";} + else if (m.glList.contains(s)) {line = m.glMap.get(s).line;item="goal";} + else if (m.asList.contains(s)) {line = m.asMap.get(s).line;item="alias";} + else if (m.exList.contains(s)) {line = m.exMap.get(s).line;item="external";} + //else if (m.incFileIDList.contains(s)) {line = -1;item="include file";} + //LogUtils.errMsg("Item ["+s+"] redefined in file ["+ m.absPath +"]."); + String msg = item+" ["+s+"] redefined"; + LogUtils.errMsgLocation(m.absPath, line, msg); + } + } + + return dvDup.size()+svDup.size()+wvDup.size()+itemDup.size(); + + } + + public static ArrayList findDuplicatesIgnoreCase(ArrayList a){ + + ArrayList duplicates = new ArrayList(); + + if (a.size()<1) return duplicates; + + ArrayList a_lowercase = Tools.allToLowerCase(a); + + duplicates.addAll(a_lowercase); + Set varSet = new LinkedHashSet(); + + varSet.addAll(a_lowercase); + + for (String s: varSet) { + duplicates.remove(s); + } + + return duplicates; + } + + public static ArrayList findDuplicates(ArrayList a){ + + ArrayList duplicates = new ArrayList(); + + if (a.size()<1) return duplicates; + + duplicates.addAll(a); + Set varSet = new LinkedHashSet(); + + varSet.addAll(a); + + for (String s: varSet) { + duplicates.remove(s); + } + + return duplicates; + } + + public static ArrayList removeDuplicates(ArrayList a){ + + Set varSet = new LinkedHashSet(); + + varSet.addAll(a); + + return new ArrayList(varSet); + + } + + + + public static boolean checkWeightObjList(StudyTemp st) { + + boolean ret = false; + + for (String seqName : st.seqList) { + + SequenceTemp seqObj = st.seqMap.get(seqName); + + + //// check duplicate weight group (objective) names + ArrayList WeightObjIdList = new ArrayList(); + + for (WeightTable wt: seqObj.wTableObjList){ + + WeightObjIdList.add(wt.id_lowcase); + + } + if (findDuplicates(WeightObjIdList).size()>0) { + + for (String id : findDuplicates(WeightObjIdList)) { + LogUtils.errMsg(" Objective ["+id+"] is redefined in Sequence ["+ seqName +"]"); + + } + + return true; + + } + + //// check deviation penalty and tolerance "Not a number" in weight group + + for (WeightTable wt: seqObj.wTableObjList){ + + if (wt.isWeightGroup) { + + try { + + double p = Double.parseDouble(wt.deviationPenalty); + + if (p<0) { + LogUtils.errMsg(" Deviation Penalty ["+ wt.deviationPenalty +"] in Objective ["+ wt.id_raw +"] must be a nonnegative number." ); + ret = true; + } + + } catch (Exception e) { + + LogUtils.errMsg(" Deviation Penalty ["+ wt.deviationPenalty +"] in Objective ["+ wt.id_raw +"] must be a pure number." ); + + ret = true; + } + + try { + + double p = Double.parseDouble(wt.deviationTolerance); + + if (p<0) { + LogUtils.errMsg(" Deviation Tolerance ["+ wt.deviationTolerance +"] in Objective ["+ wt.id_raw +"] must be a nonnegative number." ); + ret = true; + } + + } catch (Exception e) { + + LogUtils.errMsg(" Deviation Tolerance ["+ wt.deviationTolerance +"] in Objective ["+ wt.id_raw +"] must be a pure number." ); + + ret = true; + } + + for (WeightSubgroup ws: wt.subgroupMap.values()){ + + + try { + + double p = Double.parseDouble(ws.deviationPenalty); + + if (p<0) { + LogUtils.errMsg(" Deviation Penalty ["+ ws.deviationPenalty +"] in Objective ["+ wt.id_raw +"] must be a nonnegative number." ); + ret = true; + } + + } catch (Exception e) { + + LogUtils.errMsg(" Deviation Penalty ["+ ws.deviationPenalty +"] in Objective ["+ wt.id_raw +"] must be a pure number." ); + + ret = true; + } + + try { + + double p = Double.parseDouble(ws.deviationTolerance); + + if (p<0) { + LogUtils.errMsg(" Deviation Tolerance ["+ ws.deviationTolerance +"] in Objective ["+ wt.id_raw +"] must be a nonnegative number." ); + ret = true; + } + + } catch (Exception e) { + + LogUtils.errMsg(" Deviation Tolerance ["+ ws.deviationTolerance +"] in Objective ["+ wt.id_raw +"] must be a pure number." ); + + ret = true; + } + + } + + } + + } + + if (ret) return true; + + + //// check duplicate variables inside the same weight group (objective) + + for (WeightTable wt: seqObj.wTableObjList){ + + ArrayList varList = new ArrayList(); + + if (wt.isWeightGroup) { + varList.addAll(wt.varList); + varList.addAll(wt.subgroupMap.keySet()); + + for (WeightSubgroup ws: wt.subgroupMap.values()){ + + varList.addAll(ws.varList); + + } + + } + else { + varList.addAll(wt.varList); + + } + + if (findDuplicates(varList).size()>0) { + + for (String var : findDuplicates(varList)) { + LogUtils.errMsg(" Weight variable ["+var+"] in Objective ["+ wt.id_raw +"] is redefined in Sequence ["+ seqName +"]"); + } + + ret = true; + } + } + + if (ret) return true; + + //// check duplicates variables inside the sequence + + ArrayList varList = new ArrayList(); + + for (WeightTable wt: seqObj.wTableObjList){ + + if (wt.isWeightGroup) { + varList.addAll(wt.varList); + varList.addAll(wt.subgroupMap.keySet()); + + for (WeightSubgroup ws: wt.subgroupMap.values()){ + + varList.addAll(ws.varList); + + } + + } + else { + varList.addAll(wt.varList); + + } + + } + + if (findDuplicates(varList).size()>0) { + + for (String var : findDuplicates(varList)) { + LogUtils.errMsg(" Weight variable ["+var+"] is redefined in Sequence ["+ seqName +"]"); + } + + ret = true; + } + + if (ret) return true; + + + } + + return false; + + } + + public static void checkWeightVarNotInDvar(StudyTemp s) { + + for (String se : s.seqList){ + + SequenceTemp seqObj = s.seqMap.get(se); + + checkWeightVarNotInDvar(seqObj); + } + } + + public static void checkWeightVarNotInDvar(SequenceTemp seqObj) { + + Set unknowns = new HashSet(); + unknowns.addAll(seqObj.wvList); + unknowns.removeAll(seqObj.dvList); + unknowns.removeAll(seqObj.dvList_fromAlias); + +// System.out.println("### seqObj.wvList:"+seqObj.wvList); +// System.out.println("### seqObj.dvList:"+seqObj.dvList); +// System.out.println("### seqObj.dvList_fromAlias:"+seqObj.dvList_fromAlias); + + if (unknowns.size()>0) { + + LogUtils.errMsg(" Weight variables "+unknowns+" are not defined as Dvar; or are not defined as Alias and show up as terms in Goal."); + + + } + + } + + public static boolean checkInitialVarInConfigNotDeclaredInWresl(StudyTemp st) { + + Set undeclared = new HashSet(); + + undeclared.addAll(ConfigUtils.paramMap.keySet()); + + undeclared.removeAll(st.parameterList); + + if (undeclared.size()>0) { + + Error.addInitialError("Initial variable(s) in Config file not declared in main wresl file: "+undeclared); + + Error.writeErrorLog(); + return true; + } + + return false; + } + + public static boolean checkInitialConst(StudyTemp st) { + + boolean hasError = false; + + for (String k: st.parameterConstList){ + + SvarTemp pt = st.parameterMap.get(k); + String expression = pt.caseExpression.get(0); + try { + + Float.parseFloat(expression); + + } catch (Exception e) { + + String msg = "Variable ["+ k +"] declared as Const type must be a number, but it's either defined or overwritten by Config file as ["+expression+"]"; + + Error.addInitialError(msg); + LogUtils.errMsg(msg); + + hasError = true; + } + + } + + if (hasError) Error.writeErrorLog(); + return hasError; + + } + + public static boolean checkParameterHasUnknownDepedants(StudyTemp st) { + + boolean hasError = false; + + //for (String k : Lists.reverse(parameterList)) + + + for (int i=st.parameterList.size()-1; i>=0; i-- ){ + + String k = st.parameterList.get(i); + + SvarTemp pt = st.parameterMap.get(k); + + pt.dependants_unknown = new HashSet(); + pt.dependants_unknown.addAll(pt.dependants); + + pt.dependants_unknown.removeAll(st.parameterList.subList(0, i)); + + if(pt.dependants_notAllowed.size()>0){ + + String msg = "Initial svar ["+ pt.id +"] has dependent(s) not allowed: "+pt.dependants_notAllowed; + + Error.addInitialError(msg); + //LogUtils.errMsg(msg); + LogUtils.errMsgLocation(pt.fromWresl, pt.line, msg); + + hasError = true; + + } + if (pt.dependants_unknown.size()>0){ + + String msg = "Initial svar ["+ pt.id +"] has unknown dependent(s): "+pt.dependants_unknown; + + Error.addInitialError(msg); + //LogUtils.errMsg(msg); + LogUtils.errMsgLocation(pt.fromWresl, pt.line, msg); + + hasError = true; + + } + + } + + if (hasError) Error.writeErrorLog(); + return hasError; + + } + + public static void checkIfStatementHasUnknownDependants(StudyTemp st) { + + for (String q: st.modelList){ + + ModelTemp m = st.modelMap.get(q); + + checkIfStatementHasUnknownDependants(m, st.parameterMap.keySet()); + + + } + + } + + public static boolean checkIfStatementHasUnknownDependants(ModelTemp m, Set parameters) { + + + for ( String k : m.ifIncItemGroupIDList){ + + IfIncItemGroup iObj = m.ifIncItemGroupMap.get(k); + + Set dependants_unknown = iObj.dependants; + + dependants_unknown.removeAll(parameters); + + if (dependants_unknown.size()>0) { + + String msg = "Conditional include (if, elseif) has dependant(s) not defined in the initial block "+dependants_unknown + " in file: "+iObj.fromWresl; + //LogUtils.errMsg(msg); + Error.addInitialError(msg); + Error.writeErrorLog(); + return true; + + } + + } + + return false; + + } + + public static boolean checkSeqConditionHasUnknownDepedants(StudyTemp st) { + + boolean hasError = false; + + + for (String k: st.seqList){ + + SequenceTemp seqObj = st.seqMap.get(k); + ArrayList unknown_deps = new ArrayList(seqObj.dependants); + + unknown_deps.removeAll(st.controlDataParameterMap.keySet()); + unknown_deps.removeAll(Param.reservedSet); + + + if (unknown_deps.size()>0){ + + String msg = "Sequence ["+ k +"] has unknown dependent(s): "+unknown_deps; + + Error.addInitialError(msg); + LogUtils.errMsgLocation(seqObj.fromWresl, seqObj.line, msg); + + hasError = true; + + } + + } + + if (hasError) Error.writeErrorLog(); + return hasError; + + } + + +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/Misc.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/Misc.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/Misc.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/Misc.java index 976836e64..c28aa3569 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/Misc.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/Misc.java @@ -1,63 +1,63 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.wreslplus.elements.DvarTemp; -import wrimsv2.wreslplus.elements.GoalTemp; -import wrimsv2.wreslplus.elements.ModelTemp; -import wrimsv2.wreslplus.elements.WeightTemp; - -public class Misc { - - private Misc() { - } - - public static void addWeightInGroupWeightMap(String id, String fromWresl, String weight, ModelTemp mObj) { - - WeightTemp w1 = new WeightTemp(); - w1.id = id; - w1.fromWresl = fromWresl; - w1.weight = weight; - - mObj.groupWeightMap.put(id.toLowerCase(), w1); - mObj.wvList_post.add(id.toLowerCase()); - - } - - public static void createDvarInModelObj(String id, String ub, String lb, String kind, String units, - String fromWresl, ModelTemp mObj) { - - DvarTemp d = new DvarTemp(); - d.id = id; - d.upperBound = ub; - d.lowerBound = lb; - d.kind = kind; - d.units = units; - d.fromWresl = fromWresl; - //d.condition = condition; - - mObj.dvList.add(d.id.toLowerCase()); - mObj.dvMap.put(d.id.toLowerCase(), d); - - } - - public static void createGoalInModelObj(String id, String lhs, String relation, String rhs, - Set dependants, String fromWresl, String condition, ModelTemp mObj) { - - GoalTemp g = new GoalTemp(); - g.fromWresl = fromWresl; - g.id = id; - - g.caseExpression.add(lhs + relation + rhs); - g.condition = condition; - g.caseName.add(Param.defaultCaseName); - g.caseCondition.add(Param.always); - g.dependants = dependants; - - mObj.glList.add(g.id.toLowerCase()); - mObj.glMap.put(g.id.toLowerCase(), g); - - } - -} +package wrimsv2.wreslplus.elements.procedures; + +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.wreslplus.elements.DvarTemp; +import wrimsv2.wreslplus.elements.GoalTemp; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.WeightTemp; + +public class Misc { + + private Misc() { + } + + public static void addWeightInGroupWeightMap(String id, String fromWresl, String weight, ModelTemp mObj) { + + WeightTemp w1 = new WeightTemp(); + w1.id = id; + w1.fromWresl = fromWresl; + w1.weight = weight; + + mObj.groupWeightMap.put(id.toLowerCase(), w1); + mObj.wvList_post.add(id.toLowerCase()); + + } + + public static void createDvarInModelObj(String id, String ub, String lb, String kind, String units, + String fromWresl, ModelTemp mObj) { + + DvarTemp d = new DvarTemp(); + d.id = id; + d.upperBound = ub; + d.lowerBound = lb; + d.kind = kind; + d.units = units; + d.fromWresl = fromWresl; + //d.condition = condition; + + mObj.dvList.add(d.id.toLowerCase()); + mObj.dvMap.put(d.id.toLowerCase(), d); + + } + + public static void createGoalInModelObj(String id, String lhs, String relation, String rhs, + Set dependants, String fromWresl, String condition, ModelTemp mObj) { + + GoalTemp g = new GoalTemp(); + g.fromWresl = fromWresl; + g.id = id; + + g.caseExpression.add(lhs + relation + rhs); + g.condition = condition; + g.caseName.add(Param.defaultCaseName); + g.caseCondition.add(Param.always); + g.dependants = dependants; + + mObj.glList.add(g.id.toLowerCase()); + mObj.glMap.put(g.id.toLowerCase(), g); + + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcGoal.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcGoal.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcGoal.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcGoal.java index 58f6d2fbb..d77fcd658 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcGoal.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcGoal.java @@ -1,379 +1,379 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.wreslplus.elements.DvarTemp; -import wrimsv2.wreslplus.elements.GoalCase; -import wrimsv2.wreslplus.elements.GoalTemp; -import wrimsv2.wreslplus.elements.ModelTemp; -import wrimsv2.wreslplus.elements.SequenceTemp; -import wrimsv2.wreslplus.elements.StudyTemp; -import wrimsv2.wreslplus.elements.WeightTemp; - -public class ProcGoal { - - private ProcGoal() { - } - - public static void processGoalHS2(StudyTemp st) { - - Set filesProcessed = new HashSet(); - - for (String seqName : st.seqList) { - - SequenceTemp seqObj = st.seqMap.get(seqName); - ModelTemp mObj = st.modelMap.get(seqObj.model); - - for (String e: st.modelList_effective){ - - if (st.allOffspringMap_incModel.keySet().contains(e)) { - for (String f: st.allOffspringMap_incModel.get(e)) { - - if (!filesProcessed.contains(f)) { - - ModelTemp incModel = st.modelMap.get(f); - processGoalHS2(incModel, seqObj); - filesProcessed.add(f); - - } - } - } - - } - - for (String f: mObj.incFileRelativePathList_post){ - - if (!filesProcessed.contains(f)) { - - ModelTemp incModel = st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)); - processGoalHS2(incModel, seqObj); - filesProcessed.add(f); - - } - - - } - - - processGoalHS2(mObj, seqObj); - - - } - - } - - public static void processGoalHS2(ModelTemp mt, SequenceTemp seq) { - - processGoalHS2(mt); - - } - - public static void processGoalHS2(ModelTemp mObj) { - - for (String gKey : mObj.gl2List) { - - GoalTemp g2 = mObj.glMap.get(gKey); - - // added to prevent re-assignment in the later sequence - // if this goal obj is copied to different seqObj from the same included file. - // This approach is to reduce data size by not using different goal obj. - g2.caseCondition = new ArrayList(); - - for (int caseNumber = 0; caseNumber < g2.caseName.size(); caseNumber++) { - - String cn = g2.caseName.get(caseNumber); - GoalCase gc = g2.caseMap.get(cn); - g2.caseCondition.add(gc.condition); - - // convert penalty into caseExpression - Map o = ProcGoal.convertPenalty(g2, g2.id.toLowerCase(), caseNumber, g2.lhs, gc); - - String slackName = o.get("slackName"); - String surplusName = o.get("surplusName"); - // System.out.println(slackName); - // System.out.println(surplusName); - - g2.slackList.add(slackName); - g2.surplusList.add(surplusName); - g2.caseExpression.add(o.get("caseExpression")); - - Map weightMap = new HashMap(); - ArrayList dvarSlackSurplus = new ArrayList(); - - if (slackName != null) { - WeightTemp w = new WeightTemp(); - w.weight = o.get("slackWeight"); - - DvarTemp d = new DvarTemp(); - d.fromWresl = g2.fromWresl; - d.kind = "slack"; - d.timeArraySize=g2.timeArraySize; - - if (g2.hasCase) { - d.condition = Param.conditional; - w.condition = Param.conditional; - w.timeArraySize=g2.timeArraySize; - - mObj.ssList_hasCase.add(slackName); - mObj.ssMap_hasCase.put(slackName, d); - mObj.ssWeightMap_hasCase.put(slackName, w); - - weightMap.put(slackName, w.weight); - dvarSlackSurplus.add(slackName); - - } else { - - w.timeArraySize=g2.timeArraySize; - mObj.ssList_noCase.add(slackName); - mObj.ssMap_noCase.put(slackName, d); - mObj.ssWeightMap_noCase.put(slackName, w); - - } - // System.out.println(slackName+":"+g2.ruleType+":"+d.condition); - } - if (surplusName != null) { - WeightTemp w = new WeightTemp(); - w.weight = o.get("surplusWeight"); - - DvarTemp d = new DvarTemp(); - d.fromWresl = g2.fromWresl; - d.kind = "surplus"; - d.timeArraySize=g2.timeArraySize; - - if (g2.hasCase) { - d.condition = Param.conditional; - w.condition = Param.conditional; - w.timeArraySize=g2.timeArraySize; - mObj.ssList_hasCase.add(surplusName); - mObj.ssMap_hasCase.put(surplusName, d); - mObj.ssWeightMap_hasCase.put(surplusName, w); - - weightMap.put(surplusName, w.weight); - dvarSlackSurplus.add(surplusName); - - } else { - - w.timeArraySize=g2.timeArraySize; - mObj.ssList_noCase.add(surplusName); - mObj.ssMap_noCase.put(surplusName, d); - mObj.ssWeightMap_noCase.put(surplusName, w); - - } - - // System.out.println(surplusName+":"+g2.ruleType+":"+d.condition); - } - - g2.dvarWeightMapList.add(weightMap); - g2.dvarSlackSurplusList.add(dvarSlackSurplus); - - - } - - - mObj.glMap.put(gKey, g2); - - } - - - } - - public static Map convertPenalty(GoalTemp goal, String goalName, int caseIndex, String lhs, GoalCase cm) { - - String caseNumber = Integer.toString(caseIndex + 1); - String caseExpression = null; - String lhs_m = null; - // String rhs_m=null; - String relation = null; - - String lt = cm.lhs_lt_rhs; - String gt = cm.lhs_gt_rhs; - - String slackName = null; - String surplusName = null; - String slackWeight = null; - String surplusWeight = null; - - Map expression_slack_surplus = new HashMap(); - - if (ProcGoal.isConstrain(gt) && ProcGoal.isConstrain(lt)) { - - lhs_m = lhs; - relation = "="; - caseExpression = lhs_m + relation + cm.rhs; - - } - else if (ProcGoal.isConstrain(gt)) { - - if (ProcGoal.isFree(lt)) { - - lhs_m = lhs; - relation = "<"; - caseExpression = lhs_m + relation + cm.rhs; - - } - else { - - slackName = "slack__" + goalName + "_" + caseNumber; - slackWeight = lt; - if (goal.timeArraySize.equals("0")){ - lhs_m = lhs + "+" + slackName; - }else{ - lhs_m = lhs + "+" + slackName + "($m)"; - } - relation = "="; - caseExpression = lhs_m + relation + cm.rhs; - } - - } - else if (ProcGoal.isConstrain(lt)) { - - if (ProcGoal.isFree(gt)) { - - lhs_m = lhs; - relation = ">"; - caseExpression = lhs_m + relation + cm.rhs; - - } - else { - - surplusName = "surplus__" + goalName + "_" + caseNumber; - surplusWeight = gt; - if (goal.timeArraySize.equals("0")){ - lhs_m = lhs + "-" + surplusName; - }else{ - lhs_m = lhs + "-" + surplusName + "($m)"; - } - relation = "="; - caseExpression = lhs_m + relation + cm.rhs; - } - - } - else if (ProcGoal.isFree(gt) && ProcGoal.isFree(lt)) { - - caseExpression = " 1 > 0 "; - - // default to general treatment, that is, - // lhs + slack - surplus = rhs with zero weight on lhs and rhs - -// surplusName = "surplus__" + goalName + "_" + caseNumber; -// surplusWeight = gt; -// if (goal.timeArraySize.equals("0")){ -// lhs_m = lhs + "-" + surplusName; -// }else{ -// lhs_m = lhs + "-" + surplusName+"($m)"; -// } -// -// slackName = "slack__" + goalName + "_" + caseNumber; -// slackWeight = lt; -// if (goal.timeArraySize.equals("0")){ -// lhs_m = lhs_m + "+" + slackName; -// }else{ -// lhs_m = lhs_m + "+" + slackName+"($m)"; -// } -// relation = "="; -// caseExpression = lhs_m + " = " + cm.rhs; - - } - else if (ProcGoal.isFree(lt)) { - - surplusName = "surplus__" + goalName + "_" + caseNumber; - surplusWeight = gt; - if (goal.timeArraySize.equals("0")){ - lhs_m = lhs + "-" + surplusName; - }else{ - lhs_m = lhs + "-" + surplusName + ("($m)"); - } - relation = "<"; - caseExpression = lhs_m + relation + cm.rhs; - - } - else if (ProcGoal.isFree(gt)) { - - slackName = "slack__" + goalName + "_" + caseNumber; - slackWeight = lt; - if (goal.timeArraySize.equals("0")){ - lhs_m = lhs + "+" + slackName; - }else{ - lhs_m = lhs + "+" + slackName + "($m)"; - } - relation = ">"; - caseExpression = lhs_m + relation + cm.rhs; - - } - else { - surplusName = "surplus__" + goalName + "_" + caseNumber; - surplusWeight = gt; - if (goal.timeArraySize.equals("0")){ - lhs_m = lhs + "-" + surplusName; - }else{ - lhs_m = lhs + "-" + surplusName+"($m)"; - } - slackName = "slack__" + goalName + "_" + caseNumber; - slackWeight = lt; - if (goal.timeArraySize.equals("0")){ - lhs_m = lhs_m + "+" + slackName; - }else{ - lhs_m = lhs_m + "+" + slackName + "($m)"; - } - relation = "="; - caseExpression = lhs_m + relation + cm.rhs; - } - - - slackWeight = "-(" + slackWeight + ")"; - - - surplusWeight = "-(" + surplusWeight + ")"; - - - expression_slack_surplus.put("caseExpression", caseExpression); - expression_slack_surplus.put("slackName", slackName); - expression_slack_surplus.put("surplusName", surplusName); - expression_slack_surplus.put("slackWeight", slackWeight); - expression_slack_surplus.put("surplusWeight", surplusWeight); - return expression_slack_surplus; - } - - public static boolean isConstrain(String v) { - - return v.equals(Param.constrain); - - } - - public static boolean isFree(String v) { - - try { - - float p = Float.parseFloat(v); - if (p == 0) return true; - - } - catch (Exception e) { - } - - return false; - - } - - public static boolean isNumber(String v) { - - try { - - Float p = Float.parseFloat(v); - return true; - - } - catch (Exception e) { - } - - return false; - - } - - -} +package wrimsv2.wreslplus.elements.procedures; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.wreslplus.elements.DvarTemp; +import wrimsv2.wreslplus.elements.GoalCase; +import wrimsv2.wreslplus.elements.GoalTemp; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.SequenceTemp; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.WeightTemp; + +public class ProcGoal { + + private ProcGoal() { + } + + public static void processGoalHS2(StudyTemp st) { + + Set filesProcessed = new HashSet(); + + for (String seqName : st.seqList) { + + SequenceTemp seqObj = st.seqMap.get(seqName); + ModelTemp mObj = st.modelMap.get(seqObj.model); + + for (String e: st.modelList_effective){ + + if (st.allOffspringMap_incModel.keySet().contains(e)) { + for (String f: st.allOffspringMap_incModel.get(e)) { + + if (!filesProcessed.contains(f)) { + + ModelTemp incModel = st.modelMap.get(f); + processGoalHS2(incModel, seqObj); + filesProcessed.add(f); + + } + } + } + + } + + for (String f: mObj.incFileRelativePathList_post){ + + if (!filesProcessed.contains(f)) { + + ModelTemp incModel = st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)); + processGoalHS2(incModel, seqObj); + filesProcessed.add(f); + + } + + + } + + + processGoalHS2(mObj, seqObj); + + + } + + } + + public static void processGoalHS2(ModelTemp mt, SequenceTemp seq) { + + processGoalHS2(mt); + + } + + public static void processGoalHS2(ModelTemp mObj) { + + for (String gKey : mObj.gl2List) { + + GoalTemp g2 = mObj.glMap.get(gKey); + + // added to prevent re-assignment in the later sequence + // if this goal obj is copied to different seqObj from the same included file. + // This approach is to reduce data size by not using different goal obj. + g2.caseCondition = new ArrayList(); + + for (int caseNumber = 0; caseNumber < g2.caseName.size(); caseNumber++) { + + String cn = g2.caseName.get(caseNumber); + GoalCase gc = g2.caseMap.get(cn); + g2.caseCondition.add(gc.condition); + + // convert penalty into caseExpression + Map o = ProcGoal.convertPenalty(g2, g2.id.toLowerCase(), caseNumber, g2.lhs, gc); + + String slackName = o.get("slackName"); + String surplusName = o.get("surplusName"); + // System.out.println(slackName); + // System.out.println(surplusName); + + g2.slackList.add(slackName); + g2.surplusList.add(surplusName); + g2.caseExpression.add(o.get("caseExpression")); + + Map weightMap = new HashMap(); + ArrayList dvarSlackSurplus = new ArrayList(); + + if (slackName != null) { + WeightTemp w = new WeightTemp(); + w.weight = o.get("slackWeight"); + + DvarTemp d = new DvarTemp(); + d.fromWresl = g2.fromWresl; + d.kind = "slack"; + d.timeArraySize=g2.timeArraySize; + + if (g2.hasCase) { + d.condition = Param.conditional; + w.condition = Param.conditional; + w.timeArraySize=g2.timeArraySize; + + mObj.ssList_hasCase.add(slackName); + mObj.ssMap_hasCase.put(slackName, d); + mObj.ssWeightMap_hasCase.put(slackName, w); + + weightMap.put(slackName, w.weight); + dvarSlackSurplus.add(slackName); + + } else { + + w.timeArraySize=g2.timeArraySize; + mObj.ssList_noCase.add(slackName); + mObj.ssMap_noCase.put(slackName, d); + mObj.ssWeightMap_noCase.put(slackName, w); + + } + // System.out.println(slackName+":"+g2.ruleType+":"+d.condition); + } + if (surplusName != null) { + WeightTemp w = new WeightTemp(); + w.weight = o.get("surplusWeight"); + + DvarTemp d = new DvarTemp(); + d.fromWresl = g2.fromWresl; + d.kind = "surplus"; + d.timeArraySize=g2.timeArraySize; + + if (g2.hasCase) { + d.condition = Param.conditional; + w.condition = Param.conditional; + w.timeArraySize=g2.timeArraySize; + mObj.ssList_hasCase.add(surplusName); + mObj.ssMap_hasCase.put(surplusName, d); + mObj.ssWeightMap_hasCase.put(surplusName, w); + + weightMap.put(surplusName, w.weight); + dvarSlackSurplus.add(surplusName); + + } else { + + w.timeArraySize=g2.timeArraySize; + mObj.ssList_noCase.add(surplusName); + mObj.ssMap_noCase.put(surplusName, d); + mObj.ssWeightMap_noCase.put(surplusName, w); + + } + + // System.out.println(surplusName+":"+g2.ruleType+":"+d.condition); + } + + g2.dvarWeightMapList.add(weightMap); + g2.dvarSlackSurplusList.add(dvarSlackSurplus); + + + } + + + mObj.glMap.put(gKey, g2); + + } + + + } + + public static Map convertPenalty(GoalTemp goal, String goalName, int caseIndex, String lhs, GoalCase cm) { + + String caseNumber = Integer.toString(caseIndex + 1); + String caseExpression = null; + String lhs_m = null; + // String rhs_m=null; + String relation = null; + + String lt = cm.lhs_lt_rhs; + String gt = cm.lhs_gt_rhs; + + String slackName = null; + String surplusName = null; + String slackWeight = null; + String surplusWeight = null; + + Map expression_slack_surplus = new HashMap(); + + if (ProcGoal.isConstrain(gt) && ProcGoal.isConstrain(lt)) { + + lhs_m = lhs; + relation = "="; + caseExpression = lhs_m + relation + cm.rhs; + + } + else if (ProcGoal.isConstrain(gt)) { + + if (ProcGoal.isFree(lt)) { + + lhs_m = lhs; + relation = "<"; + caseExpression = lhs_m + relation + cm.rhs; + + } + else { + + slackName = "slack__" + goalName + "_" + caseNumber; + slackWeight = lt; + if (goal.timeArraySize.equals("0")){ + lhs_m = lhs + "+" + slackName; + }else{ + lhs_m = lhs + "+" + slackName + "($m)"; + } + relation = "="; + caseExpression = lhs_m + relation + cm.rhs; + } + + } + else if (ProcGoal.isConstrain(lt)) { + + if (ProcGoal.isFree(gt)) { + + lhs_m = lhs; + relation = ">"; + caseExpression = lhs_m + relation + cm.rhs; + + } + else { + + surplusName = "surplus__" + goalName + "_" + caseNumber; + surplusWeight = gt; + if (goal.timeArraySize.equals("0")){ + lhs_m = lhs + "-" + surplusName; + }else{ + lhs_m = lhs + "-" + surplusName + "($m)"; + } + relation = "="; + caseExpression = lhs_m + relation + cm.rhs; + } + + } + else if (ProcGoal.isFree(gt) && ProcGoal.isFree(lt)) { + + caseExpression = " 1 > 0 "; + + // default to general treatment, that is, + // lhs + slack - surplus = rhs with zero weight on lhs and rhs + +// surplusName = "surplus__" + goalName + "_" + caseNumber; +// surplusWeight = gt; +// if (goal.timeArraySize.equals("0")){ +// lhs_m = lhs + "-" + surplusName; +// }else{ +// lhs_m = lhs + "-" + surplusName+"($m)"; +// } +// +// slackName = "slack__" + goalName + "_" + caseNumber; +// slackWeight = lt; +// if (goal.timeArraySize.equals("0")){ +// lhs_m = lhs_m + "+" + slackName; +// }else{ +// lhs_m = lhs_m + "+" + slackName+"($m)"; +// } +// relation = "="; +// caseExpression = lhs_m + " = " + cm.rhs; + + } + else if (ProcGoal.isFree(lt)) { + + surplusName = "surplus__" + goalName + "_" + caseNumber; + surplusWeight = gt; + if (goal.timeArraySize.equals("0")){ + lhs_m = lhs + "-" + surplusName; + }else{ + lhs_m = lhs + "-" + surplusName + ("($m)"); + } + relation = "<"; + caseExpression = lhs_m + relation + cm.rhs; + + } + else if (ProcGoal.isFree(gt)) { + + slackName = "slack__" + goalName + "_" + caseNumber; + slackWeight = lt; + if (goal.timeArraySize.equals("0")){ + lhs_m = lhs + "+" + slackName; + }else{ + lhs_m = lhs + "+" + slackName + "($m)"; + } + relation = ">"; + caseExpression = lhs_m + relation + cm.rhs; + + } + else { + surplusName = "surplus__" + goalName + "_" + caseNumber; + surplusWeight = gt; + if (goal.timeArraySize.equals("0")){ + lhs_m = lhs + "-" + surplusName; + }else{ + lhs_m = lhs + "-" + surplusName+"($m)"; + } + slackName = "slack__" + goalName + "_" + caseNumber; + slackWeight = lt; + if (goal.timeArraySize.equals("0")){ + lhs_m = lhs_m + "+" + slackName; + }else{ + lhs_m = lhs_m + "+" + slackName + "($m)"; + } + relation = "="; + caseExpression = lhs_m + relation + cm.rhs; + } + + + slackWeight = "-(" + slackWeight + ")"; + + + surplusWeight = "-(" + surplusWeight + ")"; + + + expression_slack_surplus.put("caseExpression", caseExpression); + expression_slack_surplus.put("slackName", slackName); + expression_slack_surplus.put("surplusName", surplusName); + expression_slack_surplus.put("slackWeight", slackWeight); + expression_slack_surplus.put("surplusWeight", surplusWeight); + return expression_slack_surplus; + } + + public static boolean isConstrain(String v) { + + return v.equals(Param.constrain); + + } + + public static boolean isFree(String v) { + + try { + + float p = Float.parseFloat(v); + if (p == 0) return true; + + } + catch (Exception e) { + } + + return false; + + } + + public static boolean isNumber(String v) { + + try { + + Float p = Float.parseFloat(v); + return true; + + } + catch (Exception e) { + } + + return false; + + } + + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcIfIncItemGroup.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcIfIncItemGroup.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcIfIncItemGroup.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcIfIncItemGroup.java index 2096217d8..bd2111502 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcIfIncItemGroup.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcIfIncItemGroup.java @@ -1,273 +1,273 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Set; - -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.TokenStream; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.components.ControlData; -import wrimsv2.evaluator.ValueEvaluatorLexer; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.wreslplus.elements.AliasTemp; -import wrimsv2.wreslplus.elements.DvarTemp; -import wrimsv2.wreslplus.elements.GoalTemp; -import wrimsv2.wreslplus.elements.IfIncItemGroup; -import wrimsv2.wreslplus.elements.IncFileTemp; -import wrimsv2.wreslplus.elements.ModelTemp; -import wrimsv2.wreslplus.elements.StudyTemp; -import wrimsv2.wreslplus.elements.SvarTemp; -import wrimsv2.wreslplus.elements.TimeseriesTemp; -import wrimsv2.wreslplus.elements.WeightTable; -import wrimsv2.components.Error; - -public class ProcIfIncItemGroup { - - private ProcIfIncItemGroup() { - } - - public static void process(StudyTemp st){ - - for (String q: st.modelList){ - - ModelTemp m = st.modelMap.get(q); - - process(m); - - } - - } - - public static void process(ModelTemp m){ - - for ( String k : m.ifIncItemGroupIDList){ - - IfIncItemGroup gObj = m.ifIncItemGroupMap.get(k); - - // good for debug - ControlData.currEvalName=gObj.fromWresl; - ControlData.currEvalTypeIndex=9; - gObj.conditionValueList = evaluateConditions(gObj.conditionList); - - // find index - int indexOfFirstTrue = gObj.conditionValueList.indexOf(true); - int index_ItemList = m.itemList.indexOf(gObj.id); - int index_IncFileIDList = m.incFileIDList.indexOf(gObj.id); - int index_svList = m.svList.indexOf(gObj.id); - int index_dvList = m.dvList.indexOf(gObj.id); - int index_asList = m.asList.indexOf(gObj.id); - int index_tsList = m.tsList.indexOf(gObj.id); - int index_glList = m.glList.indexOf(gObj.id); - int index_gl2List = m.gl2List.indexOf(gObj.id); - - // when at least one condition is true - if (indexOfFirstTrue>-1) { - - ArrayList inc_item_list = gObj.inc_item_list.get(indexOfFirstTrue); - HashMap incFMap = gObj.inc_files_map_list.get(indexOfFirstTrue); - HashMap svarMap = gObj.inc_svar_map_list.get(indexOfFirstTrue); - HashMap dvarMap = gObj.inc_dvar_map_list.get(indexOfFirstTrue); - LinkedHashMap aliasMap = gObj.inc_alias_map_list.get(indexOfFirstTrue); - HashMap timeseriesMap = gObj.inc_timeseries_map_list.get(indexOfFirstTrue); - HashMap goalSimpleMap = gObj.inc_goalSimple_map_list.get(indexOfFirstTrue); - HashMap goalComplexMap = gObj.inc_goalComplex_map_list.get(indexOfFirstTrue); - HashMap weightTableMap = gObj.inc_weightTable_map_list.get(indexOfFirstTrue); - - // svar replace - m.svList.remove(index_svList); - m.svMap.remove(gObj.id); - ArrayList svList = new ArrayList(inc_item_list); - svList.retainAll(svarMap.keySet()); - if (svList.size()>0){ - m.svList.addAll(index_svList,svList); - m.svMap.putAll(svarMap); - } - - // dvar replace - m.dvList.remove(index_dvList); - m.dvMap.remove(gObj.id); - ArrayList dvList = new ArrayList(inc_item_list); - dvList.retainAll(dvarMap.keySet()); - if (dvList.size()>0){ - m.dvList.addAll(index_dvList,dvList); - m.dvMap.putAll(dvarMap); - } - - // alias replace - m.asList.remove(index_asList); - m.asMap.remove(gObj.id); - ArrayList asList = new ArrayList(inc_item_list); - asList.retainAll(aliasMap.keySet()); - if (asList.size()>0){ - m.asList.addAll(index_asList,asList); - m.asMap.putAll(aliasMap); - } - - // timeseries replace - m.tsList.remove(index_tsList); - m.tsMap.remove(gObj.id); - ArrayList tsList = new ArrayList(inc_item_list); - tsList.retainAll(timeseriesMap.keySet()); - if (tsList.size()>0){ - m.tsList.addAll(index_tsList,tsList); - m.tsMap.putAll(timeseriesMap); - } - - // goalSimple and goalComplex replace - m.glList.remove(index_glList); - m.glMap.remove(gObj.id); - ArrayList glList = new ArrayList(inc_item_list); - Set allGoalKeys = new HashSet(); - allGoalKeys.addAll(goalSimpleMap.keySet()); - allGoalKeys.addAll(goalComplexMap.keySet()); - glList.retainAll(allGoalKeys); - if (glList.size()>0){ - m.glList.addAll(index_glList,glList); - m.glMap.putAll(goalSimpleMap); - m.glMap.putAll(goalComplexMap); - } - - // goalComplex replace - m.gl2List.remove(index_gl2List); - ArrayList gl2List = new ArrayList(inc_item_list); - gl2List.retainAll(goalComplexMap.keySet()); - if (gl2List.size()>0){ - m.gl2List.addAll(index_gl2List,gl2List); - } - - // weightTable replace - for (String wk: weightTableMap.keySet()){ - m.wTableObjList.add(weightTableMap.get(wk)); - } - - // item replace - m.itemList.remove(index_ItemList); - m.itemTypeList.remove(index_ItemList); - m.itemList.addAll(index_ItemList, inc_item_list); - - // TODO: improve this by prepare itemTypeList before here - for (String dummy: gObj.inc_item_list.get(indexOfFirstTrue)) { - - if (incFMap.keySet().contains(dummy)){ - m.itemTypeList.add(index_ItemList, Param.incFileType); - } - else if (svarMap.keySet().contains(dummy)){ - m.itemTypeList.add(index_ItemList, Param.svType); - } - else if (dvarMap.keySet().contains(dummy)){ - m.itemTypeList.add(index_ItemList, Param.dvType); - } - else if (aliasMap.keySet().contains(dummy)){ - m.itemTypeList.add(index_ItemList, Param.asType); - } - else if (timeseriesMap.keySet().contains(dummy)){ - m.itemTypeList.add(index_ItemList, Param.tsType); - } - else if (goalSimpleMap.keySet().contains(dummy)){ - m.itemTypeList.add(index_ItemList, Param.gl1Type); - } - else if (goalComplexMap.keySet().contains(dummy)){ - m.itemTypeList.add(index_ItemList, Param.gl2Type); - } - else { - m.itemTypeList.add(index_ItemList, -999997); - } - } - - - // inc file replace - m.incFileIDList.removeAll(Collections.singleton(gObj.id)); - m.incFileMap.remove(gObj.id); - - ArrayList fileIdList = new ArrayList(inc_item_list); - fileIdList.retainAll(incFMap.keySet()); - - if (fileIdList.size()>0){ - m.incFileIDList.addAll(index_IncFileIDList, fileIdList); - m.incFileMap.putAll(incFMap); - } - - - - } - // no condition is true - else { - - // svar - m.svList.remove(gObj.id); - m.svMap.remove(gObj.id); - - // dvar - m.dvList.remove(gObj.id); - m.dvMap.remove(gObj.id); - - // alias - m.asList.remove(gObj.id); - m.asMap.remove(gObj.id); - - // timeseries - m.tsList.remove(gObj.id); - m.tsMap.remove(gObj.id); - - // goal - m.glList.remove(gObj.id); - m.gl2List.remove(gObj.id); - m.glMap.remove(gObj.id); - - m.itemList.remove(index_ItemList); - m.itemTypeList.remove(index_ItemList); - - // inc file - m.incFileIDList.removeAll(Collections.singleton(gObj.id)); - m.incFileMap.remove(gObj.id); - - } - - } - - } - - // TODO: return the index that contains the first "true" value - public static ArrayList evaluateConditions(ArrayList conditionList){ - - ArrayList ret = new ArrayList(); - - for (String conditionExpression : conditionList) { - - String evalString="c: "+conditionExpression; - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - - ValueEvaluatorParser vep = new ValueEvaluatorParser(tokenStream); - - try { - - vep.evaluator(); - ret.add(vep.evalCondition); - //if (vep.evalCondition) return ret; - - } catch (Exception e) { - // TODO: handle exception - System.out.println(" Error in processing conditional include ..."); - - ret.add(false); - - } finally { - - if (Error.getTotalError()>0) Error.writeErrorLog(); - } - - } - - return ret; - - } - -} +package wrimsv2.wreslplus.elements.procedures; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Set; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.TokenStream; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.components.ControlData; +import wrimsv2.evaluator.ValueEvaluatorLexer; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.wreslplus.elements.AliasTemp; +import wrimsv2.wreslplus.elements.DvarTemp; +import wrimsv2.wreslplus.elements.GoalTemp; +import wrimsv2.wreslplus.elements.IfIncItemGroup; +import wrimsv2.wreslplus.elements.IncFileTemp; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.SvarTemp; +import wrimsv2.wreslplus.elements.TimeseriesTemp; +import wrimsv2.wreslplus.elements.WeightTable; +import wrimsv2.components.Error; + +public class ProcIfIncItemGroup { + + private ProcIfIncItemGroup() { + } + + public static void process(StudyTemp st){ + + for (String q: st.modelList){ + + ModelTemp m = st.modelMap.get(q); + + process(m); + + } + + } + + public static void process(ModelTemp m){ + + for ( String k : m.ifIncItemGroupIDList){ + + IfIncItemGroup gObj = m.ifIncItemGroupMap.get(k); + + // good for debug + ControlData.currEvalName=gObj.fromWresl; + ControlData.currEvalTypeIndex=9; + gObj.conditionValueList = evaluateConditions(gObj.conditionList); + + // find index + int indexOfFirstTrue = gObj.conditionValueList.indexOf(true); + int index_ItemList = m.itemList.indexOf(gObj.id); + int index_IncFileIDList = m.incFileIDList.indexOf(gObj.id); + int index_svList = m.svList.indexOf(gObj.id); + int index_dvList = m.dvList.indexOf(gObj.id); + int index_asList = m.asList.indexOf(gObj.id); + int index_tsList = m.tsList.indexOf(gObj.id); + int index_glList = m.glList.indexOf(gObj.id); + int index_gl2List = m.gl2List.indexOf(gObj.id); + + // when at least one condition is true + if (indexOfFirstTrue>-1) { + + ArrayList inc_item_list = gObj.inc_item_list.get(indexOfFirstTrue); + HashMap incFMap = gObj.inc_files_map_list.get(indexOfFirstTrue); + HashMap svarMap = gObj.inc_svar_map_list.get(indexOfFirstTrue); + HashMap dvarMap = gObj.inc_dvar_map_list.get(indexOfFirstTrue); + LinkedHashMap aliasMap = gObj.inc_alias_map_list.get(indexOfFirstTrue); + HashMap timeseriesMap = gObj.inc_timeseries_map_list.get(indexOfFirstTrue); + HashMap goalSimpleMap = gObj.inc_goalSimple_map_list.get(indexOfFirstTrue); + HashMap goalComplexMap = gObj.inc_goalComplex_map_list.get(indexOfFirstTrue); + HashMap weightTableMap = gObj.inc_weightTable_map_list.get(indexOfFirstTrue); + + // svar replace + m.svList.remove(index_svList); + m.svMap.remove(gObj.id); + ArrayList svList = new ArrayList(inc_item_list); + svList.retainAll(svarMap.keySet()); + if (svList.size()>0){ + m.svList.addAll(index_svList,svList); + m.svMap.putAll(svarMap); + } + + // dvar replace + m.dvList.remove(index_dvList); + m.dvMap.remove(gObj.id); + ArrayList dvList = new ArrayList(inc_item_list); + dvList.retainAll(dvarMap.keySet()); + if (dvList.size()>0){ + m.dvList.addAll(index_dvList,dvList); + m.dvMap.putAll(dvarMap); + } + + // alias replace + m.asList.remove(index_asList); + m.asMap.remove(gObj.id); + ArrayList asList = new ArrayList(inc_item_list); + asList.retainAll(aliasMap.keySet()); + if (asList.size()>0){ + m.asList.addAll(index_asList,asList); + m.asMap.putAll(aliasMap); + } + + // timeseries replace + m.tsList.remove(index_tsList); + m.tsMap.remove(gObj.id); + ArrayList tsList = new ArrayList(inc_item_list); + tsList.retainAll(timeseriesMap.keySet()); + if (tsList.size()>0){ + m.tsList.addAll(index_tsList,tsList); + m.tsMap.putAll(timeseriesMap); + } + + // goalSimple and goalComplex replace + m.glList.remove(index_glList); + m.glMap.remove(gObj.id); + ArrayList glList = new ArrayList(inc_item_list); + Set allGoalKeys = new HashSet(); + allGoalKeys.addAll(goalSimpleMap.keySet()); + allGoalKeys.addAll(goalComplexMap.keySet()); + glList.retainAll(allGoalKeys); + if (glList.size()>0){ + m.glList.addAll(index_glList,glList); + m.glMap.putAll(goalSimpleMap); + m.glMap.putAll(goalComplexMap); + } + + // goalComplex replace + m.gl2List.remove(index_gl2List); + ArrayList gl2List = new ArrayList(inc_item_list); + gl2List.retainAll(goalComplexMap.keySet()); + if (gl2List.size()>0){ + m.gl2List.addAll(index_gl2List,gl2List); + } + + // weightTable replace + for (String wk: weightTableMap.keySet()){ + m.wTableObjList.add(weightTableMap.get(wk)); + } + + // item replace + m.itemList.remove(index_ItemList); + m.itemTypeList.remove(index_ItemList); + m.itemList.addAll(index_ItemList, inc_item_list); + + // TODO: improve this by prepare itemTypeList before here + for (String dummy: gObj.inc_item_list.get(indexOfFirstTrue)) { + + if (incFMap.keySet().contains(dummy)){ + m.itemTypeList.add(index_ItemList, Param.incFileType); + } + else if (svarMap.keySet().contains(dummy)){ + m.itemTypeList.add(index_ItemList, Param.svType); + } + else if (dvarMap.keySet().contains(dummy)){ + m.itemTypeList.add(index_ItemList, Param.dvType); + } + else if (aliasMap.keySet().contains(dummy)){ + m.itemTypeList.add(index_ItemList, Param.asType); + } + else if (timeseriesMap.keySet().contains(dummy)){ + m.itemTypeList.add(index_ItemList, Param.tsType); + } + else if (goalSimpleMap.keySet().contains(dummy)){ + m.itemTypeList.add(index_ItemList, Param.gl1Type); + } + else if (goalComplexMap.keySet().contains(dummy)){ + m.itemTypeList.add(index_ItemList, Param.gl2Type); + } + else { + m.itemTypeList.add(index_ItemList, -999997); + } + } + + + // inc file replace + m.incFileIDList.removeAll(Collections.singleton(gObj.id)); + m.incFileMap.remove(gObj.id); + + ArrayList fileIdList = new ArrayList(inc_item_list); + fileIdList.retainAll(incFMap.keySet()); + + if (fileIdList.size()>0){ + m.incFileIDList.addAll(index_IncFileIDList, fileIdList); + m.incFileMap.putAll(incFMap); + } + + + + } + // no condition is true + else { + + // svar + m.svList.remove(gObj.id); + m.svMap.remove(gObj.id); + + // dvar + m.dvList.remove(gObj.id); + m.dvMap.remove(gObj.id); + + // alias + m.asList.remove(gObj.id); + m.asMap.remove(gObj.id); + + // timeseries + m.tsList.remove(gObj.id); + m.tsMap.remove(gObj.id); + + // goal + m.glList.remove(gObj.id); + m.gl2List.remove(gObj.id); + m.glMap.remove(gObj.id); + + m.itemList.remove(index_ItemList); + m.itemTypeList.remove(index_ItemList); + + // inc file + m.incFileIDList.removeAll(Collections.singleton(gObj.id)); + m.incFileMap.remove(gObj.id); + + } + + } + + } + + // TODO: return the index that contains the first "true" value + public static ArrayList evaluateConditions(ArrayList conditionList){ + + ArrayList ret = new ArrayList(); + + for (String conditionExpression : conditionList) { + + String evalString="c: "+conditionExpression; + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + + ValueEvaluatorParser vep = new ValueEvaluatorParser(tokenStream); + + try { + + vep.evaluator(); + ret.add(vep.evalCondition); + //if (vep.evalCondition) return ret; + + } catch (Exception e) { + // TODO: handle exception + System.out.println(" Error in processing conditional include ..."); + + ret.add(false); + + } finally { + + if (Error.getTotalError()>0) Error.writeErrorLog(); + } + + } + + return ret; + + } + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcIncFile.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcIncFile.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcIncFile.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcIncFile.java index 4a67cae8c..07a4cfab3 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcIncFile.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcIncFile.java @@ -1,119 +1,119 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslplus.elements.GlobalData; -import wrimsv2.wreslplus.elements.IncFileTemp; -import wrimsv2.wreslplus.elements.ModelTemp; -import wrimsv2.wreslplus.elements.ResourceUtils; -import wrimsv2.wreslplus.elements.StudyTemp; - -public class ProcIncFile { - - private ProcIncFile() { - } - - // for main file only - public static void processPath(ModelTemp m, StudyTemp s) { - - m.pathRelativeToRunDir = ResourceUtils.getRelativePath(m.absPath, GlobalData.runDir, File.separator); - - for (String key : m.incFileMap.keySet()) { - - IncFileTemp f = m.incFileMap.get(key); - - if (f==null) { - // key is model - - m.incFileRelativePathList.addAll(s.modelMap.get(key).incFileRelativePathList); - m.incFileAbsPathList.addAll(s.modelMap.get(key).incFileAbsPathList); - - - } else { - - try { - f.absPath = new File(m.parentAbsPath, f.rawPath) - .getCanonicalPath().toLowerCase(); - m.incFileAbsPathList.add(f.absPath); - } catch (IOException e) { - e.printStackTrace(); - LogUtils.errMsg("Include file IOException: " + f.rawPath, - m.absPath); - } - - f.pathRelativeToRunDir = ResourceUtils.getRelativePath( - f.absPath, GlobalData.runDir, File.separator); - m.incFileRelativePathList.add(f.pathRelativeToRunDir); - - } - - - } - - m.incFileAbsPathList_post = new ArrayList(m.incFileAbsPathList); - m.incFileRelativePathList_post = new ArrayList(m.incFileRelativePathList); - - } - - public static void processPath(StudyTemp s) { - - - for (HashSet modSet : s.fileGroupOrder_incModel ){ - - for (String modName: modSet ){ - - ModelTemp mObj = s.modelMap.get(modName); - - processPath(mObj, s); - - } - - } - } - - // for files other than main file - public static void processPath(ModelTemp m) { - - m.pathRelativeToRunDir = ResourceUtils.getRelativePath(m.absPath, GlobalData.runDir, File.separator); - - for (String key : m.incFileMap.keySet()) { - - IncFileTemp f = m.incFileMap.get(key); - - if (f==null) { - // key is model - - // won't happen because non-main file cannot include models - - - } else { - - try { - f.absPath = new File(m.parentAbsPath, f.rawPath) - .getCanonicalPath().toLowerCase(); - m.incFileAbsPathList.add(f.absPath); - } catch (IOException e) { - e.printStackTrace(); - LogUtils.errMsg("Include file IOException: " + f.rawPath, - m.absPath); - } - - f.pathRelativeToRunDir = ResourceUtils.getRelativePath( - f.absPath, GlobalData.runDir, File.separator); - m.incFileRelativePathList.add(f.pathRelativeToRunDir); - - } - - - } - - m.incFileAbsPathList_post = new ArrayList(m.incFileAbsPathList); - m.incFileRelativePathList_post = new ArrayList(m.incFileRelativePathList); - - } - - -} +package wrimsv2.wreslplus.elements.procedures; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import wrimsv2.wreslparser.elements.LogUtils; +import wrimsv2.wreslplus.elements.GlobalData; +import wrimsv2.wreslplus.elements.IncFileTemp; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.ResourceUtils; +import wrimsv2.wreslplus.elements.StudyTemp; + +public class ProcIncFile { + + private ProcIncFile() { + } + + // for main file only + public static void processPath(ModelTemp m, StudyTemp s) { + + m.pathRelativeToRunDir = ResourceUtils.getRelativePath(m.absPath, GlobalData.runDir, File.separator); + + for (String key : m.incFileMap.keySet()) { + + IncFileTemp f = m.incFileMap.get(key); + + if (f==null) { + // key is model + + m.incFileRelativePathList.addAll(s.modelMap.get(key).incFileRelativePathList); + m.incFileAbsPathList.addAll(s.modelMap.get(key).incFileAbsPathList); + + + } else { + + try { + f.absPath = new File(m.parentAbsPath, f.rawPath) + .getCanonicalPath().toLowerCase(); + m.incFileAbsPathList.add(f.absPath); + } catch (IOException e) { + e.printStackTrace(); + LogUtils.errMsg("Include file IOException: " + f.rawPath, + m.absPath); + } + + f.pathRelativeToRunDir = ResourceUtils.getRelativePath( + f.absPath, GlobalData.runDir, File.separator); + m.incFileRelativePathList.add(f.pathRelativeToRunDir); + + } + + + } + + m.incFileAbsPathList_post = new ArrayList(m.incFileAbsPathList); + m.incFileRelativePathList_post = new ArrayList(m.incFileRelativePathList); + + } + + public static void processPath(StudyTemp s) { + + + for (HashSet modSet : s.fileGroupOrder_incModel ){ + + for (String modName: modSet ){ + + ModelTemp mObj = s.modelMap.get(modName); + + processPath(mObj, s); + + } + + } + } + + // for files other than main file + public static void processPath(ModelTemp m) { + + m.pathRelativeToRunDir = ResourceUtils.getRelativePath(m.absPath, GlobalData.runDir, File.separator); + + for (String key : m.incFileMap.keySet()) { + + IncFileTemp f = m.incFileMap.get(key); + + if (f==null) { + // key is model + + // won't happen because non-main file cannot include models + + + } else { + + try { + f.absPath = new File(m.parentAbsPath, f.rawPath) + .getCanonicalPath().toLowerCase(); + m.incFileAbsPathList.add(f.absPath); + } catch (IOException e) { + e.printStackTrace(); + LogUtils.errMsg("Include file IOException: " + f.rawPath, + m.absPath); + } + + f.pathRelativeToRunDir = ResourceUtils.getRelativePath( + f.absPath, GlobalData.runDir, File.separator); + m.incFileRelativePathList.add(f.pathRelativeToRunDir); + + } + + + } + + m.incFileAbsPathList_post = new ArrayList(m.incFileAbsPathList); + m.incFileRelativePathList_post = new ArrayList(m.incFileRelativePathList); + + } + + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcIncModel.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcIncModel.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcIncModel.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcIncModel.java index a7c406e76..287c742ad 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcIncModel.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcIncModel.java @@ -1,94 +1,94 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslplus.elements.ModelTemp; -import wrimsv2.wreslplus.elements.SequenceTemp; -import wrimsv2.wreslplus.elements.StudyTemp; -import wrimsv2.wreslplus.elements.Tools; -import wrimsv2.wreslplus.elements.WeightSubgroup; -import wrimsv2.wreslplus.elements.WeightTable; - -public class ProcIncModel { - - private ProcIncModel() { - } - - - public static void findKidMap(StudyTemp st) { - - for (String f: st.modelMap.keySet()){ - - ArrayList kids = st.modelMap.get(f).incModelList; - - - if (kids==null){ - st.noKid_incModel.add(f); - } else if (kids.isEmpty()){ - st.noKid_incModel.add(f); - } else { - //st.kidssMap.put(f, modelName, new HashSet(kids)); - st.kidMap_incModel.put(f, new HashSet(kids)); - } - - } - - System.out.println("st.kidMap_incModel"+st.kidMap_incModel); - - } - - - public static void findAllOffSpring(StudyTemp st) { - - - for (String f: st.kidMap_incModel.keySet()) { - - HashSet a = Tools.findAllOffspring(f, st.kidMap_incModel); - - st.allOffspringMap_incModel.put(f, a); - - } - - System.out.println("st.allOffspringMap_incModel"+st.allOffspringMap_incModel); - } - - - public static void findFileGroupOrder(StudyTemp st) { - - Map> toBeSorted = new HashMap>(st.allOffspringMap_incModel); - - - st.fileGroupOrder_incModel.add(st.noKid_incModel); - - - Tools.findFileHierarchy(st.fileGroupOrder_incModel, toBeSorted); - - - System.out.println("st.fileGroupOrder_incModel"+st.fileGroupOrder_incModel); - - } - - public static void findEffectiveIncludeModel(StudyTemp st) { - - - HashSet t = new HashSet(); - for (HashSet e : st.fileGroupOrder_incModel) { - t.addAll(e); - } - - st.incModelList_effective = new ArrayList(t); - - - } - - - - - - -} +package wrimsv2.wreslplus.elements.procedures; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.wreslparser.elements.LogUtils; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.SequenceTemp; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.Tools; +import wrimsv2.wreslplus.elements.WeightSubgroup; +import wrimsv2.wreslplus.elements.WeightTable; + +public class ProcIncModel { + + private ProcIncModel() { + } + + + public static void findKidMap(StudyTemp st) { + + for (String f: st.modelMap.keySet()){ + + ArrayList kids = st.modelMap.get(f).incModelList; + + + if (kids==null){ + st.noKid_incModel.add(f); + } else if (kids.isEmpty()){ + st.noKid_incModel.add(f); + } else { + //st.kidssMap.put(f, modelName, new HashSet(kids)); + st.kidMap_incModel.put(f, new HashSet(kids)); + } + + } + + System.out.println("st.kidMap_incModel"+st.kidMap_incModel); + + } + + + public static void findAllOffSpring(StudyTemp st) { + + + for (String f: st.kidMap_incModel.keySet()) { + + HashSet a = Tools.findAllOffspring(f, st.kidMap_incModel); + + st.allOffspringMap_incModel.put(f, a); + + } + + System.out.println("st.allOffspringMap_incModel"+st.allOffspringMap_incModel); + } + + + public static void findFileGroupOrder(StudyTemp st) { + + Map> toBeSorted = new HashMap>(st.allOffspringMap_incModel); + + + st.fileGroupOrder_incModel.add(st.noKid_incModel); + + + Tools.findFileHierarchy(st.fileGroupOrder_incModel, toBeSorted); + + + System.out.println("st.fileGroupOrder_incModel"+st.fileGroupOrder_incModel); + + } + + public static void findEffectiveIncludeModel(StudyTemp st) { + + + HashSet t = new HashSet(); + for (HashSet e : st.fileGroupOrder_incModel) { + t.addAll(e); + } + + st.incModelList_effective = new ArrayList(t); + + + } + + + + + + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcMainFile.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcMainFile.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcMainFile.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcMainFile.java index 09614c1f8..636ab43ed 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcMainFile.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcMainFile.java @@ -1,121 +1,121 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslplus.elements.StudyTemp; -import wrimsv2.wreslplus.elements.Tools; - -public class ProcMainFile { - - private ProcMainFile() { - } - - - public static void findKidMap_incModel(StudyTemp st) { - - for (String f: st.modelMap.keySet()){ - - ArrayList kids = st.modelMap.get(f).incModelList; - - //System.out.println("st.modelMap.get(f).incModelList: "+st.modelMap.get(f).incModelList); - - if (kids==null){ - st.noKid_incModel.add(f); - } else if (kids.isEmpty()){ - st.noKid_incModel.add(f); - } else { - st.kidMap_incModel.put(f, new HashSet(kids)); - } - - } - - - } - - - public static void findAllOffSpring_incModel(StudyTemp st) { - - - for (String f: st.kidMap_incModel.keySet()) { - - HashSet a = Tools.findAllOffspring(f, st.kidMap_incModel); - - st.allOffspringMap_incModel.put(f, a); - - } - - } - - - public static void findGroupOrder_incModel(StudyTemp st) { - - Map> toBeSorted = new HashMap>(st.allOffspringMap_incModel); - - - st.fileGroupOrder_incModel.add(st.noKid_incModel); - - - Tools.findFileHierarchy(st.fileGroupOrder_incModel, toBeSorted); - - - } - - public static void findEffectiveIncludeModel(StudyTemp st) { - - - HashSet t = new HashSet(); - for (HashSet e : st.kidMap_incModel.values()) { - t.addAll(e); - } - - st.incModelList_effective = new ArrayList(t); - - - } - - public static void findEffectiveModel(StudyTemp st) { - - for (String s: st.seqList){ - String modelName = st.seqMap.get(s).model; - - if (!st.modelList.contains(modelName)){ - - LogUtils.errMsg("model name ["+ modelName +"] not found in sequence ["+ s +"]."); - - } else { - - st.modelList_effective.add(modelName); - } - - // add included model list - for (String incM: st.modelMap.get(modelName).incModelList) { - - incM = incM.toLowerCase(); - - //System.out.println("inc models: "+incM); - - if (!st.modelList.contains(incM)){ - - LogUtils.errMsg("included model ["+ incM +"] not found in model ["+ modelName +"]."); - - } else { - - st.incModelList_effective.add(incM); - - } - - } - - } - } - - - - - - -} +package wrimsv2.wreslplus.elements.procedures; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import wrimsv2.wreslparser.elements.LogUtils; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.Tools; + +public class ProcMainFile { + + private ProcMainFile() { + } + + + public static void findKidMap_incModel(StudyTemp st) { + + for (String f: st.modelMap.keySet()){ + + ArrayList kids = st.modelMap.get(f).incModelList; + + //System.out.println("st.modelMap.get(f).incModelList: "+st.modelMap.get(f).incModelList); + + if (kids==null){ + st.noKid_incModel.add(f); + } else if (kids.isEmpty()){ + st.noKid_incModel.add(f); + } else { + st.kidMap_incModel.put(f, new HashSet(kids)); + } + + } + + + } + + + public static void findAllOffSpring_incModel(StudyTemp st) { + + + for (String f: st.kidMap_incModel.keySet()) { + + HashSet a = Tools.findAllOffspring(f, st.kidMap_incModel); + + st.allOffspringMap_incModel.put(f, a); + + } + + } + + + public static void findGroupOrder_incModel(StudyTemp st) { + + Map> toBeSorted = new HashMap>(st.allOffspringMap_incModel); + + + st.fileGroupOrder_incModel.add(st.noKid_incModel); + + + Tools.findFileHierarchy(st.fileGroupOrder_incModel, toBeSorted); + + + } + + public static void findEffectiveIncludeModel(StudyTemp st) { + + + HashSet t = new HashSet(); + for (HashSet e : st.kidMap_incModel.values()) { + t.addAll(e); + } + + st.incModelList_effective = new ArrayList(t); + + + } + + public static void findEffectiveModel(StudyTemp st) { + + for (String s: st.seqList){ + String modelName = st.seqMap.get(s).model; + + if (!st.modelList.contains(modelName)){ + + LogUtils.errMsg("model name ["+ modelName +"] not found in sequence ["+ s +"]."); + + } else { + + st.modelList_effective.add(modelName); + } + + // add included model list + for (String incM: st.modelMap.get(modelName).incModelList) { + + incM = incM.toLowerCase(); + + //System.out.println("inc models: "+incM); + + if (!st.modelList.contains(incM)){ + + LogUtils.errMsg("included model ["+ incM +"] not found in model ["+ modelName +"]."); + + } else { + + st.incModelList_effective.add(incM); + + } + + } + + } + } + + + + + + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcParameter.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcParameter.java similarity index 95% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcParameter.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcParameter.java index 235793462..5318c81f6 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcParameter.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcParameter.java @@ -1,151 +1,151 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.TokenStream; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.components.ControlData; -import wrimsv2.components.IntDouble; -import wrimsv2.components.Error; -import wrimsv2.evaluator.ValueEvaluatorLexer; -import wrimsv2.evaluator.ValueEvaluatorParser; -import wrimsv2.wreslplus.elements.ParamTemp; -import wrimsv2.wreslplus.elements.StudyTemp; -import wrimsv2.wreslplus.elements.SvarTemp; - -public class ProcParameter { - - private ProcParameter() { - } - - public static void process(StudyTemp st){ - - - st.controlDataParameterMap = convertParamMapToSvarMap(st.parameterMap); - ControlData.parameterMap=st.controlDataParameterMap; - evaluateAllParams(st.parameterList, st.controlDataParameterMap); - - } - - - private static void evaluateAllParams(ArrayList keyList, Map map) { - - for (String key: keyList) { - - Svar svar = map.get(key); - ControlData.currEvalName=key; - ControlData.currEvalTypeIndex=8; - - - for (int i=0; i 0) { - Error.writeErrorLog(); - } - - evalBoolean = evaluator.evalCondition; - - } catch (RecognitionException e) { - - Error.writeErrorLog(); - } - - return evalBoolean; - - } - - private static IntDouble callNumberEvaluator(String evalString) { - - IntDouble evalValue=null; - - evalString="v: "+evalString; - ANTLRStringStream stream = new ANTLRStringStream(evalString); - ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); - TokenStream tokenStream = new CommonTokenStream(lexer); - ValueEvaluatorParser evaluator = new ValueEvaluatorParser(tokenStream); - - - try { - evaluator.evaluator(); - - if (Error.getTotalError() > 0) { - Error.writeErrorLog(); - } - - evalValue = evaluator.evalValue.copyOf(); - - } catch (RecognitionException e) { - - Error.writeErrorLog(); - } - - return evalValue; - - } - - - - private static LinkedHashMap convertParamMapToSvarMap( - Map simpleMap) { - - LinkedHashMap pm = new LinkedHashMap(); - - for (String key: simpleMap.keySet()){ - - SvarTemp jObj = simpleMap.get(key); - - Svar svObj = new Svar(); - -// svObj.caseName.add(Param.defaultCaseName); -// svObj.caseCondition.add(Param.always); -// svObj.caseExpression.add(simpleMap.get(key).expression); - - svObj.caseName = jObj.caseName; - svObj.caseCondition = jObj.caseCondition; - svObj.caseExpression = jObj.caseExpression; - - pm.put(key, svObj); - - } - - return pm; - } -} +package wrimsv2.wreslplus.elements.procedures; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.TokenStream; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.components.ControlData; +import wrimsv2.components.IntDouble; +import wrimsv2.components.Error; +import wrimsv2.evaluator.ValueEvaluatorLexer; +import wrimsv2.evaluator.ValueEvaluatorParser; +import wrimsv2.wreslplus.elements.ParamTemp; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.SvarTemp; + +public class ProcParameter { + + private ProcParameter() { + } + + public static void process(StudyTemp st){ + + + st.controlDataParameterMap = convertParamMapToSvarMap(st.parameterMap); + ControlData.parameterMap=st.controlDataParameterMap; + evaluateAllParams(st.parameterList, st.controlDataParameterMap); + + } + + + private static void evaluateAllParams(ArrayList keyList, Map map) { + + for (String key: keyList) { + + Svar svar = map.get(key); + ControlData.currEvalName=key; + ControlData.currEvalTypeIndex=8; + + + for (int i=0; i 0) { + Error.writeErrorLog(); + } + + evalBoolean = evaluator.evalCondition; + + } catch (RecognitionException e) { + + Error.writeErrorLog(); + } + + return evalBoolean; + + } + + private static IntDouble callNumberEvaluator(String evalString) { + + IntDouble evalValue=null; + + evalString="v: "+evalString; + ANTLRStringStream stream = new ANTLRStringStream(evalString); + ValueEvaluatorLexer lexer = new ValueEvaluatorLexer(stream); + TokenStream tokenStream = new CommonTokenStream(lexer); + ValueEvaluatorParser evaluator = new ValueEvaluatorParser(tokenStream); + + + try { + evaluator.evaluator(); + + if (Error.getTotalError() > 0) { + Error.writeErrorLog(); + } + + evalValue = evaluator.evalValue.copyOf(); + + } catch (RecognitionException e) { + + Error.writeErrorLog(); + } + + return evalValue; + + } + + + + private static LinkedHashMap convertParamMapToSvarMap( + Map simpleMap) { + + LinkedHashMap pm = new LinkedHashMap(); + + for (String key: simpleMap.keySet()){ + + SvarTemp jObj = simpleMap.get(key); + + Svar svObj = new Svar(); + +// svObj.caseName.add(Param.defaultCaseName); +// svObj.caseCondition.add(Param.always); +// svObj.caseExpression.add(simpleMap.get(key).expression); + + svObj.caseName = jObj.caseName; + svObj.caseCondition = jObj.caseCondition; + svObj.caseExpression = jObj.caseExpression; + + pm.put(key, svObj); + + } + + return pm; + } +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcVarIncFile.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcVarIncFile.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcVarIncFile.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcVarIncFile.java index 93a1a3fb4..73c088a6e 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcVarIncFile.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcVarIncFile.java @@ -1,108 +1,108 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslplus.elements.ModelTemp; -import wrimsv2.wreslplus.elements.SequenceTemp; -import wrimsv2.wreslplus.elements.StudyTemp; -import wrimsv2.wreslplus.elements.Tools; -import wrimsv2.wreslplus.elements.WeightSubgroup; -import wrimsv2.wreslplus.elements.WeightTable; - -public class ProcVarIncFile { - - private ProcVarIncFile() { - } - - public static void process( StudyTemp st) { - - for (String m : st.modelList_effective){ - - process(st.modelMap.get(m)); - - } - - for (String m : st.incModelList_effective){ - - process(st.modelMap.get(m)); - - } - } - - public static void process( ModelTemp mt) { - - // TODO: use retain Set to simplify codes - mt.svIncFileList = new ArrayList(mt.itemList); - mt.svIncFileList.removeAll(mt.tsList); - mt.svIncFileList.removeAll(mt.asList); - mt.svIncFileList.removeAll(mt.dvList); - mt.svIncFileList.removeAll(mt.glList); - mt.svIncFileList.removeAll(mt.exList); - - mt.asIncFileList = new ArrayList(mt.itemList); - mt.asIncFileList.removeAll(mt.tsList); - mt.asIncFileList.removeAll(mt.svList); - mt.asIncFileList.removeAll(mt.dvList); - mt.asIncFileList.removeAll(mt.glList); - mt.asIncFileList.removeAll(mt.exList); - - mt.exIncFileList = new ArrayList(mt.itemList); - mt.exIncFileList.removeAll(mt.tsList); - mt.exIncFileList.removeAll(mt.svList); - mt.exIncFileList.removeAll(mt.dvList); - mt.exIncFileList.removeAll(mt.glList); - mt.exIncFileList.removeAll(mt.asList); - - mt.dvIncFileList = new ArrayList(mt.itemList); - mt.dvIncFileList.removeAll(mt.tsList); - mt.dvIncFileList.removeAll(mt.svList); - mt.dvIncFileList.removeAll(mt.exList); - mt.dvIncFileList.removeAll(mt.glList); - mt.dvIncFileList.removeAll(mt.asList); - - mt.glIncFileList = new ArrayList(mt.itemList); - mt.glIncFileList.removeAll(mt.tsList); - mt.glIncFileList.removeAll(mt.svList); - mt.glIncFileList.removeAll(mt.exList); - mt.glIncFileList.removeAll(mt.dvList); - mt.glIncFileList.removeAll(mt.asList); - - for (String f : mt.incFileMap.keySet()){ - - int index = mt.svIncFileList.indexOf(f); - mt.svIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); - - index = mt.asIncFileList.indexOf(f); - mt.asIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); - - index = mt.exIncFileList.indexOf(f); - mt.exIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); - - index = mt.dvIncFileList.indexOf(f); - mt.dvIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); - - index = mt.glIncFileList.indexOf(f); - mt.glIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); - } - - mt.svIncFileList_post = new ArrayList(mt.svIncFileList); - - mt.asIncFileList_post = new ArrayList(mt.asIncFileList); - - mt.exIncFileList_post = new ArrayList(mt.exIncFileList); - - mt.dvIncFileList_post = new ArrayList(mt.dvIncFileList); - - mt.glIncFileList_post = new ArrayList(mt.glIncFileList); - - } - - - - -} +package wrimsv2.wreslplus.elements.procedures; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.wreslparser.elements.LogUtils; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.SequenceTemp; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.Tools; +import wrimsv2.wreslplus.elements.WeightSubgroup; +import wrimsv2.wreslplus.elements.WeightTable; + +public class ProcVarIncFile { + + private ProcVarIncFile() { + } + + public static void process( StudyTemp st) { + + for (String m : st.modelList_effective){ + + process(st.modelMap.get(m)); + + } + + for (String m : st.incModelList_effective){ + + process(st.modelMap.get(m)); + + } + } + + public static void process( ModelTemp mt) { + + // TODO: use retain Set to simplify codes + mt.svIncFileList = new ArrayList(mt.itemList); + mt.svIncFileList.removeAll(mt.tsList); + mt.svIncFileList.removeAll(mt.asList); + mt.svIncFileList.removeAll(mt.dvList); + mt.svIncFileList.removeAll(mt.glList); + mt.svIncFileList.removeAll(mt.exList); + + mt.asIncFileList = new ArrayList(mt.itemList); + mt.asIncFileList.removeAll(mt.tsList); + mt.asIncFileList.removeAll(mt.svList); + mt.asIncFileList.removeAll(mt.dvList); + mt.asIncFileList.removeAll(mt.glList); + mt.asIncFileList.removeAll(mt.exList); + + mt.exIncFileList = new ArrayList(mt.itemList); + mt.exIncFileList.removeAll(mt.tsList); + mt.exIncFileList.removeAll(mt.svList); + mt.exIncFileList.removeAll(mt.dvList); + mt.exIncFileList.removeAll(mt.glList); + mt.exIncFileList.removeAll(mt.asList); + + mt.dvIncFileList = new ArrayList(mt.itemList); + mt.dvIncFileList.removeAll(mt.tsList); + mt.dvIncFileList.removeAll(mt.svList); + mt.dvIncFileList.removeAll(mt.exList); + mt.dvIncFileList.removeAll(mt.glList); + mt.dvIncFileList.removeAll(mt.asList); + + mt.glIncFileList = new ArrayList(mt.itemList); + mt.glIncFileList.removeAll(mt.tsList); + mt.glIncFileList.removeAll(mt.svList); + mt.glIncFileList.removeAll(mt.exList); + mt.glIncFileList.removeAll(mt.dvList); + mt.glIncFileList.removeAll(mt.asList); + + for (String f : mt.incFileMap.keySet()){ + + int index = mt.svIncFileList.indexOf(f); + mt.svIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); + + index = mt.asIncFileList.indexOf(f); + mt.asIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); + + index = mt.exIncFileList.indexOf(f); + mt.exIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); + + index = mt.dvIncFileList.indexOf(f); + mt.dvIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); + + index = mt.glIncFileList.indexOf(f); + mt.glIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); + } + + mt.svIncFileList_post = new ArrayList(mt.svIncFileList); + + mt.asIncFileList_post = new ArrayList(mt.asIncFileList); + + mt.exIncFileList_post = new ArrayList(mt.exIncFileList); + + mt.dvIncFileList_post = new ArrayList(mt.dvIncFileList); + + mt.glIncFileList_post = new ArrayList(mt.glIncFileList); + + } + + + + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcVarIncFileList.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcVarIncFileList.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcVarIncFileList.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcVarIncFileList.java index 028479cbd..e06ea81c7 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcVarIncFileList.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcVarIncFileList.java @@ -1,230 +1,230 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.wreslparser.elements.LogUtils; -import wrimsv2.wreslplus.elements.ModelTemp; -import wrimsv2.wreslplus.elements.SequenceTemp; -import wrimsv2.wreslplus.elements.StudyTemp; -import wrimsv2.wreslplus.elements.Tools; -import wrimsv2.wreslplus.elements.WeightSubgroup; -import wrimsv2.wreslplus.elements.WeightTable; - -public class ProcVarIncFileList { - - private ProcVarIncFileList() { - } - - public static void replaceIncFile( StudyTemp st) { - - - for (HashSet modSet : st.fileGroupOrder_incModel ){ - - for (String modName: modSet ){ - - ModelTemp mObj = st.modelMap.get(modName); - - replaceIncFile(mObj, st); - - } - - } - } - - // for main file (st!=null), for included file (st==null) - public static void replaceIncFile( ModelTemp mt, StudyTemp st) { - - // TODO: use retain Set to simplify codes - mt.svIncFileList = new ArrayList(mt.itemList); - mt.svIncFileList.removeAll(mt.tsList); - mt.svIncFileList.removeAll(mt.asList); - mt.svIncFileList.removeAll(mt.dvList); - mt.svIncFileList.removeAll(mt.glList); - mt.svIncFileList.removeAll(mt.exList); - - mt.asIncFileList = new ArrayList(mt.itemList); - mt.asIncFileList.removeAll(mt.tsList); - mt.asIncFileList.removeAll(mt.svList); - mt.asIncFileList.removeAll(mt.dvList); - mt.asIncFileList.removeAll(mt.glList); - mt.asIncFileList.removeAll(mt.exList); - - mt.exIncFileList = new ArrayList(mt.itemList); - mt.exIncFileList.removeAll(mt.tsList); - mt.exIncFileList.removeAll(mt.svList); - mt.exIncFileList.removeAll(mt.dvList); - mt.exIncFileList.removeAll(mt.glList); - mt.exIncFileList.removeAll(mt.asList); - - mt.dvIncFileList = new ArrayList(mt.itemList); - mt.dvIncFileList.removeAll(mt.tsList); - mt.dvIncFileList.removeAll(mt.svList); - mt.dvIncFileList.removeAll(mt.exList); - mt.dvIncFileList.removeAll(mt.glList); - mt.dvIncFileList.removeAll(mt.asList); - - mt.glIncFileList = new ArrayList(mt.itemList); - mt.glIncFileList.removeAll(mt.tsList); - mt.glIncFileList.removeAll(mt.svList); - mt.glIncFileList.removeAll(mt.exList); - mt.glIncFileList.removeAll(mt.dvList); - mt.glIncFileList.removeAll(mt.asList); - - for (String f : mt.incFileMap.keySet()){ - - int index_1; - int index_2; - int index_3; - int index_4; - int index_5; - - - // f is a include model - if (st!=null && st.incModelList_effective.contains(f)) { - - //System.out.println("# before:"+mt.svIncFileList); - - String model_label = Param.model_label+f; - - index_1 = mt.svIncFileList.indexOf(model_label); - index_2 = mt.asIncFileList.indexOf(model_label); - index_3 = mt.exIncFileList.indexOf(model_label); - index_4 = mt.dvIncFileList.indexOf(model_label); - index_5 = mt.glIncFileList.indexOf(model_label); - - mt.svIncFileList.remove(index_1); - mt.svIncFileList.addAll(index_1, st.modelMap.get(f).svIncFileList_post); - - mt.asIncFileList.remove(index_2); - mt.asIncFileList.addAll(index_2, st.modelMap.get(f).asIncFileList_post); - - mt.exIncFileList.remove(index_3); - mt.exIncFileList.addAll(index_3, st.modelMap.get(f).exIncFileList_post); - - mt.dvIncFileList.remove(index_4); - mt.dvIncFileList.addAll(index_4, st.modelMap.get(f).dvIncFileList_post); - - mt.glIncFileList.remove(index_5); - mt.glIncFileList.addAll(index_5, st.modelMap.get(f).glIncFileList_post); - //System.out.println("# after:"+mt.svIncFileList); - - } - - // f is a include file - else { - - index_1 = mt.svIncFileList.indexOf(f); - index_2 = mt.asIncFileList.indexOf(f); - index_3 = mt.exIncFileList.indexOf(f); - index_4 = mt.dvIncFileList.indexOf(f); - index_5 = mt.glIncFileList.indexOf(f); - - mt.svIncFileList.set(index_1, mt.incFileMap.get(f).pathRelativeToRunDir); - mt.asIncFileList.set(index_2, mt.incFileMap.get(f).pathRelativeToRunDir); - mt.exIncFileList.set(index_3, mt.incFileMap.get(f).pathRelativeToRunDir); - mt.dvIncFileList.set(index_4, mt.incFileMap.get(f).pathRelativeToRunDir); - mt.glIncFileList.set(index_5, mt.incFileMap.get(f).pathRelativeToRunDir); - - } - } - - mt.svIncFileList_post = new ArrayList(mt.svIncFileList); - mt.asIncFileList_post = new ArrayList(mt.asIncFileList); - mt.exIncFileList_post = new ArrayList(mt.exIncFileList); - mt.dvIncFileList_post = new ArrayList(mt.dvIncFileList); - mt.glIncFileList_post = new ArrayList(mt.glIncFileList); - - } - -// public static void replaceIncFile_( ModelTemp mt) { -// -// // TODO: use retain Set to simplify codes -// mt.svIncFileList = new ArrayList(mt.itemList); -// mt.svIncFileList.removeAll(mt.tsList); -// mt.svIncFileList.removeAll(mt.asList); -// mt.svIncFileList.removeAll(mt.dvList); -// mt.svIncFileList.removeAll(mt.glList); -// mt.svIncFileList.removeAll(mt.exList); -// -// mt.asIncFileList = new ArrayList(mt.itemList); -// mt.asIncFileList.removeAll(mt.tsList); -// mt.asIncFileList.removeAll(mt.svList); -// mt.asIncFileList.removeAll(mt.dvList); -// mt.asIncFileList.removeAll(mt.glList); -// mt.asIncFileList.removeAll(mt.exList); -// -// mt.exIncFileList = new ArrayList(mt.itemList); -// mt.exIncFileList.removeAll(mt.tsList); -// mt.exIncFileList.removeAll(mt.svList); -// mt.exIncFileList.removeAll(mt.dvList); -// mt.exIncFileList.removeAll(mt.glList); -// mt.exIncFileList.removeAll(mt.asList); -// -// for (String f : mt.incFileMap.keySet()){ -// -// int index = mt.svIncFileList.indexOf(f); -// mt.svIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); -// -// index = mt.asIncFileList.indexOf(f); -// mt.asIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); -// -// index = mt.exIncFileList.indexOf(f); -// mt.exIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); -// } -// -// mt.svIncFileList_post = new ArrayList(mt.svIncFileList); -// mt.asIncFileList_post = new ArrayList(mt.asIncFileList); -// mt.exIncFileList_post = new ArrayList(mt.exIncFileList); -// -// } - -// public static void replaceIncModel( StudyTemp st) { -// -// -// for (HashSet modSet : st.fileGroupOrder_incModel ){ -// -// for (String modName: modSet ){ -// -// ModelTemp mObj = st.modelMap.get(modName); -// -// replaceIncModel(mObj, st); -// -// } -// -// } -// -// } -// -// public static void replaceIncModel( ModelTemp mt, StudyTemp st) { -// -// -// for (String incM : mt.incModelList){ -// -// int index = -1; -// -// ModelTemp incMObj = st.modelMap.get(incM); -// -// -// -// index = mt.svIncFileList_post.indexOf(incM); -// mt.svIncFileList_post.remove(index); -// mt.svIncFileList_post.addAll(index, incMObj.svIncFileList_post); -// -// index = mt.asIncFileList_post.indexOf(incM); -// mt.asIncFileList_post.remove(index); -// mt.asIncFileList_post.addAll(index, incMObj.asIncFileList_post); -// -// index = mt.exIncFileList_post.indexOf(incM); -// mt.exIncFileList_post.remove(index); -// mt.exIncFileList_post.addAll(index, incMObj.exIncFileList_post); -// } -// -// -// } - - -} +package wrimsv2.wreslplus.elements.procedures; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.wreslparser.elements.LogUtils; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.SequenceTemp; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.Tools; +import wrimsv2.wreslplus.elements.WeightSubgroup; +import wrimsv2.wreslplus.elements.WeightTable; + +public class ProcVarIncFileList { + + private ProcVarIncFileList() { + } + + public static void replaceIncFile( StudyTemp st) { + + + for (HashSet modSet : st.fileGroupOrder_incModel ){ + + for (String modName: modSet ){ + + ModelTemp mObj = st.modelMap.get(modName); + + replaceIncFile(mObj, st); + + } + + } + } + + // for main file (st!=null), for included file (st==null) + public static void replaceIncFile( ModelTemp mt, StudyTemp st) { + + // TODO: use retain Set to simplify codes + mt.svIncFileList = new ArrayList(mt.itemList); + mt.svIncFileList.removeAll(mt.tsList); + mt.svIncFileList.removeAll(mt.asList); + mt.svIncFileList.removeAll(mt.dvList); + mt.svIncFileList.removeAll(mt.glList); + mt.svIncFileList.removeAll(mt.exList); + + mt.asIncFileList = new ArrayList(mt.itemList); + mt.asIncFileList.removeAll(mt.tsList); + mt.asIncFileList.removeAll(mt.svList); + mt.asIncFileList.removeAll(mt.dvList); + mt.asIncFileList.removeAll(mt.glList); + mt.asIncFileList.removeAll(mt.exList); + + mt.exIncFileList = new ArrayList(mt.itemList); + mt.exIncFileList.removeAll(mt.tsList); + mt.exIncFileList.removeAll(mt.svList); + mt.exIncFileList.removeAll(mt.dvList); + mt.exIncFileList.removeAll(mt.glList); + mt.exIncFileList.removeAll(mt.asList); + + mt.dvIncFileList = new ArrayList(mt.itemList); + mt.dvIncFileList.removeAll(mt.tsList); + mt.dvIncFileList.removeAll(mt.svList); + mt.dvIncFileList.removeAll(mt.exList); + mt.dvIncFileList.removeAll(mt.glList); + mt.dvIncFileList.removeAll(mt.asList); + + mt.glIncFileList = new ArrayList(mt.itemList); + mt.glIncFileList.removeAll(mt.tsList); + mt.glIncFileList.removeAll(mt.svList); + mt.glIncFileList.removeAll(mt.exList); + mt.glIncFileList.removeAll(mt.dvList); + mt.glIncFileList.removeAll(mt.asList); + + for (String f : mt.incFileMap.keySet()){ + + int index_1; + int index_2; + int index_3; + int index_4; + int index_5; + + + // f is a include model + if (st!=null && st.incModelList_effective.contains(f)) { + + //System.out.println("# before:"+mt.svIncFileList); + + String model_label = Param.model_label+f; + + index_1 = mt.svIncFileList.indexOf(model_label); + index_2 = mt.asIncFileList.indexOf(model_label); + index_3 = mt.exIncFileList.indexOf(model_label); + index_4 = mt.dvIncFileList.indexOf(model_label); + index_5 = mt.glIncFileList.indexOf(model_label); + + mt.svIncFileList.remove(index_1); + mt.svIncFileList.addAll(index_1, st.modelMap.get(f).svIncFileList_post); + + mt.asIncFileList.remove(index_2); + mt.asIncFileList.addAll(index_2, st.modelMap.get(f).asIncFileList_post); + + mt.exIncFileList.remove(index_3); + mt.exIncFileList.addAll(index_3, st.modelMap.get(f).exIncFileList_post); + + mt.dvIncFileList.remove(index_4); + mt.dvIncFileList.addAll(index_4, st.modelMap.get(f).dvIncFileList_post); + + mt.glIncFileList.remove(index_5); + mt.glIncFileList.addAll(index_5, st.modelMap.get(f).glIncFileList_post); + //System.out.println("# after:"+mt.svIncFileList); + + } + + // f is a include file + else { + + index_1 = mt.svIncFileList.indexOf(f); + index_2 = mt.asIncFileList.indexOf(f); + index_3 = mt.exIncFileList.indexOf(f); + index_4 = mt.dvIncFileList.indexOf(f); + index_5 = mt.glIncFileList.indexOf(f); + + mt.svIncFileList.set(index_1, mt.incFileMap.get(f).pathRelativeToRunDir); + mt.asIncFileList.set(index_2, mt.incFileMap.get(f).pathRelativeToRunDir); + mt.exIncFileList.set(index_3, mt.incFileMap.get(f).pathRelativeToRunDir); + mt.dvIncFileList.set(index_4, mt.incFileMap.get(f).pathRelativeToRunDir); + mt.glIncFileList.set(index_5, mt.incFileMap.get(f).pathRelativeToRunDir); + + } + } + + mt.svIncFileList_post = new ArrayList(mt.svIncFileList); + mt.asIncFileList_post = new ArrayList(mt.asIncFileList); + mt.exIncFileList_post = new ArrayList(mt.exIncFileList); + mt.dvIncFileList_post = new ArrayList(mt.dvIncFileList); + mt.glIncFileList_post = new ArrayList(mt.glIncFileList); + + } + +// public static void replaceIncFile_( ModelTemp mt) { +// +// // TODO: use retain Set to simplify codes +// mt.svIncFileList = new ArrayList(mt.itemList); +// mt.svIncFileList.removeAll(mt.tsList); +// mt.svIncFileList.removeAll(mt.asList); +// mt.svIncFileList.removeAll(mt.dvList); +// mt.svIncFileList.removeAll(mt.glList); +// mt.svIncFileList.removeAll(mt.exList); +// +// mt.asIncFileList = new ArrayList(mt.itemList); +// mt.asIncFileList.removeAll(mt.tsList); +// mt.asIncFileList.removeAll(mt.svList); +// mt.asIncFileList.removeAll(mt.dvList); +// mt.asIncFileList.removeAll(mt.glList); +// mt.asIncFileList.removeAll(mt.exList); +// +// mt.exIncFileList = new ArrayList(mt.itemList); +// mt.exIncFileList.removeAll(mt.tsList); +// mt.exIncFileList.removeAll(mt.svList); +// mt.exIncFileList.removeAll(mt.dvList); +// mt.exIncFileList.removeAll(mt.glList); +// mt.exIncFileList.removeAll(mt.asList); +// +// for (String f : mt.incFileMap.keySet()){ +// +// int index = mt.svIncFileList.indexOf(f); +// mt.svIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); +// +// index = mt.asIncFileList.indexOf(f); +// mt.asIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); +// +// index = mt.exIncFileList.indexOf(f); +// mt.exIncFileList.set(index, mt.incFileMap.get(f).pathRelativeToRunDir); +// } +// +// mt.svIncFileList_post = new ArrayList(mt.svIncFileList); +// mt.asIncFileList_post = new ArrayList(mt.asIncFileList); +// mt.exIncFileList_post = new ArrayList(mt.exIncFileList); +// +// } + +// public static void replaceIncModel( StudyTemp st) { +// +// +// for (HashSet modSet : st.fileGroupOrder_incModel ){ +// +// for (String modName: modSet ){ +// +// ModelTemp mObj = st.modelMap.get(modName); +// +// replaceIncModel(mObj, st); +// +// } +// +// } +// +// } +// +// public static void replaceIncModel( ModelTemp mt, StudyTemp st) { +// +// +// for (String incM : mt.incModelList){ +// +// int index = -1; +// +// ModelTemp incMObj = st.modelMap.get(incM); +// +// +// +// index = mt.svIncFileList_post.indexOf(incM); +// mt.svIncFileList_post.remove(index); +// mt.svIncFileList_post.addAll(index, incMObj.svIncFileList_post); +// +// index = mt.asIncFileList_post.indexOf(incM); +// mt.asIncFileList_post.remove(index); +// mt.asIncFileList_post.addAll(index, incMObj.asIncFileList_post); +// +// index = mt.exIncFileList_post.indexOf(incM); +// mt.exIncFileList_post.remove(index); +// mt.exIncFileList_post.addAll(index, incMObj.exIncFileList_post); +// } +// +// +// } + + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcWeight.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcWeight.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcWeight.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcWeight.java index a5e5dacdc..339fb8b0e 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ProcWeight.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ProcWeight.java @@ -1,311 +1,311 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; - -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.wreslplus.elements.ModelTemp; -import wrimsv2.wreslplus.elements.SequenceTemp; -import wrimsv2.wreslplus.elements.StudyTemp; -import wrimsv2.wreslplus.elements.WeightSubgroup; -import wrimsv2.wreslplus.elements.WeightTable; - -public class ProcWeight { - - private ProcWeight() { - } - - // processed after collecting weights - // TODO: improve memory efficiency by adding the slack and surplus weight element into fileModelDataMap - public static void processWeightGroup(StudyTemp st) { - - Set filesProcessed = new HashSet(); - - for (String seqName : st.seqList) { - - SequenceTemp seqObj = st.seqMap.get(seqName); - ModelTemp seqModelObj = st.modelMap.get(seqObj.model); - - for (String e: st.modelList_effective){ - - if (st.allOffspringMap_incModel.keySet().contains(e)) { - for (String f: st.allOffspringMap_incModel.get(e)) { - - if (!filesProcessed.contains(f)) { - - ModelTemp incModel = st.modelMap.get(f); - processWeightGroup(incModel); - filesProcessed.add(f); - - } - - } - } - - } - for (String f: seqModelObj.incFileRelativePathList_post){ - - if (!filesProcessed.contains(f)) { - - ModelTemp incModel = st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)); - processWeightGroup(incModel); - filesProcessed.add(f); - - } - - - } - - processWeightGroup(seqModelObj); - } - - } - - public static void processWeightGroup(ModelTemp mObj) { - - - for (WeightTable wt : mObj.wTableObjList) { - - if (wt.isWeightGroup) { - - // TODO: process subgroup here - //processSubgroup(wt); - - boolean mainCommonPenaltyIsZero = false; - try { mainCommonPenaltyIsZero = Float.parseFloat(wt.deviationPenalty)==0;} catch (Exception e) {} - - - for (WeightSubgroup wsg : wt.subgroupMap.values()){ - - boolean subCommonPenaltyIsZero = false; - try { subCommonPenaltyIsZero = Float.parseFloat(wsg.deviationPenalty)==0;} catch (Exception e) {} -/// process subgroup - - // add all var in wvList - for (String var : wsg.varList) { - Misc.addWeightInGroupWeightMap(var, wt.fromWresl, wt.commonWeight, mObj); - } - - if (!mainCommonPenaltyIsZero || !subCommonPenaltyIsZero) { - /// process subgroup - // create new dvar for subgroup id. this is the - // average for the subgroup - Misc.createDvarInModelObj(wsg.id, Param.upper_unbounded, Param.lower_unbounded, - "weightgroup_mean", "na", wt.fromWresl, mObj); - - // create new goal for subgroup average - String goal_id = "wg__" + wt.id_lowcase + "__" + wsg.id + "__mean"; - String lhs = wsg.varList.size() + "*" + wsg.id.toLowerCase(); - String rhs = ""; - for (String v : wsg.varList) { - rhs = rhs + v + "+"; - } - rhs = rhs.substring(0, rhs.length() - 1); - // TODO: dependants check - Misc.createGoalInModelObj(goal_id, lhs, "=", rhs, wt.dependants, wt.fromWresl, wt.condition, - mObj); - } - - if (!subCommonPenaltyIsZero) { - - - // create slack and surplus for var in varList - String weight = "-(" + wsg.deviationPenalty + ")"; - Double deviationTolerance = Double.parseDouble(wsg.deviationTolerance); - - for (String var : wsg.varList) { - - String slack_id = "wg__" + wt.id_lowcase.toLowerCase() + "__" + wsg.id.toLowerCase() + "__" + var + "__slack"; - String surplus_id = "wg__" + wt.id_lowcase.toLowerCase() + "__" + wsg.id.toLowerCase() + "__" + var + "__surplus"; - - // add slack - Misc.createDvarInModelObj(slack_id, Param.upper_unbounded, Param.zero, "weightgroup_slack", "na", wt.fromWresl, mObj); - mObj.dvList_deviationSlackSurplus.add(slack_id.toLowerCase()); - mObj.deviationSlackSurplus_toleranceMap.put(slack_id.toLowerCase(), deviationTolerance); - - Misc.addWeightInGroupWeightMap(slack_id, wt.fromWresl, weight, mObj); - - // add surplus - Misc.createDvarInModelObj(surplus_id, Param.upper_unbounded, Param.zero, "weightgroup_surplus", "na", wt.fromWresl, mObj); - mObj.dvList_deviationSlackSurplus.add(surplus_id.toLowerCase()); - mObj.deviationSlackSurplus_toleranceMap.put(surplus_id.toLowerCase(), deviationTolerance); - - Misc.addWeightInGroupWeightMap(surplus_id, wt.fromWresl, weight, mObj); - - // add goal for slack surplus - String goal_ss_id = "wg__" + wt.id_lowcase + "__" + wsg.id + "__" + var + "__ss"; - String lhs_ss = var + "+" + slack_id + "-" + surplus_id; - String rhs_ss = wsg.id.toLowerCase(); - - Misc.createGoalInModelObj(goal_ss_id, lhs_ss, "=", rhs_ss, wt.dependants, wt.fromWresl, wt.condition, mObj); - - } - - - } - } // end for loop subgroup - - -/// process main group - // add all var in wvList - for (String var : wt.varList) { - Misc.addWeightInGroupWeightMap(var, wt.fromWresl, wt.commonWeight, mObj); - } - if (!mainCommonPenaltyIsZero) { - - /// process main group - // create new dvar for average - String average_id = "mean__" + wt.id_lowcase; - String kind = "weightgroup_mean"; - String units = "na"; - - Misc.createDvarInModelObj(average_id, Param.upper_unbounded, Param.lower_unbounded, kind, units, wt.fromWresl, mObj); - - // create new goal for group average - ArrayList varList_and_subGroupId = new ArrayList(); - varList_and_subGroupId.addAll(wt.varList); - varList_and_subGroupId.addAll(wt.subgroupMap.keySet()); - String goal_id = "wg__" + wt.id_lowcase + "__mean"; - int mult =wt.varList.size()+wt.subgroupMap.keySet().size(); - String lhs = mult + "*" + average_id.toLowerCase(); - String rhs = ""; - for (String v : varList_and_subGroupId) { - rhs = rhs + v + "+"; - } - rhs = rhs.substring(0, rhs.length() - 1); - Misc.createGoalInModelObj(goal_id, lhs, "=", rhs, wt.dependants, wt.fromWresl, wt.condition, mObj); - - - // create slack and surplus for var in varList - String weight = "-(" + wt.deviationPenalty + ")"; - Double deviationTolerance = Double.parseDouble(wt.deviationTolerance); - - for (String var : varList_and_subGroupId) { - - String slack_id = "wg__" + wt.id_lowcase.toLowerCase() + "__" + var + "__slack"; - String surplus_id = "wg__" + wt.id_lowcase.toLowerCase() + "__" + var + "__surplus"; - - // add slack - Misc.createDvarInModelObj(slack_id, Param.upper_unbounded, Param.zero, "weightgroup_slack", "na", wt.fromWresl, mObj); - mObj.dvList_deviationSlackSurplus.add(slack_id.toLowerCase()); - mObj.deviationSlackSurplus_toleranceMap.put(slack_id.toLowerCase(), deviationTolerance); - - Misc.addWeightInGroupWeightMap(slack_id, wt.fromWresl, weight, mObj); - - // add surplus - Misc.createDvarInModelObj(surplus_id, Param.upper_unbounded, Param.zero, "weightgroup_surplus", "na", wt.fromWresl, mObj); - mObj.dvList_deviationSlackSurplus.add(surplus_id.toLowerCase()); - mObj.deviationSlackSurplus_toleranceMap.put(surplus_id.toLowerCase(), deviationTolerance); - - Misc.addWeightInGroupWeightMap(surplus_id, wt.fromWresl, weight, mObj); - - // add goal for slack surplus - String goal_ss_id = "wg__" + wt.id_lowcase + "__" + var + "__ss"; - String lhs_ss = var + "+" + slack_id + "-" + surplus_id; - String rhs_ss = average_id.toLowerCase(); - - Misc.createGoalInModelObj(goal_ss_id, lhs_ss, "=", rhs_ss, wt.dependants, wt.fromWresl, wt.condition, mObj); - - } - - } - - } - - } - - - - } - - public static void collectWeightVar(StudyTemp s) { - - Set filesProcessed = new HashSet(); - - for (String seq : s.seqList) { - - SequenceTemp seqObj = s.seqMap.get(seq); - - String m = seqObj.model; - - ModelTemp mObj = s.modelMap.get(m); - - - for (String e: s.modelList_effective){ - - if (s.allOffspringMap_incModel.keySet().contains(e)) { - for (String f: s.allOffspringMap_incModel.get(e)) { - - if (!filesProcessed.contains(f)) { - - ModelTemp incModel = s.modelMap.get(f); - collectWeightVar(incModel); - filesProcessed.add(f); - - } - - } - } - - } - - for (String f: mObj.incFileRelativePathList_post){ - - if (!filesProcessed.contains(f)) { - - String mn = s.fileModelNameMap.get(f).get(0); - - ModelTemp incModel = s.fileModelDataTable.get(f, mn); - - collectWeightVar(incModel); - filesProcessed.add(f); - - } - - } - - collectWeightVar(mObj); - - } - - } - - public static void collectWeightVar(ModelTemp mObj){ - - for (WeightTable wt : mObj.wTableObjList) { - - if (!wt.isWeightGroup) { - mObj.wvList_post.addAll(wt.varList); -// for (WeightSubgroup wsg : wt.subgroupMap.values()) { -// mObj.wvList_post.addAll(wsg.varList); -// //seqObj.wvList.addAll(wsg.varList); -// } - - } - } - - } - public static void collectWeightVar(ModelTemp mObj, StudyTemp st) { - - for (String f: mObj.incFileRelativePathList_post){ - - String mn = st.fileModelNameMap.get(f).get(0); - - ModelTemp incModel = st.fileModelDataTable.get(f, mn); - - collectWeightVar(incModel); - - } - - collectWeightVar(mObj); - - - } - - - - - - -} +package wrimsv2.wreslplus.elements.procedures; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.SequenceTemp; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.WeightSubgroup; +import wrimsv2.wreslplus.elements.WeightTable; + +public class ProcWeight { + + private ProcWeight() { + } + + // processed after collecting weights + // TODO: improve memory efficiency by adding the slack and surplus weight element into fileModelDataMap + public static void processWeightGroup(StudyTemp st) { + + Set filesProcessed = new HashSet(); + + for (String seqName : st.seqList) { + + SequenceTemp seqObj = st.seqMap.get(seqName); + ModelTemp seqModelObj = st.modelMap.get(seqObj.model); + + for (String e: st.modelList_effective){ + + if (st.allOffspringMap_incModel.keySet().contains(e)) { + for (String f: st.allOffspringMap_incModel.get(e)) { + + if (!filesProcessed.contains(f)) { + + ModelTemp incModel = st.modelMap.get(f); + processWeightGroup(incModel); + filesProcessed.add(f); + + } + + } + } + + } + for (String f: seqModelObj.incFileRelativePathList_post){ + + if (!filesProcessed.contains(f)) { + + ModelTemp incModel = st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)); + processWeightGroup(incModel); + filesProcessed.add(f); + + } + + + } + + processWeightGroup(seqModelObj); + } + + } + + public static void processWeightGroup(ModelTemp mObj) { + + + for (WeightTable wt : mObj.wTableObjList) { + + if (wt.isWeightGroup) { + + // TODO: process subgroup here + //processSubgroup(wt); + + boolean mainCommonPenaltyIsZero = false; + try { mainCommonPenaltyIsZero = Float.parseFloat(wt.deviationPenalty)==0;} catch (Exception e) {} + + + for (WeightSubgroup wsg : wt.subgroupMap.values()){ + + boolean subCommonPenaltyIsZero = false; + try { subCommonPenaltyIsZero = Float.parseFloat(wsg.deviationPenalty)==0;} catch (Exception e) {} +/// process subgroup + + // add all var in wvList + for (String var : wsg.varList) { + Misc.addWeightInGroupWeightMap(var, wt.fromWresl, wt.commonWeight, mObj); + } + + if (!mainCommonPenaltyIsZero || !subCommonPenaltyIsZero) { + /// process subgroup + // create new dvar for subgroup id. this is the + // average for the subgroup + Misc.createDvarInModelObj(wsg.id, Param.upper_unbounded, Param.lower_unbounded, + "weightgroup_mean", "na", wt.fromWresl, mObj); + + // create new goal for subgroup average + String goal_id = "wg__" + wt.id_lowcase + "__" + wsg.id + "__mean"; + String lhs = wsg.varList.size() + "*" + wsg.id.toLowerCase(); + String rhs = ""; + for (String v : wsg.varList) { + rhs = rhs + v + "+"; + } + rhs = rhs.substring(0, rhs.length() - 1); + // TODO: dependants check + Misc.createGoalInModelObj(goal_id, lhs, "=", rhs, wt.dependants, wt.fromWresl, wt.condition, + mObj); + } + + if (!subCommonPenaltyIsZero) { + + + // create slack and surplus for var in varList + String weight = "-(" + wsg.deviationPenalty + ")"; + Double deviationTolerance = Double.parseDouble(wsg.deviationTolerance); + + for (String var : wsg.varList) { + + String slack_id = "wg__" + wt.id_lowcase.toLowerCase() + "__" + wsg.id.toLowerCase() + "__" + var + "__slack"; + String surplus_id = "wg__" + wt.id_lowcase.toLowerCase() + "__" + wsg.id.toLowerCase() + "__" + var + "__surplus"; + + // add slack + Misc.createDvarInModelObj(slack_id, Param.upper_unbounded, Param.zero, "weightgroup_slack", "na", wt.fromWresl, mObj); + mObj.dvList_deviationSlackSurplus.add(slack_id.toLowerCase()); + mObj.deviationSlackSurplus_toleranceMap.put(slack_id.toLowerCase(), deviationTolerance); + + Misc.addWeightInGroupWeightMap(slack_id, wt.fromWresl, weight, mObj); + + // add surplus + Misc.createDvarInModelObj(surplus_id, Param.upper_unbounded, Param.zero, "weightgroup_surplus", "na", wt.fromWresl, mObj); + mObj.dvList_deviationSlackSurplus.add(surplus_id.toLowerCase()); + mObj.deviationSlackSurplus_toleranceMap.put(surplus_id.toLowerCase(), deviationTolerance); + + Misc.addWeightInGroupWeightMap(surplus_id, wt.fromWresl, weight, mObj); + + // add goal for slack surplus + String goal_ss_id = "wg__" + wt.id_lowcase + "__" + wsg.id + "__" + var + "__ss"; + String lhs_ss = var + "+" + slack_id + "-" + surplus_id; + String rhs_ss = wsg.id.toLowerCase(); + + Misc.createGoalInModelObj(goal_ss_id, lhs_ss, "=", rhs_ss, wt.dependants, wt.fromWresl, wt.condition, mObj); + + } + + + } + } // end for loop subgroup + + +/// process main group + // add all var in wvList + for (String var : wt.varList) { + Misc.addWeightInGroupWeightMap(var, wt.fromWresl, wt.commonWeight, mObj); + } + if (!mainCommonPenaltyIsZero) { + + /// process main group + // create new dvar for average + String average_id = "mean__" + wt.id_lowcase; + String kind = "weightgroup_mean"; + String units = "na"; + + Misc.createDvarInModelObj(average_id, Param.upper_unbounded, Param.lower_unbounded, kind, units, wt.fromWresl, mObj); + + // create new goal for group average + ArrayList varList_and_subGroupId = new ArrayList(); + varList_and_subGroupId.addAll(wt.varList); + varList_and_subGroupId.addAll(wt.subgroupMap.keySet()); + String goal_id = "wg__" + wt.id_lowcase + "__mean"; + int mult =wt.varList.size()+wt.subgroupMap.keySet().size(); + String lhs = mult + "*" + average_id.toLowerCase(); + String rhs = ""; + for (String v : varList_and_subGroupId) { + rhs = rhs + v + "+"; + } + rhs = rhs.substring(0, rhs.length() - 1); + Misc.createGoalInModelObj(goal_id, lhs, "=", rhs, wt.dependants, wt.fromWresl, wt.condition, mObj); + + + // create slack and surplus for var in varList + String weight = "-(" + wt.deviationPenalty + ")"; + Double deviationTolerance = Double.parseDouble(wt.deviationTolerance); + + for (String var : varList_and_subGroupId) { + + String slack_id = "wg__" + wt.id_lowcase.toLowerCase() + "__" + var + "__slack"; + String surplus_id = "wg__" + wt.id_lowcase.toLowerCase() + "__" + var + "__surplus"; + + // add slack + Misc.createDvarInModelObj(slack_id, Param.upper_unbounded, Param.zero, "weightgroup_slack", "na", wt.fromWresl, mObj); + mObj.dvList_deviationSlackSurplus.add(slack_id.toLowerCase()); + mObj.deviationSlackSurplus_toleranceMap.put(slack_id.toLowerCase(), deviationTolerance); + + Misc.addWeightInGroupWeightMap(slack_id, wt.fromWresl, weight, mObj); + + // add surplus + Misc.createDvarInModelObj(surplus_id, Param.upper_unbounded, Param.zero, "weightgroup_surplus", "na", wt.fromWresl, mObj); + mObj.dvList_deviationSlackSurplus.add(surplus_id.toLowerCase()); + mObj.deviationSlackSurplus_toleranceMap.put(surplus_id.toLowerCase(), deviationTolerance); + + Misc.addWeightInGroupWeightMap(surplus_id, wt.fromWresl, weight, mObj); + + // add goal for slack surplus + String goal_ss_id = "wg__" + wt.id_lowcase + "__" + var + "__ss"; + String lhs_ss = var + "+" + slack_id + "-" + surplus_id; + String rhs_ss = average_id.toLowerCase(); + + Misc.createGoalInModelObj(goal_ss_id, lhs_ss, "=", rhs_ss, wt.dependants, wt.fromWresl, wt.condition, mObj); + + } + + } + + } + + } + + + + } + + public static void collectWeightVar(StudyTemp s) { + + Set filesProcessed = new HashSet(); + + for (String seq : s.seqList) { + + SequenceTemp seqObj = s.seqMap.get(seq); + + String m = seqObj.model; + + ModelTemp mObj = s.modelMap.get(m); + + + for (String e: s.modelList_effective){ + + if (s.allOffspringMap_incModel.keySet().contains(e)) { + for (String f: s.allOffspringMap_incModel.get(e)) { + + if (!filesProcessed.contains(f)) { + + ModelTemp incModel = s.modelMap.get(f); + collectWeightVar(incModel); + filesProcessed.add(f); + + } + + } + } + + } + + for (String f: mObj.incFileRelativePathList_post){ + + if (!filesProcessed.contains(f)) { + + String mn = s.fileModelNameMap.get(f).get(0); + + ModelTemp incModel = s.fileModelDataTable.get(f, mn); + + collectWeightVar(incModel); + filesProcessed.add(f); + + } + + } + + collectWeightVar(mObj); + + } + + } + + public static void collectWeightVar(ModelTemp mObj){ + + for (WeightTable wt : mObj.wTableObjList) { + + if (!wt.isWeightGroup) { + mObj.wvList_post.addAll(wt.varList); +// for (WeightSubgroup wsg : wt.subgroupMap.values()) { +// mObj.wvList_post.addAll(wsg.varList); +// //seqObj.wvList.addAll(wsg.varList); +// } + + } + } + + } + public static void collectWeightVar(ModelTemp mObj, StudyTemp st) { + + for (String f: mObj.incFileRelativePathList_post){ + + String mn = st.fileModelNameMap.get(f).get(0); + + ModelTemp incModel = st.fileModelDataTable.get(f, mn); + + collectWeightVar(incModel); + + } + + collectWeightVar(mObj); + + + } + + + + + + +} diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ToLowerCase.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ToLowerCase.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ToLowerCase.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ToLowerCase.java index d56bc4496..de8578c9a 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ToLowerCase.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ToLowerCase.java @@ -1,536 +1,536 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import wrimsv2.wreslplus.elements.AliasTemp; -import wrimsv2.wreslplus.elements.DvarTemp; -import wrimsv2.wreslplus.elements.ExternalTemp; -import wrimsv2.wreslplus.elements.GoalCase; -import wrimsv2.wreslplus.elements.GoalTemp; -import wrimsv2.wreslplus.elements.IfIncItemGroup; -import wrimsv2.wreslplus.elements.IncFileTemp; -import wrimsv2.wreslplus.elements.ModelTemp; -import wrimsv2.wreslplus.elements.ParamTemp; -import wrimsv2.wreslplus.elements.SequenceTemp; -import wrimsv2.wreslplus.elements.StudyTemp; -import wrimsv2.wreslplus.elements.SvarTemp; -import wrimsv2.wreslplus.elements.TimeseriesTemp; -import wrimsv2.wreslplus.elements.Tools; -import wrimsv2.wreslplus.elements.WeightTable; -import wrimsv2.wreslplus.elements.WeightTemp; - -public class ToLowerCase { - - - private ToLowerCase(){} - - - //TODO: model must be in sequence obj, also condition not linked yet - public static void convert (StudyTemp s){ - - // study - for (String key : s.parameterList) { - - SvarTemp o = svar(s.parameterMap.get(key)); - s.parameterMap.remove(key); - s.parameterMap.put( key.toLowerCase(), o); - -// ParamTemp pt = new ParamTemp(); -// pt.id = s.parameterMap.get(key).id; -// pt.expression = s.parameterMap.get(key).expression.toLowerCase(); -// pt.dependants = Tools.allToLowerCase(s.parameterMap.get(key).dependants); - -// s.parameterMap.remove(key); -// s.parameterMap.put( key.toLowerCase(), o); - } - s.parameterList = Tools.allToLowerCase(s.parameterList); - s.parameterConstList = Tools.allToLowerCase(s.parameterConstList); - - // sequence - for (String key : s.seqList) { - SequenceTemp n = s.seqMap.get(key); - s.seqMap.remove(key); - s.seqMap.put( key.toLowerCase(), sequence(n)); - } - s.seqList = Tools.allToLowerCase(s.seqList); - // model - for (String key : s.modelList) { - ModelTemp n = s.modelMap.get(key); - s.modelMap.remove( key); - convert(n); - s.modelMap.put( key.toLowerCase(), n); - } - s.modelList = Tools.allToLowerCase(s.modelList); - } - - public static SequenceTemp sequence (SequenceTemp w){ - - SequenceTemp o = new SequenceTemp(); - - o.id = w.id; - o.fromWresl = w.fromWresl.toLowerCase(); - o.line = w.line; - o.model = w.model.toLowerCase(); - o.condition = w.condition.toLowerCase(); - o.order = w.order.toLowerCase(); - o.timeStep = w.timeStep; - o.dependants = Tools.allToLowerCase(w.dependants); - o.neededCycleVarMap = Tools.allToLowerCase_string_set(w.neededCycleVarMap); - - return o; - - } - - - public static void convert (ModelTemp j){ - - for (String key : j.svList) { - if (!j.svMap.keySet().contains(key)) continue; - SvarTemp o = svar(j.svMap.get(key)); - j.svMap.remove(key); - j.svMap.put( key.toLowerCase(), o); - } - for (String key : j.dvList) { - if (!j.dvMap.keySet().contains(key)) continue; - DvarTemp o = dvar(j.dvMap.get(key)); - j.dvMap.remove(key); - j.dvMap.put( key.toLowerCase(), o); - } - for (String key : j.tsList) { - if (!j.tsMap.keySet().contains(key)) continue; - TimeseriesTemp o = timeseries(j.tsMap.get(key)); - j.tsMap.remove(key); - j.tsMap.put( key.toLowerCase(), o); - } - for (String key : j.exList) { - if (!j.exMap.keySet().contains(key)) continue; - ExternalTemp o = external(j.exMap.get(key)); - j.exMap.remove(key); - j.exMap.put( key.toLowerCase(), o); - } - for (String key : j.glList) { - if (!j.glMap.keySet().contains(key)) continue; - GoalTemp o = goal(j.glMap.get(key)); - j.glMap.remove(key); - j.glMap.put( key.toLowerCase(), o); - } -// for (String key : j.ssList) { -// DvarTemp o = dvar(j.ssMap.get(key)); -// j.ssMap.remove(key); -// j.ssMap.put( key.toLowerCase(), o); -// } -// for (String key : j.ssList) { -// WeightTemp o = weight(j.ssWeightMap_hasCase.get(key)); -// j.ssWeightMap_hasCase.remove(key); -// j.ssWeightMap_hasCase.put( key.toLowerCase(), o); -// } - for (String key : j.asList) { - if (!j.asMap.keySet().contains(key)) continue; - AliasTemp o = alias(j.asMap.get(key)); - j.asMap.remove(key); - j.asMap.put( key.toLowerCase(), o); - } - for (int i=0; i0) LogUtils.errMsg(" j.wvList.size()>0 "); - - } - - public static SvarTemp svar (SvarTemp s){ - - if (s==null) return null; - - SvarTemp o = new SvarTemp(); - - o.id = s.id; - o.fromWresl = s.fromWresl.toLowerCase(); - o.line = s.line; - o.kind = s.kind.toLowerCase(); - o.units = s.units.toLowerCase(); - o.caseName = Tools.allToLowerCase(s.caseName); - o.dependants = Tools.allToLowerCase(s.dependants); - o.dependants_notAllowed = s.dependants_notAllowed; // not converted to lowercase - o.neededVarInCycleSet = Tools.allToLowerCase(s.neededVarInCycleSet); - o.needVarFromEarlierCycle = s.needVarFromEarlierCycle; - - o.caseCondition = Tools.allToLowerCase(s.caseCondition); - o.caseCondition = Tools.replace_with_space(o.caseCondition); - //o.caseCondition = Tools.replace_seperator(o.caseCondition); - o.caseCondition = Tools.add_space_between_logical(o.caseCondition); - - o.caseExpression = Tools.allToLowerCase(s.caseExpression); - o.caseExpression = Tools.replace_with_space(o.caseExpression); - //o.caseExpression = Tools.replace_seperator(o.caseExpression); - o.caseExpression = Tools.add_space_between_logical(o.caseExpression); - - o.arraySize = s.arraySize.toLowerCase(); - o.timeArraySize = s.timeArraySize.toLowerCase(); - - return o; - - } - - public static TimeseriesTemp timeseries (TimeseriesTemp t){ - - if (t==null) return null; - - TimeseriesTemp o = new TimeseriesTemp(); - - o.id = t.id; - o.fromWresl = t.fromWresl.toLowerCase(); - o.line = t.line; - o.dssBPart = t.dssBPart.toLowerCase(); - o.convertToUnits = t.convertToUnits.toLowerCase(); - o.kind = t.kind.toLowerCase(); - o.units = t.units.toLowerCase(); - - return o; - - } - - public static DvarTemp dvar (DvarTemp d){ - - if (d==null) return null; - - DvarTemp o = new DvarTemp(); - - o.id = d.id; - o.fromWresl = d.fromWresl.toLowerCase(); - o.line = d.line; - o.lowerBound = d.lowerBound.toLowerCase(); - o.upperBound = d.upperBound.toLowerCase(); - o.kind = d.kind.toLowerCase(); - o.units = d.units.toLowerCase(); - o.condition = d.condition.toLowerCase(); - - o.isInteger = d.isInteger; - o.isFromAlias = d.isFromAlias; - - o.arraySize = d.arraySize.toLowerCase(); - o.timeArraySize = d.timeArraySize.toLowerCase(); - - return o; - } - - - public static WeightTemp weight (WeightTemp w){ - - WeightTemp o = new WeightTemp(); - - o.id = w.id; - o.fromWresl = w.fromWresl.toLowerCase(); - o.line = w.line; - o.condition = w.condition.toLowerCase(); - o.weight = w.weight.toLowerCase(); - o.timeArraySize = w.timeArraySize.toLowerCase(); - - return o; - - } - - - public static WeightTable weightTable (WeightTable w){ - - WeightTable o = new WeightTable(); - - o.id_lowcase = w.id_lowcase.toLowerCase(); - o.id_raw = w.id_raw; - o.line = w.line; - o.fromWresl = w.fromWresl.toLowerCase(); - o.line = w.line; - o.condition = w.condition.toLowerCase(); - o.varList = Tools.allToLowerCase(w.varList); - o.varWeightMap = Tools.allToLowerCase_string(w.varWeightMap); - o.varLineMap = Tools.allToLowerCaseString(w.varLineMap); - o.subgroupMap = Tools.allToLowerCase_weightSubgroup(w.subgroupMap); - o.dependants = Tools.allToLowerCase(w.dependants); - o.commonWeight = w.commonWeight.toLowerCase(); - o.deviationPenalty = w.deviationPenalty.toLowerCase(); - o.deviationTolerance = w.deviationTolerance.toLowerCase(); - o.isWeightGroup = w.isWeightGroup; - o.varTimeArraySizeMap = Tools.allToLowerCase_string(w.varTimeArraySizeMap); - - return o; - - } - - - public static ExternalTemp external (ExternalTemp e){ - - ExternalTemp o = new ExternalTemp(); - - o.id = e.id; - o.fromWresl = e.fromWresl.toLowerCase(); - o.line = e.line; - o.fileName = e.fileName.toLowerCase(); - - return o; - - } - - // GoalCase is not converted to lowercase - public static GoalTemp goal (GoalTemp g){ - - if (g==null) return null; - - // TODO: convert fields in class GoalCase to lowercase - - GoalTemp o = new GoalTemp(); - - ArrayList cn = new ArrayList(g.caseMap.keySet()); - for (String key: cn){ - GoalCase gc = goalCase(g.caseMap.get(key)); - //g.caseMap.remove(key); - o.caseMap.put( key.toLowerCase(), gc); - } - - o.id = g.id; - o.fromWresl = g.fromWresl.toLowerCase(); - o.line = g.line; - o.caseName = Tools.allToLowerCase(g.caseName); - o.dependants = Tools.allToLowerCase(g.dependants); - o.neededVarInCycleSet = Tools.allToLowerCase(g.neededVarInCycleSet); - o.needVarFromEarlierCycle = g.needVarFromEarlierCycle; - - o.hasCase = g.hasCase; - o.hasLhs = g.hasLhs; - - if (g.hasLhs) { - - o.lhs = g.lhs.toLowerCase(); - - } else { // simple goal - - o.caseCondition = Tools.allToLowerCase(g.caseCondition); - o.caseCondition = Tools.replace_with_space(o.caseCondition); - //o.caseCondition = Tools.replace_seperator(o.caseCondition); - o.caseCondition = Tools.add_space_between_logical(o.caseCondition); - - o.caseExpression = Tools.allToLowerCase(g.caseExpression); - o.caseExpression = Tools.replace_with_space(o.caseExpression); - //o.caseExpression = Tools.replace_seperator(o.caseExpression); - o.caseExpression = Tools.add_space_between_logical(o.caseExpression); - - } - - o.arraySize = g.arraySize.toLowerCase(); - o.timeArraySize = g.timeArraySize.toLowerCase(); - - return o; - - } - - - public static AliasTemp alias (AliasTemp d){ - - if (d==null) return null; - - AliasTemp o = new AliasTemp(); - - o.id = d.id; - o.fromWresl = d.fromWresl.toLowerCase(); - o.line = d.line; - o.expression = d.expression.toLowerCase(); - o.kind = d.kind.toLowerCase(); - o.units = d.units.toLowerCase(); - o.noSolver = d.noSolver; - o.condition = d.condition.toLowerCase(); - o.dependants = Tools.allToLowerCase(d.dependants); - o.neededVarInCycleSet = Tools.allToLowerCase(d.neededVarInCycleSet); - o.needVarFromEarlierCycle = d.needVarFromEarlierCycle; - o.isMovedToDvar = d.isMovedToDvar; - - o.arraySize = d.arraySize.toLowerCase(); - o.timeArraySize = d.timeArraySize.toLowerCase(); - - return o; - } - - - public static GoalCase goalCase (GoalCase d){ - - GoalCase o = new GoalCase(); - - o.id = d.id; - o.rhs = d.rhs.toLowerCase(); - o.lhs_gt_rhs = d.lhs_gt_rhs.toLowerCase(); - o.lhs_lt_rhs = d.lhs_lt_rhs.toLowerCase(); - o.condition = d.condition.toLowerCase(); - - - return o; - } - - - public static IncFileTemp incFile (IncFileTemp w){ - - if (w==null) return null; - - IncFileTemp o = new IncFileTemp(); - - o.id = w.id; - o.rawPath = w.rawPath.toLowerCase(); - - return o; - - } - - public static IfIncItemGroup ifIncFileGroup (IfIncItemGroup w){ - - if (w==null) return null; - - IfIncItemGroup o = new IfIncItemGroup(); - - o.id = w.id; - o.fromWresl = w.fromWresl.toLowerCase(); - o.line = w.line; - o.dependants = Tools.allToLowerCase(w.dependants); - o.conditionList = Tools.allToLowerCase(w.conditionList); - - o.inc_item_list = Tools.allToLowerCase2(w.inc_item_list); - - for ( Map mi : w.inc_files_map_list){ - - for (String key: mi.keySet()){ - - mi.put(key, incFile(mi.get(key))); - } - } - o.inc_files_map_list = w.inc_files_map_list; - - for ( HashMap mi : w.inc_svar_map_list){ - - Set ks = new HashSet(mi.keySet()); - - for (String key: ks){ - - SvarTemp svObj = svar(mi.get(key)); - mi.remove(key); - mi.put(key.toLowerCase(), svObj); - } - } - o.inc_svar_map_list = w.inc_svar_map_list; - - for ( HashMap mi : w.inc_dvar_map_list){ - - Set ks = new HashSet(mi.keySet()); - - for (String key: ks){ - - DvarTemp dvObj = dvar(mi.get(key)); - mi.remove(key); - mi.put(key.toLowerCase(), dvObj); - } - } - o.inc_dvar_map_list = w.inc_dvar_map_list; - - for ( HashMap mi : w.inc_alias_map_list){ - - Set ks = new HashSet(mi.keySet()); - - for (String key: ks){ - - AliasTemp asObj = alias(mi.get(key)); - mi.remove(key); - mi.put(key.toLowerCase(), asObj); - } - } - o.inc_alias_map_list = w.inc_alias_map_list; - - for ( HashMap mi : w.inc_timeseries_map_list){ - - Set ks = new HashSet(mi.keySet()); - - for (String key: ks){ - - TimeseriesTemp tsObj = timeseries(mi.get(key)); - mi.remove(key); - mi.put(key.toLowerCase(), tsObj); - } - } - o.inc_timeseries_map_list = w.inc_timeseries_map_list; - - for ( HashMap mi : w.inc_goalSimple_map_list){ - - Set ks = new HashSet(mi.keySet()); - - for (String key: ks){ - - GoalTemp glObj = goal(mi.get(key)); - mi.remove(key); - mi.put(key.toLowerCase(), glObj); - } - } - o.inc_goalSimple_map_list = w.inc_goalSimple_map_list; - - for ( HashMap mi : w.inc_goalComplex_map_list){ - - Set ks = new HashSet(mi.keySet()); - - for (String key: ks){ - - GoalTemp glObj = goal(mi.get(key)); - mi.remove(key); - mi.put(key.toLowerCase(), glObj); - } - } - o.inc_goalComplex_map_list = w.inc_goalComplex_map_list; - - for ( HashMap mi : w.inc_weightTable_map_list){ - - Set ks = new HashSet(mi.keySet()); - - for (String key: ks){ - - WeightTable wtObj = weightTable(mi.get(key)); - mi.remove(key); - mi.put(key.toLowerCase(), wtObj); - } - } - o.inc_weightTable_map_list = w.inc_weightTable_map_list; - - - - return o; - } -} - +package wrimsv2.wreslplus.elements.procedures; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import wrimsv2.wreslplus.elements.AliasTemp; +import wrimsv2.wreslplus.elements.DvarTemp; +import wrimsv2.wreslplus.elements.ExternalTemp; +import wrimsv2.wreslplus.elements.GoalCase; +import wrimsv2.wreslplus.elements.GoalTemp; +import wrimsv2.wreslplus.elements.IfIncItemGroup; +import wrimsv2.wreslplus.elements.IncFileTemp; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.ParamTemp; +import wrimsv2.wreslplus.elements.SequenceTemp; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.SvarTemp; +import wrimsv2.wreslplus.elements.TimeseriesTemp; +import wrimsv2.wreslplus.elements.Tools; +import wrimsv2.wreslplus.elements.WeightTable; +import wrimsv2.wreslplus.elements.WeightTemp; + +public class ToLowerCase { + + + private ToLowerCase(){} + + + //TODO: model must be in sequence obj, also condition not linked yet + public static void convert (StudyTemp s){ + + // study + for (String key : s.parameterList) { + + SvarTemp o = svar(s.parameterMap.get(key)); + s.parameterMap.remove(key); + s.parameterMap.put( key.toLowerCase(), o); + +// ParamTemp pt = new ParamTemp(); +// pt.id = s.parameterMap.get(key).id; +// pt.expression = s.parameterMap.get(key).expression.toLowerCase(); +// pt.dependants = Tools.allToLowerCase(s.parameterMap.get(key).dependants); + +// s.parameterMap.remove(key); +// s.parameterMap.put( key.toLowerCase(), o); + } + s.parameterList = Tools.allToLowerCase(s.parameterList); + s.parameterConstList = Tools.allToLowerCase(s.parameterConstList); + + // sequence + for (String key : s.seqList) { + SequenceTemp n = s.seqMap.get(key); + s.seqMap.remove(key); + s.seqMap.put( key.toLowerCase(), sequence(n)); + } + s.seqList = Tools.allToLowerCase(s.seqList); + // model + for (String key : s.modelList) { + ModelTemp n = s.modelMap.get(key); + s.modelMap.remove( key); + convert(n); + s.modelMap.put( key.toLowerCase(), n); + } + s.modelList = Tools.allToLowerCase(s.modelList); + } + + public static SequenceTemp sequence (SequenceTemp w){ + + SequenceTemp o = new SequenceTemp(); + + o.id = w.id; + o.fromWresl = w.fromWresl.toLowerCase(); + o.line = w.line; + o.model = w.model.toLowerCase(); + o.condition = w.condition.toLowerCase(); + o.order = w.order.toLowerCase(); + o.timeStep = w.timeStep; + o.dependants = Tools.allToLowerCase(w.dependants); + o.neededCycleVarMap = Tools.allToLowerCase_string_set(w.neededCycleVarMap); + + return o; + + } + + + public static void convert (ModelTemp j){ + + for (String key : j.svList) { + if (!j.svMap.keySet().contains(key)) continue; + SvarTemp o = svar(j.svMap.get(key)); + j.svMap.remove(key); + j.svMap.put( key.toLowerCase(), o); + } + for (String key : j.dvList) { + if (!j.dvMap.keySet().contains(key)) continue; + DvarTemp o = dvar(j.dvMap.get(key)); + j.dvMap.remove(key); + j.dvMap.put( key.toLowerCase(), o); + } + for (String key : j.tsList) { + if (!j.tsMap.keySet().contains(key)) continue; + TimeseriesTemp o = timeseries(j.tsMap.get(key)); + j.tsMap.remove(key); + j.tsMap.put( key.toLowerCase(), o); + } + for (String key : j.exList) { + if (!j.exMap.keySet().contains(key)) continue; + ExternalTemp o = external(j.exMap.get(key)); + j.exMap.remove(key); + j.exMap.put( key.toLowerCase(), o); + } + for (String key : j.glList) { + if (!j.glMap.keySet().contains(key)) continue; + GoalTemp o = goal(j.glMap.get(key)); + j.glMap.remove(key); + j.glMap.put( key.toLowerCase(), o); + } +// for (String key : j.ssList) { +// DvarTemp o = dvar(j.ssMap.get(key)); +// j.ssMap.remove(key); +// j.ssMap.put( key.toLowerCase(), o); +// } +// for (String key : j.ssList) { +// WeightTemp o = weight(j.ssWeightMap_hasCase.get(key)); +// j.ssWeightMap_hasCase.remove(key); +// j.ssWeightMap_hasCase.put( key.toLowerCase(), o); +// } + for (String key : j.asList) { + if (!j.asMap.keySet().contains(key)) continue; + AliasTemp o = alias(j.asMap.get(key)); + j.asMap.remove(key); + j.asMap.put( key.toLowerCase(), o); + } + for (int i=0; i0) LogUtils.errMsg(" j.wvList.size()>0 "); + + } + + public static SvarTemp svar (SvarTemp s){ + + if (s==null) return null; + + SvarTemp o = new SvarTemp(); + + o.id = s.id; + o.fromWresl = s.fromWresl.toLowerCase(); + o.line = s.line; + o.kind = s.kind.toLowerCase(); + o.units = s.units.toLowerCase(); + o.caseName = Tools.allToLowerCase(s.caseName); + o.dependants = Tools.allToLowerCase(s.dependants); + o.dependants_notAllowed = s.dependants_notAllowed; // not converted to lowercase + o.neededVarInCycleSet = Tools.allToLowerCase(s.neededVarInCycleSet); + o.needVarFromEarlierCycle = s.needVarFromEarlierCycle; + + o.caseCondition = Tools.allToLowerCase(s.caseCondition); + o.caseCondition = Tools.replace_with_space(o.caseCondition); + //o.caseCondition = Tools.replace_seperator(o.caseCondition); + o.caseCondition = Tools.add_space_between_logical(o.caseCondition); + + o.caseExpression = Tools.allToLowerCase(s.caseExpression); + o.caseExpression = Tools.replace_with_space(o.caseExpression); + //o.caseExpression = Tools.replace_seperator(o.caseExpression); + o.caseExpression = Tools.add_space_between_logical(o.caseExpression); + + o.arraySize = s.arraySize.toLowerCase(); + o.timeArraySize = s.timeArraySize.toLowerCase(); + + return o; + + } + + public static TimeseriesTemp timeseries (TimeseriesTemp t){ + + if (t==null) return null; + + TimeseriesTemp o = new TimeseriesTemp(); + + o.id = t.id; + o.fromWresl = t.fromWresl.toLowerCase(); + o.line = t.line; + o.dssBPart = t.dssBPart.toLowerCase(); + o.convertToUnits = t.convertToUnits.toLowerCase(); + o.kind = t.kind.toLowerCase(); + o.units = t.units.toLowerCase(); + + return o; + + } + + public static DvarTemp dvar (DvarTemp d){ + + if (d==null) return null; + + DvarTemp o = new DvarTemp(); + + o.id = d.id; + o.fromWresl = d.fromWresl.toLowerCase(); + o.line = d.line; + o.lowerBound = d.lowerBound.toLowerCase(); + o.upperBound = d.upperBound.toLowerCase(); + o.kind = d.kind.toLowerCase(); + o.units = d.units.toLowerCase(); + o.condition = d.condition.toLowerCase(); + + o.isInteger = d.isInteger; + o.isFromAlias = d.isFromAlias; + + o.arraySize = d.arraySize.toLowerCase(); + o.timeArraySize = d.timeArraySize.toLowerCase(); + + return o; + } + + + public static WeightTemp weight (WeightTemp w){ + + WeightTemp o = new WeightTemp(); + + o.id = w.id; + o.fromWresl = w.fromWresl.toLowerCase(); + o.line = w.line; + o.condition = w.condition.toLowerCase(); + o.weight = w.weight.toLowerCase(); + o.timeArraySize = w.timeArraySize.toLowerCase(); + + return o; + + } + + + public static WeightTable weightTable (WeightTable w){ + + WeightTable o = new WeightTable(); + + o.id_lowcase = w.id_lowcase.toLowerCase(); + o.id_raw = w.id_raw; + o.line = w.line; + o.fromWresl = w.fromWresl.toLowerCase(); + o.line = w.line; + o.condition = w.condition.toLowerCase(); + o.varList = Tools.allToLowerCase(w.varList); + o.varWeightMap = Tools.allToLowerCase_string(w.varWeightMap); + o.varLineMap = Tools.allToLowerCaseString(w.varLineMap); + o.subgroupMap = Tools.allToLowerCase_weightSubgroup(w.subgroupMap); + o.dependants = Tools.allToLowerCase(w.dependants); + o.commonWeight = w.commonWeight.toLowerCase(); + o.deviationPenalty = w.deviationPenalty.toLowerCase(); + o.deviationTolerance = w.deviationTolerance.toLowerCase(); + o.isWeightGroup = w.isWeightGroup; + o.varTimeArraySizeMap = Tools.allToLowerCase_string(w.varTimeArraySizeMap); + + return o; + + } + + + public static ExternalTemp external (ExternalTemp e){ + + ExternalTemp o = new ExternalTemp(); + + o.id = e.id; + o.fromWresl = e.fromWresl.toLowerCase(); + o.line = e.line; + o.fileName = e.fileName.toLowerCase(); + + return o; + + } + + // GoalCase is not converted to lowercase + public static GoalTemp goal (GoalTemp g){ + + if (g==null) return null; + + // TODO: convert fields in class GoalCase to lowercase + + GoalTemp o = new GoalTemp(); + + ArrayList cn = new ArrayList(g.caseMap.keySet()); + for (String key: cn){ + GoalCase gc = goalCase(g.caseMap.get(key)); + //g.caseMap.remove(key); + o.caseMap.put( key.toLowerCase(), gc); + } + + o.id = g.id; + o.fromWresl = g.fromWresl.toLowerCase(); + o.line = g.line; + o.caseName = Tools.allToLowerCase(g.caseName); + o.dependants = Tools.allToLowerCase(g.dependants); + o.neededVarInCycleSet = Tools.allToLowerCase(g.neededVarInCycleSet); + o.needVarFromEarlierCycle = g.needVarFromEarlierCycle; + + o.hasCase = g.hasCase; + o.hasLhs = g.hasLhs; + + if (g.hasLhs) { + + o.lhs = g.lhs.toLowerCase(); + + } else { // simple goal + + o.caseCondition = Tools.allToLowerCase(g.caseCondition); + o.caseCondition = Tools.replace_with_space(o.caseCondition); + //o.caseCondition = Tools.replace_seperator(o.caseCondition); + o.caseCondition = Tools.add_space_between_logical(o.caseCondition); + + o.caseExpression = Tools.allToLowerCase(g.caseExpression); + o.caseExpression = Tools.replace_with_space(o.caseExpression); + //o.caseExpression = Tools.replace_seperator(o.caseExpression); + o.caseExpression = Tools.add_space_between_logical(o.caseExpression); + + } + + o.arraySize = g.arraySize.toLowerCase(); + o.timeArraySize = g.timeArraySize.toLowerCase(); + + return o; + + } + + + public static AliasTemp alias (AliasTemp d){ + + if (d==null) return null; + + AliasTemp o = new AliasTemp(); + + o.id = d.id; + o.fromWresl = d.fromWresl.toLowerCase(); + o.line = d.line; + o.expression = d.expression.toLowerCase(); + o.kind = d.kind.toLowerCase(); + o.units = d.units.toLowerCase(); + o.noSolver = d.noSolver; + o.condition = d.condition.toLowerCase(); + o.dependants = Tools.allToLowerCase(d.dependants); + o.neededVarInCycleSet = Tools.allToLowerCase(d.neededVarInCycleSet); + o.needVarFromEarlierCycle = d.needVarFromEarlierCycle; + o.isMovedToDvar = d.isMovedToDvar; + + o.arraySize = d.arraySize.toLowerCase(); + o.timeArraySize = d.timeArraySize.toLowerCase(); + + return o; + } + + + public static GoalCase goalCase (GoalCase d){ + + GoalCase o = new GoalCase(); + + o.id = d.id; + o.rhs = d.rhs.toLowerCase(); + o.lhs_gt_rhs = d.lhs_gt_rhs.toLowerCase(); + o.lhs_lt_rhs = d.lhs_lt_rhs.toLowerCase(); + o.condition = d.condition.toLowerCase(); + + + return o; + } + + + public static IncFileTemp incFile (IncFileTemp w){ + + if (w==null) return null; + + IncFileTemp o = new IncFileTemp(); + + o.id = w.id; + o.rawPath = w.rawPath.toLowerCase(); + + return o; + + } + + public static IfIncItemGroup ifIncFileGroup (IfIncItemGroup w){ + + if (w==null) return null; + + IfIncItemGroup o = new IfIncItemGroup(); + + o.id = w.id; + o.fromWresl = w.fromWresl.toLowerCase(); + o.line = w.line; + o.dependants = Tools.allToLowerCase(w.dependants); + o.conditionList = Tools.allToLowerCase(w.conditionList); + + o.inc_item_list = Tools.allToLowerCase2(w.inc_item_list); + + for ( Map mi : w.inc_files_map_list){ + + for (String key: mi.keySet()){ + + mi.put(key, incFile(mi.get(key))); + } + } + o.inc_files_map_list = w.inc_files_map_list; + + for ( HashMap mi : w.inc_svar_map_list){ + + Set ks = new HashSet(mi.keySet()); + + for (String key: ks){ + + SvarTemp svObj = svar(mi.get(key)); + mi.remove(key); + mi.put(key.toLowerCase(), svObj); + } + } + o.inc_svar_map_list = w.inc_svar_map_list; + + for ( HashMap mi : w.inc_dvar_map_list){ + + Set ks = new HashSet(mi.keySet()); + + for (String key: ks){ + + DvarTemp dvObj = dvar(mi.get(key)); + mi.remove(key); + mi.put(key.toLowerCase(), dvObj); + } + } + o.inc_dvar_map_list = w.inc_dvar_map_list; + + for ( HashMap mi : w.inc_alias_map_list){ + + Set ks = new HashSet(mi.keySet()); + + for (String key: ks){ + + AliasTemp asObj = alias(mi.get(key)); + mi.remove(key); + mi.put(key.toLowerCase(), asObj); + } + } + o.inc_alias_map_list = w.inc_alias_map_list; + + for ( HashMap mi : w.inc_timeseries_map_list){ + + Set ks = new HashSet(mi.keySet()); + + for (String key: ks){ + + TimeseriesTemp tsObj = timeseries(mi.get(key)); + mi.remove(key); + mi.put(key.toLowerCase(), tsObj); + } + } + o.inc_timeseries_map_list = w.inc_timeseries_map_list; + + for ( HashMap mi : w.inc_goalSimple_map_list){ + + Set ks = new HashSet(mi.keySet()); + + for (String key: ks){ + + GoalTemp glObj = goal(mi.get(key)); + mi.remove(key); + mi.put(key.toLowerCase(), glObj); + } + } + o.inc_goalSimple_map_list = w.inc_goalSimple_map_list; + + for ( HashMap mi : w.inc_goalComplex_map_list){ + + Set ks = new HashSet(mi.keySet()); + + for (String key: ks){ + + GoalTemp glObj = goal(mi.get(key)); + mi.remove(key); + mi.put(key.toLowerCase(), glObj); + } + } + o.inc_goalComplex_map_list = w.inc_goalComplex_map_list; + + for ( HashMap mi : w.inc_weightTable_map_list){ + + Set ks = new HashSet(mi.keySet()); + + for (String key: ks){ + + WeightTable wtObj = weightTable(mi.get(key)); + mi.remove(key); + mi.put(key.toLowerCase(), wtObj); + } + } + o.inc_weightTable_map_list = w.inc_weightTable_map_list; + + + + return o; + } +} + diff --git a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ToWreslData.java b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ToWreslData.java similarity index 96% rename from wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ToWreslData.java rename to wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ToWreslData.java index 7a26c70f5..fe64b4e5c 100644 --- a/wrims_v2/wrims_v2/src/wrimsv2/wreslplus/elements/procedures/ToWreslData.java +++ b/wrims-core/src/main/java/wrimsv2/wreslplus/elements/procedures/ToWreslData.java @@ -1,852 +1,852 @@ -package wrimsv2.wreslplus.elements.procedures; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; - -import com.google.common.collect.HashBasedTable; - -import wrimsv2.commondata.wresldata.Alias; -import wrimsv2.commondata.wresldata.Dvar; -import wrimsv2.commondata.wresldata.External; -import wrimsv2.commondata.wresldata.Goal; -import wrimsv2.commondata.wresldata.ModelDataSet; -import wrimsv2.commondata.wresldata.Param; -import wrimsv2.commondata.wresldata.StudyDataSet; -import wrimsv2.commondata.wresldata.Svar; -import wrimsv2.commondata.wresldata.Timeseries; -import wrimsv2.commondata.wresldata.WeightElement; -import wrimsv2.components.ControlData; -import wrimsv2.wreslplus.elements.VarCycleIndex; -import wrimsv2.wreslplus.elements.AliasTemp; -import wrimsv2.wreslplus.elements.DvarTemp; -import wrimsv2.wreslplus.elements.ExternalTemp; -import wrimsv2.wreslplus.elements.GoalTemp; -import wrimsv2.wreslplus.elements.ModelTemp; -import wrimsv2.wreslplus.elements.SequenceTemp; -import wrimsv2.wreslplus.elements.StudyTemp; -import wrimsv2.wreslplus.elements.SvarTemp; -import wrimsv2.wreslplus.elements.TimeseriesTemp; -import wrimsv2.wreslplus.elements.Tools; -import wrimsv2.wreslplus.elements.WeightTable; -import wrimsv2.wreslplus.elements.WeightTemp; - -public class ToWreslData { - - // < relative file path, svar name, svar object > - private static HashBasedTable fileSvMap; - private static HashBasedTable fileDvMap; - private static HashBasedTable fileTsMap; - private static HashBasedTable fileAsMap; - private static HashBasedTable fileGlMap; - private static HashBasedTable fileSlackSurplusNoCaseMap; - private static HashBasedTable fileGroupWeightMap; - private static HashBasedTable fileSsWeightMap_noCase; - private static HashBasedTable fileWeightMap; - private static HashBasedTable> fileWTableObjMap; - private static HashBasedTable> mainfileModelWTableObjMap; - - private static HashBasedTable StringIntegerSvarMap; - - private ToWreslData(){} - - private static void initialize() { - fileSvMap = HashBasedTable.create(); - fileDvMap = HashBasedTable.create(); - fileTsMap = HashBasedTable.create(); - fileAsMap = HashBasedTable.create(); - fileGlMap = HashBasedTable.create(); - fileSlackSurplusNoCaseMap = HashBasedTable.create(); - fileGroupWeightMap = HashBasedTable.create(); - fileSsWeightMap_noCase = HashBasedTable.create(); - fileWeightMap = HashBasedTable.create(); - fileWTableObjMap = HashBasedTable.create(); - mainfileModelWTableObjMap = HashBasedTable.create(); - StringIntegerSvarMap = HashBasedTable.create(); - } - - //TODO: model must be in sequence obj, also condition not linked yet - //TODO: remember to lowercase all evaluation strings and var names - public static StudyDataSet convertStudy (StudyTemp s){ - - if (s==null) return null; - - initialize(); - - StudyDataSet o = new StudyDataSet(); - o.setModelList(s.modelList_effective); - - o.setVarCycleValueMap(s.varCycleValueMap); - o.setTimeseriesTimeStepMap(s.timeseriesTimeStepMap); - o.setModelTimeStepList(s.seqTimeStepList); - - Map modelDataSetMap = new HashMap(); - ArrayList modelConditionList = new ArrayList(); - Map allTimeseriesMap = new LinkedHashMap(); - - o.setParameterList(s.parameterList); - //o.setParameterMap(convertParameterMap(s.parameterMap)); - o.setParameterMap(s.controlDataParameterMap); - - - //for (String k: s.modelList_effective){ - for (String se : s.seqList){ - - SequenceTemp seqObj = s.seqMap.get(se); - - String modelName = seqObj.model; - - ModelTemp mt = s.modelMap.get(modelName); - - modelConditionList.add(seqObj.condition); - ModelDataSet md = convertModel(seqObj, s); - - // insert parameters into svar map - //md.svList.addAll(0, o.getParameterList()); - //md.svMap.putAll(o.getParameterMap()); - - modelDataSetMap.put(modelName, md); - - // add ts into all ts map. TODO: check name duplications - allTimeseriesMap.putAll(md.tsMap); - } - - o.setModelDataSetMap(modelDataSetMap); - o.setModelConditionList(modelConditionList); - o.setTimeseriesMap(allTimeseriesMap); - o.setVarCycleIndexList(VarCycleIndex.varCycleIndexList); - - return o; - - } - - private static LinkedHashMap convertParameterMap( - Map simpleMap) { - - LinkedHashMap pm = new LinkedHashMap(); - - for (String key: simpleMap.keySet()){ - - Svar svObj = new Svar(); - - svObj.caseName.add(Param.defaultCaseName); - svObj.caseCondition.add(Param.always); - svObj.caseExpression.add(simpleMap.get(key)); - - pm.put(key, svObj); - - } - - return pm; - } - - - public static ModelDataSet convertModel (SequenceTemp seq, StudyTemp st){ - - ModelDataSet o = new ModelDataSet(); - - o.varUsedByLaterCycle = seq.varUsedByLaterCycle; - o.dvarUsedByLaterCycle = seq.dvarUsedByLaterCycle; - o.svarUsedByLaterCycle = seq.svarUsedByLaterCycle; - o.aliasUsedByLaterCycle = seq.aliasUsedByLaterCycle; - - // TODO: give pre-sorted var list - - o.dvSlackSurplusList = new ArrayList(seq.ssList_hasCase); - if (ControlData.isNameSorting) Collections.sort(o.dvSlackSurplusList,String.CASE_INSENSITIVE_ORDER); - - o.wtSlackSurplusList = new ArrayList(seq.ssList_hasCase); - if (ControlData.isNameSorting) Collections.sort(o.wtSlackSurplusList,String.CASE_INSENSITIVE_ORDER); - - o.dvList = new ArrayList(seq.dvIncFileList_post); - o.dvList.addAll(seq.dvList_fromAlias); - o.dvList_deviationSlackSurplus.addAll(seq.dvList_deviationSlackSurplus); - o.deviationSlackSurplus_toleranceMap.putAll(seq.deviationSlackSurplus_toleranceMap); - //o.dvList.addAll(seq.ssList_noCase); - if (ControlData.isNameSorting) Collections.sort(o.dvList,String.CASE_INSENSITIVE_ORDER); - - o.tsList = new ArrayList(seq.tsList); - if (ControlData.isNameSorting) Collections.sort(o.tsList,String.CASE_INSENSITIVE_ORDER); - - // don't sort svList. order matters in evaluator - o.svList = new ArrayList(seq.svIncFileList_post); - //System.out.println("ToWreslData => m.svIncFileList_post"+m.svIncFileList_post); - //System.out.println("ToWreslData => m.svList"+m.svList); - //o.svList = new ArrayList(m.svList); - - o.gList = new ArrayList(seq.glIncFileList_post); - o.gList.addAll(seq.glList_fromAlias); - if (ControlData.isNameSorting) Collections.sort(o.gList,String.CASE_INSENSITIVE_ORDER); - - - // don't sort exList. order matters in evaluator - o.exList = new ArrayList(seq.exIncFileList_post); - //Collections.sort(o.exList,String.CASE_INSENSITIVE_ORDER); - - // don't sort asList. order matters in evaluator - o.asList = new ArrayList(seq.asIncFileList_post); - - o.wtList = new ArrayList(seq.wvList); - o.wtList.addAll(seq.ssList_noCase); - if (ControlData.isNameSorting) Collections.sort(o.wtList,String.CASE_INSENSITIVE_ORDER); - - o.incFileList = new ArrayList(seq.incFileAbsPathList_post); - - -// for (String k: m.incFileMap.keySet()){ -// o.incFileList.add(m.incFileMap.get(k).absPath); -// } - - - - - for (String k: o.dvSlackSurplusList){ - o.dvSlackSurplusMap.put(k, convertDvar(seq.ssMap_hasCase.get(k))); - } - for (String k: o.wtSlackSurplusList){ - o.wtSlackSurplusMap.put(k, convertWeight(seq.ssWeightMap_hasCase.get(k))); - } - - -// for (String k: seq.tsMap.keySet()){ -// o.tsMap.put(k, convertTimeseries(seq.tsMap.get(k))); -// } - processTimeseries(seq, st, o); - - - -// for (String k: seq.glMap.keySet()){ -// o.gMap.put(k, convertGoal(seq.glMap.get(k))); -// } - processGoal(seq, st, o); - - - - for (String k: o.exList){ - o.exMap.put(k, convertExternal(seq.exMap.get(k))); - } - - - processSvar(seq, st, o); - - -// for (String k: o.dvList){ -// o.dvMap.put(k, convertDvar(seq.dvMap.get(k))); -// } - processDvar(seq, st, o); - - - -// for (String k: seq.ssList_noCase){ -// o.dvMap.put(k, convertDvar(seq.ssMap_noCase.get(k))); -// } - o.dvList.addAll(seq.ssList_noCase); - processSsList_noCase(seq, st, o); - - - -// for (String k: o.asList){ -// o.asMap.put(k, convertAlias(seq.asMap.get(k))); -// } - processAlias(seq, st, o); - - - - -//// TODO: be careful. this one is special. need to revisit after -//// using Map instead of ArrayList -// for (WeightTable w : seq.wTableObjList){ -// if (w.isWeightGroup){ -// o.wtMap.putAll(convertWeightTableGroup(w)); -// } else { -// o.wtMap.putAll(convertWeightTable(w)); -// } -// } - processWeightTableObjList(seq, st, o); // need to revive this one. - - - - -// for (String k: seq.ssList_noCase){ -// o.wtMap.put(k, convertWeight(seq.ssWeightMap_noCase.get(k))); -// } - processSsWeight_noCase(seq, st, o); - -//// slack and surplus from group weight -// for (String k: seq.groupWeightMap.keySet()){ -// o.wtMap.put(k, convertWeight(seq.groupWeightMap.get(k))); -// } - processGroupWeight(seq, st, o); - - return o; - - } - - - private static void processWeightTableObjList(SequenceTemp seq, StudyTemp st, ModelDataSet out) { - for (String f: seq.incFileRelativePathList_post){ - - for (WeightTable w: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).wTableObjList) { - - String objGroupName = w.id_lowcase; - - - //TODO: rewrite this based on f check. no need to check each obj group. - if (fileWeightMap.contains(f, objGroupName)){ - - out.wtMap.putAll(fileWTableObjMap.get(f, objGroupName)); - - } else { - - Map v = null; - - if (w.isWeightGroup) { - v= convertWeightTableGroup(w); - } else { - v= convertWeightTable(w); - } - - fileWTableObjMap.put(f, objGroupName,(HashMap)v); - - out.wtMap.putAll(v); - - } - - } - } - - ArrayList allUsedModels = new ArrayList(); - allUsedModels.add(seq.model); - if (st.allOffspringMap_incModel.keySet().contains(seq.model)) allUsedModels.addAll(st.allOffspringMap_incModel.get(seq.model)); - - - for (String e: allUsedModels){ - - - - ModelTemp incModel = st.modelMap.get(e); - - for (WeightTable w: incModel.wTableObjList) { - - String objGroupName = w.id_lowcase; - - if (mainfileModelWTableObjMap.contains(e, objGroupName)){ - - out.wtMap.putAll(mainfileModelWTableObjMap.get(e, objGroupName)); - - } else { - - Map v = null; - - if (w.isWeightGroup) { - v= convertWeightTableGroup(w); - } else { - v= convertWeightTable(w); - } - - mainfileModelWTableObjMap.put(e, objGroupName,(HashMap)v); - - out.wtMap.putAll(v); - - } - - } - - - - } -// -// for (WeightTable w: seq.wTableObjList){ -// -// if (! fileWTableObjMap.columnKeySet().contains(w.id.toLowerCase())) { -// -// Map v = null; -// -// if (w.isWeightGroup) { -// v= convertWeightTableGroup(w); -// } else { -// v= convertWeightTable(w); -// } -// -// out.wtMap.putAll(v); -// -// } -// } - - } - - private static void processTimeseries(SequenceTemp seq, StudyTemp st, - ModelDataSet out) { - for (String f: seq.incFileRelativePathList_post){ - - for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).tsList) { - - if (fileTsMap.contains(f, k)){ - - out.tsMap.put(k, fileTsMap.get(f, k)); - - } else { - - Timeseries v = convertTimeseries(seq.tsMap.get(k)); - fileTsMap.put(f,k,v); - out.tsMap.put(k, v); - - } - } - } - // TODO: can be improved... - for (String k: seq.tsMap.keySet()){ - if (!out.tsMap.containsKey(k)) { out.tsMap.put(k, convertTimeseries(seq.tsMap.get(k))); - } - } - - } - - - private static void processGoal(SequenceTemp seq, StudyTemp st, - ModelDataSet out) { - for (String f: seq.incFileRelativePathList_post){ - - for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).glList) { - - if (fileGlMap.contains(f, k)){ - - out.gMap.put(k, fileGlMap.get(f, k)); - - } else { - - Goal v = convertGoal(seq.glMap.get(k)); - fileGlMap.put(f,k,v); - out.gMap.put(k, v); - - } - } - } - // TODO: can be improved... - for (String k: seq.glMap.keySet()){ - if (!out.gMap.containsKey(k)) out.gMap.put(k, convertGoal(seq.glMap.get(k))); - } - - } - - - private static void processSvar(SequenceTemp seq, StudyTemp st, - ModelDataSet out) { - for (String f: seq.incFileRelativePathList_post){ - - for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).svList) { - - if (fileSvMap.contains(f, k)){ - - out.svMap.put(k, fileSvMap.get(f, k)); - - } else { - - Svar v = convertSvar(seq.svMap.get(k)); - fileSvMap.put(f,k,v); - out.svMap.put(k, v); - - } - } - } - // TODO: can be improved... - for (String k: out.svList){ - if (!out.svMap.containsKey(k)) out.svMap.put(k, convertSvar(seq.svMap.get(k))); - } - - } - - - private static void processDvar(SequenceTemp seq, StudyTemp st, - ModelDataSet out) { - for (String f: seq.incFileRelativePathList_post){ - - for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).dvList) { - - if (fileDvMap.contains(f, k)){ - - out.dvMap.put(k, fileDvMap.get(f, k)); - - } else { - - Dvar v = convertDvar(seq.dvMap.get(k)); - fileDvMap.put(f,k,v); - out.dvMap.put(k, v); - - } - } - } - // TODO: can be improved... - for (String k: out.dvList){ - if (!out.dvMap.containsKey(k)) out.dvMap.put(k, convertDvar(seq.dvMap.get(k))); - } - - } - - - private static void processSsList_noCase(SequenceTemp seq, StudyTemp st, - ModelDataSet out) { - for (String f: seq.incFileRelativePathList_post){ - - for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).ssList_noCase) { - - if (fileSlackSurplusNoCaseMap.contains(f, k)){ - - out.dvMap.put(k, fileSlackSurplusNoCaseMap.get(f, k)); - - } else { - - Dvar v = convertDvar(seq.ssMap_noCase.get(k)); - fileSlackSurplusNoCaseMap.put(f,k,v); - out.dvMap.put(k, v); - - } - } - } - // TODO: can be improved... - for (String k: seq.ssList_noCase){ - if (!out.dvMap.containsKey(k)) out.dvMap.put(k, convertDvar(seq.ssMap_noCase.get(k))); - } - - } - - private static void processSsWeight_noCase(SequenceTemp seq, StudyTemp st, ModelDataSet out) { - for (String f: seq.incFileRelativePathList_post){ - - for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).ssWeightMap_noCase.keySet()) { - - if (fileSsWeightMap_noCase.contains(f, k)){ - - out.wtMap.put(k, fileSsWeightMap_noCase.get(f, k)); - - } else { - - WeightElement v = convertWeight(seq.ssWeightMap_noCase.get(k)); - fileSsWeightMap_noCase.put(f,k,v); - out.wtMap.put(k, v); - - } - } - } - // TODO: can be improved... - for (String k: seq.ssWeightMap_noCase.keySet()){ - if (!out.wtMap.containsKey(k)) out.wtMap.put(k, convertWeight(seq.ssWeightMap_noCase.get(k))); - } - - - } - - private static void processGroupWeight(SequenceTemp seq, StudyTemp st, ModelDataSet out) { - for (String f: seq.incFileRelativePathList_post){ - - for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).groupWeightMap.keySet()) { - - if (fileGroupWeightMap.contains(f, k)){ - - out.wtMap.put(k, fileGroupWeightMap.get(f, k)); - - } else { - - WeightElement v = convertWeight(seq.groupWeightMap.get(k)); - fileGroupWeightMap.put(f,k,v); - out.wtMap.put(k, v); - - } - } - } - // TODO: can be improved... - for (String k: seq.groupWeightMap.keySet()){ - if (!out.wtMap.containsKey(k)) out.wtMap.put(k, convertWeight(seq.groupWeightMap.get(k))); - } - - - } - - private static void processAlias(SequenceTemp seq, StudyTemp st, ModelDataSet out) { - for (String f: seq.incFileRelativePathList_post){ - - for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).asList) { - - if (fileAsMap.contains(f, k)){ - - out.asMap.put(k, fileAsMap.get(f, k)); - - } else { - - Alias v = convertAlias(seq.asMap.get(k)); - fileAsMap.put(f,k,v); - out.asMap.put(k, v); - - } - } - } - // TODO: can be improved... - for (String k: out.asList){ - if (!out.asMap.containsKey(k)) out.asMap.put(k, convertAlias(seq.asMap.get(k))); - } - - } - - - public static Svar processVar (SvarTemp s){ - - Svar o = new Svar(); - try { - o.fromWresl = s.fromWresl; - o.line = s.line; - } catch (Exception e) { - System.out.println("#### error"); - System.out.println("svarName: "+s.id); - } - o.kind = s.kind; - o.units = s.units; - o.timeArraySize = s.timeArraySize; - o.caseName = s.caseName; - o.dependants = s.dependants; - o.neededVarInCycleSet = s.neededVarInCycleSet; - o.needVarFromEarlierCycle = s.needVarFromEarlierCycle; - //o.dependants.removeAll(Param.reservedSet); - //System.out.println(s.dependants); - - o.caseCondition = s.caseCondition; - //o.caseCondition = Tools.replace_with_space(o.caseCondition); - o.caseCondition = Tools.replace_seperator(o.caseCondition); - //o.caseCondition = Tools.add_space_between_logical(o.caseCondition); - - o.caseExpression = s.caseExpression; - //o.caseExpression = Tools.replace_with_space(o.caseExpression); - o.caseExpression = Tools.replace_seperator(o.caseExpression); - //o.caseExpression = Tools.add_space_between_logical(o.caseExpression); - - //System.out.println(o.caseExpression); - return o; - - } - - public static Svar convertSvar (SvarTemp s){ - - Svar o = new Svar(); - try { - o.fromWresl = s.fromWresl; - o.line = s.line; - } catch (Exception e) { - System.out.println("#### error"); - System.out.println("svarName: "+s.id); - } - o.kind = s.kind; - o.units = s.units; - o.timeArraySize = s.timeArraySize; - o.caseName = s.caseName; - o.dependants = s.dependants; - o.neededVarInCycleSet = s.neededVarInCycleSet; - o.needVarFromEarlierCycle = s.needVarFromEarlierCycle; - //o.dependants.removeAll(Param.reservedSet); - //System.out.println(s.dependants); - - o.caseCondition = s.caseCondition; - //o.caseCondition = Tools.replace_with_space(o.caseCondition); - o.caseCondition = Tools.replace_seperator(o.caseCondition); - //o.caseCondition = Tools.add_space_between_logical(o.caseCondition); - - o.caseExpression = s.caseExpression; - //o.caseExpression = Tools.replace_with_space(o.caseExpression); - o.caseExpression = Tools.replace_seperator(o.caseExpression); - //o.caseExpression = Tools.add_space_between_logical(o.caseExpression); - - //System.out.println(o.caseExpression); - //o.timeArraySize = s.timeArraySize; - - return o; - - } - - public static Timeseries convertTimeseries (TimeseriesTemp t){ - - Timeseries o = new Timeseries(); - - o.fromWresl = t.fromWresl; - o.line = t.line; - o.dssBPart = t.dssBPart; - o.convertToUnits = t.convertToUnits; - o.kind = t.kind; - o.units = t.units; - - return o; - - } - - public static Dvar convertDvar (DvarTemp d){ - - Dvar o = new Dvar(); - - o.fromWresl = d.fromWresl; - o.line = d.line; - o.lowerBound = d.lowerBound; - o.upperBound = d.upperBound; - o.kind = d.kind; - o.units = d.units; - o.condition = d.condition; - if (d.isInteger) o.integer=Param.yes; - - o.timeArraySize = d.timeArraySize; - - return o; - - } - - - public static WeightElement convertWeight (WeightTemp w){ - - WeightElement o = new WeightElement(); - - o.fromWresl = w.fromWresl; - o.line = w.line; - o.condition = w.condition; - o.weight = w.weight; - o.timeArraySize = w.timeArraySize; - - o.weight = Tools.replace_with_space(o.weight); - o.weight = Tools.replace_seperator(o.weight); - - return o; - - } - - - public static Map convertWeightTable (WeightTable w){ - - Map om = new LinkedHashMap(); - - for (String s : w.varList) { - - WeightElement o = new WeightElement(); - - o.fromWresl = w.fromWresl; - o.line = w.varLineMap.get(s); - o.condition = w.condition; - o.weight = w.varWeightMap.get(s); - - if (w.varTimeArraySizeMap.containsKey(s)){ - o.timeArraySize = w.varTimeArraySizeMap.get(s); - }else{ - o.timeArraySize = "0"; - } - - om.put(s,o); - } - - - return om; - - } - - public static Map convertWeightTableGroup (WeightTable w){ - - Map om = new LinkedHashMap(); - - for (String s : w.varList) { - - WeightElement o = new WeightElement(); - - o.fromWresl = w.fromWresl; - o.line = w.line; - o.condition = w.condition; - o.weight = w.commonWeight; - - om.put(s,o); - } - - //System.out.println("ToWreslData: w.subgroupMap.keySet(): "+w.subgroupMap.keySet()); - for (String k : w.subgroupMap.keySet()) { - - for (String s: w.subgroupMap.get(k).varList) { - - System.out.println("ToWreslData: w.subgroupMap.varList: "+w.subgroupMap.get(k).varList); - - WeightElement o = new WeightElement(); - - o.fromWresl = w.fromWresl; - o.line = w.line; - o.condition = w.condition; - o.weight = w.commonWeight; - - om.put(s,o); - } - } - - return om; - - } - - public static External convertExternal (ExternalTemp e){ - - External o = new External(); - - o.fromWresl = e.fromWresl; - o.line = e.line; - o.type = e.fileName; - - return o; - - } - - - public static Goal convertGoal (GoalTemp g){ - - Goal o = new Goal(); - - o.fromWresl = g.fromWresl; - o.line = g.line; - o.caseName = g.caseName; - o.expressionDependants = g.dependants; - o.neededVarInCycleSet = g.neededVarInCycleSet; - o.needVarFromEarlierCycle = g.needVarFromEarlierCycle; - o.expressionDependants.removeAll(Param.reservedSet); - //System.out.println(s.dependants); - - o.caseCondition = g.caseCondition; - //o.caseCondition = Tools.replace_with_space(o.caseCondition); - o.caseCondition = Tools.replace_seperator(o.caseCondition); - //o.caseCondition = Tools.add_space_between_logical(o.caseCondition); - - o.caseExpression = g.caseExpression; - //o.caseExpression = Tools.replace_with_space(o.caseExpression); - o.caseExpression = Tools.replace_seperator(o.caseExpression); - //o.caseExpression = Tools.add_space_between_logical(o.caseExpression); - - o.dvarWeightMapList = g.dvarWeightMapList; - o.dvarSlackSurplusList = g.dvarSlackSurplusList; - //System.out.println(o.caseExpression); - - o.timeArraySize = g.timeArraySize; - return o; - - } - - - public static Alias convertAlias (AliasTemp d){ - - Alias o = new Alias(); - - o.fromWresl = d.fromWresl; - o.line = d.line; - o.expression = Tools.replace_seperator(d.expression); - o.kind = d.kind; - o.units = d.units; - o.noSolver = d.noSolver; - o.condition = d.condition; - o.dependants = d.dependants; - o.neededVarInCycleSet = d.neededVarInCycleSet; - o.needVarFromEarlierCycle = d.needVarFromEarlierCycle; - - o.timeArraySize = d.timeArraySize; - - return o; - - } - -} - +package wrimsv2.wreslplus.elements.procedures; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +import com.google.common.collect.HashBasedTable; + +import wrimsv2.commondata.wresldata.Alias; +import wrimsv2.commondata.wresldata.Dvar; +import wrimsv2.commondata.wresldata.External; +import wrimsv2.commondata.wresldata.Goal; +import wrimsv2.commondata.wresldata.ModelDataSet; +import wrimsv2.commondata.wresldata.Param; +import wrimsv2.commondata.wresldata.StudyDataSet; +import wrimsv2.commondata.wresldata.Svar; +import wrimsv2.commondata.wresldata.Timeseries; +import wrimsv2.commondata.wresldata.WeightElement; +import wrimsv2.components.ControlData; +import wrimsv2.wreslplus.elements.VarCycleIndex; +import wrimsv2.wreslplus.elements.AliasTemp; +import wrimsv2.wreslplus.elements.DvarTemp; +import wrimsv2.wreslplus.elements.ExternalTemp; +import wrimsv2.wreslplus.elements.GoalTemp; +import wrimsv2.wreslplus.elements.ModelTemp; +import wrimsv2.wreslplus.elements.SequenceTemp; +import wrimsv2.wreslplus.elements.StudyTemp; +import wrimsv2.wreslplus.elements.SvarTemp; +import wrimsv2.wreslplus.elements.TimeseriesTemp; +import wrimsv2.wreslplus.elements.Tools; +import wrimsv2.wreslplus.elements.WeightTable; +import wrimsv2.wreslplus.elements.WeightTemp; + +public class ToWreslData { + + // < relative file path, svar name, svar object > + private static HashBasedTable fileSvMap; + private static HashBasedTable fileDvMap; + private static HashBasedTable fileTsMap; + private static HashBasedTable fileAsMap; + private static HashBasedTable fileGlMap; + private static HashBasedTable fileSlackSurplusNoCaseMap; + private static HashBasedTable fileGroupWeightMap; + private static HashBasedTable fileSsWeightMap_noCase; + private static HashBasedTable fileWeightMap; + private static HashBasedTable> fileWTableObjMap; + private static HashBasedTable> mainfileModelWTableObjMap; + + private static HashBasedTable StringIntegerSvarMap; + + private ToWreslData(){} + + private static void initialize() { + fileSvMap = HashBasedTable.create(); + fileDvMap = HashBasedTable.create(); + fileTsMap = HashBasedTable.create(); + fileAsMap = HashBasedTable.create(); + fileGlMap = HashBasedTable.create(); + fileSlackSurplusNoCaseMap = HashBasedTable.create(); + fileGroupWeightMap = HashBasedTable.create(); + fileSsWeightMap_noCase = HashBasedTable.create(); + fileWeightMap = HashBasedTable.create(); + fileWTableObjMap = HashBasedTable.create(); + mainfileModelWTableObjMap = HashBasedTable.create(); + StringIntegerSvarMap = HashBasedTable.create(); + } + + //TODO: model must be in sequence obj, also condition not linked yet + //TODO: remember to lowercase all evaluation strings and var names + public static StudyDataSet convertStudy (StudyTemp s){ + + if (s==null) return null; + + initialize(); + + StudyDataSet o = new StudyDataSet(); + o.setModelList(s.modelList_effective); + + o.setVarCycleValueMap(s.varCycleValueMap); + o.setTimeseriesTimeStepMap(s.timeseriesTimeStepMap); + o.setModelTimeStepList(s.seqTimeStepList); + + Map modelDataSetMap = new HashMap(); + ArrayList modelConditionList = new ArrayList(); + Map allTimeseriesMap = new LinkedHashMap(); + + o.setParameterList(s.parameterList); + //o.setParameterMap(convertParameterMap(s.parameterMap)); + o.setParameterMap(s.controlDataParameterMap); + + + //for (String k: s.modelList_effective){ + for (String se : s.seqList){ + + SequenceTemp seqObj = s.seqMap.get(se); + + String modelName = seqObj.model; + + ModelTemp mt = s.modelMap.get(modelName); + + modelConditionList.add(seqObj.condition); + ModelDataSet md = convertModel(seqObj, s); + + // insert parameters into svar map + //md.svList.addAll(0, o.getParameterList()); + //md.svMap.putAll(o.getParameterMap()); + + modelDataSetMap.put(modelName, md); + + // add ts into all ts map. TODO: check name duplications + allTimeseriesMap.putAll(md.tsMap); + } + + o.setModelDataSetMap(modelDataSetMap); + o.setModelConditionList(modelConditionList); + o.setTimeseriesMap(allTimeseriesMap); + o.setVarCycleIndexList(VarCycleIndex.varCycleIndexList); + + return o; + + } + + private static LinkedHashMap convertParameterMap( + Map simpleMap) { + + LinkedHashMap pm = new LinkedHashMap(); + + for (String key: simpleMap.keySet()){ + + Svar svObj = new Svar(); + + svObj.caseName.add(Param.defaultCaseName); + svObj.caseCondition.add(Param.always); + svObj.caseExpression.add(simpleMap.get(key)); + + pm.put(key, svObj); + + } + + return pm; + } + + + public static ModelDataSet convertModel (SequenceTemp seq, StudyTemp st){ + + ModelDataSet o = new ModelDataSet(); + + o.varUsedByLaterCycle = seq.varUsedByLaterCycle; + o.dvarUsedByLaterCycle = seq.dvarUsedByLaterCycle; + o.svarUsedByLaterCycle = seq.svarUsedByLaterCycle; + o.aliasUsedByLaterCycle = seq.aliasUsedByLaterCycle; + + // TODO: give pre-sorted var list + + o.dvSlackSurplusList = new ArrayList(seq.ssList_hasCase); + if (ControlData.isNameSorting) Collections.sort(o.dvSlackSurplusList,String.CASE_INSENSITIVE_ORDER); + + o.wtSlackSurplusList = new ArrayList(seq.ssList_hasCase); + if (ControlData.isNameSorting) Collections.sort(o.wtSlackSurplusList,String.CASE_INSENSITIVE_ORDER); + + o.dvList = new ArrayList(seq.dvIncFileList_post); + o.dvList.addAll(seq.dvList_fromAlias); + o.dvList_deviationSlackSurplus.addAll(seq.dvList_deviationSlackSurplus); + o.deviationSlackSurplus_toleranceMap.putAll(seq.deviationSlackSurplus_toleranceMap); + //o.dvList.addAll(seq.ssList_noCase); + if (ControlData.isNameSorting) Collections.sort(o.dvList,String.CASE_INSENSITIVE_ORDER); + + o.tsList = new ArrayList(seq.tsList); + if (ControlData.isNameSorting) Collections.sort(o.tsList,String.CASE_INSENSITIVE_ORDER); + + // don't sort svList. order matters in evaluator + o.svList = new ArrayList(seq.svIncFileList_post); + //System.out.println("ToWreslData => m.svIncFileList_post"+m.svIncFileList_post); + //System.out.println("ToWreslData => m.svList"+m.svList); + //o.svList = new ArrayList(m.svList); + + o.gList = new ArrayList(seq.glIncFileList_post); + o.gList.addAll(seq.glList_fromAlias); + if (ControlData.isNameSorting) Collections.sort(o.gList,String.CASE_INSENSITIVE_ORDER); + + + // don't sort exList. order matters in evaluator + o.exList = new ArrayList(seq.exIncFileList_post); + //Collections.sort(o.exList,String.CASE_INSENSITIVE_ORDER); + + // don't sort asList. order matters in evaluator + o.asList = new ArrayList(seq.asIncFileList_post); + + o.wtList = new ArrayList(seq.wvList); + o.wtList.addAll(seq.ssList_noCase); + if (ControlData.isNameSorting) Collections.sort(o.wtList,String.CASE_INSENSITIVE_ORDER); + + o.incFileList = new ArrayList(seq.incFileAbsPathList_post); + + +// for (String k: m.incFileMap.keySet()){ +// o.incFileList.add(m.incFileMap.get(k).absPath); +// } + + + + + for (String k: o.dvSlackSurplusList){ + o.dvSlackSurplusMap.put(k, convertDvar(seq.ssMap_hasCase.get(k))); + } + for (String k: o.wtSlackSurplusList){ + o.wtSlackSurplusMap.put(k, convertWeight(seq.ssWeightMap_hasCase.get(k))); + } + + +// for (String k: seq.tsMap.keySet()){ +// o.tsMap.put(k, convertTimeseries(seq.tsMap.get(k))); +// } + processTimeseries(seq, st, o); + + + +// for (String k: seq.glMap.keySet()){ +// o.gMap.put(k, convertGoal(seq.glMap.get(k))); +// } + processGoal(seq, st, o); + + + + for (String k: o.exList){ + o.exMap.put(k, convertExternal(seq.exMap.get(k))); + } + + + processSvar(seq, st, o); + + +// for (String k: o.dvList){ +// o.dvMap.put(k, convertDvar(seq.dvMap.get(k))); +// } + processDvar(seq, st, o); + + + +// for (String k: seq.ssList_noCase){ +// o.dvMap.put(k, convertDvar(seq.ssMap_noCase.get(k))); +// } + o.dvList.addAll(seq.ssList_noCase); + processSsList_noCase(seq, st, o); + + + +// for (String k: o.asList){ +// o.asMap.put(k, convertAlias(seq.asMap.get(k))); +// } + processAlias(seq, st, o); + + + + +//// TODO: be careful. this one is special. need to revisit after +//// using Map instead of ArrayList +// for (WeightTable w : seq.wTableObjList){ +// if (w.isWeightGroup){ +// o.wtMap.putAll(convertWeightTableGroup(w)); +// } else { +// o.wtMap.putAll(convertWeightTable(w)); +// } +// } + processWeightTableObjList(seq, st, o); // need to revive this one. + + + + +// for (String k: seq.ssList_noCase){ +// o.wtMap.put(k, convertWeight(seq.ssWeightMap_noCase.get(k))); +// } + processSsWeight_noCase(seq, st, o); + +//// slack and surplus from group weight +// for (String k: seq.groupWeightMap.keySet()){ +// o.wtMap.put(k, convertWeight(seq.groupWeightMap.get(k))); +// } + processGroupWeight(seq, st, o); + + return o; + + } + + + private static void processWeightTableObjList(SequenceTemp seq, StudyTemp st, ModelDataSet out) { + for (String f: seq.incFileRelativePathList_post){ + + for (WeightTable w: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).wTableObjList) { + + String objGroupName = w.id_lowcase; + + + //TODO: rewrite this based on f check. no need to check each obj group. + if (fileWeightMap.contains(f, objGroupName)){ + + out.wtMap.putAll(fileWTableObjMap.get(f, objGroupName)); + + } else { + + Map v = null; + + if (w.isWeightGroup) { + v= convertWeightTableGroup(w); + } else { + v= convertWeightTable(w); + } + + fileWTableObjMap.put(f, objGroupName,(HashMap)v); + + out.wtMap.putAll(v); + + } + + } + } + + ArrayList allUsedModels = new ArrayList(); + allUsedModels.add(seq.model); + if (st.allOffspringMap_incModel.keySet().contains(seq.model)) allUsedModels.addAll(st.allOffspringMap_incModel.get(seq.model)); + + + for (String e: allUsedModels){ + + + + ModelTemp incModel = st.modelMap.get(e); + + for (WeightTable w: incModel.wTableObjList) { + + String objGroupName = w.id_lowcase; + + if (mainfileModelWTableObjMap.contains(e, objGroupName)){ + + out.wtMap.putAll(mainfileModelWTableObjMap.get(e, objGroupName)); + + } else { + + Map v = null; + + if (w.isWeightGroup) { + v= convertWeightTableGroup(w); + } else { + v= convertWeightTable(w); + } + + mainfileModelWTableObjMap.put(e, objGroupName,(HashMap)v); + + out.wtMap.putAll(v); + + } + + } + + + + } +// +// for (WeightTable w: seq.wTableObjList){ +// +// if (! fileWTableObjMap.columnKeySet().contains(w.id.toLowerCase())) { +// +// Map v = null; +// +// if (w.isWeightGroup) { +// v= convertWeightTableGroup(w); +// } else { +// v= convertWeightTable(w); +// } +// +// out.wtMap.putAll(v); +// +// } +// } + + } + + private static void processTimeseries(SequenceTemp seq, StudyTemp st, + ModelDataSet out) { + for (String f: seq.incFileRelativePathList_post){ + + for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).tsList) { + + if (fileTsMap.contains(f, k)){ + + out.tsMap.put(k, fileTsMap.get(f, k)); + + } else { + + Timeseries v = convertTimeseries(seq.tsMap.get(k)); + fileTsMap.put(f,k,v); + out.tsMap.put(k, v); + + } + } + } + // TODO: can be improved... + for (String k: seq.tsMap.keySet()){ + if (!out.tsMap.containsKey(k)) { out.tsMap.put(k, convertTimeseries(seq.tsMap.get(k))); + } + } + + } + + + private static void processGoal(SequenceTemp seq, StudyTemp st, + ModelDataSet out) { + for (String f: seq.incFileRelativePathList_post){ + + for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).glList) { + + if (fileGlMap.contains(f, k)){ + + out.gMap.put(k, fileGlMap.get(f, k)); + + } else { + + Goal v = convertGoal(seq.glMap.get(k)); + fileGlMap.put(f,k,v); + out.gMap.put(k, v); + + } + } + } + // TODO: can be improved... + for (String k: seq.glMap.keySet()){ + if (!out.gMap.containsKey(k)) out.gMap.put(k, convertGoal(seq.glMap.get(k))); + } + + } + + + private static void processSvar(SequenceTemp seq, StudyTemp st, + ModelDataSet out) { + for (String f: seq.incFileRelativePathList_post){ + + for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).svList) { + + if (fileSvMap.contains(f, k)){ + + out.svMap.put(k, fileSvMap.get(f, k)); + + } else { + + Svar v = convertSvar(seq.svMap.get(k)); + fileSvMap.put(f,k,v); + out.svMap.put(k, v); + + } + } + } + // TODO: can be improved... + for (String k: out.svList){ + if (!out.svMap.containsKey(k)) out.svMap.put(k, convertSvar(seq.svMap.get(k))); + } + + } + + + private static void processDvar(SequenceTemp seq, StudyTemp st, + ModelDataSet out) { + for (String f: seq.incFileRelativePathList_post){ + + for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).dvList) { + + if (fileDvMap.contains(f, k)){ + + out.dvMap.put(k, fileDvMap.get(f, k)); + + } else { + + Dvar v = convertDvar(seq.dvMap.get(k)); + fileDvMap.put(f,k,v); + out.dvMap.put(k, v); + + } + } + } + // TODO: can be improved... + for (String k: out.dvList){ + if (!out.dvMap.containsKey(k)) out.dvMap.put(k, convertDvar(seq.dvMap.get(k))); + } + + } + + + private static void processSsList_noCase(SequenceTemp seq, StudyTemp st, + ModelDataSet out) { + for (String f: seq.incFileRelativePathList_post){ + + for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).ssList_noCase) { + + if (fileSlackSurplusNoCaseMap.contains(f, k)){ + + out.dvMap.put(k, fileSlackSurplusNoCaseMap.get(f, k)); + + } else { + + Dvar v = convertDvar(seq.ssMap_noCase.get(k)); + fileSlackSurplusNoCaseMap.put(f,k,v); + out.dvMap.put(k, v); + + } + } + } + // TODO: can be improved... + for (String k: seq.ssList_noCase){ + if (!out.dvMap.containsKey(k)) out.dvMap.put(k, convertDvar(seq.ssMap_noCase.get(k))); + } + + } + + private static void processSsWeight_noCase(SequenceTemp seq, StudyTemp st, ModelDataSet out) { + for (String f: seq.incFileRelativePathList_post){ + + for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).ssWeightMap_noCase.keySet()) { + + if (fileSsWeightMap_noCase.contains(f, k)){ + + out.wtMap.put(k, fileSsWeightMap_noCase.get(f, k)); + + } else { + + WeightElement v = convertWeight(seq.ssWeightMap_noCase.get(k)); + fileSsWeightMap_noCase.put(f,k,v); + out.wtMap.put(k, v); + + } + } + } + // TODO: can be improved... + for (String k: seq.ssWeightMap_noCase.keySet()){ + if (!out.wtMap.containsKey(k)) out.wtMap.put(k, convertWeight(seq.ssWeightMap_noCase.get(k))); + } + + + } + + private static void processGroupWeight(SequenceTemp seq, StudyTemp st, ModelDataSet out) { + for (String f: seq.incFileRelativePathList_post){ + + for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).groupWeightMap.keySet()) { + + if (fileGroupWeightMap.contains(f, k)){ + + out.wtMap.put(k, fileGroupWeightMap.get(f, k)); + + } else { + + WeightElement v = convertWeight(seq.groupWeightMap.get(k)); + fileGroupWeightMap.put(f,k,v); + out.wtMap.put(k, v); + + } + } + } + // TODO: can be improved... + for (String k: seq.groupWeightMap.keySet()){ + if (!out.wtMap.containsKey(k)) out.wtMap.put(k, convertWeight(seq.groupWeightMap.get(k))); + } + + + } + + private static void processAlias(SequenceTemp seq, StudyTemp st, ModelDataSet out) { + for (String f: seq.incFileRelativePathList_post){ + + for (String k: st.fileModelDataTable.get(f, st.fileModelNameMap.get(f).get(0)).asList) { + + if (fileAsMap.contains(f, k)){ + + out.asMap.put(k, fileAsMap.get(f, k)); + + } else { + + Alias v = convertAlias(seq.asMap.get(k)); + fileAsMap.put(f,k,v); + out.asMap.put(k, v); + + } + } + } + // TODO: can be improved... + for (String k: out.asList){ + if (!out.asMap.containsKey(k)) out.asMap.put(k, convertAlias(seq.asMap.get(k))); + } + + } + + + public static Svar processVar (SvarTemp s){ + + Svar o = new Svar(); + try { + o.fromWresl = s.fromWresl; + o.line = s.line; + } catch (Exception e) { + System.out.println("#### error"); + System.out.println("svarName: "+s.id); + } + o.kind = s.kind; + o.units = s.units; + o.timeArraySize = s.timeArraySize; + o.caseName = s.caseName; + o.dependants = s.dependants; + o.neededVarInCycleSet = s.neededVarInCycleSet; + o.needVarFromEarlierCycle = s.needVarFromEarlierCycle; + //o.dependants.removeAll(Param.reservedSet); + //System.out.println(s.dependants); + + o.caseCondition = s.caseCondition; + //o.caseCondition = Tools.replace_with_space(o.caseCondition); + o.caseCondition = Tools.replace_seperator(o.caseCondition); + //o.caseCondition = Tools.add_space_between_logical(o.caseCondition); + + o.caseExpression = s.caseExpression; + //o.caseExpression = Tools.replace_with_space(o.caseExpression); + o.caseExpression = Tools.replace_seperator(o.caseExpression); + //o.caseExpression = Tools.add_space_between_logical(o.caseExpression); + + //System.out.println(o.caseExpression); + return o; + + } + + public static Svar convertSvar (SvarTemp s){ + + Svar o = new Svar(); + try { + o.fromWresl = s.fromWresl; + o.line = s.line; + } catch (Exception e) { + System.out.println("#### error"); + System.out.println("svarName: "+s.id); + } + o.kind = s.kind; + o.units = s.units; + o.timeArraySize = s.timeArraySize; + o.caseName = s.caseName; + o.dependants = s.dependants; + o.neededVarInCycleSet = s.neededVarInCycleSet; + o.needVarFromEarlierCycle = s.needVarFromEarlierCycle; + //o.dependants.removeAll(Param.reservedSet); + //System.out.println(s.dependants); + + o.caseCondition = s.caseCondition; + //o.caseCondition = Tools.replace_with_space(o.caseCondition); + o.caseCondition = Tools.replace_seperator(o.caseCondition); + //o.caseCondition = Tools.add_space_between_logical(o.caseCondition); + + o.caseExpression = s.caseExpression; + //o.caseExpression = Tools.replace_with_space(o.caseExpression); + o.caseExpression = Tools.replace_seperator(o.caseExpression); + //o.caseExpression = Tools.add_space_between_logical(o.caseExpression); + + //System.out.println(o.caseExpression); + //o.timeArraySize = s.timeArraySize; + + return o; + + } + + public static Timeseries convertTimeseries (TimeseriesTemp t){ + + Timeseries o = new Timeseries(); + + o.fromWresl = t.fromWresl; + o.line = t.line; + o.dssBPart = t.dssBPart; + o.convertToUnits = t.convertToUnits; + o.kind = t.kind; + o.units = t.units; + + return o; + + } + + public static Dvar convertDvar (DvarTemp d){ + + Dvar o = new Dvar(); + + o.fromWresl = d.fromWresl; + o.line = d.line; + o.lowerBound = d.lowerBound; + o.upperBound = d.upperBound; + o.kind = d.kind; + o.units = d.units; + o.condition = d.condition; + if (d.isInteger) o.integer=Param.yes; + + o.timeArraySize = d.timeArraySize; + + return o; + + } + + + public static WeightElement convertWeight (WeightTemp w){ + + WeightElement o = new WeightElement(); + + o.fromWresl = w.fromWresl; + o.line = w.line; + o.condition = w.condition; + o.weight = w.weight; + o.timeArraySize = w.timeArraySize; + + o.weight = Tools.replace_with_space(o.weight); + o.weight = Tools.replace_seperator(o.weight); + + return o; + + } + + + public static Map convertWeightTable (WeightTable w){ + + Map om = new LinkedHashMap(); + + for (String s : w.varList) { + + WeightElement o = new WeightElement(); + + o.fromWresl = w.fromWresl; + o.line = w.varLineMap.get(s); + o.condition = w.condition; + o.weight = w.varWeightMap.get(s); + + if (w.varTimeArraySizeMap.containsKey(s)){ + o.timeArraySize = w.varTimeArraySizeMap.get(s); + }else{ + o.timeArraySize = "0"; + } + + om.put(s,o); + } + + + return om; + + } + + public static Map convertWeightTableGroup (WeightTable w){ + + Map om = new LinkedHashMap(); + + for (String s : w.varList) { + + WeightElement o = new WeightElement(); + + o.fromWresl = w.fromWresl; + o.line = w.line; + o.condition = w.condition; + o.weight = w.commonWeight; + + om.put(s,o); + } + + //System.out.println("ToWreslData: w.subgroupMap.keySet(): "+w.subgroupMap.keySet()); + for (String k : w.subgroupMap.keySet()) { + + for (String s: w.subgroupMap.get(k).varList) { + + System.out.println("ToWreslData: w.subgroupMap.varList: "+w.subgroupMap.get(k).varList); + + WeightElement o = new WeightElement(); + + o.fromWresl = w.fromWresl; + o.line = w.line; + o.condition = w.condition; + o.weight = w.commonWeight; + + om.put(s,o); + } + } + + return om; + + } + + public static External convertExternal (ExternalTemp e){ + + External o = new External(); + + o.fromWresl = e.fromWresl; + o.line = e.line; + o.type = e.fileName; + + return o; + + } + + + public static Goal convertGoal (GoalTemp g){ + + Goal o = new Goal(); + + o.fromWresl = g.fromWresl; + o.line = g.line; + o.caseName = g.caseName; + o.expressionDependants = g.dependants; + o.neededVarInCycleSet = g.neededVarInCycleSet; + o.needVarFromEarlierCycle = g.needVarFromEarlierCycle; + o.expressionDependants.removeAll(Param.reservedSet); + //System.out.println(s.dependants); + + o.caseCondition = g.caseCondition; + //o.caseCondition = Tools.replace_with_space(o.caseCondition); + o.caseCondition = Tools.replace_seperator(o.caseCondition); + //o.caseCondition = Tools.add_space_between_logical(o.caseCondition); + + o.caseExpression = g.caseExpression; + //o.caseExpression = Tools.replace_with_space(o.caseExpression); + o.caseExpression = Tools.replace_seperator(o.caseExpression); + //o.caseExpression = Tools.add_space_between_logical(o.caseExpression); + + o.dvarWeightMapList = g.dvarWeightMapList; + o.dvarSlackSurplusList = g.dvarSlackSurplusList; + //System.out.println(o.caseExpression); + + o.timeArraySize = g.timeArraySize; + return o; + + } + + + public static Alias convertAlias (AliasTemp d){ + + Alias o = new Alias(); + + o.fromWresl = d.fromWresl; + o.line = d.line; + o.expression = Tools.replace_seperator(d.expression); + o.kind = d.kind; + o.units = d.units; + o.noSolver = d.noSolver; + o.condition = d.condition; + o.dependants = d.dependants; + o.neededVarInCycleSet = d.neededVarInCycleSet; + o.needVarFromEarlierCycle = d.needVarFromEarlierCycle; + + o.timeArraySize = d.timeArraySize; + + return o; + + } + +} + diff --git a/wrims_v2/wrims_v2/src/README.md b/wrims_v2/wrims_v2/src/README.md new file mode 100644 index 000000000..04f118c3a --- /dev/null +++ b/wrims_v2/wrims_v2/src/README.md @@ -0,0 +1,14 @@ +Source files in this folder -- wrims_v2/wrimms_v2/src -- have been moved to wrims-core/src + +- java files (\*.java) were moved to wrims-core/src/main/java/wrimsv2 + - ./main/\*.java to src/main/java/main/\*.java + - ./serial/\*.java to src/main/java/serial/\*.java + - ./wrimsv2/\*/\*.java to src/main/java/wrims/\*/\*.java +- antlr files (\*.g) were moved to wrims-core/src/main/java/wrimsv2 + - where the antlr files were in "grammar" folders, the structure is recreated in src/main/antlr + +Test files will be moved to wrims-core/src/test/java/ as test procedures are updated + +C, C++, and Fortran files will be moved to sub-projects as we move forward. + +Don't lose track of src/wrimsv2/external/create_c_header.bat until we determine that it's not needed. \ No newline at end of file