[
  {
    "path": ".config/deploy-artifacts.sh",
    "content": "#!/bin/bash\n\necho \"Auto-deploying Hipster4j snapshots...\"\necho \"Current branch: $TRAVIS_BRANCH\"\nif [ \"$TRAVIS_PULL_REQUEST\" != \"false\" ]; then\n  echo \"Skipping snapshot deployment for pull request\"\n  exit\nfi\necho \"Running mvn deploy, current directory: `pwd`\"\n# Deploy to Sonatype Nexus OSS\nmvn --settings .config/maven-settings.xml deploy -DskipTests=true\necho \"Deployment script finished.\" \n"
  },
  {
    "path": ".config/maven-settings.xml",
    "content": "<!--\n~ Copyright 2014 Centro de Investigación en Tecnoloxías da Información (CITIUS),\n~ University of Santiago de Compostela (USC) http://citius.usc.es.\n~\n~ Licensed under the Apache License, Version 2.0 (the \"License\");\n~ you may not use this file except in compliance with the License.\n~ You may obtain a copy of the License at\n~\n~ http://www.apache.org/licenses/LICENSE-2.0\n~\n~ Unless required by applicable law or agreed to in writing, software\n~ distributed under the License is distributed on an \"AS IS\" BASIS,\n~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n~ See the License for the specific language governing permissions and\n~ limitations under the License.\n-->\n\n<settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n          xsi:schemaLocation=\"http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd\">\n    <servers>\n        <!-- Sonatype Maven repository for snapshots -->\n        <server>\n            <id>sonatype-nexus-snapshots</id>\n            <username>${env.SONATYPE_SNAPSHOT_USERNAME}</username>\n            <password>${env.SONATYPE_SNAPSHOT_PASSWORD}</password>\n        </server>\n        <server>\n            <id>bintray-hipster4j-maven</id>\n            <username>${env.BINTRAY_USER}</username>\n            <password>${env.BINTRAY_API_KEY}</password>\n        </server>\n    </servers>\n\n    <profiles>\n        <profile>\n            <repositories>\n                <repository>\n                    <snapshots>\n                        <enabled>false</enabled>\n                    </snapshots>\n                    <id>bintray-hipster4j-maven</id>\n                    <name>bintray</name>\n                    <url>http://dl.bintray.com/hipster4j/maven</url>\n                </repository>\n            </repositories>\n            <pluginRepositories>\n                <pluginRepository>\n                    <snapshots>\n                        <enabled>false</enabled>\n                    </snapshots>\n                    <id>bintray-hipster4j-maven</id>\n                    <name>bintray-plugins</name>\n                    <url>http://dl.bintray.com/hipster4j/maven</url>\n                </pluginRepository>\n            </pluginRepositories>\n            <id>bintray</id>\n        </profile>\n    </profiles>\n    <activeProfiles>\n        <activeProfile>bintray</activeProfile>\n    </activeProfiles>\n</settings> \n"
  },
  {
    "path": ".config/publish-javadocs.sh",
    "content": "#!/bin/bash\n\nif [ \"$TRAVIS_PULL_REQUEST\" != \"false\" ]; then\n  echo \"Skipping Javadoc publication for pull request\"\n  exit\nfi\n\nif [ \"$TRAVIS_TAG\" == \"\" ]; then\n  echo \"Current version is not a release, skipping Javadoc publication\"\n  exit\nfi\n\necho \"Auto publishing latest javadocs...\"\necho \"TRAVIS_REPO_SLUG=$TRAVIS_REPO_SLUG - TRAVIS_JDK_VERSION=$TRAVIS_JDK_VERSION - TRAVIS_PULL_REQUEST=$TRAVIS_PULL_REQUEST\"\n\n# Decide the documentation version folder name depending on the branch and the version in the pom.xml\nVERSION=`grep -m 1 \"<hipster.version>\" pom.xml | cut -d \">\" -f 2 | cut -d \"<\" -f 1`\n\n# Validate if the version is correct (example 1.0.0-SNAPSHOT, or 1.0.0-alpha-1)\nVERSION_REGEX='^[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9_]+(-[0-9]+)?)?$'\nif [[ $VERSION =~ $VERSION_REGEX ]]; then\n  echo \"Current version is $VERSION\"\nelse\n  echo \"Version error. Unrecognized version $VERSION\"\n  exit 1\nfi\n\necho \"Deploying Hipster [$VERSION] javadocs to GitHub gh-pages\"\necho \"Current directory is: `pwd`\"\n\necho \"Building javadocs...\"\n# Generate Javadocs in target/apidocs\nmvn javadoc:aggregate\n\n# Clone Hipster4j GitHub gh-pages for Javadocs\ngit clone --quiet --branch=gh-pages https://github.com/hipster4j/hipster-javadocs.git gh-pages > /dev/null\n\n# Overwrite the previous version with the new one\ncp -Rf target/apidocs/* gh-pages/\n\n# Create a new folder with the version number and copy the latest version to it\nmkdir gh-pages/$VERSION\ncp -Rf target/apidocs/* gh-pages/$VERSION/\n\n# Now prepare for uploading the site to gh-pages\ncd gh-pages\n\n# Config git user and credentials\ngit config --global user.email \"travis@travis-ci.org\"\ngit config --global user.name \"travis-ci\"\ngit config credential.helper \"store --file=.git/credentials\"\necho \"https://${GITHUB_TOKEN}:@github.com\" > .git/credentials\n\ngit add -A\ngit commit -a -m \"auto-commit $TRAVIS_BRANCH Hipster4j Javadocs v$VERSION (build $TRAVIS_BUILD_NUMBER)\"\ngit push -q origin gh-pages > /dev/null\necho \"Finished\"\n\n"
  },
  {
    "path": ".github/workflows/maven.yml",
    "content": "# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time\n# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven\n\nname: Java CI with Maven\n\non:\n  push:\n    branches-ignore: 'wip/*'\n  pull_request:\n    branches: '*'\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n\n    steps:\n    - uses: actions/checkout@v2\n    - name: Set up JDK 11\n      uses: actions/setup-java@v2\n      with:\n        java-version: '11'\n        distribution: 'adopt'\n        cache: maven\n    - name: Build with Maven\n      run: mvn -B package --file pom.xml\n"
  },
  {
    "path": ".gitignore",
    "content": "*.class\n\n# Package Files #\n*.jar\n*.war\n*.ear\n*~\n\n.classpath\n.project\n.directory\n.settings/\ntarget/\n\n# Netbeans specific #\nnbproject/private/\nbuild/\nnbbuild/\ndist/\nnbdist/\nnbactions.xml\nnb-configuration.xml\n\n# Idea specific #\n*.iml\n.idea\n\n# Eclipse specific #\n.metadata/\n\n"
  },
  {
    "path": ".gitlab-sync",
    "content": "\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Change Log\n\n## [1.0.1](https://github.com/citiususc/hipster/tree/1.0.1) (2016-05-16)\n[Full Changelog](https://github.com/citiususc/hipster/compare/v1.0.0...v1.0.1)\n\n**Fixed bugs:**\n\n- open queue does not manage repeated elements [\\#170](https://github.com/citiususc/hipster/issues/170)\n\n**Closed issues:**\n\n- Add heuristic to maze example [\\#165](https://github.com/citiususc/hipster/issues/165)\n- Implementation of Annealing localsearch [\\#158](https://github.com/citiususc/hipster/issues/158)\n\n## [v1.0.0](https://github.com/citiususc/hipster/tree/v1.0.0) (2016-02-22)\n[Full Changelog](https://github.com/citiususc/hipster/compare/v1.0.0-rc2...v1.0.0)\n\n**Implemented enhancements:**\n\n- Complete javadoc documentation for hipster.algorithm.problem \\(core\\) [\\#5](https://github.com/citiususc/hipster/issues/5)\n- Complete javadoc documentation for hipster.algorithm.multiobjective \\(core\\) [\\#4](https://github.com/citiususc/hipster/issues/4)\n- Add a depth or path size attribute to nodes [\\#140](https://github.com/citiususc/hipster/issues/140)\n- Replace Stack with ArrayDeque [\\#137](https://github.com/citiususc/hipster/issues/137)\n- Detect negative cycle conditions in BellmanFord [\\#136](https://github.com/citiususc/hipster/issues/136)\n- Update scripts to auto-generate javadocs for snapshot versions [\\#121](https://github.com/citiususc/hipster/issues/121)\n\n**Fixed bugs:**\n\n- When Search Result printed Action list is now in reverse order \\(in v1.0.0.rc2 vs v1.0.0.rc1\\) [\\#141](https://github.com/citiususc/hipster/issues/141)\n- Fix coveralls maven plugin [\\#131](https://github.com/citiususc/hipster/issues/131)\n\n**Closed issues:**\n\n- Update gitignore file to include Eclipse editor files [\\#146](https://github.com/citiususc/hipster/issues/146)\n- When checking if point in bounds, also check lower bounds. [\\#144](https://github.com/citiususc/hipster/issues/144)\n- Integration with codecov.io [\\#152](https://github.com/citiususc/hipster/issues/152)\n- Replace Cobertura with JaCoCo [\\#151](https://github.com/citiususc/hipster/issues/151)\n- Change maven compiler version to 1.6 [\\#150](https://github.com/citiususc/hipster/issues/150)\n- Fix incorrect URL for javadoc publication [\\#149](https://github.com/citiususc/hipster/issues/149)\n- Remove unused citius-nexus-snapshot in maven-settings.xml [\\#148](https://github.com/citiususc/hipster/issues/148)\n- Upgrade config to deploy on bintray [\\#143](https://github.com/citiususc/hipster/issues/143)\n- Show unit time \\(ms\\) in algorithm result toString\\(\\) method [\\#139](https://github.com/citiususc/hipster/issues/139)\n- Detect \"NoSuchElementException\" situations in AbstractIterator [\\#138](https://github.com/citiususc/hipster/issues/138)\n\n**Merged pull requests:**\n\n- Implementation of the Annealing search algorithm [\\#168](https://github.com/citiususc/hipster/pull/168) ([cmoins](https://github.com/cmoins))\n- Semicolon bug [\\#167](https://github.com/citiususc/hipster/pull/167) ([andyg7](https://github.com/andyg7))\n- Contrib/165 [\\#166](https://github.com/citiususc/hipster/pull/166) ([PaulJackson123](https://github.com/PaulJackson123))\n- Implementation of Depth Limited Search \\#157 [\\#164](https://github.com/citiususc/hipster/pull/164) ([gabizekany](https://github.com/gabizekany))\n- Contrib/issue 64 [\\#160](https://github.com/citiususc/hipster/pull/160) ([michaelhaaf](https://github.com/michaelhaaf))\n- Contrib/issue 137 [\\#156](https://github.com/citiususc/hipster/pull/156) ([michaelhaaf](https://github.com/michaelhaaf))\n- fix \\#146 : Update .gitignore to include Eclipse specific files. [\\#147](https://github.com/citiususc/hipster/pull/147) ([gahrae](https://github.com/gahrae))\n- fix \\#144 : Make Maze2D.pointInBounds\\(\\) check lower bounds too. [\\#145](https://github.com/citiususc/hipster/pull/145) ([gahrae](https://github.com/gahrae))\n\n## [v1.0.0-rc2](https://github.com/citiususc/hipster/tree/v1.0.0-rc2) (2015-08-12)\n[Full Changelog](https://github.com/citiususc/hipster/compare/v1.0.0-rc1...v1.0.0-rc2)\n\n**Implemented enhancements:**\n\n- Fix deploy script to deploy only SNAPSHOT versions [\\#111](https://github.com/citiususc/hipster/issues/111)\n- Update travis.yml to use the new container-based CI [\\#135](https://github.com/citiususc/hipster/issues/135)\n- StateTransitionFunction is not lazy [\\#134](https://github.com/citiususc/hipster/issues/134)\n- LazyActionStateTransitionFunction is not lazy [\\#133](https://github.com/citiususc/hipster/issues/133)\n- LazyNodeExpander is not lazy [\\#132](https://github.com/citiususc/hipster/issues/132)\n- Create a branch whitelist in travis.yml [\\#129](https://github.com/citiususc/hipster/issues/129)\n- Refactor the basic \\(non-guava\\) graph implementations and improve unit tests [\\#128](https://github.com/citiususc/hipster/issues/128)\n- Confusing usage of the GraphBuilder [\\#119](https://github.com/citiususc/hipster/issues/119)\n- Remove dependencies with Guava from hipster-core [\\#113](https://github.com/citiususc/hipster/issues/113)\n\n**Fixed bugs:**\n\n- Java \\<1.8 Incompatibility [\\#130](https://github.com/citiususc/hipster/issues/130)\n- BellmanFord iterator search method fails [\\#127](https://github.com/citiususc/hipster/issues/127)\n- NullPointerException using Bellman-Ford algorithm [\\#124](https://github.com/citiususc/hipster/issues/124)\n- RomaniaaProblemOptimalSearchTest does not detect solutions with different length [\\#123](https://github.com/citiususc/hipster/issues/123)\n- AD\\* node expander check isConsistent\\(\\) after node.g and node.v changed [\\#122](https://github.com/citiususc/hipster/issues/122)\n- assert check in BinaryOperation constructor done with `equals\\(\\)` instead of `compare\\(\\)` [\\#120](https://github.com/citiususc/hipster/issues/120)\n- restrictive type in ProblemBuilder\\(...\\)defineProblemWithoutExplicitActions\\(\\).useTransitionFunction\\(\\) [\\#115](https://github.com/citiususc/hipster/issues/115)\n- change visibility of attributes and methods in Algorithm subclasses [\\#114](https://github.com/citiususc/hipster/issues/114)\n- AbstractNode.path\\(\\) in reversed order [\\#72](https://github.com/citiususc/hipster/issues/72)\n- Method search\\(SearchListener\\) from Algorithms does not stop [\\#49](https://github.com/citiususc/hipster/issues/49)\n\n**Closed issues:**\n\n- Create new module \"hipster-extensions\" with classes depending on Guava [\\#125](https://github.com/citiususc/hipster/issues/125)\n- Update `site.url` in parent pom.xml [\\#126](https://github.com/citiususc/hipster/issues/126)\n- hipster.version in branch development should not be the same than last release [\\#118](https://github.com/citiususc/hipster/issues/118)\n- hipster.version defined in root pom.xmi but not used [\\#117](https://github.com/citiususc/hipster/issues/117)\n- Implement common tests for heuristic search algorithms [\\#71](https://github.com/citiususc/hipster/issues/71)\n\n## [v1.0.0-rc1](https://github.com/citiususc/hipster/tree/v1.0.0-rc1) (2014-12-10)\n[Full Changelog](https://github.com/citiususc/hipster/compare/v1.0.0-alpha-1...v1.0.0-rc1)\n\n**Implemented enhancements:**\n\n- Complete package-index descriptions [\\#86](https://github.com/citiususc/hipster/issues/86)\n- Bump doxia version to 1.6 [\\#85](https://github.com/citiususc/hipster/issues/85)\n- Add DFS cycle support [\\#84](https://github.com/citiususc/hipster/issues/84)\n- Add a status bar at the bottom of the ASCII Visualizer [\\#79](https://github.com/citiususc/hipster/issues/79)\n- Add option to disable the ASCII Visualizer realtime printing [\\#76](https://github.com/citiususc/hipster/issues/76)\n- Add support for custom goal test conditions \\[CISTI2014\\] [\\#70](https://github.com/citiususc/hipster/issues/70)\n- Modify action/state function interfaces to use nodes to compute successors [\\#68](https://github.com/citiususc/hipster/issues/68)\n- Search Problems should provide an initial node and the node expander [\\#67](https://github.com/citiususc/hipster/issues/67)\n- Remove redundant algorithm factories [\\#60](https://github.com/citiususc/hipster/issues/60)\n- Make Nodes generic in each algorithm implementation [\\#57](https://github.com/citiususc/hipster/issues/57)\n- Implement abstract definition for graph-based problems [\\#56](https://github.com/citiususc/hipster/issues/56)\n- Create a node transition function [\\#53](https://github.com/citiususc/hipster/issues/53)\n- Clean algorithm factory duplications [\\#50](https://github.com/citiususc/hipster/issues/50)\n- Rename Algorithms class to Hipster [\\#48](https://github.com/citiususc/hipster/issues/48)\n- Cannot access the heuristic from HeuristicNode [\\#45](https://github.com/citiususc/hipster/issues/45)\n- Change factory.node to factory.makeNode [\\#42](https://github.com/citiususc/hipster/issues/42)\n- Reorganize maven modules [\\#39](https://github.com/citiususc/hipster/issues/39)\n- Pretty 8-puzzle string representation [\\#26](https://github.com/citiususc/hipster/issues/26)\n- Complete javadoc documentation for hipster.util.parallel \\(core\\) [\\#14](https://github.com/citiususc/hipster/issues/14)\n- Complete javadoc documentation for hipster.util.maze \\(core\\) [\\#13](https://github.com/citiususc/hipster/issues/13)\n- Complete javadoc documentation for hipster.algorithm.node.impl \\(core\\) [\\#12](https://github.com/citiususc/hipster/issues/12)\n- Complete javadoc documentation for hipster.algorithm.node.adstar \\(core\\) [\\#11](https://github.com/citiususc/hipster/issues/11)\n- Complete javadoc documentation for hipster.algorithm.node \\(core\\) [\\#10](https://github.com/citiususc/hipster/issues/10)\n- Complete javadoc documentation for hipster.algorithm.function.impl [\\#9](https://github.com/citiususc/hipster/issues/9)\n- Complete javadoc documentation for hipster.algorithm.impl \\(core\\) [\\#8](https://github.com/citiususc/hipster/issues/8)\n- Complete javadoc documentation for hipster.function \\(core\\) [\\#7](https://github.com/citiususc/hipster/issues/7)\n- Complete javadoc documentation for hipster.collection [\\#6](https://github.com/citiususc/hipster/issues/6)\n- Complete javadoc documentation for hipster.algorithm.factory \\(core\\) [\\#3](https://github.com/citiususc/hipster/issues/3)\n- Complete javadoc documentation for hipster.algorithm.combinatorial \\(core\\) [\\#2](https://github.com/citiususc/hipster/issues/2)\n- Complete javadoc documentation for hipster.algorithm \\(core\\) [\\#1](https://github.com/citiususc/hipster/issues/1)\n\n**Fixed bugs:**\n\n- Fix google analytics tracking code [\\#90](https://github.com/citiususc/hipster/issues/90)\n- Fix download links in the main web page [\\#89](https://github.com/citiususc/hipster/issues/89)\n- Fix link to milestones in README.md [\\#88](https://github.com/citiususc/hipster/issues/88)\n- Twitter icon is missing in the website [\\#80](https://github.com/citiususc/hipster/issues/80)\n- IDA\\* minFLimit inconsistent updates [\\#74](https://github.com/citiususc/hipster/issues/74)\n- Fix NQueens.java getLineSeparator\\(\\) incompatible with jdk 6 [\\#69](https://github.com/citiususc/hipster/issues/69)\n- Variable num of iters with Dijkstra/A\\*/IDA\\* after refactor [\\#63](https://github.com/citiususc/hipster/issues/63)\n- Bad value of HeuristicNode.getScore\\(\\) when the initial node is instantiated by HeuristicNodeImplFactory [\\#52](https://github.com/citiususc/hipster/issues/52)\n- Fix A\\* cost comparator [\\#43](https://github.com/citiususc/hipster/issues/43)\n- SetCoverIterator fails when there is only one element [\\#35](https://github.com/citiususc/hipster/issues/35)\n\n**Closed issues:**\n\n- Generate maven site with markdown with reflow maven skin [\\#31](https://github.com/citiususc/hipster/issues/31)\n- Update bash scripts for automatic deployment [\\#112](https://github.com/citiususc/hipster/issues/112)\n- collections / adapters package - Javadoc documentation [\\#110](https://github.com/citiususc/hipster/issues/110)\n- util.graph package - Javadoc documentation [\\#109](https://github.com/citiususc/hipster/issues/109)\n- util.examples / util.examples.maze - Javadoc documentation [\\#108](https://github.com/citiususc/hipster/issues/108)\n- thirdparty package - Javadoc documentation [\\#107](https://github.com/citiususc/hipster/issues/107)\n- model.problem package - Javadoc documentation [\\#106](https://github.com/citiususc/hipster/issues/106)\n- model.impl package - Javadoc documentation [\\#105](https://github.com/citiususc/hipster/issues/105)\n- model.function.impl package - Javadoc documentation [\\#104](https://github.com/citiususc/hipster/issues/104)\n- model.function package - Javadoc documentation [\\#103](https://github.com/citiususc/hipster/issues/103)\n- model package - Javadoc documentation [\\#102](https://github.com/citiususc/hipster/issues/102)\n- examples.problem package - Javadoc documentation [\\#101](https://github.com/citiususc/hipster/issues/101)\n- examples package - Javadoc documentation [\\#100](https://github.com/citiususc/hipster/issues/100)\n- localsearch package - Javadoc documentation [\\#99](https://github.com/citiususc/hipster/issues/99)\n- MultiobjectiveLS / Iterator - Javadoc documentation \\(package Algorithm\\) [\\#98](https://github.com/citiususc/hipster/issues/98)\n- IDAStar / Iterator - Javadoc documentation \\(package Algorithm\\) [\\#97](https://github.com/citiususc/hipster/issues/97)\n- Hipster class - Javadoc documentation \\(package Algorithm\\) [\\#96](https://github.com/citiususc/hipster/issues/96)\n- DFS Algorithm - Javadoc documentation \\(package Algorithm\\) [\\#95](https://github.com/citiususc/hipster/issues/95)\n- BFS Algorithm - Javadoc documentation \\(package Algorithm\\) [\\#94](https://github.com/citiususc/hipster/issues/94)\n- BellmanFord / Iterator - Javadoc documentation \\(package Algorithm\\) [\\#93](https://github.com/citiususc/hipster/issues/93)\n- ADStarForward / Iterator - Javadoc documentation \\(package Algorithm\\) [\\#92](https://github.com/citiususc/hipster/issues/92)\n- Fix SearchResult toString method [\\#87](https://github.com/citiususc/hipster/issues/87)\n- Add an example using the ProblemBuilder in README.md [\\#82](https://github.com/citiususc/hipster/issues/82)\n- Create a Swing-based Maze search visualizer [\\#73](https://github.com/citiususc/hipster/issues/73)\n- Adapt AD\\* to the new generic action node model [\\#66](https://github.com/citiususc/hipster/issues/66)\n- Auto deploy javadoc to gh-pages with Maven [\\#61](https://github.com/citiususc/hipster/issues/61)\n- Enforced Hill Climbing [\\#55](https://github.com/citiususc/hipster/issues/55)\n- Create N-queen example [\\#54](https://github.com/citiususc/hipster/issues/54)\n- Publish 1.0.0-rc1 artifacts to the central repository [\\#40](https://github.com/citiususc/hipster/issues/40)\n- IterativeSetCover does not fulfill the iterator contract [\\#38](https://github.com/citiususc/hipster/issues/38)\n- Insert pluginManagement in parent pom [\\#37](https://github.com/citiususc/hipster/issues/37)\n- Move examples to a hipster-examples package [\\#36](https://github.com/citiususc/hipster/issues/36)\n- Implement IDA\\* algorithm [\\#34](https://github.com/citiususc/hipster/issues/34)\n- Customize doclava css for javadoc [\\#30](https://github.com/citiususc/hipster/issues/30)\n- Add test for HashQueue [\\#29](https://github.com/citiususc/hipster/issues/29)\n- Prepare the release of the 0.1.0 version [\\#28](https://github.com/citiususc/hipster/issues/28)\n- Maze search examples with realtime output printing [\\#27](https://github.com/citiususc/hipster/issues/27)\n- Create README.md with markdown [\\#21](https://github.com/citiususc/hipster/issues/21)\n- 8-Puzzle example with different heuristics [\\#16](https://github.com/citiususc/hipster/issues/16)\n- Implementation of the breadth-first-search algorithm [\\#15](https://github.com/citiususc/hipster/issues/15)\n\n## [v1.0.0-alpha-1](https://github.com/citiususc/hipster/tree/v1.0.0-alpha-1) (2014-05-21)\n\n\n\\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to Hipster4j\r\n\r\nFirst of all, thank you so much for being interested in contributing to Hipster4j!. This document will guide you through this process. You can contribute in different ways:\r\n\r\n- Reporting issues\r\n- Fixing bugs or developing new features\r\n- Creating new examples\r\n- Sending a motivating email telling us how do you like the library (or dislike) :)\r\n\r\n## Issues\r\nFeel free to open new issues or participating in the discussion of the existing ones on \r\n[this repository](https://github.com/citiususc/hipster/issues), but before doing so, please make sure that the issue is not duplicated and/or the discussion is related to the topic of the issue.\r\n\r\n## Pull requests\r\nCode contributions are welcome following a process which guarantees the long-term maintainability of the project. \r\nYou can contribute either with bugfixes or new features. Before submitting a new feature, we highly encourage you to first open a new issue describing its motivation and details and discuss it with one of the project mantainers. This will ensure that the feature fits well in the project.\r\n\r\n### Step 1: Open a new issue (if not opened yet)\r\nBefore starting to code, it is desirable to first open an issue describing the bug or the new feature. Please be sure the issue is not duplicated.\r\n\r\n### Step 2: Fork the repository\r\nFork the project https://github.com/citiususc/hipster into your account. Then, check out your copy of the project locally.\r\n```\r\ngit clone git@github.com:username/hipster.git\r\ncd hipster\r\ngit remote add upstream https://github.com/citiususc/hipster.git\r\n```\r\n\r\n### Step 3: Create a new feature branch `contrib/issue-number`\r\nPut your code in a new feature branch. The name of the new branch should start with `contrib/`. This convention will help us to keep track of future changes from pull requests.\r\n```\r\ngit checkout -b contrib/issue-number origin/branch\r\n```\r\nNote that origin/‘branch’ would correspond with any of the current development branches (for example 1.0.X) but never the origin/master branch. For example, suppose that the latest version of the project is v1.0.0 and you want to fix a new bug that you discovered in this version. If the new reported issue has an id, say, #186, then you would create your feature branch in this way:\r\n```\r\ngit checkout -b contrib/issue-186 origin/1.0.X\r\n```\r\n\r\n### Step 4: Committing your changes\r\nFirst of all, make sure that git is configured with your complete name and email address. It is desirable to use the same email of your Github account, this will help to identify the contributions:\r\n```\r\ngit config --global user.name \"Your Name\"\r\ngit config --global user.email \"your@email.com\"\r\n```\r\nWrite a good commit message. It should describe the changes you made and its motivation. Be sure to reference the issue you are working in the commit that finishes your contribution using one the [keywords to close issues in Github](https://help.github.com/articles/closing-issues-via-commit-messages/).\r\nIf your commit message is too long, try to summarize the changes in the header of the message, like this:\r\n```\r\nfix #xx : summarize your commit in one line\r\n\r\nIf needed, explain more in detail the changes introduced in your \r\ncommit and the motivation. You could introduce some background \r\nabout the issue you worked in. \r\n\r\nThis message can contain several paragraphs and be as long as \r\nyou need, but try to do a good indentation: the columns should \r\nbe shorter than 72 characters and with a proper word-wrap. \r\nThe command `git log` will print this complete text in a nice \r\nway if you format it properly.\r\n```\r\nThe header and the body of the commit message must be separated by a line in blank. The header is the message shown when running the command `git shortlog`.\r\n\r\n#### Keep your branch in sync\r\nRemember to keep in sync your version. Use git rebase instead of git merge to bring all the changes from the upstream branch to your feature branch:\r\n\r\n```\r\ngit fetch upstream\r\ngit rebase upstream/branch #where branch would be 1.0.X, 1.1.X etc\r\n```\r\n\r\n#### Test your code\r\nVerify that your changes are actually working by adding the required unit tests. It is desirable to include unit test covering all new features you implement. Also, if you find a bug which is not currently detected by the unit tests you might consider to implement a new one or modify the current implementation. After this, you can verify that everything works fine after your changes with:\r\n\r\n```\r\nmvn clean test\r\n```\r\n\r\n### Step 5: Push your changes\r\n\r\nPush your changes to your forked project with:\r\n```\r\ngit push origin my-feature-branch\r\n```\r\n\r\n### Step 6: Create and submit a pull request\r\nGo to your forked project on GitHub, select your feature branch and click the “Compare, review, create a pull request button”. After that, we will review your pull request in a few days (hopefully!), but if we delay please be patient :). We do our best in our spare time to keep the project updated, but unfortunately there may be some periods of time in which we simply can’t work in the project.\r\n\r\n\r\n\r\n### License Agreement\r\nBy contributing your code, you agree to license your contribution under the terms of the [Apache 2.0 license](https://raw.githubusercontent.com/citiususc/hipster/4ca93e681ad7335acbd0bea9e49fe678d56f3519/LICENSE).\r\n\r\nAlso, remember to add this header to each new file that you’ve created:\r\n\r\n```\r\n/*\r\n* Copyright 2015 Centro de Investigación en Tecnoloxías da Información (CITIUS), \r\n* University of Santiago de Compostela (USC).\r\n*\r\n* Licensed under the Apache License, Version 2.0 (the \"License\");\r\n* you may not use this file except in compliance with the License.\r\n* You may obtain a copy of the License at\r\n*\r\n* http://www.apache.org/licenses/LICENSE-2.0\r\n*\r\n* Unless required by applicable law or agreed to in writing, software\r\n* distributed under the License is distributed on an \"AS IS\" BASIS,\r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n* See the License for the specific language governing permissions and\r\n* limitations under the License.\r\n*/\r\n```\r\n\r\nThat’s all!\r\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n \n"
  },
  {
    "path": "README.md",
    "content": "![Hipster](src/main/doclava/custom/assets/hipster-template/assets/images/header-logo.png?raw=true)\n\n![CI](https://github.com/citiususc/hipster/actions/workflows/maven.yml/badge.svg)\n[![](https://jitpack.io/v/citiususc/hipster.svg)](https://jitpack.io/#citiususc/hipster)\n\nA powerful and friendly heuristic search library implemented in Java.\n\n## What's Hipster4j?\n\nThe aim of Hipster4j is to provide an easy to use yet powerful and flexible type-safe Java library for heuristic search. \nHipster relies on a flexible model with generic operators that allow you to reuse and change the behavior of the algorithms very easily. Algorithms are also implemented in an iterative way, avoiding recursion. This has many benefits: full control over the search, access to the internals at runtime or a better and clear scale-out for large search spaces using the heap memory.\n\nYou can use Hipster4j to solve from simple graph search problems to more advanced state-space search problems where the state space is complex and weights are not just double values but custom defined costs.\n\n## Features\n\nThe current version of the library comes with some very well-known and wide used search algorithms. We're working to add more algorithms soon:\n\n* Search algorithms:\n    * Uninformed search:\n        * DFS: Depth-First-Search.\n        * BFS: Breadth-First-Search.\n        * Dijkstra's algorithm.\n        * Bellman-Ford.\n    * Informed search:\n        * A star (A*).\n        * IDA star (IDA*), Iterative Deepening A*.\n        * AD star (AD*): Anytime Dynamic A*.\n    * Local search:\n        * Hill-Climbing.\n        * Enforced-Hill-Climbing.\n    * Multiobjective search\n        * Multiobjective LS algorithm. Original paper: Martins, E. D. Q. V., & Santos, J. L. E. (1999). *\"The labeling algorithm for the multiobjective shortest path problem\"*. <i>Departamento de Matematica, Universidade de Coimbra, Portugal, Tech. Rep. TR-99/005</i> ([see an example](https://github.com/citiususc/hipster/wiki/Multiobjective-Search-with-Hipster-and-TinkerPop-Blueprints))\n* 3rd party adapters:\n    * [Java Universal/Graph (JUNG)](http://jung.sourceforge.net/) adapter.\n\nIf you don't find the algorithm or the feature you are looking for, please consider contributing to Hipster!. You can open a new issue or better fork this repository and create a pull request with your contribution.\n\n## Getting started\n\nThe easiest way to use Hipster is adding it as a dependency with your favourite dependency manager.\nMaven users can include the library using the following snippet:\n\n#### Snapshots\n\nYou can use the latest (unstable) version of Hipster under development. Just add the following dependency into your pom.xml:\n\n```xml\n<!-- Use sonatype oss public for snapshots -->\n<repositories>\n  <repository>\n    <id>sonatype-oss-public</id>\n    <url>https://oss.sonatype.org/content/groups/public/</url>\n    <snapshots>\n      <enabled>true</enabled>\n    </snapshots>\n  </repository>\n</repositories>\n\n<dependencies>\n  <!-- \n    Add this dependency under your pom.xml <dependencies> section to add\n    all the dependencies of Hipster to your project. Add hipster-core\n    instead of hipster-all for basic functionality.\n  -->\n  <dependency>\n    <groupId>es.usc.citius.hipster</groupId>\n    <artifactId>hipster-all</artifactId>\n    <version>1.0.2-SNAPSHOT</version>\n  </dependency>\n</dependencies>\n```\n\n#### Releases\n\nCurrent stable release is v1.0.1. See the [milestones](https://github.com/citiususc/hipster/milestones) to check the current development status.\n\n```xml\n<dependencies>\n  <!--\n    Add this dependency under your pom.xml <dependencies> section to add\n    all the dependencies of Hipster to your project. Add hipster-core\n    instead of hipster-all for core functionality.\n  -->\n  <dependency>\n    <groupId>es.usc.citius.hipster</groupId>\n    <artifactId>hipster-all</artifactId>\n    <version>1.0.1</version>\n  </dependency>\n</dependencies>\n```\n\n#### Quick Example\n\nLet's solve the graph used in [this Wikipedia article](http://en.wikipedia.org/wiki/Shortest_path_problem)\nabout Shortest paths.\n\n![DirectedGraph](http://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Shortest_path_with_direct_weights.svg/512px-Shortest_path_with_direct_weights.svg.png)\n\nAlthough Hipster is graph agnostic, we include some useful classes to create a graph or a\ndirected graph and the search problem. We create a graph using the GraphBuilder class and then\nwe use the GraphSearchProblem to create the required components to solve it using Dijkstra's algorithm:\n\n```java\n// Create a simple weighted directed graph with Hipster where\n// vertices are Strings and edge values are just doubles\nHipsterDirectedGraph<String,Double> graph = \n    GraphBuilder.<String,Double>create()\n     .connect(\"A\").to(\"B\").withEdge(4d)\n     .connect(\"A\").to(\"C\").withEdge(2d)\n     .connect(\"B\").to(\"C\").withEdge(5d)\n     .connect(\"B\").to(\"D\").withEdge(10d)\n     .connect(\"C\").to(\"E\").withEdge(3d)\n     .connect(\"D\").to(\"F\").withEdge(11d)\n     .connect(\"E\").to(\"D\").withEdge(4d)\n     .createDirectedGraph();\n\n// Create the search problem. For graph problems, just use\n// the GraphSearchProblem util class to generate the problem with ease.\nSearchProblem p = GraphSearchProblem\n                           .startingFrom(\"A\")\n                           .in(graph)\n                           .takeCostsFromEdges()\n                           .build();\n                           \n// Search the shortest path from \"A\" to \"F\"\nSystem.out.println(Hipster.createDijkstra(p).search(\"F\"));\n```\n\nOutput result:\n`Total solutions: 1\nTotal time: 6 ms\nTotal number of iterations: 6\n+ Solution 1: \n - States: \n\t[A, C, E, D, F]\n - Actions: \n\t[2.0, 3.0, 4.0, 11.0]\n - Search information: \n\tWeightedNode{state=F, cost=20.0, estimation=0.0, score=20.0}`\n\nBut that's not all. Hipster comes with different problem examples\nthat illustrate how Hipster can be used to solve a [wide variety of problems](https://github.com/citiususc/hipster/tree/0c0ec9cb5087fede9930a6efbd5126afd69896ac/hipster-examples/src/main/java/es/usc/citius/hipster/examples) (not only graph search).\n\n## What's next?\n\nIf you want to learn how to solve a problem by searching with Hipster, check the [wiki](https://github.com/citiususc/hipster/wiki) and the [JavaDoc documentation](http://www.hipster4j.org/hipster-javadocs).\nWe also suggest you to check [this presentation](https://speakerdeck.com/pablormier/hipster-an-open-source-java-library-for-heuristic-search) for a quick introduction.\n\n## License & Citation\n\nThis software is licensed under the Apache 2 license, quoted below.\n\n    Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS),\n    University of Santiago de Compostela (USC).\n\n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n    \n    \n\n### Citation\n\nThis library was presented in the \"9th Iberian Conference on Information Systems and Technologies (CISTI), 2014\". If you use this library in your research projects, we encourage you to please cite our work: \n\n> Rodriguez-Mier, P., Gonzalez-Sieira, A., Mucientes, M., Lama, M. & Bugarin, A. (2014). **Hipster: An Open Source Java Library for Heuristic Search**. _9th Iberian Conference on Information Systems and Technologies (CISTI)_.\n\n```\n@inproceedings{RodriguezMier2014,\n  author = {Rodriguez-Mier, Pablo and Gonzalez-Sieira, Adrian and Mucientes, Manuel and and Lama, Manuel and Bugarin, Alberto},\n  booktitle = {9th Iberian Conference on Information Systems and Technologies (CISTI 2014)},\n  month = jun,\n  volume = 1,\n  title = {{Hipster: An Open Source Java Library for Heuristic Search}},\n  pages = {481--486},\n  isbn = \"978-989-98434-2-4\"\n  address = \"Barcelona\",\n  year = {2014}\n}\n```\n"
  },
  {
    "path": "hipster-all/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n  ~ Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n  ~\n  ~    Licensed under the Apache License, Version 2.0 (the \"License\");\n  ~    you may not use this file except in compliance with the License.\n  ~    You may obtain a copy of the License at\n  ~\n  ~        http://www.apache.org/licenses/LICENSE-2.0\n  ~\n  ~    Unless required by applicable law or agreed to in writing, software\n  ~    distributed under the License is distributed on an \"AS IS\" BASIS,\n  ~    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  ~    See the License for the specific language governing permissions and\n  ~    limitations under the License.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <parent>\n        <groupId>es.usc.citius.hipster</groupId>\n        <artifactId>hipster-pom</artifactId>\n        <version>1.0.2-SNAPSHOT</version>\n    </parent>\n    <modelVersion>4.0.0</modelVersion>\n    <artifactId>hipster-all</artifactId>\n\n    <properties>\n        <hipster.root.dir>${project.basedir}/..</hipster.root.dir>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>es.usc.citius.hipster</groupId>\n            <artifactId>hipster-core</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>es.usc.citius.hipster</groupId>\n            <artifactId>hipster-examples</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>es.usc.citius.hipster</groupId>\n            <artifactId>hipster-test</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n    </dependencies>\n\n    <build>\n        <plugins>\n            <plugin>\n                <artifactId>maven-assembly-plugin</artifactId>\n                <configuration>\n                    <descriptorRefs>\n                        <descriptorRef>jar-with-dependencies</descriptorRef>\n                    </descriptorRefs>\n                    <finalName>${project.artifactId}-${project.version}-all</finalName>\n                    <appendAssemblyId>false</appendAssemblyId>\n                </configuration>\n                <executions>\n                    <execution>\n                        <id>make-assembly</id>\n                        <phase>package</phase>\n                        <goals>\n                            <goal>single</goal>\n                        </goals>\n                    </execution>\n                </executions>\n            </plugin>\n        </plugins>\n    </build>\n</project>"
  },
  {
    "path": "hipster-all/src/main/java/es/usc/citius/hipster/all/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n *\n */\npackage es.usc.citius.hipster.all;"
  },
  {
    "path": "hipster-core/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <parent>\n        <groupId>es.usc.citius.hipster</groupId>\n        <artifactId>hipster-pom</artifactId>\n        <version>1.0.2-SNAPSHOT</version>\n    </parent>\n    <modelVersion>4.0.0</modelVersion>\n    <artifactId>hipster-core</artifactId>\n\n    <properties>\n        <hipster.root.dir>${project.basedir}/..</hipster.root.dir>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>com.google.guava</groupId>\n            <artifactId>guava</artifactId>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n\n</project>"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/ADStarForward.java",
    "content": "/*\n* Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\npackage es.usc.citius.hipster.algorithm;\n\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.impl.*;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Queue;\n\n/**\n * <p>Iterative implementation of the forward Anytime Dynamic A* (AD*-f) search algorithm.</p>\n *\n * <p>AD* is an anytime, dynamic search algorithm. It is able to obtain suboptimal-bounded solutions,\n * tuning the quality of the solution based on the available search time (this is done by adjusting\n * the heuristic inflation parameter, epsilon). This algorithm is executed\n * iteratively improving the quality of the solution and reusing previous search efforts. The algorithm\n * also takes into account the changes produced over the graph arc costs to incrementally repair\n * the previous solution. AD* provides anytime results and an efficient\n * way to solve dynamic search problems.</p>\n *\n * <p>This is the forward implementation of AD*, the algorithm starts exploring the state space\n * from the beginning state and trying to reach a goal state (or multiple ones).</p>\n *\n * <p><u>Reference</u>:\n * </br>Maxim Likhachev, David Ferguson, Geoffrey Gordon, Anthony (Tony) Stentz, and Sebastian Thrun,\n * <b><a href=\"http://www-cgi.cs.cmu.edu/afs/cs.cmu.edu/Web/People/maxim/files/ad_icaps05.pdf\">\n * \"Anytime Dynamic A*: An Anytime, Replanning Algorithm\"</a></b>\n * <i>Proceedings of the International Conference on Automated Planning and Scheduling (ICAPS), June, 2005.</i></p>\n *\n * @param <A> class defining the action\n * @param <S> class defining the state\n * @param <C> class defining the cost, must implement {@link java.lang.Comparable}\n * @param <N> type of the nodes\n *\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class ADStarForward<A,S,C extends Comparable<C>, N extends es.usc.citius.hipster.model.ADStarNode<A, S, C, N>> extends Algorithm<A, S, N> {\n\n    protected S begin;\n    protected Collection<S> goals;\n    protected ADStarNodeExpander<A, S, C, N> expander;\n\n    /**\n     * Create an instance of the algorithm with a begin, a goal and a component to\n     * expand new nodes from the current one.\n     *\n     * @param begin begin state\n     * @param goal goal state\n     * @param expander component which generates new nodes from the current\n     */\n    public ADStarForward(S begin, S goal, ADStarNodeExpander<A, S, C, N> expander) {\n        this(begin, Collections.singleton(goal), expander);\n    }\n\n    /**\n     * Create an instance of the algorithm with a begin, multiple goals and a component to\n     * expand new nodes from the current one.\n     *\n     * @param begin begin state\n     * @param goals collection of goal states\n     * @param expander component which generates new nodes from the current\n     */\n    public ADStarForward(S begin, Collection<S> goals, ADStarNodeExpander<A, S, C, N> expander) {\n        this.begin = begin;\n        this.goals = goals;\n        this.expander = expander;\n    }\n\n    @Override\n    public Iterator iterator() {\n        return new Iterator();\n    }\n\n    /**\n     * Internal iterator that implements all the logic of the A* search\n     */\n    public class Iterator implements java.util.Iterator<N> {\n        //queues used by the algorithm\n        protected Map<S, N> open;\n        protected Map<S, N> closed;\n        protected Map<S, N> incons;\n        protected Collection<Transition<A, S>> transitionsChanged;\n        protected Queue<N> queue;\n        protected boolean replan;\n        protected final N beginNode;\n        protected final Collection<N> goalNodes;\n\n        protected Iterator() {\n            this.replan = false;\n            //initialize nodes\n            this.beginNode = expander.makeNode(null, new Transition<A, S>(null, begin));\n            //initialize goal node collection\n            this.goalNodes = new ArrayList<N>(goals.size());\n            //iterate over the set of goals\n            for(S current : goals){\n                //create new node for current goal\n                this.goalNodes.add(expander.makeNode(beginNode, new Transition<A, S>(null, current)));\n            }\n            //initialize queues of the algorithm\n            this.open = new HashMap<S, N>();\n            this.closed = new HashMap<S, N>();\n            this.incons = new HashMap<S, N>();\n            this.queue = new PriorityQueue<N>();\n            //initialize list of visited nodes\n            expander.clearVisited();\n            //initialize set of changed transitions\n            this.transitionsChanged = new HashSet<Transition<A, S>>();\n            //mark begin node as visited by the algorithm\n            expander.getVisited().put(beginNode.state(), beginNode);\n            //mark goal nodes as visited\n            for(N current : goalNodes){\n                //mark current current as visited by the algorithm\n                expander.getVisited().put(current.state(), current);\n            }\n            //insert beginning node at OPEN\n            insertOpen(beginNode);\n        }\n\n        /**\n         * Inserts a node in the open queue.\n         *\n         * @param node instance of node to add\n         */\n        protected void insertOpen(N node) {\n            this.open.put(node.state(), node);\n            this.queue.offer(node);\n        }\n\n        /**\n         * Retrieves the most promising node from the open collection, or null if it\n         * is empty.\n         *\n         * @return most promising node\n         */\n        protected N takePromising() {\n            while (!queue.isEmpty()) {\n                N head = queue.peek();\n                if (!open.containsKey(head.state())) {\n                    queue.poll();\n                } else {\n                    return head;\n                }\n            }\n            return null;\n        }\n\n        /**\n         * Updates the membership of the node to the algorithm queues.\n         *\n         * @param node instance of node\n         */\n        protected void updateQueues(N node) {\n            S state = node.state();\n            if (node.getV().compareTo(node.getG()) != 0) {\n                if (!this.closed.containsKey(state)) {\n                    insertOpen(node);\n                } else {\n                    this.incons.put(state, node);\n                }\n            } else {\n                this.open.remove(state);\n                //this.queue.remove(node);\n                this.incons.remove(state);\n            }\n            //remove flag to update queues\n            node.setDoUpdate(false);\n        }\n\n        /**\n         * The iterator will have next() nodes when the stop condition of the algorithm is not reached, or if the\n         * value of Epsilon has changed and a replanning is needed. It may happen that after chaning Epsilon the\n         * solution does not improve, and therefore this method will return false. In that case, Epsilon should be\n         * reduced again until the minimum value of 1 is reached. In that case, the solution will be optimal.\n         *\n         * @see #setEpsilon(double)\n         *\n         * @return true if a replan is pending or the solution has not been found\n         */\n        @Override\n        public boolean hasNext() {\n            N current = takePromising();\n            N minGoal = Collections.min(goalNodes);\n            return replan || this.open.containsKey(minGoal.state()) || minGoal.compareTo(current) >= 0 || minGoal.getV().compareTo(minGoal.getG()) < 0;\n        }\n\n        /**\n         * Removing is not supported.\n         */\n        @Override\n        public void remove() {\n            throw new UnsupportedOperationException();\n        }\n\n        @Override\n        public N next() {\n            //First node in OPEN retrieved, not removed\n            N current = takePromising();\n            S state = current.state();\n            N minGoal = Collections.min(goalNodes);\n            if (minGoal.compareTo(current) >= 0 || minGoal.getV().compareTo(minGoal.getG()) < 0) {\n                //s removed from OPEN\n                open.remove(state);\n                //this.queue.remove(current);\n                //if v(s) > g(s)\n                boolean consistent = current.isConsistent();\n                if (consistent) {\n                    //v(s) = g(s)\n                    current.setV(current.getG());\n                    //closed = closed U current\n                    closed.put(state, current);\n                } else {\n                    //v(s) = Infinity\n                    expander.setMaxV(current);\n                    updateQueues(current);\n                }\n                expander.setNodeConsistent(consistent);\n                //expand successors\n                for (N successorNode : expander.expand(current)) {\n                    if(successorNode.isDoUpdate()){\n                        updateQueues(successorNode);\n                    }\n                }\n            } else {\n                this.replan = false;\n                // for all directed edges (u, v) with changed edge costs\n                for(N nodeTransitionsChanged : expander.expandTransitionsChanged(beginNode, transitionsChanged)){\n                    updateQueues(nodeTransitionsChanged);\n                }\n                //empty the list of transitions\n                transitionsChanged.clear();\n                //move states from INCONS to OPEN\n                open.putAll(incons);\n                //empty INCONS queue\n                incons.clear();\n                //updateQueues the priorities for all s in OPEN according to key(s)\n                queue.clear();\n                for(N node : open.values()){\n                    //key is recalculated according to the new value of Epsilon\n                    expander.updateKey(node);\n                    //insert into the priority queue\n                    queue.offer(node);\n                }\n                //closed = empty\n                closed.clear();\n                current = takePromising();\n            }\n            return current;\n        }\n\n        /**\n         * AD* uses the OPEN queue to order the most promising nodes to be expanded by the\n         * algorithm. This method retrieves the original map (not a copy) that contains\n         * the pairs of <State, Node>\n         *\n         * @return open map with the unexplored nodes and states.\n         */\n        public Map<S, N> getOpen() { return open; }\n\n        /**\n         * Get the internal map used by the algorithm to keep the relations between\n         * explored states and nodes. Modifications to the map can alter the normal\n         * function of the algorithm.\n         *\n         * @return closed map with the explored nodes and states\n         */\n        public Map<S, N> getClosed() { return closed; }\n\n        public Map<S, N> getIncons() { return incons; }\n\n        /**\n         * Retrieves the list of goal nodes for its modification.\n         *\n         * @return list of goals\n         */\n        public Collection<N> getGoalNodes() {\n            return goalNodes;\n        }\n\n        /**\n         * Updates the value of epsilon to improve the cost of the solutions.\n         * The update of Epsilon must be manually done, as this parameter higlhy depends on the heuristic used,\n         * and the search problem. Use only values of epsilon above 1, as the opposite will lead to diminish the\n         * estimate of the heuristic, which is supposed to be optimistic. Values below 1 result in underestimating\n         * the cost to the goal, and therefore in a greater number of expansions to find the same solution than with\n         * epsilon = 1.\n         *\n         * @param epsilon new value of epsilon (sub-optimal bound to obtain anytime solutions)\n         */\n        public void setEpsilon(double epsilon){\n            this.replan = true;\n            expander.setEpsilon(epsilon);\n        }\n\n        /**\n         * Queries the current value of Epsilon (sub-optimal bound for anytime solutions).\n         *\n         * @return current value of Epsilon\n         */\n        public double getEpsilon(){\n            return expander.getEpsilon();\n        }\n\n        /**\n         * Marks transitions to be processed in the next replan event.\n         *\n         * @param transitions\n         */\n        public void addTransitionsChanged(Collection<Transition<A, S>> transitions){\n            this.replan = true;\n            transitionsChanged.addAll(transitions);\n        }\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/AStar.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.algorithm;\n\nimport es.usc.citius.hipster.model.HeuristicNode;\nimport es.usc.citius.hipster.model.function.NodeExpander;\n\nimport java.util.*;\n\n/**\n * <p>\n * Implementation of the A* algorithm. The A* algorithm extends the original\n * Dijkstra's algorithm by including heuristics to improve the search. By default,\n * the implementation uses a {@link java.util.PriorityQueue} for the nodes, which requires\n * {@literal O(log n)} time for insertions. The queue can be changed to use another\n * type of queue, for example a fibonacci heap as a queue, which works with constant amortized\n * time for insertions.\n * </p>\n *\n * <a href=\"http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=4082128\">Original paper</a>:\n * Hart, Peter E., Nils J. Nilsson, and Bertram Raphael. <b>\"A formal basis for the heuristic determination of minimum cost paths.\"</b>. <i>IEEE Transactions on Systems Science and Cybernetics 4.2 (1968): 100-107</i>.\n *\n * @param <A> action type.\n * @param <S> state type.\n * @param <C> comparable cost used to compare states.\n * @param <N> type of the heuristic search node used.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class AStar<A,S,C extends Comparable<C>,N extends HeuristicNode<A,S,C,N>> extends Algorithm<A,S,N> {\n\n    protected final N initialNode;\n    protected final NodeExpander<A,S,N> expander;\n\n    /**\n     * Default constructor for ADStarForward. Requires the initial state, the successor function to generate\n     * the neighbor states of a current one and the factory to instantiate new nodes.\n     *\n     * @param initialNode the initial node (which contains the initial state of the search).\n     * @param expander function to obtain (expand) a node to obtain the successor nodes.\n     */\n    public AStar(N initialNode, NodeExpander<A,S,N> expander) {\n        this.initialNode = initialNode;\n        this.expander = expander;\n    }\n\n    @Override\n    public Iterator iterator() {\n        return new Iterator();\n    }\n\n    /**\n     * Internal iterator that implements all the logic of the A* search\n     */\n    public class Iterator implements java.util.Iterator<N> {\n        protected Map<S, N> open;\n        protected Map<S, N> closed;\n        protected Queue<N> queue;\n\n        protected Iterator() {\n            open = new HashMap<S, N>();\n            closed = new HashMap<S, N>();\n            queue = new PriorityQueue<N>();\n            queue.add(initialNode);\n            open.put(initialNode.state(), initialNode);\n        }\n\n        /**\n         * Returns true if open queue is not empty.\n         */\n        public boolean hasNext() {\n            return !open.values().isEmpty();\n        }\n\n        protected N takePromising() {\n            // Poll until a valid state is found\n            N node = queue.poll();\n            while (!open.containsKey(node.state())) {\n                node = queue.poll();\n            }\n            return node;\n        }\n\n        /**\n         * Calculates the next visited state. Each state contains the information of the partial path\n         * explored. To check if the state is the goal state, just check the corresponding node of\n         * the state with {@code currentNode.transition().to().equals(myGoalState)}\n         *\n         * @return next visited state.\n         */\n        public N next() {\n            // Get and remove the best node in the queue\n            N current = takePromising();\n            S currentState = current.state();\n            // Remove from open as well\n            open.remove(currentState);\n\n            // Analyze the cost of each movement from the current node\n            for(N successorNode : expander.expand(current)){\n                N successorOpen = open.get(successorNode.state());\n                if (successorOpen != null) {\n                    if (successorOpen.getScore().compareTo(successorNode.getScore()) <= 0) {\n                        // Keep analyzing the other movements, discard this movement\n                        continue;\n                    }\n                }\n\n                N successorClose = closed.get(successorNode.state());\n                if (successorClose != null) {\n                    // Check if this path improves the cost of a closed neighbor.\n                    if (successorClose.getScore().compareTo(successorNode.getScore()) <= 0) {\n                        continue;\n                    }\n                }\n\n                // In any other case, add the new successor to the open list to explore later\n                open.put(successorNode.state(), successorNode);\n                queue.add(successorNode);\n            }\n            // Once analyzed, the current node moves to the closed list\n            closed.put(currentState, current);\n            return current;\n        }\n\n        /**\n         * Remove is not supported\n         */\n        public void remove() {\n            throw new UnsupportedOperationException();\n        }\n\n        /**\n         * Get the internal map used by the algorithm to keep the relations between\n         * unexplored states and nodes. The map returned is the original copy. Modifications to\n         * the map can alter the normal function of the algorithm.\n         *\n         * @return open map with the unexplored nodes and states.\n         */\n        public Map<S, N> getOpen() {\n            return open;\n        }\n\n        public void setOpen(Map<S, N> open) {\n            this.open = open;\n        }\n\n        /**\n         * Get the internal map used by the algorithm to keep the relations between\n         * explored states and nodes. Modifications to the map can alter the normal\n         * function of the algorithm.\n         *\n         * @return closed map with the explored nodes and states\n         */\n        public Map<S, N> getClosed() {\n            return closed;\n        }\n\n        /**\n         * Replace the original close map with the provided one. Modifications to the close map\n         * can cause malfunction. Use only for optimization purposes.\n         *\n         * @param closed internal close map.\n         */\n        public void setClosed(Map<S, N> closed) {\n            this.closed = closed;\n        }\n\n        /**\n         * Returns the original queue used by the algorithm to sort the unexplored\n         * nodes. The original queue is a java {@code PriorityQueue}. External modifications\n         * to the queue can cause malfunction. This method can be used for example to check\n         * the size of the queue during the search or to implement low level optimizations.\n         *\n         * @return original copy of the internal queue.\n         */\n        public Queue<N> getQueue() {\n            return queue;\n        }\n\n        /**\n         * Replace the original open map with the provided one. Modifications to the open map\n         * can cause malfunction. Use only for optimization purposes.\n         *\n         * @param queue internal open map.\n         */\n        public void setQueue(Queue<N> queue) {\n            this.queue = queue;\n        }\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/Algorithm.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.algorithm;\n\n\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.util.Predicate;\n\nimport java.util.*;\n\n/**\n * Abstract class implemented by each search algorithm. This class provides basic methods\n * to each algorithm for searching or printing detailed information about the search.\n *\n * @param <A> type of the actions ({@code Void} if actions are not explicit).\n * @param <S> type of the states.\n * @param <N> type of the nodes.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic abstract class Algorithm<A,S,N extends Node<A,S,N>> implements Iterable<N> {\n\n\n    /**\n     * Holds information about the search process.\n     */\n    public final class SearchResult {\n        private int iterations;\n        private Collection<N> goalNodes;\n        private long elapsed;\n\n\n        public SearchResult(N goalNode, int iterations, long elapsed) {\n            this.goalNodes = Collections.singletonList(goalNode);\n            this.iterations = iterations;\n            this.elapsed = elapsed;\n        }\n\n        public SearchResult(Collection<N> goalNodes, int iterations, long elapsed) {\n            this.goalNodes = goalNodes;\n            this.iterations = iterations;\n            this.elapsed = elapsed;\n        }\n\n        /**\n         * @return the elapsed time (in milliseconds) between the begin of the search and the\n         * search result generation.\n         */\n        public long getElapsed() {\n            return elapsed;\n        }\n\n        /**\n         * Number of iterations performed by the search algorithm.\n         * @return number of iterations.\n         */\n        public int getIterations() {\n            return iterations;\n        }\n\n        /**\n         * @return goal node.\n         */\n        public N getGoalNode() {\n            return goalNodes.iterator().next();\n        }\n\n        public Collection<N> getGoalNodes() {\n            return goalNodes;\n        }\n\n        public List<List<S>> getOptimalPaths() {\n            List<List<S>> paths = new ArrayList<List<S>>(goalNodes.size());\n            for(N goalNode : goalNodes){\n                paths.add(recoverStatePath(goalNode));\n            }\n\n            return paths;\n        }\n\n        @Override\n        public String toString() {\n            final String ls = System.getProperty(\"line.separator\");\n            StringBuilder builder = new StringBuilder();\n            builder.append(\"Total solutions: \").append(goalNodes.size()).append(ls);\n            builder.append(\"Total time: \").append(getElapsed()).append(\" ms\").append(ls);\n            builder.append(\"Total number of iterations: \").append(getIterations()).append(ls);\n            // Take solutions\n            int solution=1;\n            for(N goalNode : goalNodes){\n                builder.append(\"+ Solution \").append(solution).append(\": \").append(ls);\n                builder.append(\" - States: \").append(ls);\n                builder.append(\"\\t\").append(recoverStatePath(goalNode).toString()).append(ls);\n                builder.append(\" - Actions: \").append(ls);\n                builder.append(\"\\t\").append(recoverActionPath(goalNode).toString()).append(ls);\n                builder.append(\" - Search information: \").append(ls);\n                builder.append(\"\\t\").append(goalNode.toString()).append(ls);\n                solution++;\n            }\n            return builder.toString();\n        }\n    }\n\n    public interface SearchListener<N> {\n        void handle(N node);\n    }\n\n    /**\n     * Run the algorithm until the goal is found or no more states are\n     * available.\n     * @return SearchResult with the information of the search\n     */\n    public SearchResult search(final S goalState){\n        return search(new Predicate<N>() {\n            @Override\n            public boolean apply(N n) {\n                if (goalState != null) {\n                    return n.state().equals(goalState);\n                }\n                return false;\n            }\n        });\n    }\n\n\n    /**\n     * Executes the search algorithm until the predicate condition is\n     * satisfied or there are no more nodes to explore.\n     *\n     * @param condition predicate with the boolean condition.\n     * @return {@link es.usc.citius.hipster.algorithm.Algorithm.SearchResult with information about the search}\n     */\n    public SearchResult search(Predicate<N> condition){\n        int iteration = 0;\n        Iterator<N> it = iterator();\n        long begin = System.currentTimeMillis();\n        N currentNode = null;\n        while(it.hasNext()){\n            iteration++;\n            currentNode = it.next();\n            if (condition.apply(currentNode)) {\n                break;\n            }\n\n        }\n        long end = System.currentTimeMillis();\n        return new SearchResult(currentNode, iteration, end - begin);\n    }\n\n    /**\n     * <p>\n     * Executes the search algorithm and invokes the method\n     * {@link SearchListener#handle(Object)} passing the current\n     * explored node to the listener.\n     * </p>\n     *\n     * <pre class=\"prettyprint\">\n     *  {@code Hipster.createDijkstra(problem).search(new Algorithm.SearchListener() {\n     *      @Override\n     *          public void handle(Node node) {\n     *              // Do something with the node.\n     *          }\n     *      });\n     *  }\n     * </pre>\n     *\n     * @param listener listener used to receive the explored nodes.\n     */\n    public void search(SearchListener<N> listener){\n        Iterator<N> it = iterator();\n        while(it.hasNext()){\n            listener.handle(it.next());\n        }\n    }\n\n    /**\n     * Returns a path with all the states of the path.\n     *\n     * @param <S> type of the state.\n     * @param <N> type of the node.\n     * @return a list with the states of the path, from the initial state\n     * to the state of the provided node ({@link es.usc.citius.hipster.model.Node#state()}).\n     */\n    public static <S, N extends Node<?,S,N>>  List<S> recoverStatePath(N node){\n        List<S> states = new LinkedList<S>();\n        for(N n : node.path()){\n            states.add(n.state());\n        }\n        return states;\n    }\n\n    /**\n     * Returns a path of the actions applied from the initial state\n     * to the state of the provided node ({@link es.usc.citius.hipster.model.Node#state()}).\n     *\n     * @param <A> type of the actions.\n     * @param <N> type of the nodes.\n     * @return list with the ordered actions.\n     */\n    public static <A, N extends Node<A,?,N>>  List<A> recoverActionPath(N node){\n        List<A> actions = new LinkedList<A>();\n        for(N n : node.path()){\n            if (n.action() != null) actions.add(n.action());\n        }\n        return actions;\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/BellmanFord.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.algorithm;\n\nimport es.usc.citius.hipster.model.CostNode;\nimport es.usc.citius.hipster.model.function.NodeExpander;\nimport es.usc.citius.hipster.util.Predicate;\nimport es.usc.citius.lab.hipster.collections.HashQueue;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Queue;\n\n/**\n * <p>\n * Optimized implementation of the Bellman-Ford algorithm. The main difference with the standard version\n * of Bellman-Ford is that this implementation does not relax all edges at each iteration. This implies that\n * the first time the goal state is reached, the cost may not be the optimal one. The optimal cost is only guaranteed\n * when the queue is empty (when bellmanFordIt.hasNext() == false).\n * </p>\n *\n * <a href=\"http://www.ams.org/mathscinet-getitem?mr=0102435\">Original paper</a>:\n * Bellman, R. <b>\"On a routing problem\"</b>. <i>Quarterly of Applied Mathematics (1958) 16: 87–90</i>.\n *\n * @param <A> action type.\n * @param <S> state type.\n * @param <C> comparable cost used to compare states.\n * @param <N> type of the heuristic search node used.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class BellmanFord<A,S,C extends Comparable<C>,N extends CostNode<A,S,C,N>> extends Algorithm<A,S,N> {\n    protected N initialNode;\n    protected NodeExpander<A,S,N> nodeExpander;\n    protected boolean checkNegativeCycles = true;\n\n    public BellmanFord(N initialNode, NodeExpander<A, S, N> nodeExpander) {\n        this.initialNode = initialNode;\n        this.nodeExpander = nodeExpander;\n    }\n\n    /**\n     * Bellman-Ford iterator. Each invocation to {@code next()} returns the\n     * next expanded node with the approximated cost. The cost is only optimal\n     * when the queue is fully processed.\n     */\n    public class Iterator implements java.util.Iterator<N> {\n        protected Queue<S> queue;\n        protected Map<S, N> explored;\n\n        protected Iterator(){\n            this.queue = new HashQueue<S>();\n            this.explored = new HashMap<S, N>();\n            this.queue.add(initialNode.state());\n            this.explored.put(initialNode.state(), initialNode);\n        }\n\n        /**\n         * Assigns a node to the processing queue and adds it to the\n         * explored set of nodes.\n         *\n         * @param node node to update the queue status\n         */\n        protected void enqueue(N node) {\n            S state = node.state();\n            if (!this.queue.contains(state)) {\n                this.queue.add(state);\n            }\n            this.explored.put(state, node);\n        }\n\n        /**\n         * Removes the head of the processing queue and\n         * returns the corresponding node.\n         *\n         * @return node of the processing queue head\n         */\n        protected N dequeue() {\n            S state = this.queue.poll();\n            return this.explored.get(state);\n        }\n\n\n        @Override\n        public boolean hasNext() {\n            return !queue.isEmpty();\n        }\n\n        @Override\n        public N next() {\n            // Take the next node\n            N currentNode = dequeue();\n            if (checkNegativeCycles && currentNode.pathSize() > explored.size()){\n                throw new NegativeCycleException();\n            }\n            for (N successor : nodeExpander.expand(currentNode)) {\n                // Check if there is any improvement in the old cost\n                N previousNode = this.explored.get(successor.state());\n                if (previousNode != null) {\n                    // Check both paths. If the new path is better than the previous\n                    // path, update and enqueue. Else, discard this node.\n                    //if (comparator.compare(successorNode, previousNode) <= 0){\n                    if (successor.getCost().compareTo(previousNode.getCost()) < 0) {\n                        // Replace the worst version and re-enqueue (if not in queue)\n                        enqueue(successor);\n                    }\n                } else {\n                    enqueue(successor);\n                }\n            }\n            return currentNode;\n        }\n\n        @Override\n        public void remove() {\n            throw new UnsupportedOperationException();\n        }\n    }\n\n    @Override\n    public SearchResult search(Predicate<N> condition){\n        int iteration = 0;\n        Iterator it = iterator();\n        long begin = System.currentTimeMillis();\n        N currentNode = null;\n        N goalNode = null;\n        while(it.hasNext()){\n            iteration++;\n            currentNode = it.next();\n            if (goalNode == null && condition.apply(currentNode)) {\n                goalNode = currentNode;\n            }\n        }\n        long end = System.currentTimeMillis();\n        if (goalNode != null) {\n            N goal = it.explored.get(goalNode.state());\n            return new SearchResult(goal, iteration, end - begin);\n        }\n\n        return new SearchResult(Collections.<N>emptyList(), iteration, end - begin);\n    }\n\n    @Override\n    public Iterator iterator() {\n        return new Iterator();\n    }\n\n    public N getInitialNode() {\n        return initialNode;\n    }\n\n    public void setInitialNode(N initialNode) {\n        this.initialNode = initialNode;\n    }\n\n    public NodeExpander<A, S, N> getNodeExpander() {\n        return nodeExpander;\n    }\n\n    public void setNodeExpander(NodeExpander<A, S, N> nodeExpander) {\n        this.nodeExpander = nodeExpander;\n    }\n\n    public boolean isCheckNegativeCycles() {\n        return checkNegativeCycles;\n    }\n\n    public void setCheckNegativeCycles(boolean checkNegativeCycles) {\n        this.checkNegativeCycles = checkNegativeCycles;\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/BreadthFirstSearch.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.algorithm;\n\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.model.function.NodeExpander;\n\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.Map;\nimport java.util.Queue;\n\n/**\n * <p>\n * Breadth First Search (BFS) implementation. This is an uninformed algorithm that explores\n * first the neighbors at distance 1 (direct neighbors), then the neighbors at distance 2\n * (neighbors of the neighbors), and so on. The algorithm is complete but not optimal\n * (it is only optimal if the cost of the problem is uniform and each transition has a cost of one).\n * </p>\n *\n * See this <a href=\"http://en.wikipedia.org/wiki/Breadth-first_search\">Wikipedia article</a> for more information about BFS.\n *\n * @param <A> action type.\n * @param <S> state type.\n * @param <N> type of the heuristic search node used.\n */\npublic class BreadthFirstSearch<A,S,N extends Node<A,S,N>> extends Algorithm<A,S,N> {\n    protected final N initialNode;\n    protected final NodeExpander<A,S,N> expander;\n\n    public BreadthFirstSearch(N initialNode, NodeExpander<A, S, N> expander) {\n        this.initialNode = initialNode;\n        this.expander = expander;\n    }\n\n    /**\n     * Implements all the BFS search logic as an iterator\n     */\n    public class Iterator implements java.util.Iterator<N> {\n        protected Queue<N> queue = new LinkedList<N>();\n        protected Map<S, N> visited = new HashMap<S, N>();\n\n        /**\n         * Iterator cannot be instantiated from outside.\n         * Use {@link BreadthFirstSearch#iterator()} to create a new BFS iterator.\n         */\n        protected Iterator(){\n            visited.put(initialNode.state(), initialNode);\n            queue.add(initialNode);\n        }\n\n        @Override\n        public boolean hasNext() {\n            return !queue.isEmpty();\n        }\n\n        @Override\n        public N next() {\n            // Take next node\n            N current = queue.poll();\n            for(N successorNode : expander.expand(current)){\n                if (!visited.containsKey(successorNode.state())){\n                    visited.put(successorNode.state(), successorNode);\n                    queue.add(successorNode);\n                }\n            }\n            return current;\n        }\n\n        @Override\n        public void remove() {\n            throw new UnsupportedOperationException();\n        }\n\n        /* Access methods to the internals of the iterator */\n\n        public Queue<N> getQueue() {\n            return queue;\n        }\n\n        public void setQueue(Queue<N> queue) {\n            this.queue = queue;\n        }\n\n        public Map<S, N> getVisited() {\n            return visited;\n        }\n\n        public void setVisited(Map<S, N> visited) {\n            this.visited = visited;\n        }\n    }\n\n    @Override\n    public Iterator iterator() {\n        return new Iterator();\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/DepthFirstSearch.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.algorithm;\n\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.model.function.NodeExpander;\n\nimport java.util.*;\n\n/**\n * <p>\n * Depth First Search (DFS) is a blind algorithm that performs an exploration\n * of the graph in a way that always reaches the deepest node before backtracking.\n * The Hipster implementation is a graph-based search that can handle cycles.\n * This algorithm is complete (it always finds a solution if it exists) but not\n * optimal.\n * </p>\n *\n * For more information see <a href=\"http://en.wikipedia.org/wiki/Depth-first_search\">this article of the Wikipedia</a> about DFS.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class DepthFirstSearch<A,S,N extends Node<A,S,N>> extends Algorithm<A,S,N> {\n    protected N initialNode;\n    protected NodeExpander<A,S,N> expander;\n\n    // TODO; DRY common structures with other algorithms (like IDA)\n\n    public DepthFirstSearch(N initialNode, NodeExpander<A, S, N> expander) {\n        this.expander = expander;\n        this.initialNode = initialNode;\n    }\n\n    public class StackFrameNode {\n        // Iterable used to compute neighbors of the current node\n        private java.util.Iterator<N> successors;\n        // Current search node\n        private N node;\n        // Boolean value to check if the node is still unvisited\n        // in the stack or not\n        boolean visited = false;\n        // Boolean to indicate that this node is fully processed\n        boolean processed = false;\n\n        StackFrameNode(java.util.Iterator successors, N node) {\n            this.successors = successors;\n            this.node = node;\n        }\n\n        StackFrameNode(N node) {\n            this.node = node;\n            this.successors = expander.expand(node).iterator();\n        }\n\n        public N getNode() {\n            return node;\n        }\n\n        public java.util.Iterator<N> getSuccessors() {\n            return successors;\n        }\n\n        public boolean isVisited() {\n            return visited;\n        }\n\n        public boolean isProcessed() {\n            return processed;\n        }\n    }\n\n    /**\n     * DFS iterator used to expand always the deepest non-visited node.\n     */\n    public class Iterator implements java.util.Iterator<N> {\n        protected Deque<StackFrameNode> stack = new ArrayDeque<StackFrameNode>();\n        protected StackFrameNode next;\n        protected Set<S> closed = new HashSet<S>();\n        protected boolean graphSupport = true;\n\n        protected Iterator(){\n            this.stack.addLast(new StackFrameNode(initialNode));\n        }\n\n\n        @Override\n        public boolean hasNext() {\n            if (next == null){\n                // Compute next\n                next = nextUnvisited();\n                if (next == null) return false;\n            }\n            return true;\n        }\n\n        @Override\n        public N next(){\n            if (next != null){\n                StackFrameNode e = next;\n                // Compute the next one\n                next = null;\n                // Return current node\n                return e.node;\n            }\n            // Compute next\n            StackFrameNode nextUnvisited = nextUnvisited();\n            if (nextUnvisited!=null){\n                return nextUnvisited.node;\n            }\n            return null;\n\n        }\n\n        @Override\n        public void remove() {\n            throw new UnsupportedOperationException();\n        }\n\n\n        protected StackFrameNode nextUnvisited(){\n            StackFrameNode nextNode;\n            do {\n                nextNode = processNextNode();\n            } while(nextNode != null && (nextNode.processed || nextNode.visited || closed.contains(nextNode.node.state())));\n\n            if (nextNode != null){\n                nextNode.visited = true;\n                // For graphs, the DFS needs to keep track of all nodes\n                // that were processed and removed from the stack, in order\n                // to avoid cycles.\n                if (graphSupport) closed.add(nextNode.node.state());\n            }\n            return nextNode;\n        }\n\n\n        protected StackFrameNode processNextNode(){\n\n            if (stack.isEmpty()) return null;\n\n            // Take last node in the stack but do not remove\n            StackFrameNode current = stack.peekLast();\n            // Find a successor\n            if (current.successors.hasNext()){\n                N successor = current.successors.next();\n                // push the node (if not explored)\n                if (!graphSupport || !closed.contains(successor.state())) {\n                    stack.addLast(new StackFrameNode(successor));\n                }\n                return current;\n            } else {\n                // Visited?\n                if (current.visited){\n                    current.processed = true;\n                }\n               return stack.removeLast();\n            }\n        }\n\n        public Deque<StackFrameNode> getStack() {\n            return stack;\n        }\n\n        public void setStack(Deque<StackFrameNode> stack) {\n            this.stack = stack;\n        }\n\n        public StackFrameNode getNext() {\n            return next;\n        }\n\n        public void setNext(StackFrameNode next) {\n            this.next = next;\n        }\n\n        public Set<S> getClosed() {\n            return closed;\n        }\n\n        public void setClosed(Set<S> closed) {\n            this.closed = closed;\n        }\n\n        public boolean isGraphSupport() {\n            return graphSupport;\n        }\n\n        public void setGraphSupport(boolean graphSupport) {\n            this.graphSupport = graphSupport;\n        }\n    }\n    @Override\n    public java.util.Iterator<N> iterator() {\n        return new Iterator();\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/DepthLimitedSearch.java",
    "content": "package es.usc.citius.hipster.algorithm;\n\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.model.function.NodeExpander;\nimport es.usc.citius.hipster.model.impl.UnweightedNode;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Stack;\n/**\n * Copyright 2015 Centro de Investigación en Tecnoloxías da Información (CITIUS),\n * University of Santiago de Compostela (USC).\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * <p>\n * In computer science maximumDepth-limited search is an algorithm to explore the vertices of a graph.\n * It is a modification of maximumDepth-first search and is used for example in the iterative deepening\n * maximumDepth-first search algorithm.\n * </p>\n *\n * For more information see <a href=\"http://en.wikipedia.org/wiki/Depth-limited_search\">this article of the Wikipedia</a> about DLS.\n *\n * @author Gabriella Zekany\n */\npublic class DepthLimitedSearch <A,S,N extends Node<A,S,N>> extends Algorithm<A,S,N> {\n    protected N initialNode;\n    protected N finalNode;\n    protected NodeExpander nodeExpander;\n    protected int maximumDepth;\n    protected int currentDepth;\n    protected ArrayList<S> path;\n\n    public DepthLimitedSearch(N initialNode, N finalNode, NodeExpander nodeExpander, int maximumDepth) {\n        this.initialNode = initialNode;\n        this.finalNode = finalNode;\n        this.nodeExpander = nodeExpander;\n        this.maximumDepth = maximumDepth;\n        this.currentDepth = 0;\n        this.path = new ArrayList<>();\n    }\n\n    public int getMaximumDepth() {\n        return this.maximumDepth;\n    }\n\n    public int getCurrentDepth() {\n        return this.currentDepth;\n    }\n\n    public ArrayList<S> getPath() {\n        return path;\n    }\n\n    public void incrementCurrentDepth() {\n        this.currentDepth ++;\n    }\n\n    public boolean execute() {\n        Stack<StackNode> nodeStack = new Stack();\n        StackNode tempStackNode = new StackNode(this.initialNode);\n        nodeStack.add(tempStackNode);\n\n        while(!nodeStack.isEmpty()) {\n            if(this.currentDepth <= this.maximumDepth) {\n                StackNode temp = nodeStack.pop();\n                if(!path.contains(temp.getNode()) && ((UnweightedNode) temp.getNode()).state().equals(((UnweightedNode)this.finalNode).state())){\n                    this.path.add((S) temp.getNode().state());\n                    return true;\n                }  else {\n                    this.path.add((S) temp.getNode().state());\n                    for(StackNode child : temp.getChildren()) {\n                        if(!this.path.contains(child.getNode().state())) {\n                            nodeStack.add(child);\n                        }\n                    }\n                    this.incrementCurrentDepth();\n                }\n            } else {\n                return false;\n            }\n        }\n        return false;\n    }\n\n    private class StackNode {\n        private N node;\n        private java.util.Iterator<N> children;\n\n        public StackNode(N node) {\n            this.node = node;\n            this.children = nodeExpander.expand(node).iterator();\n        }\n\n        public N getNode() {\n            return node;\n        }\n\n        public void setNode(N node) {\n            this.node = node;\n        }\n\n        public List<StackNode> getChildren() {\n            ArrayList<StackNode> result = new ArrayList<>();\n            while(this.children.hasNext()) {\n                StackNode temp = new StackNode(this.children.next());\n                result.add(temp);\n            }\n            return result;\n        }\n\n        public void setChildren(java.util.Iterator<N> children) {\n            this.children = children;\n        }\n    }\n\n    @Override\n    public Iterator<N> iterator() {\n        return null;\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/Hipster.java",
    "content": "/*\r\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\r\n *\r\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *    you may not use this file except in compliance with the License.\r\n *    You may obtain a copy of the License at\r\n *\r\n *        http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n *    Unless required by applicable law or agreed to in writing, software\r\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *    See the License for the specific language governing permissions and\r\n *    limitations under the License.\r\n */\r\n\r\npackage es.usc.citius.hipster.algorithm;\r\n\r\nimport es.usc.citius.hipster.algorithm.localsearch.AnnealingSearch;\r\nimport es.usc.citius.hipster.algorithm.localsearch.HillClimbing;\r\nimport es.usc.citius.hipster.algorithm.localsearch.AnnealingSearch.AcceptanceProbability;\r\nimport es.usc.citius.hipster.algorithm.localsearch.AnnealingSearch.SuccessorFinder;\r\nimport es.usc.citius.hipster.model.CostNode;\r\nimport es.usc.citius.hipster.model.HeuristicNode;\r\nimport es.usc.citius.hipster.model.Node;\r\nimport es.usc.citius.hipster.model.function.NodeExpander;\r\nimport es.usc.citius.hipster.model.function.impl.ADStarNodeExpander;\r\nimport es.usc.citius.hipster.model.function.impl.ADStarNodeFactory;\r\nimport es.usc.citius.hipster.model.impl.ADStarNodeImpl;\r\nimport es.usc.citius.hipster.model.problem.SearchComponents;\r\nimport es.usc.citius.hipster.model.problem.SearchProblem;\r\n\r\nimport java.util.Collections;\r\n\r\n/**\r\n * Util class to create algorithms easily. Each method expects a\r\n * {@link es.usc.citius.hipster.model.problem.SearchProblem} with the components\r\n * of the algorithm and returns an iterable algorithm that can be used to search\r\n * a goal or iterate over the state space. A SearchProblem can be easily defined\r\n * with the {@link es.usc.citius.hipster.model.problem.ProblemBuilder} class.\r\n *\r\n * @see es.usc.citius.hipster.model.problem.ProblemBuilder\r\n *\r\n * @author Pablo Rodríguez Mier <\r\n *         <a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc\r\n *         .es</a>>\r\n * @author Adrián González Sieira <\r\n *         <a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\r\n */\r\npublic final class Hipster {\r\n\r\n\tprivate Hipster() {\r\n\r\n\t}\r\n\r\n\t/**\r\n\t * Instantiates a A* algorithm given a problem definition.\r\n\t *\r\n\t * @param components\r\n\t *            search problem definition with the components of the algorithm\r\n\t * @param <A>\r\n\t *            type of the actions\r\n\t * @param <S>\r\n\t *            type of the states\r\n\t * @param <C>\r\n\t *            type of the cost\r\n\t * @param <N>\r\n\t *            type of the nodes\r\n\t * @return instance of {@link es.usc.citius.hipster.algorithm.AStar} for the\r\n\t *         problem definition\r\n\t */\r\n\tpublic static <A, S, C extends Comparable<C>, N extends HeuristicNode<A, S, C, N>> AStar<A, S, C, N> createAStar(\r\n\t\t\tSearchProblem<A, S, N> components) {\r\n\t\treturn new AStar<A, S, C, N>(components.getInitialNode(), components.getExpander());\r\n\t}\r\n\r\n\t/**\r\n\t * Instantiates a Dijkstra algorithm (A* algorithm with no heuristic\r\n\t * function) given a problem definition.\r\n\t *\r\n\t * @param components\r\n\t *            search problem definition with the components of the algorithm\r\n\t * @param <A>\r\n\t *            type of the actions\r\n\t * @param <S>\r\n\t *            type of the states\r\n\t * @param <C>\r\n\t *            type of the cost\r\n\t * @param <N>\r\n\t *            type of the nodes\r\n\t * @return instance of {@link es.usc.citius.hipster.algorithm.AStar} for the\r\n\t *         problem definition, using no heuristic.\r\n\t */\r\n\tpublic static <A, S, C extends Comparable<C>, N extends HeuristicNode<A, S, C, N>> AStar<A, S, C, N> createDijkstra(\r\n\t\t\tSearchProblem<A, S, N> components) {\r\n\t\t// TODO: There is no difference with AStar. Actually if the NodeExpander\r\n\t\t// uses heuristics, this \"Dijkstra\" impl works as the AStar. This should\r\n\t\t// be changed!\r\n\t\treturn new AStar<A, S, C, N>(components.getInitialNode(), components.getExpander());\r\n\t}\r\n\r\n\t/**\r\n\t * Instantiates a Bellman Ford algorithm for a problem definition.\r\n\t *\r\n\t * @param components\r\n\t *            search problem definition with the components of the algorithm\r\n\t * @param <A>\r\n\t *            type of the actions\r\n\t * @param <S>\r\n\t *            type of the states\r\n\t * @param <C>\r\n\t *            type of the cost\r\n\t * @param <N>\r\n\t *            type of the nodes\r\n\t * @return instance of {@link es.usc.citius.hipster.algorithm.BellmanFord}\r\n\t *         for the problem definition\r\n\t */\r\n\tpublic static <A, S, C extends Comparable<C>, N extends CostNode<A, S, C, N>> BellmanFord<A, S, C, N> createBellmanFord(\r\n\t\t\tSearchProblem<A, S, N> components) {\r\n\t\treturn new BellmanFord<A, S, C, N>(components.getInitialNode(), components.getExpander());\r\n\t}\r\n\r\n\t/**\r\n\t * Instantiates Breadth First Search algorithm for a problem definition.\r\n\t *\r\n\t * @param components\r\n\t *            search problem definition with the components of the algorithm\r\n\t * @param <A>\r\n\t *            type of the actions\r\n\t * @param <S>\r\n\t *            type of the states\r\n\t * @param <N>\r\n\t *            type of the nodes\r\n\t * @return instance of\r\n\t *         {@link es.usc.citius.hipster.algorithm.BreadthFirstSearch} for\r\n\t *         the problem definition\r\n\t */\r\n\tpublic static <A, S, N extends Node<A, S, N>> BreadthFirstSearch<A, S, N> createBreadthFirstSearch(\r\n\t\t\tSearchProblem<A, S, N> components) {\r\n\t\treturn new BreadthFirstSearch<A, S, N>(components.getInitialNode(), components.getExpander());\r\n\t}\r\n\r\n\t/**\r\n\t * Instantiates Depth First Search algorithm for a problem definition.\r\n\t *\r\n\t * @param components\r\n\t *            search problem definition with the components of the algorithm\r\n\t * @param <A>\r\n\t *            type of the actions\r\n\t * @param <S>\r\n\t *            type of the states\r\n\t * @param <N>\r\n\t *            type of the nodes\r\n\t * @return instance of\r\n\t *         {@link es.usc.citius.hipster.algorithm.DepthFirstSearch} for the\r\n\t *         problem definition\r\n\t */\r\n\tpublic static <A, S, N extends Node<A, S, N>> DepthFirstSearch<A, S, N> createDepthFirstSearch(\r\n\t\t\tSearchProblem<A, S, N> components) {\r\n\t\treturn new DepthFirstSearch<A, S, N>(components.getInitialNode(), components.getExpander());\r\n\t}\r\n\r\n\t/**\r\n\t * Instantiates Depth Limited Search algorithm for a problem definition.\r\n\t *\r\n\t * @param components\r\n\t *            search problem definition with the components of the algorithm\r\n\t * @param <A>\r\n\t *            type of the actions\r\n\t * @param <S>\r\n\t *            type of the states\r\n\t * @param <N>\r\n\t *            type of the nodes\r\n\t * @return instance of\r\n\t *         {@link es.usc.citius.hipster.algorithm.DepthFirstSearch} for the\r\n\t *         problem definition\r\n\t */\r\n\tpublic static <A, S, N extends Node<A, S, N>> DepthLimitedSearch<A, S, N> createDepthLimitedSearch(\r\n\t\t\tSearchProblem<A, S, N> components, int depth) {\r\n\t\treturn new DepthLimitedSearch<A, S, N>(components.getInitialNode(), components.getFinalNode(),\r\n\t\t\t\tcomponents.getExpander(), depth);\r\n\t}\r\n\r\n\t/**\r\n\t * Instantiates a IDA* algorithm given a problem definition.\r\n\t *\r\n\t * @param components\r\n\t *            search problem definition with the components of the algorithm\r\n\t * @param <A>\r\n\t *            type of the actions\r\n\t * @param <S>\r\n\t *            type of the states\r\n\t * @param <C>\r\n\t *            type of the cost\r\n\t * @param <N>\r\n\t *            type of the nodes\r\n\t * @return instance of {@link es.usc.citius.hipster.algorithm.IDAStar} for\r\n\t *         the problem definition\r\n\t */\r\n\tpublic static <A, S, C extends Comparable<C>, N extends HeuristicNode<A, S, C, N>> IDAStar<A, S, C, N> createIDAStar(\r\n\t\t\tSearchProblem<A, S, N> components) {\r\n\t\treturn new IDAStar<A, S, C, N>(components.getInitialNode(), components.getExpander());\r\n\t}\r\n\r\n\t/**\r\n\t * Instantiates a Hill Climbing algorithm given a problem definition.\r\n\t *\r\n\t * @param components\r\n\t *            search problem definition with the components of the algorithm\r\n\t * @param enforced\r\n\t *            flag to use Enforced Hill Climbing instead of classic Hill\r\n\t *            Climbing algorithm\r\n\t * @param <A>\r\n\t *            type of the actions\r\n\t * @param <S>\r\n\t *            type of the states\r\n\t * @param <C>\r\n\t *            type of the cost\r\n\t * @param <N>\r\n\t *            type of the nodes\r\n\t * @return instance of\r\n\t *         {@link es.usc.citius.hipster.algorithm.localsearch.HillClimbing}\r\n\t *         for the problem definition\r\n\t */\r\n\tpublic static <A, S, C extends Comparable<C>, N extends HeuristicNode<A, S, C, N>> HillClimbing<A, S, C, N> createHillClimbing(\r\n\t\t\tSearchProblem<A, S, N> components, boolean enforced) {\r\n\t\treturn new HillClimbing<A, S, C, N>(components.getInitialNode(), components.getExpander(), enforced);\r\n\t}\r\n\r\n\t/**\r\n\t * Instantiates an AnnealingSearch algorithm given a problem definition.\r\n\t *\r\n\t * @param components\r\n\t *            search problem definition with the components of the algorithm\r\n\t * @param alpha\r\n\t *            coefficient of the geometric cooling schedule\r\n\t * @param <A>\r\n\t *            type of the actions\r\n\t * @param <S>\r\n\t *            type of the states\r\n\t * @param <C>\r\n\t *            type of the cost\r\n\t * @param <N>\r\n\t *            type of the nodes\r\n\t * @return instance of\r\n\t *         {@link es.usc.citius.hipster.algorithm.localsearch.HillClimbing}\r\n\t *         for the problem definition\r\n\t */\r\n\tpublic static <A, S, N extends HeuristicNode<A, S, Double, N>> AnnealingSearch<A, S, N> createAnnealingSearch(\r\n\t\t\tSearchProblem<A, S, N> components, Double alpha, Double minTemp,\r\n\t\t\tAcceptanceProbability acceptanceProbability, SuccessorFinder<A, S, N> successorFinder) {\r\n\t\treturn new AnnealingSearch<A, S, N>(components.getInitialNode(), components.getExpander(), alpha,\r\n\t\t\t\tminTemp, acceptanceProbability, successorFinder);\r\n\t}\r\n\r\n\t/**\r\n\t * Instantiates a Multi-objective Label Setting algorithm given a problem\r\n\t * definition.\r\n\t *\r\n\t * @param components\r\n\t *            search problem definition with the components of the algorithm\r\n\t * @param <A>\r\n\t *            type of the actions\r\n\t * @param <S>\r\n\t *            type of the states\r\n\t * @param <C>\r\n\t *            type of the cost\r\n\t * @param <N>\r\n\t *            type of the nodes\r\n\t * @return instance of\r\n\t *         {@link es.usc.citius.hipster.algorithm.MultiobjectiveLS} for the\r\n\t *         problem definition\r\n\t */\r\n\tpublic static <A, S, C extends Comparable<C>, N extends HeuristicNode<A, S, C, N>> MultiobjectiveLS<A, S, C, N> createMultiobjectiveLS(\r\n\t\t\tSearchProblem<A, S, N> components) {\r\n\t\treturn new MultiobjectiveLS<A, S, C, N>(components.getInitialNode(), components.getExpander());\r\n\t}\r\n\r\n\t/**\r\n\t * Instantiates a Anytime Dynamic A* algorithm given the search components.\r\n\t * Search components can be obtained easily for graph-based problems using\r\n\t * {@link es.usc.citius.hipster.util.graph.GraphSearchProblem}.\r\n\t *\r\n\t * @param components\r\n\t *            search components to be used by the algorithm\r\n\t * @param <A>\r\n\t *            type of the actions\r\n\t * @param <S>\r\n\t *            type of the states\r\n\t * @param <C>\r\n\t *            type of the cost\r\n\t * @return instance of {@link es.usc.citius.hipster.algorithm.ADStarForward}\r\n\t *         for the search components\r\n\t */\r\n\tpublic static <A, S, C extends Comparable<C>> ADStarForward<A, S, C, ADStarNodeImpl<A, S, C>> createADStar(\r\n\t\t\tSearchComponents<A, S, C> components) {\r\n\t\t// node factory instantiation\r\n\t\tADStarNodeFactory<A, S, C> factory = new ADStarNodeFactory<A, S, C>(components);\r\n\t\t// node expander instantiation\r\n\t\tADStarNodeExpander<A, S, C, ADStarNodeImpl<A, S, C>> expander = new ADStarNodeExpander<A, S, C, ADStarNodeImpl<A, S, C>>(\r\n\t\t\t\tcomponents, factory, 1.0);\r\n\t\t// instantiate algorithm\r\n\t\treturn new ADStarForward(components.getBegin(), Collections.singleton(components.getGoal()), expander);\r\n\t}\r\n}\r\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/IDAStar.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.algorithm;\n\n\n\n\nimport es.usc.citius.hipster.model.HeuristicNode;\nimport es.usc.citius.hipster.model.function.NodeExpander;\n\n/**\n * <p>\n * Implementation of the IDA* algorithm. Similar to Iterative DFS but using heuristics to limit\n * the space search and keeping a very low memory usage.\n * </p>\n *\n * <a href=\"http://www.sciencedirect.com/science/article/pii/0004370285900840\">Original paper</a>:\n * Richard E. Korf <i><b>\"Depth-first Iterative-Deepening: An Optimal Admissible Tree Search.\"</b></i>,\n * Artificial Intelligence, vol. 27, pp. 97-109, 1985.\n *\n * @param <A> action type.\n * @param <S> state type.\n * @param <C> comparable cost used to compare states.\n * @param <N> type of the heuristic search node.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Jennnnyz\n *\n */\npublic class IDAStar<A,S,C extends Comparable<C>,N extends HeuristicNode<A,S,C,N>> extends DepthFirstSearch<A,S,N> {\n\n    /**\n     * \n     * @param initialNode\n     * @param expander \n     */\n    public IDAStar(N initialNode, NodeExpander<A,S,N> expander) {\n        super(initialNode, expander);\n    }\n\n    /**\n     * IDA iterator. It expands the next state to be explored. Backtracking\n     * is automatically performed so if the state reaches a dead-end the next\n     * call to {@code iterator.next()} returns the next state after performing\n     * backtracking.\n     */\n\n    public class Iterator extends DepthFirstSearch.Iterator {\n        protected C fLimit;\n        protected C minfLimit;\n        protected int reinitialization = 0;\n\n        protected Iterator(){\n            // Set initial bound\n            super();\n            fLimit = initialNode.getEstimation();\n            minfLimit = null;\n        }\n\n        protected void updateMinFLimit(C currentFLimit){\n            if (minfLimit == null){\n                minfLimit = currentFLimit;\n            } else {\n                if (minfLimit.compareTo(currentFLimit)>0){\n                    minfLimit = currentFLimit;\n                }\n            }\n        }\n\n        @Override\n        protected StackFrameNode nextUnvisited(){\n            StackFrameNode nextNode;\n            do {\n                nextNode = processNextNode();\n                // No more neighbors to visit with the current fLimit. Update the new fLimit\n                if (nextNode == null){\n                    // Reinitialize\n                    if (minfLimit != null && minfLimit.compareTo(fLimit)>0){\n                        fLimit = minfLimit;\n                        reinitialization++;\n                        minfLimit = null;\n                        super.getStack().addLast(new StackFrameNode(initialNode));\n                        nextNode = processNextNode();\n                    }\n                }\n            } while(nextNode != null && (nextNode.processed || nextNode.visited));\n\n            if (nextNode != null){\n                nextNode.visited = true;\n            }\n            return nextNode;\n        }\n\n        @Override\n        protected StackFrameNode processNextNode(){\n            // Get and process the current node. Cases:\n            //   1 - empty stack, return null\n            //   2 - node exceeds the bound: update minfLimit, pop and skip.\n            //   3 - node has neighbors: expand and return current.\n            //   4 - node has no neighbors:\n            //       4.1 - Node visited before: processed node, pop and skip to the next node.\n            //       4.2 - Not visited: we've reached a leaf node.\n            //             mark as visited, pop and return.\n\n            // 1- If the stack is empty, change fLimit and reinitialize the search\n            if (super.getStack().isEmpty()) return null;\n\n            // Take current node in the stack but do not remove\n            StackFrameNode current = (StackFrameNode) super.stack.peekLast();\n\n            // 2 - Check if the current node exceeds the limit bound\n            C fCurrent = current.getNode().getScore();\n            if (fCurrent.compareTo(fLimit)>0){\n                // Current node exceeds the limit bound, update minfLimit, pop and skip.\n                updateMinFLimit(fCurrent);\n                // Remove from stack\n                current.processed = true;\n                return (StackFrameNode) super.getStack().removeLast();\n            }\n\n            // Find a successor\n            if (current.getSuccessors().hasNext()){\n                // 3 - Node has at least one neighbor\n                N successor = current.getSuccessors().next();\n                // push the node\n                super.getStack().addLast(new StackFrameNode(successor));\n                return current;\n\n            } else {\n                // 4 - Visited?\n                if (current.visited){\n                    current.processed = true;\n                }\n                return (StackFrameNode) super.getStack().removeLast();\n            }\n        }\n\n        public C getfLimit() {\n            return fLimit;\n        }\n\n        public void setfLimit(C fLimit) {\n            this.fLimit = fLimit;\n        }\n\n        public C getMinfLimit() {\n            return minfLimit;\n        }\n\n        public void setMinfLimit(C minfLimit) {\n            this.minfLimit = minfLimit;\n        }\n\n        public int getReinitialization() {\n            return reinitialization;\n        }\n\n        public void setReinitialization(int reinitialization) {\n            this.reinitialization = reinitialization;\n        }\n    }\n\n    @Override\n    public Iterator iterator() {\n        return new Iterator();\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/MultiobjectiveLS.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.algorithm;\n\nimport es.usc.citius.hipster.model.HeuristicNode;\nimport es.usc.citius.hipster.model.function.NodeExpander;\nimport es.usc.citius.hipster.util.Predicate;\n\nimport java.util.*;\n\n/**\n * <p>Implementation of the multi-objective label setting algorithm described\n * by Martins and Santos.</p>\n *\n * Original paper:\n * Martins, E. D. Q. V., & Santos, J. L. E. (1999). <b>\"The labeling algorithm for the multiobjective shortest path problem\"</b>. <i>Departamento de Matematica, Universidade de Coimbra, Portugal, Tech. Rep. TR-99/005</i>.\n *\n * @param <A> action type.\n * @param <S> state type.\n * @param <C> comparable cost used to compare states.\n * @param <N> type of the heuristic search node used.\n *           \n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class MultiobjectiveLS<A,S,C extends Comparable<C>,N extends HeuristicNode<A,S,C,N>> extends Algorithm<A,S,N> {\n\n    protected N initialNode;\n    protected NodeExpander<A,S,N> nodeExpander;\n\n    public MultiobjectiveLS(N initialNode, NodeExpander<A, S, N> nodeExpander) {\n        this.initialNode = initialNode;\n        this.nodeExpander = nodeExpander;\n    }\n\n    /**\n     * MultiobjectiveLS iterator. It expands one state at a time and updates\n     * an internal connected (nonDominated) which stores all non-dominated paths.\n     * In order to find all non-dominated shortest path, the algorithm must be\n     * executed until {@code iterator.hasNext() == false}. Paths can be recovered\n     * with {@code iterator.getNonDominated.get(goalState)}\n     */\n    public class Iterator implements java.util.Iterator<N> {\n        protected Queue<N> queue = new LinkedList<N>();\n        public Map<S, Collection<N>> nonDominated;\n        //auxiliary variable which stores an empty list to avoid nullable values in code\n        private final Collection<N> EMPTYLIST = new ArrayList<N>();\n\n        protected Iterator(){\n            queue = new PriorityQueue<N>();\n            this.nonDominated = new HashMap<S, Collection<N>>();\n            this.queue.add(initialNode);\n        }\n\n        public boolean hasNext() {\n            return !this.queue.isEmpty();\n        }\n\n        @Override\n        public N next() {\n            // 1- Take smallest lexicographical element from queue\n            // 2- For all successors:\n            // \t\t- Build the new node, which represents a path from s to t.\n            //\t\t- Check all non dominated paths tracked from s to t. If\n            //\t\t  this new node is dominated, discard it.\n            //\t\t- Add the new node, sorted by a lexicographical comparator\n            //\t\t- Check and remove dominated paths\n            // Repeat 1.\n            // Finally, the node that contains the goal state t, contains\n            // the set of all non-dominated paths from s to t.\n            N current = queue.poll();\n            // Take successors\n            for (N candidate : nodeExpander.expand(current)) {\n                // Take non-dominated (nd) nodes associated to the current state\n                // (i.e., all non-dominated paths from start to currentState\n                Collection<N> ndNodes = EMPTYLIST;\n                if(!nonDominated.containsKey(candidate.state())){\n                    nonDominated.put(candidate.state(), new ArrayList<N>());\n                }\n                else{\n                    ndNodes = nonDominated.get(candidate.state());\n                }\n                // Check if the node is non-dominated\n                if (!isDominated(candidate, ndNodes)) {\n                    // Assign the candidate to the queue\n                    this.queue.add(candidate);\n                    // Add new non dominated path\n                    ndNodes.add(candidate);\n                    // Re-analyze dominance and remove new dominated paths\n                    // Find all paths that can be dominated by the new non-dominated path\n                    for (N dominated : dominatedBy(candidate, ndNodes)) {\n                        ndNodes.remove(dominated);\n                    }\n                }\n            }\n            return current;\n        }\n\n        @Override\n        public void remove() {\n            throw new UnsupportedOperationException();\n        }\n\n        protected Collection<N> dominatedBy(N node, Iterable<N> nonDominated) {\n            Collection<N> dominated = new HashSet<N>();\n            for (N n : nonDominated) {\n                if (node.getScore().compareTo(n.getScore())<0) {\n                    dominated.add(n);\n                }\n            }\n            return dominated;\n        }\n\n        protected boolean isDominated(N node, Iterable<N> nonDominated) {\n            // Compare all non-dominated nodes with node\n            for (N nd : nonDominated) {\n                if (nd.getScore().compareTo(node.getScore())< 0) {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        public Queue<N> getQueue() {\n            return queue;\n        }\n\n        public Map<S, Collection<N>> getNonDominated() {\n            return nonDominated;\n        }\n    }\n\n    @Override\n    public SearchResult search(Predicate<N> condition){\n        int iteration = 0;\n        Iterator it = new Iterator();\n        long beginTime = System.currentTimeMillis();\n        N currentNode;\n        N goalNode = null;\n        while(it.hasNext()){\n            iteration++;\n            currentNode = it.next();\n            if (condition.apply(currentNode)) {\n                goalNode = currentNode;\n            }\n        }\n        long elapsed = System.currentTimeMillis() - beginTime;\n        if (goalNode != null) {\n            Collection<N> solutions = it.nonDominated.get(goalNode.state());\n            return new SearchResult(solutions, iteration, elapsed);\n        }\n        return new SearchResult(Collections.<N>emptyList(), iteration, elapsed);\n    }\n\n    @Override\n    public java.util.Iterator<N> iterator() {\n        return new Iterator();\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/NegativeCycleException.java",
    "content": "package es.usc.citius.hipster.algorithm;\n\n\npublic class NegativeCycleException extends RuntimeException {\n    private static final String message = \"Existence of a negative cycle detected\";\n\n    public NegativeCycleException() {\n        super(message);\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/localsearch/AnnealingSearch.java",
    "content": "package es.usc.citius.hipster.algorithm.localsearch;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Iterator;\r\nimport java.util.LinkedList;\r\nimport java.util.List;\r\nimport java.util.Queue;\r\nimport java.util.Random;\r\n\r\nimport es.usc.citius.hipster.algorithm.Algorithm;\r\nimport es.usc.citius.hipster.model.HeuristicNode;\r\nimport es.usc.citius.hipster.model.Node;\r\nimport es.usc.citius.hipster.model.function.NodeExpander;\r\n\r\n/**\r\n * Implementation of the simulated annealing search that is a probabilistic\r\n * technique for approximating the global optimum of a given function. It starts\r\n * the exploration from a random point as a global optimum and selects one of\r\n * its neighbors with a neighboring function. The neighbor will become the new\r\n * optimum if its associated cost is lower or if the acceptance probability\r\n * function returns a probability greater than a random number. The probability\r\n * function takes as an input the cost of the current selected node, the cost of\r\n * its randomly selected neighbour and the current temperature. The higher the\r\n * cost of the neighbour is or the lower the temperature is, the more unlikely\r\n * it is that the neighbour becomes the new optimum. The process continues until\r\n * the temperature is below a given threshold. The temperature decreases at each\r\n * iteration according to a geometric cooling schedule that has two parameters\r\n * alpha and temperature min. The main idea of this algorithm is to avoid to be\r\n * \"trapped\" in a bad local optimum by exploring more deeply the state space by\r\n * looking at states whose cost is not optimum but that may have interesting\r\n * neighbours. A user can adjusted the algorithm by tuning the alpha coefficient\r\n * (default 0.9) or the min temperature (0.00001) or by providing his own\r\n * implementation of the acceptance probability function (default: exp((old\r\n * score - new score) / current temperature)) or the neighbouring function\r\n * (random selection by default). Note: costs are Double in this implementation\r\n * and have no type parameters.\r\n * \r\n * see <a href=\"https://en.wikipedia.org/wiki/Simulated_annealing\">in\r\n * Wikipedia</a> and <a href=\"http://katrinaeg.com/simulated-annealing.html\">in\r\n * annealing search</a> for more details.\r\n * \r\n * @param <A>\r\n *            class defining the action\r\n * @param <S>\r\n *            class defining the state\r\n * @param <C>\r\n *            class defining the cost, must implement\r\n *            {@link java.lang.Comparable}\r\n * @param <N>\r\n *            type of the nodes\r\n * \r\n * @author Christophe Moins <\r\n *         <a href=\"mailto:christophe.moins@yahoo.fr\">christophe.moins@yahoo.fr\r\n *         </a>>\r\n */\r\npublic class AnnealingSearch<A, S, N extends HeuristicNode<A, S, Double, N>> extends Algorithm<A, S, N> {\r\n\r\n\tstatic final private Double DEFAULT_ALPHA = 0.9;\r\n\tstatic final private Double DEFAULT_MIN_TEMP = 0.00001;\r\n\tstatic final private Double START_TEMP = 1.;\r\n\r\n\tprivate N initialNode;\r\n\tprivate Double alpha;\r\n\tprivate Double minTemp;\r\n\tprivate AcceptanceProbability acceptanceProbability;\r\n\tprivate SuccessorFinder<A, S, N> successorFinder;\r\n\t// expander to find all the successors of a given node.\r\n\tprivate NodeExpander<A, S, N> nodeExpander;\r\n\r\n\tpublic AnnealingSearch(N initialNode, NodeExpander<A, S, N> nodeExpander, Double alpha, Double minTemp,\r\n\t\t\tAcceptanceProbability acceptanceProbability, SuccessorFinder<A, S, N> successorFinder) {\r\n\t\tif (initialNode == null) {\r\n\t\t\tthrow new IllegalArgumentException(\"Provide a valid initial node\");\r\n\t\t}\r\n\t\tthis.initialNode = initialNode;\r\n\t\tif (nodeExpander == null) {\r\n\t\t\tthrow new IllegalArgumentException(\"Provide a valid node expander\");\r\n\t\t}\r\n\t\tthis.nodeExpander = nodeExpander;\r\n\t\tif (alpha != null) {\r\n\t\t\tif ((alpha <= 0.) || (alpha >= 1.0)) {\r\n\t\t\t\tthrow new IllegalArgumentException(\"alpha must be between 0. and 1.\");\r\n\t\t\t}\r\n\t\t\tthis.alpha = alpha;\r\n\t\t} else {\r\n\t\t\tthis.alpha = DEFAULT_ALPHA;\r\n\t\t}\r\n\t\tif (minTemp != null) {\r\n\t\t\tif ((minTemp < 0.) || (minTemp > 1.)) {\r\n\t\t\t\tthrow new IllegalArgumentException(\"Minimum temperature must be between 0. and 1.\");\r\n\t\t\t}\r\n\t\t\tthis.minTemp = minTemp;\r\n\t\t} else {\r\n\t\t\tthis.minTemp = DEFAULT_MIN_TEMP;\r\n\t\t}\r\n\t\tif (acceptanceProbability != null) {\r\n\t\t\tthis.acceptanceProbability = acceptanceProbability;\r\n\t\t} else {\r\n\t\t\tthis.acceptanceProbability = new AcceptanceProbability() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic Double compute(Double oldScore, Double newScore, Double temp) {\r\n\t\t\t\t\treturn (newScore < oldScore ? 1 : Math.exp((oldScore - newScore) / temp));\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t}\r\n\t\tif (successorFinder != null) {\r\n\t\t\tthis.successorFinder = successorFinder;\r\n\t\t} else {\r\n\t\t\t// default implementation of the successor: picks up a successor\r\n\t\t\t// randomly\r\n\t\t\tthis.successorFinder = new SuccessorFinder<A, S, N>() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic N estimate(N node, NodeExpander<A, S, N> nodeExpander) {\r\n\t\t\t\t\tList<N> successors = new ArrayList<>();\r\n\t\t\t\t\t// find a random successor\r\n\t\t\t\t\tfor (N successor : nodeExpander.expand(node)) {\r\n\t\t\t\t\t\tsuccessors.add(successor);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tRandom randIndGen = new Random();\r\n\t\t\t\t\treturn successors.get(Math.abs(randIndGen.nextInt()) % successors.size());\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic ASIterator iterator() {\r\n\t\t// TODO Auto-generated method stub\r\n\t\treturn new ASIterator();\r\n\t}\r\n\r\n\tpublic class ASIterator implements Iterator<N> {\r\n\r\n\t\tprivate Queue<N> queue = new LinkedList<N>();\r\n\t\tprivate Double bestScore = null;\r\n\t\tprivate Double curTemp = START_TEMP;\r\n\r\n\t\tprivate ASIterator() {\r\n\t\t\tbestScore = initialNode.getEstimation();\r\n\t\t\tqueue.add(initialNode);\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic boolean hasNext() {\r\n\t\t\treturn !queue.isEmpty();\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic N next() {\r\n\t\t\tN currentNode = this.queue.poll();\r\n\t\t\tif (curTemp > minTemp) {\r\n\t\t\t\tN newNode = null;\r\n\t\t\t\t// we add a loop to increase the effect of a change of alpha.\r\n\t\t\t\tfor (int i = 0; i < 100; i++) {\r\n\t\t\t\t\tN randSuccessor = successorFinder.estimate(currentNode, nodeExpander);\r\n\t\t\t\t\tDouble score = randSuccessor.getScore();\r\n\t\t\t\t\tif (acceptanceProbability.compute(bestScore, score, curTemp) > Math.random()) {\r\n\t\t\t\t\t\tnewNode = randSuccessor;\r\n\t\t\t\t\t\tbestScore = score;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (newNode != null) {\r\n\t\t\t\t\tqueue.add(newNode);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tqueue.add(currentNode);\r\n\t\t\t\t}\r\n\t\t\t\tcurTemp *= alpha;\r\n\t\t\t}\r\n\t\t\treturn currentNode;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void remove() {\r\n\t\t\tthrow new UnsupportedOperationException();\r\n\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Interface to compute the acceptance probability. If the new score is less\r\n\t * than the old score, 1 will be returned so that the node is selected.\r\n\t * Otherwise, we compute a probability that will decrease when the newScore\r\n\t * or the temperature increase.\r\n\t * \r\n\t */\r\n\r\n\tpublic interface AcceptanceProbability {\r\n\t\tDouble compute(Double oldScore, Double newScore, Double temp);\r\n\t}\r\n\r\n\t/**\r\n\t * Interface to find the successor of a node.\r\n\t *\r\n\t * @param <N>\r\n\t */\r\n\tpublic interface SuccessorFinder<A, S, N extends Node<A, S, N>> {\r\n\t\t/**\r\n\t\t * @param Node\r\n\t\t * @return the successor of a node.\r\n\t\t */\r\n\t\tN estimate(N node, NodeExpander<A, S, N> nodeExpander);\r\n\t}\r\n}\r\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/localsearch/HillClimbing.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.algorithm.localsearch;\n\n\n\n\nimport es.usc.citius.hipster.algorithm.Algorithm;\nimport es.usc.citius.hipster.model.HeuristicNode;\nimport es.usc.citius.hipster.model.function.NodeExpander;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n/**\n * Implementation of the Hill Climbing algorithm. This is a local search algorithm which starts the exploration\n * of the state space in a random point, and then tries to improve the solution varying a single element of it.\n * This process is repeated iteratively until no further improvements are produced in the solution state.\n *\n * This algorithm performs well finding local optimums, but there is no guarantee to find the best possible solution\n * in the state space. If the state space has a convex cost function then this algoritm is guaranteed to be optimal,\n * but only in that case.\n *\n * Enforced hill climbing uses a BFS search to deal with local optimums, increasing the number of explored states\n * when the neighborhood of a state does not improve the solution.\n *\n * You can find a more detailed description of the algorithm <a href=\"en.wikipedia.org/wiki/Hill_climbing\">in Wikipedia</a>\n * and the book <a href=\"http://aima.cs.berkeley.edu/\">Artificial Intelligence: A Modern Approach</a>\n *\n * @param <A> class defining the action\n * @param <S> class defining the state\n * @param <C> class defining the cost, must implement {@link java.lang.Comparable}\n * @param <N> type of the nodes\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class HillClimbing<A,S,C extends Comparable<C>,N extends HeuristicNode<A,S,C,N>> extends Algorithm<A,S,N> {\n\n    private N initialNode;\n    private NodeExpander<A,S,N> nodeExpander;\n    private boolean enforced;\n\n    public HillClimbing(N initialNode, NodeExpander<A, S, N> nodeExpander) {\n        this(initialNode, nodeExpander, false);\n    }\n\n    /**\n     * Creates a new hill climbing algorithm with an initial node, a node expander and the boolean flag to\n     * use or not enforced hill climbing.\n     *\n     * @param initialNode initial node of the search\n     * @param nodeExpander component which creates new nodes from a current one\n     * @param enforcedHillClimbing flag to use enforced hill climbing\n     */\n    public HillClimbing(N initialNode, NodeExpander<A, S, N> nodeExpander, boolean enforcedHillClimbing) {\n        this.initialNode = initialNode;\n        this.nodeExpander = nodeExpander;\n        this.enforced = enforcedHillClimbing;\n    }\n\n    public class EHCIterator implements Iterator<N> {\n        private Queue<N> queue = new LinkedList<N>();\n        private C bestScore = null;\n\n        private EHCIterator() {\n            bestScore = initialNode.getEstimation();\n            queue.add(initialNode);\n        }\n\n        @Override\n        public boolean hasNext() {\n            return !queue.isEmpty();\n        }\n\n        @Override\n        public N next() {\n            N current = this.queue.poll();\n            N bestNode = null;\n            // Generate successors\n            for(N successor : nodeExpander.expand(current)){\n                // Is this successor better? (has lower score?)\n                // Hill climbing, just select the best node\n                if (enforced){\n                    C score = successor.getScore();\n                    if (score.compareTo(bestScore) < 0){\n                        bestScore = score;\n                        this.queue.clear();\n                        this.queue.add(successor);\n                        break;\n                    }\n                } else {\n                    if (bestNode == null) bestNode = successor;\n                    if (successor.compareTo(bestNode) < 0){\n                        bestNode = successor;\n                    }\n                }\n\n                if (enforced){\n                    // Add the successor to the queue to perform BFS search\n                    // (enforced hill climbing)\n                    this.queue.add(successor);\n                }\n            }\n            // After exploring all successors, only add the best successor\n            // to the queue (normal hill climbing)\n            if (!enforced) this.queue.add(bestNode);\n            // Return the current expanded node\n            return current;\n        }\n\n        @Override\n        public void remove() {\n            throw new UnsupportedOperationException();\n        }\n\n        /**\n         * @return queue of the next nodes to be explored\n         */\n        public Queue<N> getQueue() {\n            return queue;\n        }\n\n        /**\n         * @param queue new queue of nodes to be used by the algorithm\n         */\n        public void setQueue(Queue<N> queue) {\n            this.queue = queue;\n        }\n\n        /**\n         * @return best score found by the algorithm at the current iteration\n         */\n        public C getBestScore() {\n            return bestScore;\n        }\n\n        /**\n         * @param bestScore new best score found\n         */\n        public void setBestScore(C bestScore) {\n            this.bestScore = bestScore;\n        }\n    }\n\n\n    @Override\n    public EHCIterator iterator() {\n        return new EHCIterator();\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/localsearch/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Implementation of local search algorithms (such as hill climbing).\n */\npackage es.usc.citius.hipster.algorithm.localsearch;"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/algorithm/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Implementation of the different algorithms included in the library. Use the\n * class {@link es.usc.citius.hipster.algorithm.Hipster} to create algorithms in an easy way.\n */\npackage es.usc.citius.hipster.algorithm;"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/DirectedEdge.java",
    "content": "package es.usc.citius.hipster.graph;\n\npublic class DirectedEdge<V,E> implements GraphEdge<V,E> {\n\n    private Pair<V> vertices;\n    private E value;\n\n    public DirectedEdge(V vertex1, V vertex2, E value) {\n        this.vertices = new Pair<V>(vertex1, vertex2);\n        this.value = value;\n    }\n\n    @Override\n    public V getVertex1() {\n        return vertices.getE1();\n    }\n\n    @Override\n    public V getVertex2() {\n        return vertices.getE2();\n    }\n\n    @Override\n    public E getEdgeValue() {\n        return value;\n    }\n\n    @Override\n    public Type getType() {\n        return Type.DIRECTED;\n    }\n\n    @Override\n    public boolean equals(Object o) {\n        if (this == o) return true;\n        if (o == null || getClass() != o.getClass()) return false;\n\n        DirectedEdge<?, ?> that = (DirectedEdge<?, ?>) o;\n\n        if (!vertices.equals(that.vertices)) return false;\n        return !(value != null ? !value.equals(that.value) : that.value != null);\n\n    }\n\n    @Override\n    public int hashCode() {\n        int result = vertices.hashCode();\n        result = 31 * result + (value != null ? value.hashCode() : 0);\n        return result;\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/GraphBuilder.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.graph;\n\nimport java.util.LinkedList;\nimport java.util.List;\n\n/**\n * <p>Graph builder assistant to create a Hipster graph. Usage example:</p>\n * <pre class=\"prettyprint\">\n * {@code\n * HipsterGraph<String,Double> =\n * GraphBuilder.<String,Double>create()\n * .connect(\"A\").to(\"B\").withEdge(4d)\n * .connect(\"A\").to(\"C\").withEdge(2d)\n * .connect(\"B\").to(\"C\").withEdge(5d)\n * .createDirectedGraph();\n * }\n * </pre>\n */\npublic class GraphBuilder<V, E> {\n\n    private class Connection {\n        private V vertex1;\n        private V vertex2;\n        private E edge;\n\n        private Connection(V vertex1, V vertex2, E edge) {\n            this.vertex1 = vertex1;\n            this.vertex2 = vertex2;\n            this.edge = edge;\n        }\n\n        private Connection(V vertex1, V vertex2) {\n            this.vertex1 = vertex1;\n            this.vertex2 = vertex2;\n            this.edge = (E) new Object();\n        }\n\n        public V getVertex1() {\n            return vertex1;\n        }\n\n        public void setVertex1(V vertex1) {\n            this.vertex1 = vertex1;\n        }\n\n        public V getVertex2() {\n            return vertex2;\n        }\n\n        public void setVertex2(V vertex2) {\n            this.vertex2 = vertex2;\n        }\n\n        public E getEdge() {\n            return edge;\n        }\n\n        public void setEdge(E edge) {\n            this.edge = edge;\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            if (this == o) return true;\n            if (o == null || getClass() != o.getClass()) return false;\n\n            Connection that = (Connection) o;\n\n            if (!vertex1.equals(that.vertex1)) return false;\n            return vertex2.equals(that.vertex2);\n\n        }\n    }\n\n    private List<Connection> connections = new LinkedList<Connection>();\n\n    private GraphBuilder() {}\n\n    public static <V, E> GraphBuilder<V,E> create() {\n        return new GraphBuilder<V, E>();\n    }\n\n    public Vertex1 connect(V vertex) {\n        return new Vertex1(vertex);\n    }\n\n    public GraphBuilder<V, E> connect(V vertex1, V vertex2) {\n        Vertex1 vertex = new Vertex1(vertex1);\n        vertex.to(vertex2);\n        return this;\n    }\n\n    public HipsterDirectedGraph<V,E> createDirectedGraph() {\n        HashBasedHipsterDirectedGraph<V, E> graph = HashBasedHipsterDirectedGraph.create();\n        for (Connection c : connections) {\n            graph.add(c.vertex1);\n            graph.add(c.vertex2);\n            graph.connect(c.vertex1, c.vertex2, c.edge);\n        }\n        return graph;\n    }\n\n    public HipsterGraph<V,E> createUndirectedGraph() {\n        HashBasedHipsterGraph<V, E> graph = HashBasedHipsterGraph.create();\n        for (Connection c : connections) {\n            graph.add(c.vertex1);\n            graph.add(c.vertex2);\n            graph.connect(c.vertex1, c.vertex2, c.edge);\n        }\n        return graph;\n    }\n\n    /**\n     * @see GraphBuilder#createDirectedGraph()\n     * @return type-erased directed graph\n     */\n    @Deprecated\n    public HipsterDirectedGraph buildDirectedGraph(){\n        return createDirectedGraph();\n    }\n\n    /**\n     * @see GraphBuilder#createUndirectedGraph()\n     * @return type-erased undirected graph\n     */\n    @Deprecated\n    public HipsterGraph buildUndirectedGraph(){\n        return createUndirectedGraph();\n    }\n\n\n    public final class Vertex1 {\n        V vertex1;\n\n        private Vertex1(V vertex) {\n            this.vertex1 = vertex;\n        }\n\n        public Vertex2 to(V vertex) {\n            return new Vertex2(vertex);\n        }\n\n        public class Vertex2 {\n            V vertex2;\n\n            private Vertex2(V vertex) {\n                this.vertex2 = vertex;\n                connections.add(new Connection(vertex1, vertex2));\n            }\n\n            public GraphBuilder<V, E> withEdge(E edge) {\n                Connection connection = new Connection(vertex1, vertex2);\n                int connectionIndex = connections.indexOf(connection);\n                if(connectionIndex != -1 ) {\n                    connections.get(connectionIndex).setEdge(edge);\n                } else {\n                    connection.setEdge(edge);\n                    connections.add(connection);\n                }\n                return GraphBuilder.this;\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/GraphEdge.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.graph;\n\n\n/**\n * Hipster graph edge implementation to represent edges (or arcs) of a directed or\n * undirected graph.\n *\n * @param <V> vertex type.\n * @param <E> edge type.\n */\npublic interface GraphEdge<V,E> {\n    enum Type { DIRECTED, UNDIRECTED }\n\n    V getVertex1();\n    V getVertex2();\n    E getEdgeValue();\n    Type getType();\n\n//    @Override\n//    public String toString() {\n//        return getVertex1() + \" ---(\" + edgeValue + \")---\" + (isDirected() ? \"> \" : \" \") + getVertex2();\n//    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/GraphSearchProblem.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.graph;\n\n\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.CostFunction;\nimport es.usc.citius.hipster.model.function.HeuristicFunction;\nimport es.usc.citius.hipster.model.function.TransitionFunction;\nimport es.usc.citius.hipster.model.function.impl.BinaryOperation;\nimport es.usc.citius.hipster.model.function.impl.ScalarOperation;\nimport es.usc.citius.hipster.model.impl.UnweightedNode;\nimport es.usc.citius.hipster.model.impl.WeightedNode;\nimport es.usc.citius.hipster.model.problem.ProblemBuilder;\nimport es.usc.citius.hipster.model.problem.SearchComponents;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\nimport es.usc.citius.hipster.util.Function;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\n/**\n * Builder to generate a {@link es.usc.citius.hipster.model.problem.SearchProblem} but using\n * a HipsterGraph.\n * \n * @author Pablo Rodríguez Mier\n */\npublic final class GraphSearchProblem {\n\n    public static <V> FromVertex<V> startingFrom(V vertex) {\n        return new FromVertex<V>(vertex);\n    }\n\n    public static class FromVertex<V> {\n        private V fromVertex;\n        private V toVertex;\n\n        public FromVertex<V> goalAt(V vertex) {\n            this.toVertex = vertex;\n            return this;\n        }\n\n        private FromVertex(V fromVertex) {\n            this.fromVertex = fromVertex;\n        }\n\n        public <E> CostType<E> in(final HipsterGraph<V, E> graph) {\n            TransitionFunction<E, V> tf;\n            if (graph instanceof HipsterDirectedGraph) {\n                final HipsterDirectedGraph<V, E> dg = (HipsterDirectedGraph<V, E>) graph;\n                tf = new TransitionFunction<E, V>() {\n                    @Override\n                    public Iterable<Transition<E, V>> transitionsFrom(final V state) {\n                        ArrayList<Transition<E, V>> transitions = new ArrayList<Transition<E, V>>();\n                        for(GraphEdge<V, E> edge : dg.outgoingEdgesOf(state)){\n                            transitions.add(Transition.create(state, edge.getEdgeValue(), edge.getVertex2()));\n                        }\n                        return transitions;\n                    }\n                };\n            } else {\n                tf = new TransitionFunction<E, V>() {\n                    @Override\n                    public Iterable<Transition<E, V>> transitionsFrom(final V state) {\n                        ArrayList<Transition<E, V>> transitions = new ArrayList<Transition<E, V>>();\n                        for(GraphEdge<V, E> edge : graph.edgesOf(state)){\n                            V oppositeVertex = edge.getVertex1().equals(state) ? edge.getVertex2() : edge.getVertex1();\n                            transitions.add(Transition.create(state, edge.getEdgeValue(), oppositeVertex));\n                        }\n                        return transitions;\n                    }\n                };\n            }\n            return new CostType<E>(tf);\n        }\n\n        public <E> CostType<E> inGraphWithLexicographicalOrder(final HipsterGraph<V, E> graph) {\n\n            class ComparatorTransitions implements Comparator<Transition<E, V>>{\n\n                @Override\n                public int compare(Transition<E, V> o1, Transition<E, V> o2) {\n                    return o1.getState().toString().compareTo(o2.getState().toString());\n                }\n            }\n\n            TransitionFunction<E, V> tf;\n            if (graph instanceof HipsterDirectedGraph) {\n                final HipsterDirectedGraph<V, E> dg = (HipsterDirectedGraph<V, E>) graph;\n                tf = new TransitionFunction<E, V>() {\n                    @Override\n                    public Iterable<Transition<E, V>> transitionsFrom(final V state) {\n                        ArrayList<Transition<E, V>> transitions = new ArrayList<Transition<E, V>>();\n                        for(GraphEdge<V, E> edge : dg.outgoingEdgesOf(state)){\n                            transitions.add(Transition.create(state, edge.getEdgeValue(), edge.getVertex2()));\n                        }\n                        Collections.sort(transitions, new ComparatorTransitions());\n                        return transitions;\n                    }\n                };\n            } else {\n                tf = new TransitionFunction<E, V>() {\n                    @Override\n                    public Iterable<Transition<E, V>> transitionsFrom(final V state) {\n                        ArrayList<Transition<E, V>> transitions = new ArrayList<Transition<E, V>>();\n                        for(GraphEdge<V, E> edge : graph.edgesOf(state)){\n                            V oppositeVertex = edge.getVertex1().equals(state) ? edge.getVertex2() : edge.getVertex1();\n                            transitions.add(Transition.create(state, edge.getEdgeValue(), oppositeVertex));\n                        }\n                        Collections.sort(transitions, new ComparatorTransitions());\n                        return transitions;\n                    }\n                };\n            }\n            return new CostType<E>(tf);\n        }\n\n        public class CostType<E> {\n            private TransitionFunction<E, V> tf;\n\n            private CostType(TransitionFunction<E, V> tf) {\n                this.tf = tf;\n            }\n\n            public HeuristicType<Double> takeCostsFromEdges() {\n                // Try to automatically obtain weights from edges\n                CostFunction<E, V, Double> cf = new CostFunction<E, V, Double>() {\n                    @Override\n                    public Double evaluate(Transition<E, V> transition) {\n                        E action = transition.getAction();\n\n                        if (action instanceof Number) {\n                            // Try to cast to number automatically\n                            return ((Number) action).doubleValue();\n                        } else if (action instanceof String){\n                            // Try to parse to a number\n                            try {\n                                return Double.parseDouble((String) action);\n                            } catch (NumberFormatException e){\n                                throw new IllegalArgumentException(\"Exception ocurred when trying\" +\n                                        \"to cast \" + action + \" to a number. Use the method \" +\n                                        \"extractCostsFromEdges to define a custom evaluation strategy.\", e);\n                            }\n                        } else {\n                            // TODO: Throw exception instead?\n                            // Assume uniform costs.\n                            return 1d;\n                            /*\n                            throw new ClassCastException(\"The defined graph uses edges of type \" +\n                                    action.getClass() + \" instead of Number. For custom edge costs\" +\n                                    \" please use withGenericCosts method.\");*/\n                        }\n\n                    }\n                };\n                return new HeuristicType<Double>(cf, BinaryOperation.doubleAdditionOp()).useScaleAlgebra(ScalarOperation.doubleMultiplicationOp());\n            }\n\n            public HeuristicType<Double> extractCostFromEdges(final Function<E, Double> extractor) {\n                CostFunction<E, V, Double> cf = new CostFunction<E, V, Double>() {\n                    @Override\n                    public Double evaluate(Transition<E, V> transition) {\n                        return extractor.apply(transition.getAction());\n                    }\n                };\n                return new HeuristicType<Double>(cf, BinaryOperation.doubleAdditionOp()).useScaleAlgebra(ScalarOperation.doubleMultiplicationOp());\n            }\n\n            public <C extends Comparable<C>> HeuristicType<C> useGenericCosts(BinaryOperation<C> costAlgebra) {\n                CostFunction<E, V, C> cf = new CostFunction<E, V, C>() {\n                    @Override\n                    public C evaluate(Transition<E, V> transition) {\n                        return (C) transition.getAction();\n                    }\n                };\n                return new HeuristicType<C>(cf, costAlgebra);\n            }\n\n            public SearchProblem<E, V, UnweightedNode<E, V>> build() {\n                return ProblemBuilder.create()\n                        .initialState(fromVertex, toVertex)\n                        .defineProblemWithExplicitActions()\n                        .useTransitionFunction(tf)\n                        .build();\n            }\n\n            public class HeuristicType<C extends Comparable<C>> {\n                private CostFunction<E, V, C> cf;\n                private BinaryOperation<C> costAlgebra;\n                private ScalarOperation<C> scaleAlgebra;\n\n                private HeuristicType(CostFunction<E, V, C> cf, BinaryOperation<C> costAlgebra) {\n                    this.cf = cf;\n                    this.costAlgebra = costAlgebra;\n                }\n\n                public HeuristicType<C> useScaleAlgebra(ScalarOperation<C> scaleAlgebra){\n                    this.scaleAlgebra = scaleAlgebra;\n                    return this;\n                }\n\n                public Final useHeuristicFunction(HeuristicFunction<V, C> hf) {\n                    return new Final(hf);\n                }\n\n                public SearchProblem<E, V, WeightedNode<E, V, C>> build() {\n                    return ProblemBuilder.create()\n                            .initialState(fromVertex)\n                            .defineProblemWithExplicitActions()\n                            .useTransitionFunction(tf)\n                            .useGenericCostFunction(cf, costAlgebra)\n                            .build();\n                }\n\n                public class Final {\n                    private HeuristicFunction<V, C> hf;\n\n                    private Final(HeuristicFunction<V, C> hf) {\n                        this.hf = hf;\n                    }\n\n                    public SearchComponents<E, V, C> components(){\n                        return new SearchComponents<E, V, C>(fromVertex, toVertex, cf, hf, tf, tf, costAlgebra, scaleAlgebra);\n                    }\n\n                    public SearchProblem<E, V, WeightedNode<E, V, C>> build() {\n                        return ProblemBuilder.create()\n                                .initialState(fromVertex)\n                                .defineProblemWithExplicitActions()\n                                .useTransitionFunction(tf)\n                                .useGenericCostFunction(cf, costAlgebra)\n                                .useHeuristicFunction(hf)\n                                .build();\n                    }\n                }\n            }\n        }\n\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/HashBasedHipsterDirectedGraph.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.graph;\n\nimport es.usc.citius.hipster.util.Function;\nimport es.usc.citius.hipster.util.F;\n\nimport java.util.*;\n\n/**\n * Implementation of a HipsterDirectedGraph using a Guava Hash Table.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class HashBasedHipsterDirectedGraph<V, E> extends HashBasedHipsterGraph<V, E> implements HipsterMutableGraph<V, E>, HipsterDirectedGraph<V, E> {\n\n\n    @Override\n    public GraphEdge<V, E> buildEdge(V v1, V v2, E value) {\n        return new DirectedEdge<V, E>(v1, v2, value);\n    }\n\n    @Override\n    public Iterable<GraphEdge<V, E>> outgoingEdgesOf(final V vertex) {\n        return F.filter(edgesOf(vertex), new Function<GraphEdge<V, E>, Boolean>() {\n            @Override\n            public Boolean apply(GraphEdge<V, E> edge) {\n                return edge.getVertex1().equals(vertex);\n            }\n        });\n    }\n\n    @Override\n    public Iterable<GraphEdge<V, E>> incomingEdgesOf(final V vertex) {\n        return F.filter(edgesOf(vertex), new Function<GraphEdge<V, E>, Boolean>() {\n            @Override\n            public Boolean apply(GraphEdge<V, E> edge) {\n                return edge.getVertex2().equals(vertex);\n            }\n        });\n    }\n\n    @Override\n    public Iterable<GraphEdge<V, E>> edges() {\n        // TODO: [java-8-migration] use stream filter\n        return F.map(\n                F.filter(HashBasedHipsterDirectedGraph.super.vedges(),\n                        new Function<Map.Entry<V, GraphEdge<V, E>>, Boolean>() {\n                            @Override\n                            public Boolean apply(Map.Entry<V, GraphEdge<V, E>> input) {\n                                return input.getKey().equals(input.getValue().getVertex1());\n                            }\n                        }),\n                new Function<Map.Entry<V, GraphEdge<V, E>>, GraphEdge<V, E>>() {\n                    @Override\n                    public GraphEdge<V, E> apply(Map.Entry<V, GraphEdge<V, E>> input) {\n                        return input.getValue();\n                    }\n                });\n    }\n\n    public static <V, E> HashBasedHipsterDirectedGraph<V, E> create() {\n        return new HashBasedHipsterDirectedGraph<V, E>();\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/HashBasedHipsterGraph.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.graph;\n\n\nimport es.usc.citius.hipster.util.F;\nimport es.usc.citius.hipster.util.Function;\n\nimport java.util.*;\n\n/**\n * Lightweight implementation of an in-memory, mutable graph backed to a {@link HashMap} where\n * keys are vertices and edges are {@link GraphEdge}s\n */\npublic class HashBasedHipsterGraph<V,E> implements HipsterMutableGraph<V,E> {\n    protected HashMap<V, Set<GraphEdge<V, E>>> connected;\n\n    public HashBasedHipsterGraph(){\n        this.connected = new HashMap<V, Set<GraphEdge<V, E>>>();\n    }\n\n    @Override\n    public boolean add(V v){\n        //add a new entry to the hash map if it does not exist\n        if(!connected.containsKey(v)){\n            connected.put(v, new LinkedHashSet<GraphEdge<V, E>>());\n            return true;\n        }\n        return false;\n    }\n\n    @Override\n    public Set<V> add(V... vertices) {\n        Set<V> added = new HashSet<V>();\n        for(V v : vertices){\n            if (add(v)) added.add(v);\n        }\n        return added;\n    }\n\n    @Override\n    public boolean remove(V v){\n        // Remove all edges related to v\n        Set<GraphEdge<V, E>> edges = this.connected.get(v);\n        if (edges == null) return false;\n\n        for(Iterator<GraphEdge<V,E>> it = edges.iterator(); it.hasNext(); ){\n            // Remove the edge in the list of the selected vertex\n            GraphEdge<V,E> edge = it.next();\n            it.remove();\n\n            V v2 = edge.getVertex1().equals(v) ? edge.getVertex2() : edge.getVertex1();\n            for(Iterator<GraphEdge<V,E>> it2 = this.connected.get(v2).iterator(); it2.hasNext();){\n                GraphEdge<V,E> edge2 = it2.next();\n                if (edge2.getVertex1().equals(v) || edge2.getVertex2().equals(v)){\n                    it2.remove();\n                }\n            }\n        }\n        this.connected.remove(v);\n        return true;\n    }\n\n    @Override\n    public Set<V> remove(V... vertices) {\n        Set<V> removed = new HashSet<V>();\n        for(V v : vertices){\n            if (remove(v)) removed.add(v);\n        }\n        return removed;\n    }\n\n    @Override\n    public GraphEdge<V,E> connect(V v1, V v2, E value){\n        // Check non-null arguments\n        if(v1 == null || v2 == null) throw new IllegalArgumentException(\"Invalid vertices. A vertex cannot be null\");\n        // Ensure that the vertices are in the graph\n        if (!connected.containsKey(v1)) throw new IllegalArgumentException(v1 + \" is not a vertex of the graph\");\n        if (!connected.containsKey(v2)) throw new IllegalArgumentException(v2 + \" is not a vertex of the graph\");\n        GraphEdge<V,E> edge = buildEdge(v1, v2, value);\n        // Associate the vertices with their edge\n        connected.get(v1).add(edge);\n        connected.get(v2).add(edge);\n        return edge;\n    }\n\n    public GraphEdge<V,E> buildEdge(V v1, V v2, E value){\n        return new UndirectedEdge<V, E>(v1, v2, value);\n    }\n\n    private Map.Entry<V, GraphEdge<V,E>> createEntry(final V vertex, final GraphEdge<V,E> edge){\n        return new Map.Entry<V, GraphEdge<V, E>>() {\n            @Override\n            public V getKey() {\n                return vertex;\n            }\n\n            @Override\n            public GraphEdge<V, E> getValue() {\n                return edge;\n            }\n\n            @Override\n            public GraphEdge<V, E> setValue(GraphEdge<V, E> value) {\n                throw new UnsupportedOperationException();\n            }\n        };\n    }\n\n    protected Iterable<Map.Entry<V, GraphEdge<V,E>>> vedges(){\n        // TODO: [java-8-migration]\n        return F.flatMap(connected.entrySet(), new Function<Map.Entry<V, Set<GraphEdge<V, E>>>, Iterable<Map.Entry<V, GraphEdge<V, E>>>>() {\n            @Override\n            public Iterable<Map.Entry<V, GraphEdge<V, E>>> apply(final Map.Entry<V, Set<GraphEdge<V, E>>> entry) {\n                return F.map(entry.getValue(), new Function<GraphEdge<V, E>, Map.Entry<V, GraphEdge<V, E>>>() {\n                    @Override\n                    public Map.Entry<V, GraphEdge<V, E>> apply(GraphEdge<V, E> input) {\n                        return createEntry(entry.getKey(), input);\n                    }\n                });\n            }\n        });\n    }\n    /**\n     * Returns a list of the edges in the graph.\n     * @return edges of the graph.\n     */\n    @Override\n    public Iterable<GraphEdge<V, E>> edges() {\n        return F.map(vedges(), new Function<Map.Entry<V, GraphEdge<V, E>>, GraphEdge<V, E>>() {\n            @Override\n            public GraphEdge<V, E> apply(Map.Entry<V, GraphEdge<V, E>> entry) {\n                return entry.getValue();\n            }\n        });\n    }\n\n    /**\n     * Returns the vertices of the graph. Any changes in the\n     * returned iterator affect the underlying graph structure.\n     * @return iterator with the vertices of the graph\n     */\n    @Override\n    public Iterable<V> vertices() {\n        return connected.keySet();\n    }\n\n    @Override\n    public Iterable<GraphEdge<V, E>> edgesOf(V vertex) {\n        Set<GraphEdge<V, E>> set = connected.get(vertex);\n        if (set == null) set = Collections.emptySet();\n        return set;\n    }\n\n    /**\n     * Returns the internal HashMap representation of the graph\n     * @return HashMap where keys are vertices and values a set with the connected edges\n     */\n    public HashMap<V, Set<GraphEdge<V, E>>> getConnected() {\n        return connected;\n    }\n\n    public void setConnected(HashMap<V, Set<GraphEdge<V, E>>> connected) {\n        this.connected = connected;\n    }\n\n    public static <V,E> HashBasedHipsterGraph<V, E> create() {\n        return new HashBasedHipsterGraph<V, E>();\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/HipsterDirectedGraph.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.graph;\n\n/**\n * A simple representation of a directed graph with two methods for\n * retrieving the outgoing edges and the incoming edges for a vertex.\n * @param <V> vertex type.\n * @param <E> edge type.\n */\npublic interface HipsterDirectedGraph<V,E> extends HipsterGraph<V,E> {\n    Iterable<GraphEdge<V,E>> outgoingEdgesOf(V vertex);\n    Iterable<GraphEdge<V,E>> incomingEdgesOf(V vertex);\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/HipsterGraph.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.graph;\n\n/**\n * Basic definition of the read-only methods for a graph in terms of edges and vertices.\n * @param <V> vertex type.\n * @param <E> edge type.\n */\npublic interface HipsterGraph<V,E> {\n    /**\n     * Returns an {@link Iterable} of the edges in the graph.\n     * @return an iterable of {@link GraphEdge} in the graph\n     */\n    Iterable<GraphEdge<V,E>> edges();\n\n    /**\n     * Returns an iterable of the vertices in the graph.\n     * @return iterable of vertices\n     */\n    Iterable<V> vertices();\n\n    /**\n     * Return all the edges that are connected with the given vertex.\n     * @param vertex vertex to be queried\n     * @return an iterable of {@link GraphEdge}s connected to the vertex\n     */\n    Iterable<GraphEdge<V,E>> edgesOf(V vertex);\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/HipsterMutableGraph.java",
    "content": "package es.usc.citius.hipster.graph;\n\n\nimport java.util.Set;\n\n/**\n * Interface that defines the basic mutable methods to manipulate graphs\n * @param <V> vertex type.\n * @param <E> edge type.\n */\npublic interface HipsterMutableGraph<V,E> extends HipsterGraph<V,E> {\n    /**\n     * Adds a new vertex to the graph.\n     * @param vertex vertex to be added\n     * @return true if the vertex was added to the graph, false if the vertex is already present\n     */\n    boolean add(V vertex);\n\n    /**\n     * Adds multiple vertices to the graph.\n     * @param vertices vertices to be added\n     * @return set with the vertices added\n     */\n    Set<V> add(V... vertices);\n\n    /**\n     * Removes the vertex from the graph\n     * @param vertex vertex to be removed\n     * @return true if the vertex was removed, false if the vertex is not present\n     */\n    boolean remove(V vertex);\n\n    /**\n     * Removes multiple vertices from the graph\n     * @param vertices vertices to be removed\n     * @return set of vertices removed from the graph\n     */\n    Set<V> remove(V... vertices);\n\n    /**\n     * Connects to vertices of the graph through an edge\n     * @param vertex1 source vertex\n     * @param vertex2 target (destination) vertex\n     * @param edgeValue value of the edge connecting vertex1 and vertex2\n     * @return a new {@link GraphEdge} connecting both vertices\n     */\n    GraphEdge<V,E> connect(V vertex1, V vertex2, E edgeValue);\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/Pair.java",
    "content": "package es.usc.citius.hipster.graph;\n\n\npublic class Pair<E> {\n    private E e1, e2;\n\n    public Pair(E e1, E e2) {\n        if (e1 == null) throw new IllegalArgumentException(\"First element cannot be null\");\n        this.e1 = e1;\n        if (e2 == null) throw new IllegalArgumentException(\"Second element cannot be null\");\n        this.e2 = e2;\n    }\n\n    public E _1() {\n        return e1;\n    }\n\n    public E _2() {\n        return e2;\n    }\n\n    public E getE1() {\n        return e1;\n    }\n\n    public void setE1(E e1) {\n        this.e1 = e1;\n    }\n\n    public E getE2() {\n        return e2;\n    }\n\n    public void setE2(E e2) {\n        this.e2 = e2;\n    }\n\n    @Override\n    public boolean equals(Object o) {\n        if (this == o) return true;\n        if (o == null || getClass() != o.getClass()) return false;\n\n        Pair<?> pair = (Pair<?>) o;\n\n        if (!e1.equals(pair.e1)) return false;\n        return e2.equals(pair.e2);\n\n    }\n\n    @Override\n    public int hashCode() {\n        int result = e1.hashCode();\n        result = 31 * result + e2.hashCode();\n        return result;\n    }\n\n    @Override\n    public String toString() {\n        return \"(\" + e1 + \", \" + e2 + \")\";\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/UndirectedEdge.java",
    "content": "package es.usc.citius.hipster.graph;\n\n\npublic class UndirectedEdge<V,E> implements GraphEdge<V,E> {\n\n    private UnorderedPair<V> vertices;\n    private E value;\n\n    public UndirectedEdge(V vertex1, V vertex2, E value) {\n        this.vertices = new UnorderedPair<V>(vertex1, vertex2);\n        this.value = value;\n    }\n\n    @Override\n    public V getVertex1() {\n        return vertices.getE1();\n    }\n\n    @Override\n    public V getVertex2() {\n        return vertices.getE2();\n    }\n\n    @Override\n    public E getEdgeValue() {\n        return value;\n    }\n\n    @Override\n    public Type getType() {\n        return Type.UNDIRECTED;\n    }\n\n    @Override\n    public boolean equals(Object o) {\n        if (this == o) return true;\n        if (o == null || getClass() != o.getClass()) return false;\n\n        UndirectedEdge<?, ?> that = (UndirectedEdge<?, ?>) o;\n\n        if (!vertices.equals(that.vertices)) return false;\n        return !(value != null ? !value.equals(that.value) : that.value != null);\n\n    }\n\n    @Override\n    public int hashCode() {\n        int result = vertices.hashCode();\n        result = 31 * result + (value != null ? value.hashCode() : 0);\n        return result;\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/UniqueEdge.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.graph;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\n/**\n * Dumb class that can be used to generate unique edges for a graph with a value.\n * Do not use this for production code!\n * @param <V> edge value type\n *\n * @author Pablo Rodríguez Mier\n */\npublic class UniqueEdge<V> {\n    private V value;\n    private final String edgeId;\n    private static final AtomicInteger idGenerator = new AtomicInteger(0);\n\n    public UniqueEdge(V value) {\n        this.value = value;\n        this.edgeId = String.valueOf(idGenerator.getAndIncrement());\n    }\n\n    public V getValue() {\n        return value;\n    }\n\n    public void setValue(V value) {\n        this.value = value;\n    }\n\n    public String getEdgeId() {\n        return edgeId;\n    }\n\n    public static <V> UniqueEdge<V> create(V value){\n        return new UniqueEdge<V>(value);\n    }\n\n    @Override\n    public boolean equals(Object o) {\n        if (this == o) return true;\n        if (o == null || getClass() != o.getClass()) return false;\n\n        UniqueEdge that = (UniqueEdge) o;\n\n        if (!edgeId.equals(that.edgeId)) return false;\n        if (value != null ? !value.equals(that.value) : that.value != null) return false;\n\n        return true;\n    }\n\n    @Override\n    public int hashCode() {\n        int result = value != null ? value.hashCode() : 0;\n        result = 31 * result + edgeId.hashCode();\n        return result;\n    }\n\n    @Override\n    public String toString() {\n        return \"UniqueEdge{\" +\n                \"value=\" + value +\n                \", edgeId='\" + edgeId + '\\'' +\n                '}';\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/UnorderedPair.java",
    "content": "package es.usc.citius.hipster.graph;\n\npublic class UnorderedPair<E> {\n    private E e1, e2;\n\n    public UnorderedPair(E e1, E e2) {\n        if (e1 == null) throw new IllegalArgumentException(\"First element cannot be null\");\n        this.e1 = e1;\n        if (e2 == null) throw new IllegalArgumentException(\"Second element cannot be null\");\n        this.e2 = e2;\n    }\n\n    public boolean contains(Object vertex){\n        return e1.equals(vertex) || e2.equals(vertex);\n    }\n\n    public E getE1() {\n        return e1;\n    }\n\n    public void setE1(E e1) {\n        this.e1 = e1;\n    }\n\n    public E getE2() {\n        return e2;\n    }\n\n    public void setE2(E e2) {\n        this.e2 = e2;\n    }\n\n    @Override\n    public boolean equals(Object o) {\n        if (this == o) return true;\n        if (o == null || getClass() != o.getClass()) return false;\n\n        UnorderedPair<?> that = (UnorderedPair<?>) o;\n        return that.contains(e1) && that.contains(e2);\n    }\n\n    @Override\n    public int hashCode() {\n        return e1.hashCode() + e2.hashCode();\n    }\n\n    @Override\n    public String toString() {\n        return \"(\" + e1 + \", \" + e2 + \")\";\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/graph/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Lightweight graph interfaces and in-memory graph implementations.\n */\npackage es.usc.citius.hipster.graph;"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/ADStarNode.java",
    "content": "package es.usc.citius.hipster.model;\n\nimport es.usc.citius.hipster.model.function.ScalarFunction;\nimport es.usc.citius.hipster.model.function.impl.BinaryOperation;\n\n/**\n * Implementation of {@link es.usc.citius.hipster.model.Node} to be used with the AD* algorithm, implemented in\n * {@link es.usc.citius.hipster.algorithm.ADStarForward}. AD* nodes are formed by two cost elements, G and V,\n * and a {@link es.usc.citius.hipster.model.ADStarNode.Key} which is used to order the nodes by priority\n * in the queues of the algorithm. This implementation extends {@link es.usc.citius.hipster.model.HeuristicNode}.\n *\n * @param <A> type of the actions\n * @param <S> type of the state\n * @param <C> type of the cost (must extend {@link java.lang.Comparable})\n * @param <N> node type\n *\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic interface ADStarNode<A, S, C extends Comparable<C>, N extends ADStarNode<A,S,C,N>> extends HeuristicNode<A, S, C, N> {\n\n    /**\n     * @return G-cost of the node\n     */\n    public C getG();\n\n    /**\n     * @return V-cost (also RHS) of the node\n     */\n    public C getV();\n\n    /**\n     * @return determines if the nodes must be updated by a {@link es.usc.citius.hipster.model.function.impl.ADStarNodeUpdater}.\n     */\n    public boolean isDoUpdate();\n\n    /**\n     * @return determines if the node is in a consistent or inconsistent state based on the values of G and V\n     */\n    public boolean isConsistent();\n\n    /**\n     * @param g new value of G\n     */\n    public void setG(C g);\n\n    /**\n     * @param v new value of V\n     */\n    public void setV(C v);\n\n    /**\n     * @param update set a new value for the calculate flag of this node\n     */\n    public void setDoUpdate(boolean update);\n\n    /**\n     * @param key new key to compare the priority of the nodes\n     */\n    public void setKey(Key<C> key);\n\n    /**\n     * @return retrieves the current key of the node\n     */\n    public Key<C> getKey();\n\n    /**\n     * @param parent new parent of the node\n     */\n    public void setPreviousNode(N parent);\n\n    /**\n     * @param state state of this node\n     */\n    public void setState(S state);\n\n    /**\n     * @param action action between the parent and this node\n     */\n    public void setAction(A action);\n\n\n    /**\n     * Inner class defining the key of the node, which depends on the values of G and V. The\n     * key of the node is the comparison criterion for ADStarForward to order the open queue.\n     */\n    public static class Key<C extends Comparable<C>> implements Comparable<Key<C>> {\n\n        private C first;\n        private C second;\n\n        /**\n         * Constructor to calculate a the key to order the nodes in the Open\n         * queue.\n         *\n         * @param g g value of the node\n         * @param v v value of the node\n         * @param h value of the heuristic\n         * @param e inflation value\n         */\n        public Key(C g, C v, C h, double e, BinaryOperation<C> add, ScalarFunction<C> scale) {\n            calculate(g, v, h, e, add, scale);\n        }\n\n        /**\n         * Updates the value of the key. This is done for efficiency, to avoid\n         * creating new instances.\n         */\n        public void update(C g, C v, C h, double e, BinaryOperation<C> add, ScalarFunction<C> scale){\n            calculate(g, v, h, e, add, scale);\n        }\n\n        /**\n         * Updates the value of the key\n         */\n        private void calculate(C g, C v, C h, double e, BinaryOperation<C> add, ScalarFunction<C> scale){\n            if (v.compareTo(g) >= 0) {\n                this.first = add.apply(g, scale.scale(h, e)); //g + h*e\n                this.second = g;\n            } else {\n                this.first = add.apply(v, h); //v + h\n                this.second = v;\n            }\n        }\n\n        /**\n         * Instantiates a new Key given its first and second value instead of\n         * calculating them.\n         *\n         * @param first first cost value\n         * @param second second cost value\n         */\n        public Key(C first, C second){\n            this.first = first;\n            this.second = second;\n        }\n\n        /**\n         * Compares by the first value and, if equal, by the second one.\n         *\n         * @param o other Key object\n         * @return comparison result\n         */\n        public int compareTo(Key<C> o) {\n            int firstCompare = this.first.compareTo(o.first);\n            if (firstCompare == 0) {\n                return this.second.compareTo(o.second);\n            } else {\n                return firstCompare;\n            }\n        }\n\n        /**\n         * @return first value of the key\n         */\n        public C getFirst() {\n            return first;\n        }\n\n        /**\n         * @return second value of the key\n         */\n        public C getSecond() {\n            return second;\n        }\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/AbstractNode.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model;\n\n\nimport java.util.LinkedList;\nimport java.util.List;\n\n/**\n * Basic implementation of the interface {@link es.usc.citius.hipster.model.Node}. All implementations of\n * the interface may extend this class to reuse the implemented {@link #path()} method and\n * the getters.\n *\n * @param <A> type of the actions\n * @param <S> type of the state\n * @param <N> type of the node\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class AbstractNode<A,S,N extends AbstractNode<A,S,N>> implements Node<A,S,N> {\n    protected N previousNode;\n    protected S state;\n    protected A action;\n    protected int pathSize;\n\n    /**\n     * Generic constructor of nodes.\n     *\n     * @param previousNode parent node\n     * @param state current state\n     * @param action action between the previous node and the current state\n     */\n    public AbstractNode(N previousNode, S state, A action) {\n        this.previousNode = previousNode;\n        this.state = state;\n        this.action = action;\n        this.pathSize =  (previousNode != null) ? previousNode.pathSize + 1 : 1;\n    }\n\n    @Override\n    public List<N> path() {\n        LinkedList<N> path = new LinkedList<N>();\n        N currentNode = (N) this;\n        while(currentNode != null){\n            path.addFirst(currentNode);\n            currentNode = currentNode.previousNode;\n        }\n        return path;\n    }\n\n    @Override\n    public int pathSize() {\n        return pathSize;\n    }\n\n    @Override\n    public N previousNode() {\n        return this.previousNode;\n    }\n\n    @Override\n    public S state() {\n        return state;\n    }\n\n    @Override\n    public A action() {\n        return action;\n    }\n\n    @Override\n    public String toString() {\n        return \"Node{\" +\n                \"action=\" + action +\n                \", state=\" + this.state() +\n                '}';\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/CostNode.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model;\n\n/**\n * Defines a node which stores an attribute for the cost, extending\n * the interface of a basic node {@link es.usc.citius.hipster.model.Node}. The cost has\n * a generic definition but must be comparable. This type of node is used by algorithms\n * which store information about the cost from the cost but do not use a heuristic function\n * to estimate the cost to the goal.\n *\n * @param <A> type of the actions\n * @param <S> type of the state\n * @param <C> type of the cost (must extend {@link java.lang.Comparable})\n * @param <N> node type\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic interface CostNode<A,S,C extends Comparable<C>,N extends CostNode<A,S,C,N>> extends Node<A,S,N>, Comparable<N> {\n\n    /**\n     * @return the cost of this node\n     */\n    C getCost();\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/HeuristicNode.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model;\n\n/**\n * Type of node which stores an estimated (heuristic) cost to the goal, extending\n * the interface of a cost node {@link es.usc.citius.hipster.model.CostNode}. Cost and\n * heuristic are of the same type and must be comparable. This type of node is used by algorithms\n * which store information about the cost from the cost and use a heuristic function\n * to estimate the cost to the goal.\n *\n * @param <A> type of the actions\n * @param <S> type of the state\n * @param <C> type of the cost (must extend {@link java.lang.Comparable})\n * @param <N> node type\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic interface HeuristicNode<A,S,C extends Comparable<C>, N extends HeuristicNode<A,S,C,N>> extends CostNode<A,S,C,N> {\n\n    /**\n     * Retrieves the total cost (typically f = g + h) of this node,\n     * where g = {@link HeuristicNode#getCost()} and\n     * h = {@link HeuristicNode#getEstimation()}\n     *\n     * @return total cost (f function).\n     */\n    C getScore();\n\n    /**\n     * Return the estimated cost to goal state from the current state.\n     * @return cost estimation.\n     */\n    C getEstimation();\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/Node.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model;\n\nimport java.util.List;\n\n/**\n * A node encapsulates the information generated by the search algorithms during their execution. As different\n * type of algorithms exist (uninformed, informed, heuristic, anytime, etc.), different type of nodes\n * are required. This interface provide the skeleton for the node definition and the basic methods required\n * by all type of nodes.\n *\n * @param <A> type of the actions\n * @param <S> type of the state\n * @param <N> node type\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic interface Node<A,S,N extends Node<A,S,N>> {\n\n    /**\n     * Generates the ordered list of nodes with the path between the beginning state\n     * and the current node.\n     *\n     * @return ordered List the nodes of the path\n     */\n    List<N> path();\n\n    /**\n     * Returns the length of the path from the start to the current node. Note that pathSize() == path().size()\n     * but this method provides a fast way to obtain the length of the path without tracking back the nodes of the path.\n     * @return length of the path from the initial node to this node.\n     */\n    int pathSize();\n\n    /**\n     * Returns the previous node to the current.\n     *\n     * @return instance of {@link es.usc.citius.hipster.model.Node}\n     */\n    N previousNode();\n\n    /**\n     * State of the current node\n     * @return\n     */\n    S state();\n\n    /**\n     * Action of the node used to reach the state node\n     * @return\n     */\n    A action();\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/SimpleTransition.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model;\n\n\n/**\n * A SimpleTransition is just a transition without explicit actions {@code Transition<Void,S>}.\n *\n * @param <S> state type of the transition\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class SimpleTransition<S> extends Transition<Void, S> {\n\n    /**\n     * Instantiates a new transition only specifying the destination\n     * of the transition.\n     *\n     * @param state destination of the transition\n     */\n    public SimpleTransition(S state) {\n        super(null, state);\n    }\n\n    /**\n     * Instantiates a new transition specifying the origin and destination\n     * of the transition.\n     *\n     * @param fromState origin state of the transition\n     * @param toState destination state of the transition\n     */\n    public SimpleTransition(S fromState, S toState) {\n        super(fromState, null, toState);\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/Transition.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model;\n\n/**\n * Defines a transition between states. When two states are connected\n * a transition exists between them. An action may be specified\n * to be part of a transition, which is needed in some kind of problems\n * to evaluate their cost.\n *\n * When the problem does not involve actions, this class is used\n * as follows: {@code Transition<Void,S>}\n *\n * @param <A> type of the actions\n * @param <S> type of the state\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class Transition<A,S> {\n    // Source state (origin) of the transition\n    private S fromState;\n    // Action applied to fromState\n    private A action;\n    // Resultant state after applying the action to fromState\n    private S state;\n\n    /**\n     * Constructor for transitions which does not store information about\n     * the parent state.\n     *\n     * @param action action associated to this transition\n     * @param state to which this transition is addressed\n     */\n    public Transition(A action, S state) {\n        this.action = action;\n        this.state = state;\n    }\n\n    /**\n     * Constructor for transitions that store the\n     * state from which the transition comes from.\n     *\n     * @param fromState state origin of the transition\n     * @param action action associated to this transition\n     * @param toState state destination of the transition\n     *\n     * @see {@link #create(Object, Object, Object)}\n     */\n    public Transition(S fromState, A action, S toState) {\n        this.fromState = fromState;\n        this.action = action;\n        this.state = toState;\n    }\n\n    /**\n     * Instantiates a transition specifying an action, the origin and\n     * destination states.\n     *\n     * @param fromState state origin of the transition\n     * @param action action associated to this transition\n     * @param toState state destination of the transition\n     * @param <A> type of the actions\n     * @param <S> type of the state\n     * @return instance of a transition with an origin, destination and action\n     */\n    public static <A,S> Transition<A,S> create(S fromState, A action, S toState){\n        return new Transition<A, S>(fromState, action, toState);\n    }\n\n    /**\n     * Offers a way to instantiate a transition without specifying an action but\n     * only the origin and destination states.\n     *\n     * @param fromState state origin of the transition\n     * @param toState state destination of the transition\n     * @param <S> type of the state\n     * @return instance of a transition with an origin and destination, but without an action\n     */\n    public static <S> Transition<Void,S> create(S fromState, S toState){\n        return new Transition<Void, S>(fromState, null, toState);\n    }\n\n    /**\n     * @return action associated to this transition\n     */\n    public A getAction() {\n        return action;\n    }\n\n    /**\n     * @param action new action for this transition\n     */\n    public void setAction(A action) {\n        this.action = action;\n    }\n\n    /**\n     * @return state which this transition is addressed\n     */\n    public S getState() {\n        return state;\n    }\n\n    /**\n     * @param state new state destination of this transition\n     */\n    public void setState(S state) {\n        this.state = state;\n    }\n\n    /**\n     * @return state origin of this transition\n     */\n    public S getFromState() {\n        return fromState;\n    }\n\n    @Override\n    public String toString() {\n        return fromState + \" ---(\" + action + \")---> \" + state;\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/ActionFunction.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function;\n\n/**\n * Interface that defines an action function that computes applicable\n * actions for a given state. For example, in the 8-Puzzle problem,\n * the action function for a configuration of the board returns all the possible\n * movements (UP, DOWN, RIGHT, LEFT) depending on the empty tile position.\n *\n * @param <A> action type.\n * @param <S> state type\n */\npublic interface ActionFunction<A,S> {\n    /**\n     * Compute a set of applicable actions for the given state\n     * @param state\n     * @return Set of applicable actions\n     */\n    Iterable<A> actionsFor(S state);\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/ActionStateTransitionFunction.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function;\n\n/**\n * Interface to define a transition function that takes an action\n * and a concrete state and returns the new state. For example, in\n * the 8-Puzzle, this function takes a board with a concrete configuration\n * and a valid action, and returns the new board resulting of moving the empty\n * tile in the direction that corresponds to the action applied.\n *\n * @param <A> action type.\n * @param <S> state type.\n */\npublic interface ActionStateTransitionFunction<A,S> {\n    /**\n     * Apply an action to a state and return the resultant state.\n     * @param action action to apply\n     * @param state state where the actions is applied to\n     * @return the new resultant action\n     */\n    S apply(A action, S state);\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/BinaryFunction.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function;\n\n/**\n * A binary operation takes two elements of the same type\n * and combines them returning an element of the same type. \n * </p>\n * This interface is useful to define abstract arithmetic functions \n * used by the search algorithms (i. e. cost addition) and avoid the explicit\n * definition of the operations in the algorithm. When the cost definition changes,\n * the binary function can be changed without modifying the implementation\n * of the algorithms.\n * </p>\n * The abstract definition of binary operations requires to complete the method\n * {@link #apply(Object, Object)}, which returns an object of the same type. Here is \n * an example for the {@link Double} addition operation:\n *\n * <pre class=\"prettyprint\">\n * new BinaryFunction<Double>(){\n *          Double apply(Double a, Double b){\n *              return a + b;\n *          }\n *     }\n * </pre>\n * \n * @param <T> type of the domain of the function\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic interface BinaryFunction<T> {\n\t\n\t/**\n\t * Combination of two elements of the same type,\n\t * returning an element of the same type.\n\t * \n\t * @param a first element\n\t * @param b second element\n\t * @return result of the combination\n\t */\n    T apply(T a, T b);\n    \n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/CostFunction.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function;\n\n\nimport es.usc.citius.hipster.model.Transition;\n\n/**\n * The cost function evaluates a transition\n * between states. A search algorithm will find the solution that minimizes the\n * total cost of the function defined here.\n * \n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic interface CostFunction<A, S, C extends Comparable<C>> {\n\n    public C evaluate(Transition<A,S> transition);\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/HeuristicFunction.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function;\n\n/**\n * Defines a function that takes a state and estimates the distance\n * to the goal of the problem. The cost is generic (for example a Double)\n * and should be defined by the user.\n *\n * @param <S> state type.\n * @param <C> cost type.\n */\npublic interface HeuristicFunction<S,C> {\n    C estimate(S state);\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/NodeExpander.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function;\n\nimport es.usc.citius.hipster.model.Node;\n\n/**\n * Defines a function that takes a {@link es.usc.citius.hipster.model.Node} and expands it\n * in order to generate all the possible successors. Nodes are the abstract representation of\n * a state with some additional information (such as the accumulated cost and a pointer to the previous\n * node that can be used to track the current search path).\n * \n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic interface NodeExpander<A,S,N extends Node<A,S,N>> {\n\n    Iterable<N> expand(N node);\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/NodeFactory.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function;\n\n\nimport es.usc.citius.hipster.model.Transition;\n\n/**\n * Generator of nodes. Creates a new node using the information of the current\n * node and the transition between the state of the {@code fromNode} to the current state.\n * @param <A> action type.\n * @param <S> state type.\n * @param <N> node type.\n */\npublic interface NodeFactory<A,S,N> {\n    N makeNode(N fromNode, Transition<A,S> transition);\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/ScalarFunction.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\npackage es.usc.citius.hipster.model.function;\n\n/**\n * A scalar function takes an object and modifies its magnitude by a \n * numeric factor without changing its type.\n * </p>\n * This interface can be used to do abstract definitions of the scaling\n * operation for algorithms that need it without explicitly defining them\n * inside the algorithms, making them easily replaceable when the cost definition\n * changes.\n * </p>\n * The definition of scalar functions requires the implementation of the {@link #scale(Object, double)}.\n * Here is an example for the {@link Double} scaling operation:\n * <pre>\n *     {@code \n *     new ScalarFunction<Double>(){\n *              Double scale(Double a, double b){\n *                  return a*b;\n *              }\n *          }\n *     }\n * </pre>\n *\n * To create a default scalar function to operate with doubles,\n * simple use {@link es.usc.citius.hipster.model.function.impl.Product}.\n *\n * @param <T> type of the domain of the function\n * \n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic interface ScalarFunction<T> {\n\n    /**\n     * Scale operation.\n     *\n     * @param a value to be scaled\n     * @param b scale factor\n     * @return {@literal a} scaled by a factor of {@literal b}.\n     */\n    T scale(T a, double b);\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/TransitionFunction.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function;\n\n\nimport es.usc.citius.hipster.model.Transition;\n\n/**\n * Defines a function that returns the possible transitions from\n * a given state. A transition is just a class that keeps the source state,\n * the action and the resultant state.\n *\n * @param <A> type of the action\n * @param <S> type of the state\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic interface TransitionFunction<A,S> {\n\n    /**\n     * Generate the outgoing transitions from a state.\n     *\n     * @param state current state\n     * @return set of transitions from the current state\n     */\n    Iterable<Transition<A,S>> transitionsFrom(S state);\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/ADStarNodeExpander.java",
    "content": "package es.usc.citius.hipster.model.function.impl;\n\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.*;\nimport es.usc.citius.hipster.model.ADStarNode;\nimport es.usc.citius.hipster.model.problem.SearchComponents;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * This class is an implementation of {@link es.usc.citius.hipster.model.function.NodeExpander} for nodes\n * of type {@link es.usc.citius.hipster.model.ADStarNode}. This node expander executes the main\n * function of a node expander: taking as input a node generates the successor nodes using the information\n * of the transition, cost and heuristic functions. This expander, to be used\n * with {@link es.usc.citius.hipster.algorithm.ADStarForward}, also\n * executes the following operations:\n *\n * <li>\n *     <ul>Obtain a set of iterable nodes from the transitions that changed since the last solution found of AD*</ul>\n *     <ul>Update nodes in consistent and inconsistent states</ul>\n *     <ul>Store the nodes visited by the algorithm</ul>\n *     <ul>Get the predecessors nodes of a current one which were visited by the algorithm</ul>\n * </li>\n *\n * @param <A> type of the actions\n * @param <S> type of the state\n * @param <C> type of the cost (must extend {@link java.lang.Comparable})\n * @param <N> node type\n *\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class ADStarNodeExpander<A, S, C extends Comparable<C>, N extends es.usc.citius.hipster.model.ADStarNode<A, S, C, N>>\n        implements NodeExpander<A, S, N>{\n\n    private final TransitionFunction<A, S> successorFunction;\n    private final TransitionFunction<A, S> predecessorFunction;\n    private final CostFunction<A, S, C> costFunction;\n    private final HeuristicFunction<S, C> heuristicFunction;\n    private final BinaryOperation<C> add;\n    private final ScalarFunction<C> scale;\n    private final NodeFactory<A, S, N> nodeFactory;\n    private Map<S, N> visited;\n    private double epsilon;\n    private boolean nodeConsistent;\n\n    /**\n     * Builds a node expander from a search components and a node factory. A epsilon value (used to inflate\n     * the heuristic and obtain solutions anytime) must be specified, being >= 1.\n     *\n     *\n     * @param components search components of the search\n     * @param factory node factory\n     * @param epsilon heuristic inflation value (>=1)\n     */\n    public ADStarNodeExpander(SearchComponents<A, S, C> components, NodeFactory<A, S, N> factory, double epsilon){\n        this(components.successorFunction(), components.predecessorFunction(), components.costFunction(),\n                components.heuristicFunction(), components.costAlgebra(), components.scaleAlgebra(), factory, epsilon);\n    }\n\n    /**\n     * Builds a node expander specifying the required components individually. A epsilon value (used to inflate\n     * the heuristic and obtain solutions anytime) must be specified, being >= 1.\n     *\n     * @param successorFunction successor function\n     * @param predecessorFunction predecessor function\n     * @param costFunction evaluation function\n     * @param heuristicFunction heuristic function\n     * @param add cost addition function\n     * @param scale cost scale function\n     * @param nodeFactory node factory\n     * @param epsilon heuristic inflation value (>=1)\n     */\n    public ADStarNodeExpander(TransitionFunction<A, S> successorFunction, TransitionFunction<A, S> predecessorFunction,\n                              CostFunction<A, S, C> costFunction, HeuristicFunction<S, C> heuristicFunction,\n                              BinaryOperation<C> add, ScalarFunction<C> scale, NodeFactory<A, S, N> nodeFactory,\n                              double epsilon) {\n        this.successorFunction = successorFunction;\n        this.predecessorFunction = predecessorFunction;\n        this.costFunction = costFunction;\n        this.heuristicFunction = heuristicFunction;\n        this.add = add;\n        this.scale = scale;\n        this.nodeFactory = nodeFactory;\n        this.visited = new HashMap<S, N>();\n        this.epsilon = epsilon;\n    }\n\n    public void setNodeConsistent(boolean nodeConsistent) {\n        this.nodeConsistent = nodeConsistent;\n    }\n\n    @Override\n    public Iterable<N> expand(N node) {\n        Collection<N> nodes = new ArrayList<N>();\n        //if s' not visited before: v(s')=g(s')=Infinity; bp(s')=null\n        for (Transition<A, S> transition : successorFunction.transitionsFrom(node.state())) {\n            N successorNode = visited.get(transition.getState());\n            if (successorNode == null) {\n                successorNode = nodeFactory.makeNode(node, transition);\n                visited.put(transition.getState(), successorNode);\n            }\n            //if consistent\n            if (nodeConsistent) {\n                //if g(s') > g(s) + c(s, s')\n                // bp(s') = s\n                // g(s') = g(s) + c(s, s')\n                //set to update queues after this\n                successorNode.setDoUpdate(updateConsistent(successorNode, node, transition));\n            } else {\n                //Generate\n                if (successorNode.previousNode() != null && successorNode.previousNode().state().equals(node.state())) {\n                    // bp(s') = arg min s'' predecessor of s' such that (v(s'') + c(s'', s'))\n                    // g(s') = v(bp(s')) + c(bp(s'), s'')\n                    updateInconsistent(successorNode, predecessorsMap(transition.getState()));\n                    //update queues after this\n                    successorNode.setDoUpdate(true);\n                }\n            }\n            nodes.add(successorNode);\n        }\n        return nodes;\n    }\n\n    /**\n     * Generates an iterable list of nodes, updated as inconsistent after applying the cost changes in the\n     * list of transitions passed as parameter.\n     *\n     * @param begin beginning state of the search\n     * @param transitions list of transitions with changed costs\n     * @return list of updated nodes\n     */\n    public Iterable<N> expandTransitionsChanged(N begin, Iterable<Transition<A, S>> transitions){\n        Collection<N> nodes = new ArrayList<N>();\n        for (Transition<A, S> transition : transitions) {\n            S state = transition.getState();\n            //if v != start\n            if (!state.equals(begin.state())) {\n                //if s' not visited before: v(s')=g(s')=Infinity; bp(s')=null\n                N node = this.visited.get(state);\n                if (node == null) {\n                    node = nodeFactory.makeNode(begin, transition);\n                    visited.put(state, node);\n                }\n                // bp(v) = arg min s'' predecessor of v such that (v(s'') + c(s'', v))\n                // g(v) = v(bp(v)) + c(bp(v), v)\n                updateInconsistent(node, predecessorsMap(transition.getState()));\n                nodes.add(node);\n            }\n        }\n        return nodes;\n    }\n\n    /**\n     * Updates a node in consistent state (V > G) updating the path\n     * and the cost if the parent node and the transition improves the current cost of the node.\n     *\n     * @param node {@link es.usc.citius.hipster.algorithm.ADStarForward} node to update, in consistent state\n     * @param parent previous {@link es.usc.citius.hipster.algorithm.ADStarForward} of the node\n     * @param transition {@link es.usc.citius.hipster.model.Transition} between the parent and the node\n     * @return true if the node has changed its {@link es.usc.citius.hipster.model.impl.ADStarNodeImpl.Key}\n     */\n    private boolean updateConsistent(N node, N parent, Transition<A, S> transition) {\n        // parent.getG().add(this.costFunction.evaluate(transition));\n        C accumulatedCost = add.apply(parent.getG(), costFunction.evaluate(transition));\n        if (node.getG().compareTo(accumulatedCost) > 0) {\n            node.setPreviousNode(parent);\n            // node.previousNode = parent;\n            node.setG(accumulatedCost);\n            node.setState(transition.getState());\n            node.setAction(transition.getAction());\n            // node.state = transition;\n            node.setKey(new es.usc.citius.hipster.model.ADStarNode.Key<C>(node.getG(), node.getV(),\n                    heuristicFunction.estimate(transition.getState()), epsilon, add, scale));\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * Updates a node in inconsistent state (V <= G), evaluating all the predecessors of the current node\n     * and updating the parent to the node which combination of cost and transition is minimal.\n     *\n     * @param node inconsistent {@link es.usc.citius.hipster.algorithm.ADStarForward} node to update\n     * @param predecessorMap map containing the the predecessor nodes and\n     * @return true if the node has changed its {@link es.usc.citius.hipster.model.impl.ADStarNodeImpl.Key}\n     */\n    private boolean updateInconsistent(N node, Map<Transition<A, S>, N> predecessorMap) {\n        C minValue = add.getIdentityElem();\n        N minParent = null;\n        Transition<A, S> minTransition = null;\n        for (Map.Entry<Transition<A, S>, N> current : predecessorMap\n                .entrySet()) {\n            C value = add.apply(current.getValue().getV(), costFunction.evaluate(current.getKey()));\n            //T value = current.getValue().v.add(this.costFunction.evaluate(current.getKey()));\n            if (value.compareTo(minValue) < 0) {\n                minValue = value;\n                minParent = current.getValue();\n                minTransition = current.getKey();\n            }\n        }\n        node.setPreviousNode(minParent);\n        // node.previousNode = minParent;\n        node.setG(minValue);\n        node.setState(minTransition.getState());\n        node.setAction(minTransition.getAction());\n        // node.state = minTransition;\n        node.getKey().update(node.getG(), node.getV(), heuristicFunction.estimate(minTransition.getState()), epsilon, add, scale);\n        return true;\n    }\n\n    /**\n     * Retrieves a map with the predecessors states and the node associated\n     * to each predecessor state.\n     *\n     * @param current current state to calculate predecessors of\n     * @return map pairs of <state, node> with the visited predecessors of the state\n     */\n    private Map<Transition<A, S>, N> predecessorsMap(S current){\n        //Map<Transition, Node> containing predecessors relations\n        Map<Transition<A, S>, N> mapPredecessors = new HashMap<Transition<A, S>, N>();\n        //Fill with non-null pairs of <Transition, Node>\n        for (Transition<A, S> predecessor : predecessorFunction.transitionsFrom(current)) {\n            N predecessorNode = visited.get(predecessor.getState());\n            if (predecessorNode != null) {\n                mapPredecessors.put(predecessor, predecessorNode);\n            }\n        }\n        return mapPredecessors;\n    }\n\n    /**\n     * Assigns the maximum value to V in the current node.\n     *\n     * @param node {@link es.usc.citius.hipster.model.impl.ADStarNodeImpl} to modify the value of V\n     */\n    public void setMaxV(N node) {\n        node.setV(this.add.getMaxElem());\n    }\n\n    /**\n     * Assigns the maximum value to G in the current node.\n     *\n     * @param node {@link es.usc.citius.hipster.model.impl.ADStarNodeImpl} to modify the value of V\n     */\n    public void setMaxG(N node)  {\n        node.setG(this.add.getMaxElem());\n    }\n\n    /**\n     * Assign a value to the inflation parameter of the heuristic.\n     *\n     * @param epsilon new value\n     */\n    public void setEpsilon(double epsilon) {\n        this.epsilon = epsilon;\n    }\n\n    /**\n     * Queries the current value of epsilon (sub-optimal bound for anytime solutions).\n     *\n     * @return current value of epsilon\n     */\n    public double getEpsilon() {\n        return epsilon;\n    }\n\n    /**\n     * @return map with the states and nodes visited by the algorithm\n     */\n    public Map<S, N> getVisited() { return visited; }\n\n    /**\n     * Clears the set of visited nodes.\n     */\n    public void clearVisited() { this.visited = new HashMap<S, N>(); }\n\n    /**\n     * Creates a new node from the parent and a transition, calling the node factory.\n     *\n     * @param from parent node\n     * @param transition transition between the parent and the new node\n     * @return new node created by the node factory\n     */\n    public N makeNode(N from, Transition<A, S> transition){\n        return nodeFactory.makeNode(from, transition);\n    }\n\n    /**\n     * Updating the priority of a node is required when changing the value of Epsilon.\n     */\n    public void updateKey(N node){\n        node.getKey().update(node.getG(), node.getV(), heuristicFunction.estimate(node.state()), epsilon, add, scale);\n    }\n\n    public void setMaxKey(N node){\n        node.setKey(new ADStarNode.Key<C>(add.getMaxElem(), add.getMaxElem()));\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/ADStarNodeFactory.java",
    "content": "/*\n* Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS).\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\npackage es.usc.citius.hipster.model.function.impl;\n\nimport es.usc.citius.hipster.model.ADStarNode;\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.HeuristicFunction;\nimport es.usc.citius.hipster.model.function.NodeFactory;\nimport es.usc.citius.hipster.model.impl.ADStarNodeImpl;\nimport es.usc.citius.hipster.model.problem.SearchComponents;\n\n/**\n * The ADStarNodeBuilder is used for instantiate new {@link es.usc.citius.hipster.model.impl.ADStarNodeImpl}.\n *\n * @param <S> class defining the state\n * @param <C> class defining the cost\n *\n * @author Adrián González Sieira <<a href=\"mailto:adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class ADStarNodeFactory<A, S, C extends Comparable<C>> implements NodeFactory<A, S, ADStarNodeImpl<A, S, C>> {\n\n    protected C max;\n    protected C min;\n    protected BinaryOperation<C> addOperation;\n    protected ScalarOperation<C> scaleOperation;\n    protected HeuristicFunction<S, C> hf;\n\n    /**\n     * Constructor which takes the minimum and\n     * maximum cost values managed by the algorithm to initialize the\n     * node values properly.\n     *\n     * @param addOp addition operation\n     * @param scaleOp scaling operation\n     * @param hf heuristic function\n     */\n    public ADStarNodeFactory(BinaryOperation<C> addOp, ScalarOperation<C> scaleOp, HeuristicFunction<S, C> hf) {\n        this.hf = hf;\n        this.addOperation = addOp;\n        this.scaleOperation = scaleOp;\n        this.min = addOperation.getIdentityElem();\n        this.max = addOperation.getMaxElem();\n    }\n\n    /**\n     * Constructor which takes the search components instead of taking all the separated\n     * arguments.\n     *\n     * @param components search components of the algorithm\n     */\n    public ADStarNodeFactory(SearchComponents<A, S, C> components){\n        this(components.costAlgebra(), components.scaleAlgebra(), components.heuristicFunction());\n    }\n\n    @Override\n    public ADStarNodeImpl<A, S ,C> makeNode(ADStarNodeImpl<A, S, C> from, Transition<A, S> transition) {\n        if (from == null) {\n            return new ADStarNodeImpl<A, S, C>(transition, null, min, max, new ADStarNode.Key<C>(min, max, hf.estimate(transition.getState()), 1.0, addOperation, scaleOperation));\n        } else {\n            return new ADStarNodeImpl<A, S, C>(transition, null, max, max, new ADStarNode.Key<C>(max, max));\n        }\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/ADStarNodeUpdater.java",
    "content": "/*\n* Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS).\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\npackage es.usc.citius.hipster.model.function.impl;\n\nimport es.usc.citius.hipster.model.function.CostFunction;\nimport es.usc.citius.hipster.model.function.HeuristicFunction;\nimport es.usc.citius.hipster.model.function.ScalarFunction;\n\n/**\n * The ADStarNodeUpdater is used by the {@link es.usc.citius.hipster.algorithm.ADStarForward}\n * algorithm to update the G and V values of the {@link es.usc.citius.hipster.model.impl.ADStarNodeImpl}\n * explored by the algorithm. Different operations are executed depending on its consistent or inconsistent state:\n * <ul>\n * <li>\n * For nodes in consistent state, if the cost of the parent added to the cost of the transition\n * improves the current value of G, the path changes to include the new transition and the {@link es.usc.citius.hipster.model.impl.ADStarNodeImpl.Key}\n * is updated taking into account the new cost.\n * </li>\n * <li>\n * For nodes in inconsistent state, all their predecessors are explored to select the one with minimum\n * G and transition cost. The path changes according to the new minimum cost and the {@link es.usc.citius.hipster.model.impl.ADStarNodeImpl.Key} is updated.\n * </li>\n * <ul>\n *\n * In both cases the updater returns true if the {@link es.usc.citius.hipster.model.impl.ADStarNodeImpl.Key} values\n * change to reinsert it in the Open queue with a new priority.\n *\n * @param <A> class defining the action\n * @param <S> class defining the state\n * @param <C> class defining the cost, must implement {@link java.lang.Comparable}\n *\n * @author Adrián González Sieira <<a href=\"mailto:adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class ADStarNodeUpdater<A, S, C extends Comparable<C>> {\n\n    private final CostFunction<A, S, C> costFunction;\n    private final HeuristicFunction<S, C> heuristicFunction;\n    private final BinaryOperation<C> add;\n    private final ScalarFunction<C> scale;\n    private double epsilon;\n\n    /**\n     * The constructor for ADStarNodeUpdater takes the elements that involve the cost\n     * definition to update the G and V values of the {@link es.usc.citius.hipster.model.impl.ADStarNodeImpl}\n     * as the {@link es.usc.citius.hipster.algorithm.ADStarForward} algorithm is being executed.\n     *\n     * @param costFunction function to evaluate instances of {@link es.usc.citius.hipster.model.Transition}\n     * @param heuristicFunction function to estimate the cost of to the goal\n     * @param add operation to accumulate the cost\n     * @param scale operation to scale the cost by a factor\n     * @param epsilon inflation factor of the {@link es.usc.citius.hipster.algorithm.ADStarForward} algorithm\n     */\n    public ADStarNodeUpdater(CostFunction<A, S, C> costFunction,\n                             HeuristicFunction<S, C> heuristicFunction, BinaryOperation<C> add,\n                             ScalarFunction<C> scale, double epsilon) {\n        this.costFunction = costFunction;\n        this.heuristicFunction = heuristicFunction;\n        this.epsilon = epsilon;\n        this.add = add;\n        this.scale = scale;\n    }\n\n\n\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/BinaryOperation.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\npackage es.usc.citius.hipster.model.function.impl;\n\nimport es.usc.citius.hipster.model.function.BinaryFunction;\n\n/**\n * A implementation of {@link es.usc.citius.hipster.model.function.BinaryFunction} used to define\n * a custom cost algebra that also has the following definitions:\n * <ul>\n * \t\t<li>identity element (A*I = A)</li>\n * \t\t<li>maximum element (A*M = M)</li>\n * </ul>\n *\n * @param <E> element type\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class BinaryOperation<E extends Comparable<E>> implements BinaryFunction<E> {\n\n\tprivate E maxElem;\n\tprivate E identityElem;\n\tprivate BinaryFunction<E> op;\n\n\t/**\n\t *\n\t *\n\t * @param operation\n\t * @param identityElem\n\t * @param maxElem\n\t */\n\tpublic BinaryOperation(BinaryFunction<E> operation, E identityElem, E maxElem) {\n        // Check properties\n        assert operation.apply(identityElem, maxElem).compareTo(maxElem) == 0;\n        assert operation.apply(maxElem, identityElem).compareTo(maxElem) == 0;\n        assert operation.apply(identityElem, identityElem).compareTo(identityElem) == 0;\n        //Preconditions.checkArgument(operation.apply(identityElem, maxElem).equals(maxElem), \"Property error: I x A != A\");\n        //Preconditions.checkArgument(operation.apply(maxElem, identityElem).equals(maxElem), \"Property error: A x I != A\");\n        //Preconditions.checkArgument(operation.apply(identityElem, identityElem).equals(identityElem), \"Property error: I x I != I\");\n\t\tthis.maxElem = maxElem;\n\t\tthis.identityElem = identityElem;\n\t\tthis.op = operation;\n\t}\n\n\t@Override\n\tpublic E apply(E a, E b) {\n\t\treturn this.op.apply(a, b);\n\t}\n\n\t/**\n\t * @return maximum cost\n\t */\n\tpublic E getMaxElem() {\n\t\treturn maxElem;\n\t}\n\n\t/**\n\t * @return minimum (identity) cost\n\t */\n\tpublic E getIdentityElem() {\n\t\treturn identityElem;\n\t}\n\n    /**\n     * @return a default addition implementation which works with doubles.\n\t * For example, {@literal BinaryOperation.doubleAdditionOp().apply(2.5d, 1.0d)} returns 3.5d.\n     */\n\tpublic static BinaryOperation<Double> doubleAdditionOp() {\n\t\treturn new BinaryOperation<Double>(new BinaryFunction<Double>() {\n\t\t\tpublic Double apply(Double a, Double b) {\n\t\t\t\treturn a + b;\n\t\t\t}\n\t\t}, 0d, Double.POSITIVE_INFINITY);\n\t}\n\n    /**\n     * @return a multiplication implementation which works with doubles.\n     * For example, {@literal BinaryOperation.doubleMultiplicationOp.apply(2.5d, 2.0d)} returns 5.0d.\n     */\n\tpublic static BinaryOperation<Double> doubleMultiplicationOp() {\n\t\treturn new BinaryOperation<Double>(new BinaryFunction<Double>() {\n\n\t\t\tpublic Double apply(Double a, Double b) {\n\t\t\t\treturn a * b;\n\t\t\t}\n\t\t}, 1d, Double.POSITIVE_INFINITY);\n\t}\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/LazyActionStateTransitionFunction.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function.impl;\n\n\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.ActionFunction;\nimport es.usc.citius.hipster.model.function.ActionStateTransitionFunction;\nimport es.usc.citius.hipster.model.function.TransitionFunction;\nimport es.usc.citius.hipster.util.F;\nimport es.usc.citius.hipster.util.Function;\n\nimport java.util.ArrayList;\n\n/**\n * Implementation of a {@link es.usc.citius.hipster.model.function.TransitionFunction} generates\n * an {@link java.lang.Iterable} of {@link es.usc.citius.hipster.model.Transition} which are instantiated\n * in a lazy way, as the elements are iterated by the algorithms, and not in advance. This class\n * is used for problems with explicit actions.\n *\n * @param <A> type of the actions\n * @param <S> type of the states\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class LazyActionStateTransitionFunction<A,S> implements TransitionFunction<A,S> {\n    private final ActionFunction<A,S> af;\n    private final ActionStateTransitionFunction<A,S> tf;\n\n    /**\n     * Main constructor which initializes this class with the transition functions.\n     *\n     * @param af function which computes the actions applicable in each state\n     * @param tf function which computes the state after applying an action in a concrete state\n     */\n    public LazyActionStateTransitionFunction(ActionFunction<A, S> af, ActionStateTransitionFunction<A, S> tf) {\n        this.af = af;\n        this.tf = tf;\n    }\n\n    @Override\n    public Iterable<Transition<A, S>> transitionsFrom(final S state) {\n        return F.map(af.actionsFor(state), new Function<A, Transition<A, S>>() {\n            @Override\n            public Transition<A, S> apply(A a) {\n                return Transition.create(state, a, tf.apply(a, state));\n            }\n        });\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/LazyNodeExpander.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function.impl;\n\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.NodeExpander;\nimport es.usc.citius.hipster.model.function.NodeFactory;\nimport es.usc.citius.hipster.model.function.TransitionFunction;\nimport es.usc.citius.hipster.util.F;\nimport es.usc.citius.hipster.util.Function;\n\nimport java.util.ArrayList;\n\n/**\n * Implementation of a {@link es.usc.citius.hipster.model.function.NodeExpander} which generates\n * an {@link java.lang.Iterable} of {@link es.usc.citius.hipster.model.Node} which are instantiated\n * in a lazy way, as required by the algorithms, and not in advance.\n *\n * @param <A> type of the actions\n * @param <S> type of the states\n * @param <N> type of the nodes\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class LazyNodeExpander<A,S,N extends Node<A,S,N>> implements NodeExpander<A,S,N> {\n    private TransitionFunction<A,S> tf;\n    private NodeFactory<A,S,N> factory;\n\n    /**\n     * Initializes this node expander taking a node factory and the transition function\n     * of the problem.\n     *\n     * @param tf transition function\n     * @param factory node factory\n     */\n    public LazyNodeExpander(TransitionFunction<A, S> tf, NodeFactory<A, S, N> factory) {\n        this.tf = tf;\n        this.factory = factory;\n    }\n\n    @Override\n    public Iterable<N> expand(final N node) {\n        // The default expansion of a node consists of\n        // computing the successor transitions of the current state and\n        // generating the associated nodes for each successor\n        return F.map(tf.transitionsFrom(node.state()), new Function<Transition<A, S>, N>() {\n            @Override\n            public N apply(Transition<A, S> t) {\n                return factory.makeNode(node, t);\n            }\n        });\n    }\n\n    /**\n     * @return transition function\n     */\n    public TransitionFunction<A, S> getTransitionFunction() {\n        return tf;\n    }\n\n    /**\n     * @return classic node factory\n     */\n    public NodeFactory<A, S, N> getNodeFactory() {\n        return factory;\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/Product.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function.impl;\n\n\nimport es.usc.citius.hipster.model.function.ScalarFunction;\n\n/**\n * Implementation of {@link es.usc.citius.hipster.model.function.ScalarFunction} product\n * for {@link java.lang.Double} elements.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class Product implements ScalarFunction<Double> {\n\n    /**\n     * Returns a*b\n     *\n     * @param a value to be scaled\n     * @param b scale factor\n     * @return a*b\n     */\n    public Double scale(Double a, double b) {\n        return a * b;\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/ScalarOperation.java",
    "content": "package es.usc.citius.hipster.model.function.impl;\n\n\nimport es.usc.citius.hipster.model.function.ScalarFunction;\n\n/**\n * A scalar operation is an implementation of {@link ScalarFunction} that\n * also defines:\n * <ul>\n * \t\t<li>identity element (A*i = A)</li>\n * </ul>\n *\n * @param <E> element type\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class ScalarOperation<E extends Comparable<E>> implements ScalarFunction<E> {\n\n\tprivate double identityElem;\n\tprivate ScalarFunction<E> op;\n\n\t/**\n\t * Unique constructor for {@link ScalarOperation}, that takes the {@link ScalarFunction}\n\t * applied and the identity element.\n\t *\n\t * @param operation operation definition\n\t * @param identityElem identity\n\t */\n\tpublic ScalarOperation(ScalarFunction<E> operation, double identityElem) {\n\t\tthis.identityElem = identityElem;\n\t\tthis.op = operation;\n\t}\n\n\t@Override\n\tpublic E scale(E a, double b) {\n\t\treturn this.op.scale(a, b);\n\t}\n\n\t/**\n\t * @return identity element\n\t */\n\tpublic double getIdentityElem() {\n\t\treturn identityElem;\n\t}\n\n\t/**\n\t * Builds the scaling operation for Doubles, that is the multiplying\n\t * operation for the factor.\n\t *\n\t * @return {@link ScalarOperation} for Double\n\t */\n\tpublic static ScalarOperation<Double> doubleMultiplicationOp() {\n\t\treturn new ScalarOperation<Double>(new ScalarFunction<Double>() {\n\n\t\t\t@Override\n\t\t\tpublic Double scale(Double a, double b) {\n\t\t\t\treturn a * b;\n\t\t\t}\n\n\t\t}, 1d);\n\t}\n\t\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/StateTransitionFunction.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function.impl;\n\n\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.TransitionFunction;\nimport es.usc.citius.hipster.util.F;\nimport es.usc.citius.hipster.util.Function;\n\nimport java.util.ArrayList;\n\n/**\n * Implementation of a {@link es.usc.citius.hipster.model.function.TransitionFunction} which generates\n * an {@link java.lang.Iterable} of {@link es.usc.citius.hipster.model.Transition} which are instantiated\n * in a lazy way, as the elements are iterated by the algorithms, and not in advance. This class\n * is used for problems without explicit actions.\n *\n * @param <S> type of the states\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic abstract class StateTransitionFunction<S> implements TransitionFunction<Void, S> {\n\n    @Override\n    public Iterable<Transition<Void, S>> transitionsFrom(final S state) {\n        //generate successor states\n        return F.map(successorsOf(state), new Function<S, Transition<Void, S>>() {\n            @Override\n            public Transition<Void, S> apply(S current) {\n                return Transition.create(state, null, current);\n            }\n        });\n    }\n\n    /**\n     * Obtain the successor states of a given one.\n     *\n     * @param state current states\n     * @return successor states of the current\n     */\n    public abstract Iterable<S> successorsOf(S state);\n}\n\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/WeightedNodeFactory.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.function.impl;\n\n\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.CostFunction;\nimport es.usc.citius.hipster.model.function.HeuristicFunction;\nimport es.usc.citius.hipster.model.function.NodeFactory;\nimport es.usc.citius.hipster.model.impl.WeightedNode;\n\n/**\n * Implementation of {@link es.usc.citius.hipster.model.function.NodeFactory} for nodes of type\n * {@link es.usc.citius.hipster.model.impl.WeightedNode}. The new nodes have a cost which\n * is the sum of the cost of the parent and the cost of the {@link es.usc.citius.hipster.model.Transition}\n * between the parent node and the current one, calculated by a {@link es.usc.citius.hipster.model.function.CostFunction}.\n *\n * Also, the score is the sum of the cost of the node and the estimated cost to the goal,\n * according to a {@link es.usc.citius.hipster.model.function.HeuristicFunction}.\n *\n * @param <A> type of the actions\n * @param <S> type of the states\n * @param <C> type of the cost\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class WeightedNodeFactory<A,S,C extends Comparable<C>> implements NodeFactory<A,S,WeightedNode<A,S,C>>{\n\n    private CostFunction<A,S,C> gf;\n    private HeuristicFunction<S,C> hf;\n    private BinaryOperation<C> costAccumulator;\n\n\n    /**\n     * Instantiates a node factory using a cost function, a heuristic function and a cost accumulator.\n     *\n     * @param costFunction cost function\n     * @param heuristicFunction heuristic function\n     * @param costAccumulator function to accumulate the cost elements\n     */\n    public WeightedNodeFactory(CostFunction<A, S, C> costFunction, HeuristicFunction<S, C> heuristicFunction, BinaryOperation<C> costAccumulator) {\n        this.gf = costFunction;\n        this.hf = heuristicFunction;\n        this.costAccumulator = costAccumulator;\n    }\n\n    /**\n     * Instantiates a node factory using a cost function and a cost accumulator. The\n     * heuristic function is considered to return always the identity element of the cost.\n     *\n     * @param costFunction cost function\n     * @param costAccumulator function to accumulate the cost elements\n     */\n    public WeightedNodeFactory(CostFunction<A, S, C> costFunction, BinaryOperation<C> costAccumulator) {\n        this.gf = costFunction;\n        this.hf = new HeuristicFunction<S, C>() {\n            public C estimate(S state) {\n                return WeightedNodeFactory.this.costAccumulator.getIdentityElem();\n            }\n        };\n        this.costAccumulator = costAccumulator;\n    }\n\n    @Override\n    public WeightedNode<A, S, C> makeNode(WeightedNode<A, S, C> fromNode, Transition<A, S> transition) {\n        C cost, estimatedDistance, score;\n\n        if (fromNode == null){\n            cost = costAccumulator.getIdentityElem();\n        } else {\n            cost = costAccumulator.apply(fromNode.getCost(), this.gf.evaluate(transition));\n        }\n        estimatedDistance = this.hf.estimate(transition.getState());\n        score = costAccumulator.apply(cost, estimatedDistance);\n\n        return new WeightedNode<A,S,C>(fromNode, transition.getState(), transition.getAction(), cost, estimatedDistance, score);\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Default implementations of many function operators required by the search algorithms.\n */\npackage es.usc.citius.hipster.model.function.impl;"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/function/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Interfaces that define the functions used to compute costs, expand nodes, etc.\n */\npackage es.usc.citius.hipster.model.function;"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/impl/ADStarNodeImpl.java",
    "content": "package es.usc.citius.hipster.model.impl;\n\nimport es.usc.citius.hipster.model.ADStarNode;\nimport es.usc.citius.hipster.model.AbstractNode;\nimport es.usc.citius.hipster.model.Transition;\n\n/**\n * Interface defining the basic operations for {@link es.usc.citius.hipster.model.Node} to be used with\n * {@link es.usc.citius.hipster.algorithm.ADStarForward}. Contains the declaration of the methods to retrieve\n * te cost elements of the node (G and V) and the definition of the {@link ADStarNodeImpl.Key}\n * to compare {@link ADStarNodeImpl} elements.\n *\n * @param <A> type of the actions ({@code Void} if actions are not explicit).\n * @param <S> type of the states.\n * @param <C> type of the cost\n *\n * @author Adrián González Sieira <adrian.gonzalez@usc.es>\n */\npublic class ADStarNodeImpl<A, S, C extends Comparable<C>>\n        extends AbstractNode<A, S, ADStarNodeImpl<A, S, C>>\n        implements ADStarNode<A, S, C, ADStarNodeImpl<A, S, C>> {\n\n    protected C g;\n    protected C v;\n    protected es.usc.citius.hipster.model.ADStarNode.Key<C> key;\n    protected boolean doUpdate;\n\n    /**\n     * Default constructor for ADStarNode. Requires the transition used\n     * to reach the new one and the previous node. The current cost (G),\n     * score (V) and key to compare between ADStarNode instances are also required.\n     *\n     * @param transition incoming transition\n     * @param previousNode parent node\n     * @param g accumulated cost from begin\n     * @param v score to goal\n     * @param k key value evaluated over G and V\n     */\n    public ADStarNodeImpl(Transition<A, S> transition, ADStarNodeImpl<A, S, C> previousNode, C g, C v, es.usc.citius.hipster.model.ADStarNode.Key<C> k) {\n        super(previousNode, transition.getState(), transition.getAction());\n        this.g = g;\n        this.v = v;\n        this.key = k;\n    }\n\n    /**\n     * Cost from beginning state.\n     *\n     * @return object representing the current cost\n     */\n    @Override\n    public C getG() {\n        return g;\n    }\n\n    /**\n     * Score to goal given as heuristic.\n     *\n     * @return object representing the estimated cost to goal\n     */\n    @Override\n    public C getV() {\n        return v;\n    }\n\n    @Override\n    public boolean isDoUpdate() {\n        return doUpdate;\n    }\n\n    @Override\n    public void setG(C g) {\n        this.g = g;\n    }\n\n    @Override\n    public void setV(C v) {\n        this.v = v;\n    }\n\n    @Override\n    public void setKey(es.usc.citius.hipster.model.ADStarNode.Key<C> key) {\n        this.key = key;\n    }\n\n    @Override\n    public Key<C> getKey() {\n        return key;\n    }\n\n    @Override\n    public void setPreviousNode(ADStarNodeImpl<A, S, C> parent){\n        this.previousNode = parent;\n    }\n\n    @Override\n    public void setState(S state){\n        this.state = state;\n    }\n\n    @Override\n    public void setAction(A action){\n        this.action = action;\n    }\n\n    @Override\n    public void setDoUpdate(boolean doUpdate) {\n        this.doUpdate = doUpdate;\n    }\n\n    /**\n     * Returns if the node is in a consistent state or not.\n     * @return v > g\n     */\n    public boolean isConsistent(){ return v.compareTo(g) > 0; }\n\n    @Override\n    public C getEstimation() {\n        return v;\n    }\n\n    @Override\n    public C getScore() {\n        return key.getFirst();\n    }\n\n    @Override\n    public C getCost() {\n        return g;\n    }\n\n    /**\n     * Method to retrieve the parent ADStarNode, the same\n     * retrieved by {@link es.usc.citius.hipster.model.Transition#getFromState()}.\n     *\n     * @return parent {@link ADStarNodeImpl},\n     */\n    @SuppressWarnings(\"unchecked\") //suppress warnings to return an ADStarNode instead of Node, which is the inherited return type from parent\n    @Override\n    public ADStarNodeImpl<A, S, C> previousNode() {\n        return (ADStarNodeImpl<A, S, C>) previousNode;\n    }\n\n    /**\n     * Compares ADSTarNode instances attending to their {@link es.usc.citius.hipster.model.ADStarNode.Key}\n     * values.\n     *\n     * @param o ADStarNode instance\n     * @return usual comparison value\n     */\n    @Override\n    public int compareTo(ADStarNodeImpl<A, S, C> o) {\n        return this.key.compareTo(o.key);\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/impl/UnweightedNode.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.impl;\n\nimport es.usc.citius.hipster.model.AbstractNode;\nimport es.usc.citius.hipster.model.Transition;\n\n/**\n * Simple implementation of a search node which does not keep any information about\n * costs. If your problem does not use actions, you can use instances of\n * {@code new UnweightedNode<Void,S>}.\n *\n * @param <A> Generic actions of the problem\n * @param <S> Generic states of the problem\n *\n * @see UnweightedNode#newNodeWithoutAction(UnweightedNode, Object)\n */\npublic class UnweightedNode<A,S> extends AbstractNode<A,S,UnweightedNode<A,S>> {\n\n    /**\n     * Creates an unweighted node based on the parent, a state and an action.\n     *\n     * @param previousNode parent node\n     * @param state state of the new node\n     * @param action action connecting the parent node and the new one\n     */\n    public UnweightedNode(UnweightedNode<A, S> previousNode, S state, A action) {\n        super(previousNode, state, action);\n    }\n\n    /**\n     * Creates an unweighted node based on the parent and the transition between\n     * them.\n     *\n     * @param previousNode parent node\n     * @param transition transition connecting the parent node and the new one\n     */\n    public UnweightedNode(UnweightedNode<A, S> previousNode, Transition<A, S> transition) {\n        super(previousNode, transition.getState(), transition.getAction());\n    }\n\n    /**\n     * This static method creates an unweighted node without defining an explicit action, using\n     * the parent node and a state.\n     *\n     * @param previousNode parent node\n     * @param state state of the node to be created\n     * @param <S> type of the state\n     * @return new node for the state specified, without need of specifying the action connecting them\n     */\n    public static <S> UnweightedNode<Void,S> newNodeWithoutAction(UnweightedNode<Void,S> previousNode, S state){\n        return new UnweightedNode<Void, S>(previousNode, state, null);\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/impl/WeightedNode.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.impl;\n\n\nimport es.usc.citius.hipster.model.AbstractNode;\nimport es.usc.citius.hipster.model.HeuristicNode;\n\n/**\n * Basic implementation of a node which does not which keeps information about\n * the cost. For problems which does not use actions, instances of\n * {@code new WeightedNode<Void,S,C>} may be used.\n *\n * @param <A> type of the actions\n * @param <S> type of the states\n * @param <C> type of the cost\n */\npublic class WeightedNode<A,S,C extends Comparable<C>>\n        extends AbstractNode<A,S,WeightedNode<A,S,C>>\n        implements HeuristicNode<A,S,C, WeightedNode<A,S,C>> {\n\n    private C cost;\n    private C estimation;\n    private C score;\n\n    /**\n     * Basic constructor for instantiating a new weighted node.\n     *\n     * @param previousNode parent node\n     * @param state state of the node to be created\n     * @param action action connecting the parent node and the current one\n     * @param cost cost of the new node\n     * @param estimation estimated cost between the current node and the goal\n     * @param score score of the new node\n     */\n    public WeightedNode(WeightedNode<A, S, C> previousNode, S state, A action, C cost, C estimation, C score) {\n        super(previousNode, state, action);\n        this.cost = cost;\n        this.estimation = estimation;\n        this.score = score;\n    }\n\n    @Override\n    public C getScore() {\n        return score;\n    }\n\n    @Override\n    public C getEstimation() {\n        return estimation;\n    }\n\n    @Override\n    public C getCost() {\n        return cost;\n    }\n\n    @Override\n    public int compareTo(WeightedNode<A, S, C> o) {\n        return score.compareTo(o.score);\n    }\n\n    @Override\n    public String toString() {\n        return \"WeightedNode{\" +\n                \"state=\" + this.state() +\n                \", cost=\" + cost +\n                \", estimation=\" + estimation +\n                \", score=\" + score +\n                '}';\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/impl/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Default implementation of some components of the model.\n */\npackage es.usc.citius.hipster.model.impl;"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Search component model used in Hipster (cost function, heuristic function, nodes, transitions...).\n */\npackage es.usc.citius.hipster.model;"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/problem/ProblemBuilder.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.model.problem;\n\n\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.*;\nimport es.usc.citius.hipster.model.function.impl.*;\nimport es.usc.citius.hipster.model.impl.UnweightedNode;\nimport es.usc.citius.hipster.model.impl.WeightedNode;\n\n/**\n * Problem builder that is used to guide the user through the creation of a\n * {@link SearchProblem} with the main components\n * required to instantiate an algorithm.\n */\npublic final class ProblemBuilder {\n\n    private ProblemBuilder(){\n\n    }\n\n    /**\n     * Internal wizard assistant class.\n     */\n    public static final class Wizard {\n        private Wizard(){}\n\n        /**\n         * Step to define the initial state of the problem.\n         */\n        public static final class ActionState<S> {\n            private final S initialState;\n            private final S finalState;\n\n            public ActionState(S initialState) {\n                this.initialState = initialState;\n                this.finalState = null;\n            }\n\n            public ActionState(S initialState, S finalState) {\n                this.initialState = initialState;\n                this.finalState = finalState;\n            }\n\n            /**\n             * Create a problem model that uses explicit actions.\n             * This forces to implement functions to operate with actions,\n             * such as the {@link es.usc.citius.hipster.model.function.ActionFunction}\n             * to obtain applicable actions for a given state,\n             * or {@link es.usc.citius.hipster.model.function.ActionStateTransitionFunction}\n             * to apply actions to states in order to obtain new states.\n             * Use this function when you want to define explicitly the actions of your problem\n             * (for example, in the 8-Puzzle, actions are UP/DOWN/LEFT/RIGHT movements, see example\n             * problems for more information).\n             */\n            public WithAction defineProblemWithExplicitActions(){\n                return new WithAction();\n            }\n\n            /**\n             * This generates a simple problem model without explicit actions. Use this\n             * when you just want to create a simple {@link es.usc.citius.hipster.model.function.impl.StateTransitionFunction}\n             * for your search problem that defines the reachable states from\n             * a given states, without worrying about actions.\n             */\n            public WithoutAction defineProblemWithoutActions(){\n                return new WithoutAction();\n            }\n\n            /**\n             * Builder step to define a search problem without actions.\n             */\n            public final class WithoutAction {\n                private WithoutAction(){}\n\n\n                /**\n                 * Define the transition function for your problem. The transition function\n                 * ({@link es.usc.citius.hipster.model.function.impl.StateTransitionFunction})\n                 * is the function that computes all the reachable states from a given state.\n                 * <pre class=\"prettyprint\">\n                 * {@code\n                 * StateTransitionFunction<S> tf =\n                 *      new StateTransitionFunction<S>(){\n                 *          public Iterable<S> successorsOf(S state) {\n                 *              return successors; // return successors of state\n                 *          }\n                 *      }\n                 * }\n                 * </pre>\n                 *\n                 * @param transitionFunction transition function to be used.\n                 */\n                public Uninformed<Void> useTransitionFunction(TransitionFunction<Void, S> transitionFunction){\n                    return new Uninformed<Void>(transitionFunction);\n                }\n            }\n\n            /**\n             * Builder step to define a search problem with actions.\n             */\n            public final class WithAction {\n                private WithAction(){}\n\n                /**\n                 * Select the action function that returns the applicable actions for\n                 * each state in your problem.\n                 * @param actionFunction action function to be used.\n                 */\n                public <A> Action<A> useActionFunction(ActionFunction<A, S> actionFunction){\n                    return new Action<A>(actionFunction);\n                }\n\n                /**\n                 * Builder step to select the transition function of a action-explicit search problem.\n                 */\n                public final class Action<A> {\n                    private ActionFunction<A, S> af;\n\n                    public Action(ActionFunction<A, S> af) {\n                        this.af = af;\n                    }\n\n                    /**\n                     * Select the {@link es.usc.citius.hipster.model.function.ActionStateTransitionFunction}\n                     * that takes a state and an action and returns the resultant state of applying the action\n                     * to the state.\n                     *\n                     * @param atf action state function to be used.\n                     */\n                    public Uninformed<A> useTransitionFunction(ActionStateTransitionFunction<A, S> atf){\n                        return new Uninformed<A>(new LazyActionStateTransitionFunction<A, S>(af, atf));\n                    }\n                }\n\n                /**\n                 * Use a transition function that computes all the actions/states that are\n                 * reachable from a given state. The function returns a set of Transition\n                 * with the action and the new resultant state. If you prefer to define actions\n                 * separately, use useActionFunction instead.\n                 * @param transitionFunction transition function.\n                 *\n                 */\n                public <A> Uninformed<A> useTransitionFunction(TransitionFunction<A, S> transitionFunction){\n                    return new Uninformed<A>(transitionFunction);\n                }\n            }\n\n            /**\n             * Creates a uninformed problem (a problem without a cost/heuristic evaluator) to\n             * be used with uninformed algorithms like DFS, BFS.\n             *\n             * @param <A> action type.\n             */\n            public final class Uninformed<A> {\n                private final TransitionFunction<A,S> tf;\n\n                private Uninformed(TransitionFunction<A, S> tf){\n                    this.tf = tf;\n                }\n\n                public SearchProblem<A, S, UnweightedNode<A, S>> build(){\n                    NodeFactory<A,S,UnweightedNode<A,S>> factory = new NodeFactory<A, S, UnweightedNode<A, S>>() {\n                        @Override\n                        public UnweightedNode<A, S> makeNode(UnweightedNode<A, S> fromNode, Transition<A, S> transition) {\n                            return new UnweightedNode<A, S>(fromNode, transition);\n                        }\n                    };\n                    UnweightedNode<A,S> initialNode = factory.makeNode(null, Transition.<A, S>create(null, null, initialState));\n                    UnweightedNode<A,S> finalNode = factory.makeNode(null, Transition.<A, S>create(null, null, finalState));\n                    NodeExpander<A,S,UnweightedNode<A,S>> nodeExpander = new LazyNodeExpander<A, S, UnweightedNode<A, S>>(tf, factory);\n                    return new SearchProblem<A,S, UnweightedNode<A,S>>(initialNode, finalNode, nodeExpander);\n                }\n\n                /**\n                 * Define a cost function. This immediately defines an InformedSearchProblem\n                 * @param cf\n                 *\n                 */\n                public Informed<Double> useCostFunction(CostFunction<A, S, Double> cf){\n                    // Create default components\n                    return new Informed<Double>(cf, BinaryOperation.doubleAdditionOp());\n                }\n\n                public <C extends Comparable<C>> Informed<C> useGenericCostFunction(CostFunction<A,S,C> cf, BinaryOperation<C> costAlgebra){\n                    return new Informed<C>(cf, costAlgebra);\n                }\n\n                /**\n                 * An informed search problem builder generates informed search problems with a generic cost\n                 */\n                public final class Informed<C extends Comparable<C>> {\n                    private CostFunction<A,S,C> cf;\n                    private BinaryOperation<C> costAlgebra;\n\n                    public Informed(CostFunction<A, S, C> cf, BinaryOperation<C> costAlgebra) {\n                        this.cf = cf;\n                        this.costAlgebra = costAlgebra;\n                    }\n\n                    public SearchProblem<A, S, WeightedNode<A, S, C>> build(){\n                        WeightedNodeFactory<A,S,C> factory = new WeightedNodeFactory<A,S,C>(\n                                cf,\n                                new HeuristicFunction<S, C>() {\n                                    @Override\n                                    public C estimate(S state) {\n                                        return costAlgebra.getIdentityElem();\n                                    }\n                                }, costAlgebra);\n                        // Make the initial node. The initial node contains the initial state\n                        // of the problem, and it comes from no previous node (null) and using no action (null)\n                        WeightedNode<A,S,C> initialNode = factory.makeNode(null, Transition.<A,S>create(null, null, initialState));\n                        // Create a Lazy Node Expander by default\n                        NodeExpander<A,S,WeightedNode<A,S,C>> expander = new LazyNodeExpander<A, S, WeightedNode<A, S, C>>(tf, factory);\n                        // Create the algorithm with all those components\n                        return new SearchProblem<A,S,WeightedNode<A,S,C>>(initialNode, expander);\n                    }\n\n                    public Heuristic useHeuristicFunction(HeuristicFunction<S, C> hf){\n                        return new Heuristic(hf);\n                    }\n\n                    /**\n                     * Defines the heuristic function to be used.\n                     */\n                    public final class Heuristic {\n                        private HeuristicFunction<S,C> hf;\n\n                        public Heuristic(HeuristicFunction<S, C> hf) {\n                            this.hf = hf;\n                        }\n\n                        public SearchProblem<A, S, WeightedNode<A, S, C>> build(){\n                            WeightedNodeFactory<A, S, C> factory = new WeightedNodeFactory<A,S,C>(\n                                    cf, hf, costAlgebra);\n                            WeightedNode<A,S,C> initialNode = factory.makeNode(null, Transition.<A,S>create(null, null, initialState));\n                            LazyNodeExpander<A, S, WeightedNode<A, S, C>> nodeExpander =\n                                    new LazyNodeExpander<A, S, WeightedNode<A, S, C>>(tf, factory);\n\n                            return new SearchProblem<A, S, WeightedNode<A,S,C>>(initialNode, nodeExpander);\n                        }\n                    }\n                }\n            }\n        }\n\n        public <S> ActionState<S> initialState(S initialState){\n            return new ActionState<S>(initialState);\n        }\n\n        public <S> ActionState<S> initialState(S initialState, S finalState){\n            return new ActionState<S>(initialState, finalState);\n        }\n\n    }\n\n    /**\n     * <p>\n     * Creates the builder. Chain method calls until you have the problem\n     * ready to call {@code build()}. Example usage:\n     * </p>\n     * <pre class=\"prettyprint\">\n     *     {@code\n     *     Hipster.SearchProblem p =\n     *          ProblemBuilder.create()\n     *              .initialState(initialState)\n     *              .defineProblemWithExplicitActions()\n     *                  .useActionFunction(af)\n     *                  .useTransitionFunction(atf)\n     *                  .useCostFunction(cf)\n     *                  .useHeuristicFunction(hf)\n     *                  .build();\n     *     }\n     * </pre>\n     */\n    public static Wizard create(){\n        return new Wizard();\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/problem/SearchComponents.java",
    "content": "package es.usc.citius.hipster.model.problem;\n\nimport es.usc.citius.hipster.model.function.CostFunction;\nimport es.usc.citius.hipster.model.function.HeuristicFunction;\nimport es.usc.citius.hipster.model.function.TransitionFunction;\nimport es.usc.citius.hipster.model.function.impl.BinaryOperation;\nimport es.usc.citius.hipster.model.function.impl.ScalarOperation;\n\n/**\n * This class should be used to instantiate an ADStar algorithm through the {@code Hipster.createADStar} method.\n * This may change in future versions.\n *\n * @author Adrián González Sieira <adrian.gonzalez@usc.es>\n */\npublic class SearchComponents<A, S, C extends Comparable<C>> {\n\n    // NOTE: This part of the API is still under discussion and is subject to changes\n    // in future versions. \n\n    private final CostFunction<A, S, C> cf;\n    private final HeuristicFunction<S, C> hf;\n    private final TransitionFunction<A, S> sf;\n    private final TransitionFunction<A, S> pf;\n    private final BinaryOperation<C> costAlgebra;\n    private final ScalarOperation<C> scaleAlgebra;\n    private final S begin;\n    private final S goal;\n\n    public SearchComponents(S begin, S goal, CostFunction<A, S, C> cf, HeuristicFunction<S, C> hf, TransitionFunction<A, S> sf,\n                            TransitionFunction<A, S> pf, BinaryOperation<C> costAlgebra, ScalarOperation<C> scaleOperation) {\n        this.begin = begin;\n        this.goal = goal;\n        this.cf = cf;\n        this.hf = hf;\n        this.sf = sf;\n        this.pf = pf;\n        this.costAlgebra = costAlgebra;\n        this.scaleAlgebra = scaleOperation;\n    }\n\n    public SearchComponents(S begin, S goal, CostFunction<A, S, C> cf, HeuristicFunction<S, C> hf, TransitionFunction<A, S> sf,\n                            BinaryOperation<C> costAlgebra) {\n        this(begin, goal, cf, hf, sf, null, costAlgebra, null);\n    }\n\n    public SearchComponents(S begin, S goal, CostFunction<A, S, C> cf, HeuristicFunction<S, C> hf, TransitionFunction<A, S> sf,\n                            BinaryOperation<C> costAlgebra, ScalarOperation<C> scaleOperation) {\n        this(begin, goal, cf, hf, sf, null, costAlgebra, scaleOperation);\n    }\n\n    public CostFunction<A, S, C> costFunction() {\n        return cf;\n    }\n\n    public HeuristicFunction<S, C> heuristicFunction() {\n        return hf;\n    }\n\n    public TransitionFunction<A, S> successorFunction() {\n        return sf;\n    }\n\n    public TransitionFunction<A, S> predecessorFunction() {\n        return pf;\n    }\n\n    public BinaryOperation<C> costAlgebra() {\n        return costAlgebra;\n    }\n\n    public ScalarOperation<C> scaleAlgebra() {\n        return scaleAlgebra;\n    }\n\n    public S getBegin() {\n        return begin;\n    }\n\n    public S getGoal() {\n        return goal;\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/problem/SearchProblem.java",
    "content": "package es.usc.citius.hipster.model.problem;\n\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.model.function.NodeExpander;\n\n/**\n * Defines a search problems in terms of a initial node to start with and the node expander\n * function that generates new successor nodes. A SearchProblem can be fully defined using\n * the {@link es.usc.citius.hipster.model.problem.ProblemBuilder} class assistant builder.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class SearchProblem<A,S,N extends Node<A,S,N>> {\n    private N initialNode;\n    private N finalNode;\n    private NodeExpander<A,S,N> expander;\n\n    public SearchProblem(N initialNode, NodeExpander<A, S, N> expander) {\n        this.initialNode = initialNode;\n        this.finalNode = null;\n        this.expander = expander;\n    }\n\n    public SearchProblem(N initialNode, N finalNode, NodeExpander<A, S, N> expander) {\n        this.initialNode = initialNode;\n        this.finalNode = finalNode;\n        this.expander = expander;\n    }\n\n    public N getInitialNode() {\n        return initialNode;\n    }\n\n    public NodeExpander<A, S, N> getExpander() {\n        return expander;\n    }\n\n    public N getFinalNode() {\n        return finalNode;\n    }\n\n    public void setFinalNode(N finalNode) {\n        this.finalNode = finalNode;\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/model/problem/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * <p>\n * Util classes to create a new search problem. Use {@link es.usc.citius.hipster.model.problem.ProblemBuilder}\n * to define a search problem required to instantiate a new algorithm with {@link es.usc.citius.hipster.algorithm.Hipster}\n * class. Example:\n * </p>\n * <pre class=\"prettyprint\">\n *     {@code\n *     Hipster.SearchProblem p =\n *          ProblemBuilder.create()\n *              .initialState(initialState)\n *              .defineProblemWithExplicitActions()\n *                  .useActionFunction(af)\n *                  .useTransitionFunction(atf)\n *                  .useCostFunction(cf)\n *                  .useHeuristicFunction(hf)\n *                  .build();\n *\n *     Hipster.createAStar(p).search(goalState);\n *     }\n * </pre>\n */\npackage es.usc.citius.hipster.model.problem;"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/util/F.java",
    "content": "package es.usc.citius.hipster.util;\n\n\nimport java.util.Iterator;\n\n\n/**\n * This class contains a very limited set of functions to process iterables and iterators in a lazy way.\n * Guava / Java 8 is not an option due to current size / compatibility restrictions.\n * Required since the removal of Guava dependencies (issue #125 https://github.com/citiususc/hipster/issues/125)\n * NOTE: This class may be removed in future versions to take advantage of Java 8 functional Streams\n *\n * Pure functional programmers, please forgive us for this crime\n *\n * @author Pablo Rodríguez Mier\n */\npublic final class F {\n\n    private F() {}\n\n    public static <T,E> Iterable<E> map(final Iterable<T> it, final Function<? super T,? extends E> mapf){\n        return new Iterable<E>() {\n            @Override\n            public Iterator<E> iterator() {\n                return map(it.iterator(), mapf);\n            }\n        };\n    }\n\n    public static <T,E> Iterator<E> map(final Iterator<T> it, final Function<? super T,? extends E> mapf){\n        return new Iterators.AbstractIterator<E>() {\n            @Override\n            protected E computeNext() {\n                if (it.hasNext()){\n                    return mapf.apply(it.next());\n                }\n                return null;\n            }\n        };\n    }\n\n    public static <T> Iterable<T> filter(final Iterable<T> it, final Function<? super T, Boolean> condition) {\n        return new Iterable<T>() {\n            @Override\n            public Iterator<T> iterator() {\n                return filter(it.iterator(), condition);\n            }\n        };\n    }\n\n    public static <T> Iterator<T> filter(final Iterator<T> it, final Function<? super T, Boolean> condition) {\n        return new Iterators.AbstractIterator<T>() {\n            @Override\n            protected T computeNext() {\n                while(it.hasNext()){\n                    T next = it.next();\n                    if (condition.apply(next)){\n                        return next;\n                    }\n                }\n                return null;\n            }\n        };\n    }\n\n    public static <E,T> Iterable<T> flatMap(final Iterable<E> it, final Function<? super E, ? extends Iterable<? extends T>> mapf){\n        return new Iterable<T>() {\n            @Override\n            public Iterator<T> iterator() {\n                return flatMap(it.iterator(), new Function<E, Iterator<? extends T>>() {\n                    @Override\n                    public Iterator<? extends T> apply(E input) {\n                        return mapf.apply(input).iterator();\n                    }\n                });\n            }\n        };\n    }\n\n    public static <E,T> Iterator<T> flatMap(final Iterator<E> it, final Function<? super E, ? extends Iterator<? extends T>> mapf){\n        return new Iterators.AbstractIterator<T>() {\n            Iterator<Iterator<? extends T>> mapIt = map(it, mapf);\n            Iterator<? extends T> current = mapIt.hasNext() ? mapIt.next() : Iterators.<T>empty();\n\n            @Override\n            protected T computeNext() {\n                if (current.hasNext()) return current.next();\n                if (mapIt.hasNext()){\n                    current = mapIt.next();\n                    return computeNext();\n                }\n                return null;\n            }\n        };\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/util/Function.java",
    "content": "package es.usc.citius.hipster.util;\n\n/**\n *\n *\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic interface Function<E, V> {\n\n    public V apply(E input);\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/util/Iterators.java",
    "content": "package es.usc.citius.hipster.util;\n\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic final class Iterators {\n\n    public static abstract class AbstractIterator<E> implements Iterator<E> {\n        protected E current;\n\n        protected AbstractIterator(){}\n\n        protected abstract E computeNext();\n\n        @Override\n        public boolean hasNext() {\n            if (current == null){\n                current = computeNext();\n            }\n            return current != null;\n        }\n\n        @Override\n        public E next() {\n            E next;\n            if (current != null) {\n                next = current;\n                current = null;\n                return next;\n            } else {\n                next = computeNext();\n                if (next == null) throw new NoSuchElementException(\"next\");\n                return next;\n            }\n        }\n\n        @Override\n        public void remove() {\n            throw new UnsupportedOperationException(\"remove\");\n        }\n    }\n\n    public static <E> Iterator<E> empty() {\n        return new AbstractIterator<E>() {\n            @Override\n            protected E computeNext() {\n                return null;\n            }\n        };\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/util/Predicate.java",
    "content": "package es.usc.citius.hipster.util;\n\n/**\n * Definition of predictcate to be used with search iterators implementing the\n * class {@link es.usc.citius.hipster.algorithm.Algorithm}. A predicate can\n * be used to define the stop condition of the algorithm\n * when using the method {@link es.usc.citius.hipster.algorithm.Algorithm#se}\n *\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic interface Predicate<T extends Object> {\n\n    public boolean apply(T input);\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/util/examples/RomanianProblem.java",
    "content": "package es.usc.citius.hipster.util.examples;\n\nimport es.usc.citius.hipster.graph.GraphBuilder;\nimport es.usc.citius.hipster.model.function.HeuristicFunction;\nimport es.usc.citius.hipster.graph.HipsterGraph;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * <p>\n * Definition of the states, transitions, costs and heuristics for the Romania Problem\n * as described in http://www.pearsonhighered.com/assets/hip/us/hip_us_pearsonhighered/samplechapter/0136042597.pdf.\n * </p>\n *\n * <img src=\"../../../../../../../assets/images/javadoc/romanian-problem.png\" />\n *\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class RomanianProblem {\n\n    /**\n     * Enum with all the cities of the problem.\n     */\n    public enum City{\n        Arad, Bucharest, Craiova, Drobeta, Eforie, Fagaras, Giurgiu,\n        Hirsova, Iasi, Lugoj, Mehadia, Neamt, Oradea, Pitesti, Rimnicu_Vilcea,\n        Sibiu, Timisoara,  Urziceni, Vaslui, Zerind;\n    }\n\n    private static final Map<City, Double> heuristicMap = new HashMap<City, Double>();\n    private static final HipsterGraph<City,Double> graph;\n\n    /**\n     * Define the heuristic values of the problem and create the graph.\n     */\n    static {\n        heuristicMap.put(City.Oradea, 380d);\n        heuristicMap.put(City.Zerind, 374d);\n        heuristicMap.put(City.Arad, 366d);\n        heuristicMap.put(City.Timisoara, 329d);\n        heuristicMap.put(City.Lugoj, 244d);\n        heuristicMap.put(City.Mehadia, 241d);\n        heuristicMap.put(City.Drobeta, 242d);\n        heuristicMap.put(City.Craiova, 160d);\n        heuristicMap.put(City.Rimnicu_Vilcea, 193d);\n        heuristicMap.put(City.Pitesti, 100d);\n        heuristicMap.put(City.Sibiu, 253d);\n        heuristicMap.put(City.Fagaras, 176d);\n        heuristicMap.put(City.Giurgiu, 77d);\n        heuristicMap.put(City.Urziceni, 80d);\n        heuristicMap.put(City.Hirsova, 151d);\n        heuristicMap.put(City.Eforie, 161d);\n        heuristicMap.put(City.Vaslui, 199d);\n        heuristicMap.put(City.Iasi, 226d);\n        heuristicMap.put(City.Neamt, 234d);\n        heuristicMap.put(City.Bucharest, 0d);\n\n        graph = GraphBuilder.<City,Double>create()\n                .connect(City.Arad).to(City.Zerind).withEdge(75d)\n                .connect(City.Arad).to(City.Timisoara).withEdge(118d)\n                .connect(City.Arad).to(City.Sibiu).withEdge(140d)\n                .connect(City.Bucharest).to(City.Giurgiu).withEdge(90d)\n                .connect(City.Bucharest).to(City.Urziceni).withEdge(85d)\n                .connect(City.Bucharest).to(City.Fagaras).withEdge(211d)\n                .connect(City.Bucharest).to(City.Pitesti).withEdge(101d)\n                .connect(City.Craiova).to(City.Drobeta).withEdge(120d)\n                .connect(City.Craiova).to(City.Rimnicu_Vilcea).withEdge(146d)\n                .connect(City.Craiova).to(City.Pitesti).withEdge(138d)\n                .connect(City.Drobeta).to(City.Mehadia).withEdge(75d)\n                .connect(City.Eforie).to(City.Hirsova).withEdge(86d)\n                .connect(City.Fagaras).to(City.Sibiu).withEdge(99d)\n                .connect(City.Hirsova).to(City.Urziceni).withEdge(98d)\n                .connect(City.Iasi).to(City.Neamt).withEdge(87d)\n                .connect(City.Iasi).to(City.Vaslui).withEdge(92d)\n                .connect(City.Lugoj).to(City.Timisoara).withEdge(111d)\n                .connect(City.Lugoj).to(City.Mehadia).withEdge(70d)\n                .connect(City.Oradea).to(City.Zerind).withEdge(71d)\n                .connect(City.Oradea).to(City.Sibiu).withEdge(151d)\n                .connect(City.Pitesti).to(City.Rimnicu_Vilcea).withEdge(97d)\n                .connect(City.Rimnicu_Vilcea).to(City.Sibiu).withEdge(80d)\n                .connect(City.Urziceni).to(City.Vaslui).withEdge(142d)\n                .createUndirectedGraph();\n\n\n    }\n\n    /**\n     * Returns a {@link es.usc.citius.hipster.graph.HipsterGraph} that represents the map of Romania.\n     * @return graph with the cities and costs.\n     */\n    public static HipsterGraph<City, Double> graph(){\n        return graph;\n    }\n\n    /**\n     * Heuristics definition for the Romania problem. Goal is considered Bucharest.\n     * @return map with the heuristics definition for the Romania problem.\n     */\n    public static Map<City, Double> heuristics(){\n        return heuristicMap;\n    }\n\n    /**\n     * Heuristic function required to define search problems to be used with Hipster.\n     * @see es.usc.citius.hipster.model.problem.SearchProblem\n     * @return {@link es.usc.citius.hipster.model.function.HeuristicFunction} with the {@link #heuristics()} values.\n     */\n    public static HeuristicFunction<City, Double> heuristicFunction(){\n        return new HeuristicFunction<City, Double>() {\n            @Override\n            public Double estimate(City state) {\n                return heuristics().get(state);\n            }\n        };\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/util/examples/maze/Maze2D.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS).\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage es.usc.citius.hipster.util.examples.maze;\n\nimport java.awt.*;\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.*;\nimport java.util.List;\n\n/**\n * <p>\n * This class defines a 2D ASCII Maze used to easily validate the search algorithms.\n * Example usage:</p>\n *\n * <pre>\n *     {@code public static String[] example = new String[]{\n *                  \"XXSXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",\n *                  \"XX XXXXXXXXXXXXX     XXXXXXXXXXX\",\n *                  \"XX    XXXXXXXXXX XXX XX     XXXX\",\n *                  \"XXXXX  XXXXXX    XXX XX XXX XXXX\",\n *                  \"XXX XX XXXXXX XX XXX XX  XX XXXX\",\n *                  \"XXX     XXXXX XXXXXX XXXXXX XXXX\",\n *                  \"XXXXXXX       XXXXXX        XXXX\",\n *                  \"XXXXXXXXXX XXXXX XXXXXXXXXXXXXXX\",\n *                  \"XXXXXXXXXX XX    XXXXX      XXXX\",\n *                  \"XXXXXXXXXX    XXXXXXXX XXXX XXXX\",\n *                  \"XXXXXXXXXXX XXXXXXXXXX XXXX XXXX\",\n *                  \"XXXXXXXXXXX            XXXX XXXX\",\n *                  \"XXXXXXXXXXXXXXXXXXXXXXXX XX XXXX\",\n *                  \"XXXXXX              XXXX XX XXXX\",\n *                  \"XXXXXX XXXXXXXXXXXX XX      XXXX\",\n *                  \"XXXXXX XXG   XXXXXX XXXX XXXXXXX\",\n *                  \"XXXXXX XXXXX   XXX            XX\",\n *                  \"XXXXXX XXXXXXX XXXXXXXXXXX XXXXX\",\n *                  \"XXXXXX XXXXXXX XXXXXXXXXXXXXXXXX\",\n *                  \"XXXXXX            XXXXXXXXXXXXXX\"};\n *\n *            Maze2D maze = new Maze2D(example);\n *     }\n * </pre>\n *\n * Symbol connected used by Maze2D:\n * <ul>\n *     <li>\"X\": occupied tile</li>\n *     <li>\" \": empty tile</li>\n *     <li>\"S\": initial state (starting point)</li>\n *     <li>\"G\": goal state</li>\n *     <li>\".\": visited tile</li>\n * </ul>\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class Maze2D {\n\n    private char maze[][];\n    private Point initialLoc;\n    private Point goalLoc;\n    private int rows;\n    private int columns;\n    private static Set<Character> FREE_TILES = new HashSet<Character>(Arrays.asList(' ', 'S', 'G', '.'));\n\n    /**\n     * Symbols allowed to create a maze\n     */\n    public static enum Symbol {\n        OCCUPIED('X'),\n        EMPTY(' '),\n        START('S'),\n        GOAL('G'),\n        VISITED('.');\n        public final char character;\n\n        Symbol(char symbol) {\n            this.character = symbol;\n        }\n\n        public char value() {\n            return character;\n        }\n\n        public static Symbol parse(char c) {\n            for (Symbol s : Symbol.values()) {\n                if (s.character == c) {\n                    return s;\n                }\n            }\n            // If the symbol is not recognized, it is considered as an occupied tile\n            return OCCUPIED;\n        }\n    }\n\n    /**\n     * Creates a new 2D ASCII Maze.\n     *\n     * @param maze    2D Byte array of that represents the maze using {@link Symbol}\n     */\n    public Maze2D(char maze[][]) {\n        this.maze = maze;\n        this.rows = maze.length;\n        this.columns = findMaxRowLength(maze);\n        this.initialLoc = charToPoint(Symbol.START.value());\n        this.goalLoc = charToPoint(Symbol.GOAL.value());\n    }\n\n    private Point charToPoint(char c){\n        for(int row = 0; row < this.rows; row++){\n            for(int column = 0; column < this.columns; column++){\n                if (maze[row][column] == c) return new Point(column, row);\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Creates a new 2D ASCII Maze from a array of Strings.\n     *\n     * @param maze2D Array of strings representing the maze. Use symbols from {@code Symbol}\n     */\n    public Maze2D(String[] maze2D) throws IllegalFormatException {\n        // Initialize maze\n        this.rows = maze2D.length;            // y axis (rows)\n        this.columns = findMaxRowLength(maze2D);  // x axis (columns)\n\n        maze = new char[rows][columns];\n        // Define valid cells\n        for (int row = 0; row < this.rows; row++) {\n            // if the current row has less than 'columns' characters, fill with empty tiles\n            if (maze2D[row].length() < this.columns) {\n                String string = \"\";\n                for(int i = 0; i < this.columns - maze2D[row].length(); i++) {\n                    string = string.concat(String.valueOf(Symbol.EMPTY.value()));\n                }\n                maze2D[row] = maze2D[row].concat(string);\n            }\n            for (int column = 0; column < this.columns; column++) {\n                char charPoint = maze2D[row].charAt(column);\n                // Parse character\n                maze[row][column] = charPoint;\n                // Note that point(x=2,y=1) is located in maze[1][2]\n                if (maze[row][column] == Symbol.GOAL.value()) {\n                    this.goalLoc = new Point(column, row);\n                } else if (maze[row][column] == Symbol.START.value()) {\n                    this.initialLoc = new Point(column, row);\n                }\n            }\n        }\n\n        if (this.getInitialLoc() == null){\n            throw new IllegalArgumentException(\"No initial location. Use the symbol S\");\n        }\n\n        if (this.getGoalLoc() == null){\n            throw new IllegalArgumentException(\"No goal location. Use the symbol G\");\n        }\n    }\n\n    /**\n     * Find the maximum length of the rows of the maze.\n     *\n     * @param maze instance of maze\n     * @return max lenght of all rows\n     */\n    private int findMaxRowLength(String maze[]){\n        int max = 0;\n        for (String rowMaze : maze) {\n            if (rowMaze.length() > max) max = rowMaze.length();\n        }\n        return max;\n    }\n\n    /**\n     * Find the maximum length of the rows of the maze.\n     *\n     * @param maze instance of maze\n     * @return max lenght of all rows\n     */\n    private int findMaxRowLength(char maze[][]){\n        int max = 0;\n        for (int row = 0; row < maze.length; row++) {\n            if (maze[row].length > max) max = maze[row].length;\n        }\n        return max;\n    }\n\n    /**\n     * Read a maze from a file in plain text.\n     *\n     * @param file file with the plain ascii text.\n     * @return a new Maze2D.\n     * @throws IOException\n     */\n    public static Maze2D read(File file) throws IOException {\n        ArrayList<String> array = new ArrayList<String>();\n        BufferedReader br = new BufferedReader(new FileReader(file));\n        String line;\n        while ((line = br.readLine()) != null) {\n            array.add(line);\n        }\n        br.close();\n        return new Maze2D((String[]) array.toArray());\n    }\n\n    /**\n     * Check if the point {@code p} in the maze is empty or occupied.\n     *\n     * @param p Point to check\n     * @return True if is free, false if is not empty.\n     */\n    public boolean isFree(Point p) {\n        return FREE_TILES.contains(this.maze[p.y][p.x]);\n    }\n\n    /**\n     * Return all tiles (i,j) of the maze\n     *\n     * @return List of points, from (0,0) to (m,n).\n     */\n    public List<Point> getMazePoints() {\n        List<Point> points = new ArrayList<Point>();\n        for (int row = 0; row < this.rows; row++) {\n            for (int column = 0; column < this.columns; column++) {\n                points.add(new Point(column, row));\n            }\n        }\n        return points;\n    }\n\n    /**\n     * Replace a tile in the maze\n     *\n     * @param p      Point of the tile to be replaced\n     * @param symbol New symbol\n     */\n    public void updateLocation(Point p, Symbol symbol) {\n        int row = p.y;\n        int column = p.x;\n        this.maze[row][column] = symbol.value();\n    }\n\n    /**\n     * Replace all tiles inside the rectangle with the provided symbol.\n     * @param a point a of the rectangle.\n     * @param b point b of the rectangle.\n     * @param symbol symbol to be inserted in each tile.\n     */\n    public void updateRectangle(Point a, Point b, Symbol symbol) {\n        int xfrom = (a.x < b.x) ? a.x : b.x;\n        int xto = (a.x > b.x) ? a.x : b.x;\n        int yfrom = (a.y < b.y) ? a.y : b.y;\n        int yto = (a.y > b.y) ? a.y : b.y;\n        for (int x = xfrom; x <= xto; x++) {\n            for (int y = yfrom; y <= yto; y++) {\n                updateLocation(new Point(x, y), symbol);\n            }\n        }\n    }\n\n    /**\n     * Puts a {@link Symbol#OCCUPIED} in the indicated point.\n     * @param p point to put an obstacle in.\n     */\n    public void putObstacle(Point p) {\n        updateLocation(p, Symbol.OCCUPIED);\n    }\n\n    /**\n     * Puts a {@link Symbol#EMPTY} character in the indicated point.\n     * @param p point to be free.\n     */\n    public void removeObstacle(Point p) {\n        updateLocation(p, Symbol.EMPTY);\n    }\n\n    /**\n     * Fill a rectangle defined by points a and b with occupied tiles.\n     * @param a point a of the rectangle.\n     * @param b point b of the rectangle.\n     */\n    public void putObstacleRectangle(Point a, Point b) {\n        updateRectangle(a, b, Symbol.OCCUPIED);\n    }\n\n    /**\n     * Fill a rectangle defined by points a and b with empty tiles.\n     * @param a point a of the rectangle.\n     * @param b point b of the rectangle.\n     */\n    public void removeObstacleRectangle(Point a, Point b) {\n        updateRectangle(a, b, Symbol.EMPTY);\n    }\n\n    /**\n     * Generates a string representation of this maze but replacing all the indicated\n     * points with the characters provided.\n     * @param replacements list with maps of point-character replacements.\n     * @return String representation of the maze with the replacements.\n     */\n    public String getReplacedMazeString(List<Map<Point, Character>> replacements) {\n        String[] stringMaze = toStringArray();\n        for (Map<Point, Character> replacement : replacements) {\n            for (Point p : replacement.keySet()) {\n                int row = p.y;\n                int column = p.x;\n                char c = stringMaze[row].charAt(column);\n                if (c != Symbol.START.value() && c != Symbol.GOAL.value()) {\n                    stringMaze[row] = replaceChar(stringMaze[row], column, replacement.get(p));\n                }\n            }\n        }\n        String output = \"\";\n        for (String line : stringMaze) {\n            output += String.format(\"%s%n\", line);\n        }\n        return output;\n    }\n\n    /**\n     * Generates a string representation of this maze, with the indicated points replaced\n     * with the symbol provided.\n     * @param points points of the maze.\n     * @param symbol symbol to be inserted in each point.\n     * @return the string representation of the maze with the points changed.\n     */\n    public String getStringMazeFilled(Collection<Point> points, char symbol) {\n        Map<Point, Character> replacements = new HashMap<Point, Character>();\n        for (Point p : points) {\n            replacements.put(p, symbol);\n        }\n        return getReplacedMazeString(Collections.singletonList(replacements));\n    }\n\n    private static String replaceChar(String line, int position, char c) {\n        StringBuilder l = new StringBuilder(line);\n        l.setCharAt(position, c);\n        return l.toString();\n    }\n\n    /**\n     * Calculates whether a location is empty or not.\n     * @param loc point location to be tested.\n     * @return true if point is filled with {@link Symbol#EMPTY}. False otherwise.\n     */\n    public boolean validLocation(Point loc) {\n        try {\n            return isFree(loc);\n        } catch (ArrayIndexOutOfBoundsException ex) {\n            return false;\n        }\n    }\n\n    /**\n     * Check if the provided point is in the maze bounds or outside.\n     * @param loc point to be tested.\n     * @return true if the point is in the maze.\n     */\n    public boolean pointInBounds(Point loc) {\n        return loc.x >= 0 && loc.x < this.columns && loc.y >= 0 && loc.y < this.rows;\n    }\n\n    /**\n     * Return all neighbor empty points from a specific location point.\n     * @param loc source point\n     * @return collection of empty neighbor points.\n     */\n    public Collection<Point> validLocationsFrom(Point loc) {\n        Collection<Point> validMoves = new HashSet<Point>();\n        // Check for all valid movements\n        for (int row = -1; row <= 1; row++) {\n            for (int column = -1; column <= 1; column++) {\n                try {\n                    if (isFree(new Point(loc.x + column, loc.y + row))) {\n                        validMoves.add(new Point(loc.x + column, loc.y + row));\n                    }\n                } catch (ArrayIndexOutOfBoundsException ex) {\n                    // Invalid move!\n                }\n            }\n        }\n        validMoves.remove(loc);\n\n        return validMoves;\n    }\n\n    public char[][] getMazeCharArray() {\n        return maze;\n    }\n\n    public String[] toStringArray() {\n        char[][] chars = getMazeCharArray();\n        String[] str = new String[chars.length];\n        for (int i = 0; i < chars.length; i++) {\n            str[i] = String.copyValueOf(chars[i]);\n        }\n        return str;\n    }\n\n    @Override\n    public String toString() {\n        String output = \"\";\n        String[] stringArray = toStringArray();\n        for (int i = 0; i < maze.length; i++) {\n            output += String.format(\"%s%n\", stringArray[i]);\n        }\n        return output;\n    }\n\n    /**\n     * Returns a set of points that are different with respect this maze.\n     * Both mazes must have same size.\n     * @param to maze to be compared.\n     * @return set of different points.\n     */\n    public Set<Point> diff(Maze2D to) {\n        char[][] maze1 = this.getMazeCharArray();\n        char[][] maze2 = to.getMazeCharArray();\n        Set<Point> differentLocations = new HashSet<Point>();\n        for (int row = 0; row < this.rows; row++) {\n            for (int column = 0; column < this.columns; column++) {\n                if (maze1[row][column] != maze2[row][column]) {\n                    differentLocations.add(new Point(column, row));\n                }\n            }\n        }\n        return differentLocations;\n    }\n\n    /**\n     * Get this maze as a byte array.\n     * @return\n     */\n    public char[][] getMaze() {\n        return maze;\n    }\n\n    /**\n     * Get the initial point (the point with the symbol {@link Symbol#START}) in this maze.\n     * @return\n     */\n    public Point getInitialLoc() {\n        return initialLoc;\n    }\n\n    /**\n     * Get the goal point (the point with the symbol {@link Symbol#GOAL}) in this maze.\n     * @return\n     */\n    public Point getGoalLoc() {\n        return goalLoc;\n    }\n\n    /**\n     * Generate an empty squared maze of the indicated size.\n     * @param size maze size.\n     * @return empty maze.\n     */\n    public static Maze2D empty(int size) {\n        char[][] maze = new char[size][size];\n        for (int i = 0; i < size; i++) {\n            Arrays.fill(maze[i], Symbol.EMPTY.value());\n        }\n        maze[0][0] = Symbol.START.value();\n        maze[size][size] = Symbol.GOAL.value();\n        return new Maze2D(maze);\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/util/examples/maze/MazeSearch.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS).\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage es.usc.citius.hipster.util.examples.maze;\n\n\nimport es.usc.citius.hipster.model.Node;\n\nimport java.awt.*;\nimport java.util.*;\nimport java.util.List;\n\n\n/**\n * This class executes the search iterators over maps of type {@link es.usc.citius.hipster.util.examples.maze.Maze2D}.\n * And prints the results in the console.\n *\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic final class MazeSearch {\n\n\n    private MazeSearch() {\n    }\n\n    /**\n     * Inner class to define the results of the search process over\n     * {@link es.usc.citius.hipster.util.examples.maze.Maze2D}.\n     */\n    public static final class Result {\n\n        public static final Result NO_RESULT = new Result(Collections.EMPTY_LIST, Double.POSITIVE_INFINITY);\n        private List<Point> path;\n        private Double cost;\n\n        public Result(List<Point> path, Double cost) {\n            this.path = path;\n            this.cost = cost;\n        }\n\n        public Double getCost() {\n            return cost;\n        }\n\n        public List<Point> getPath() {\n            return path;\n        }\n\n        @Override\n        public int hashCode() {\n            int hash = 3;\n            hash = 83 * hash + (this.path != null ? this.path.hashCode() : 0);\n            hash = 83 * hash + (this.cost != null ? this.cost.hashCode() : 0);\n            return hash;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (obj == null) {\n                return false;\n            }\n            if (getClass() != obj.getClass()) {\n                return false;\n            }\n            final Result other = (Result) obj;\n            if (this.path != other.path && (this.path == null || !this.path.equals(other.path))) {\n                return false;\n            }\n            return !(this.cost != other.cost && (this.cost == null || !this.cost.equals(other.cost)));\n        }\n    }\n\n    /**\n     * Prints the maze and the result of the current iteration until the solution is found.\n     *\n     * @param it search iterator\n     * @param maze maze to perform the search\n     * @throws InterruptedException sleep exception between iterations\n     */\n    public static void printSearch(Iterator<? extends Node<?,Point,?>> it, Maze2D maze) throws InterruptedException {\n        Collection<Point> explored = new HashSet<Point>();\n        while (it.hasNext()) {\n            Node<?,Point,?> currentNode = it.next();\n            if (currentNode.previousNode() != null) {\n                explored.add(currentNode.previousNode().state());\n            }\n            List<Point> statePath = new ArrayList<Point>();\n            for(Node<?, Point, ?> current : currentNode.path()){\n                statePath.add(current.state());\n            }\n            //clearOutput(20);\n            System.out.println(getMazeStringSolution(maze, explored, statePath));\n            Thread.sleep(50);\n            if (currentNode.state().equals(maze.getGoalLoc())) {\n                return;\n            }\n        }\n    }\n\n    /**\n     * Clears the output of the console between results printed by {@link #printSearch(java.util.Iterator, Maze2D)}.\n     *\n     * @param newlines number of new lines\n     */\n    public static void clearOutput(int newlines) {\n        char[] chars = new char[newlines];\n        Arrays.fill(chars, '\\n');\n        System.out.println(chars);\n    }\n\n    /**\n     * Returns the maze passed as parameter but replacing some characters to print the path found in the\n     * current iteration.\n     *\n     * @param maze used to search\n     * @param explored collection of the points of the maze explored by the iterator\n     * @param path current path found by the iterator\n     * @return maze with the characters of the explored points and the current path replaced, to print the results in the console\n     */\n    public static String getMazeStringSolution(Maze2D maze, Collection<Point> explored, Collection<Point> path) {\n        List<Map<Point, Character>> replacements = new ArrayList<Map<Point, Character>>();\n        Map<Point, Character> replacement = new HashMap<Point, Character>();\n        for (Point p : explored) {\n            replacement.put(p, '.');\n        }\n        replacements.add(replacement);\n        replacement = new HashMap<Point, Character>();\n        for (Point p : path) {\n            replacement.put(p, '*');\n        }\n        replacements.add(replacement);\n        return maze.getReplacedMazeString(replacements);\n    }\n\n\n    /*\n    public static Result executeIteratorSearch(Iterator<? extends CostNode<Point, Double>> it, Point goal) {\n        int steps = 0;\n        while (it.hasNext()) {\n            CostNode<Point, Double> currentNode = it.next();\n            steps++;\n            if (currentNode.transition().to().equals(goal)) {\n                List<Node<Point>> nodePath = currentNode.path();\n                Double cost = currentNode.getCost();\n                List<Point> statePath = AbstractNode.statesFrom(nodePath);\n                return new Result(statePath, cost);\n            }\n        }\n        return Result.NO_RESULT;\n    }*/\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/util/examples/maze/Mazes.java",
    "content": "package es.usc.citius.hipster.util.examples.maze;\n\n\n/**\n * Class containing a set of {@link es.usc.citius.hipster.util.examples.maze.Maze2D} to execute in the tests\n * of the search iterators.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic final class Mazes {\n\n    private Mazes(){\n\n    }\n\n\n    /**\n     * 6x9 small maze with a shortest path distance of 5.656854249492381\n     */\n    public static String[] testMaze1 = new String[]{\n            \"        \",\n            \"    X   \",\n            \"  S X G \",\n            \"    X   \",\n            \"        \",\n            \"        \"};\n\n\n    /**\n     * 20x32 maze with a shortest path distance of 81.69848480983497\n     */\n    public static String[] testMaze2 = new String[]{\n            \"XXSXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",\n            \"XX XXXXXXXXXXXXX     XXXXXXXXXXX\",\n            \"XX    XXXXXXXXXX XXX XX     XXXX\",\n            \"XXXXX  XXXXXX    XXX XX XXX XXXX\",\n            \"XXX XX XXXXXX XX XXX XX  XX XXXX\",\n            \"XXX     XXXXX XXXXXX XXXXXX XXXX\",\n            \"XXXXXXX       XXXXXX        XXXX\",\n            \"XXXXXXXXXX XXXXX XXXXXXXXXXXXXXX\",\n            \"XXXXXXXXXX XX    XXXXX      XXXX\",\n            \"XXXXXXXXXX    XXXXXXXX XXXX XXXX\",\n            \"XXXXXXXXXXX XXXXXXXXXX XXXX XXXX\",\n            \"XXXXXXXXXXX            XXXX XXXX\",\n            \"XXXXXXXXXXXXXXXXXXXXXXXX XX XXXX\",\n            \"XXXXXX              XXXX XX XXXX\",\n            \"XXXXXX XXXXXXXXXXXX XX      XXXX\",\n            \"XXXXXX XXG   XXXXXX XXXX XXXXXXX\",\n            \"XXXXXX XXXXX   XXX            XX\",\n            \"XXXXXX XXXXXXX XXXXXXXXXXX XXXXX\",\n            \"XXXXXX XXXXXXX XXXXXXXXXXXXXXXXX\",\n            \"XXXXXX            XXXXXXXXXXXXXX\"};\n\n\n    /**\n     * 13x33 maze with a shortest path distance of 15.55634918610405\n     */\n    public static String[] testMaze3 = new String[]{\n            \"                      G          \",\n            \"                                 \",\n            \"                                 \",\n            \"                                 \",\n            \"                                 \",\n            \"                                 \",\n            \"                                 \",\n            \"                                 \",\n            \"                                 \",\n            \"                                 \",\n            \"                                 \",\n            \"           S                     \",\n            \"                                 \"};\n\n\n    /**\n     * 13x33 maze with a shortest path distance of 27.07106781186548\n     */\n    public static String[] testMaze4 = new String[]{\n            \"                      G          \",\n            \"                                 \",\n            \"                                 \",\n            \"                                 \",\n            \"                                 \",\n            \"     XXXXXXXXXXXXXXXXXXXXX       \",\n            \"     XXXXXXXXXXXXXXXXXXXXX       \",\n            \"                       XXX       \",\n            \"                       XXX       \",\n            \"                       XXX       \",\n            \"                       XXX       \",\n            \"           S                     \",\n            \"                                 \"};\n\n    /**\n     * 13x33 maze with a shortest path distance of 34.14213562373095\n     */\n    public static String[] testMaze5 = new String[]{\n            \"                  X   G          \",\n            \"                  X              \",\n            \"                  XXXXXXXX       \",\n            \"       XXXXXXXXXX  XXXXX         \",\n            \"                X    XXXXXXXXXX  \",\n            \"     XXXXXX  XXXXXXX  XXXX       \",\n            \"     XXXXXX XXXXXXX  XXXXX       \",\n            \"                       XXX       \",\n            \"                       XXX       \",\n            \"                       XXX       \",\n            \"                       XXX       \",\n            \"           S                     \",\n            \"                                 \"};\n\n\n    public static String[] exampleMaze1 = new String[]{\n            \"|             _________                      |\",\n            \"|             |       |                      |\",\n            \"|             |   G                          |\",\n            \"|             |_______|                      |\",\n            \"|                                            |\",\n            \"| ||_____________________||  ||___|| ||_     |\",\n            \"| ||                                         |\",\n            \"| //___________   ____________   _______     |\",\n            \"|            //  //         //  //           |\",\n            \"|           //  //                           |\",\n            \"|          //  //                            |\",\n            \"|         //  //                             |\",\n            \"|                                            |\",\n            \"|                                            |\",\n            \"|                   S                        |\",\n            \"|                                            |\"\n    };\n\n    /**\n     * ASCII Maze examples with the shortest path distance.\n     */\n    public enum TestMaze {\n        MAZE1(new Maze2D(testMaze1),5.656854249492381),\n        MAZE2(new Maze2D(testMaze2),81.69848480983497),\n        MAZE3(new Maze2D(testMaze3),15.55634918610405),\n        MAZE4(new Maze2D(testMaze4),27.07106781186548),\n        MAZE5(new Maze2D(testMaze5),34.14213562373095);\n\n        double minimalPathCost;\n        Maze2D maze;\n\n\n        TestMaze(Maze2D maze, double minimalPathCost){\n            this.maze = maze;\n            this.minimalPathCost = minimalPathCost;\n        }\n\n        public double getMinimalPathCost() {\n            return minimalPathCost;\n        }\n\n        public Maze2D getMaze() {\n            return maze;\n        }\n\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/util/examples/maze/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Util classes to define a simple maze problem to test different search algorithms.\n */\npackage es.usc.citius.hipster.util.examples.maze;"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/hipster/util/examples/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Toy examples for algorithm validation.\n */\npackage es.usc.citius.hipster.util.examples;"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/lab/hipster/collections/FibonacciHeap.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.lab.hipster.collections;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.NoSuchElementException;\n\n/**\n *\n * <p>Author: <b>Keith Schwarz</b> (htiek@cs.stanford.edu)</p>\n *\n * An implementation of a priority queue backed by a Fibonacci heap,\n * as described by Fredman and Tarjan.  Fibonacci heaps are interesting\n * theoretically because they have asymptotically good runtime guarantees\n * for many operations.  In particular, insert, peek, and decrease-key all\n * run in amortized O(1) time.  dequeueMin and delete each run in amortized\n * O(lg n) time.  This allows algorithms that rely heavily on decrease-key\n * to gain significant performance boosts.  For example, Dijkstra's algorithm\n * for single-source shortest paths can be shown to run in O(m + n lg n) using\n * a Fibonacci heap, compared to O(m lg n) using a standard binary or binomial\n * heap.\n *\n * Internally, a Fibonacci heap is represented as a circular, doubly-linked\n * list of trees obeying the min-heap property.  Each node stores pointers\n * to its parent (if any) and some arbitrary child.  Additionally, every\n * node stores its degree (the number of children it has) and whether it\n * is a \"marked\" node.  Finally, each Fibonacci heap stores a pointer to\n * the tree with the minimum value.\n *\n * To insert a node into a Fibonacci heap, a singleton tree is created and\n * merged into the rest of the trees.  The merge operation works by simply\n * splicing together the doubly-linked lists of the two trees, then updating\n * the min pointer to be the smaller of the minima of the two heaps.  Peeking\n * at the smallest element can therefore be accomplished by just looking at\n * the min element.  All of these operations complete in O(1) time.\n *\n * The tricky operations are dequeueMin and decreaseKey.  dequeueMin works\n * by removing the root of the tree containing the smallest element, then\n * merging its children with the topmost roots.  Then, the roots are scanned\n * and merged so that there is only one tree of each degree in the root list.\n * This works by maintaining a dynamic array of trees, each initially null,\n * pointing to the roots of trees of each dimension.  The list is then scanned\n * and this array is populated.  Whenever a conflict is discovered, the\n * appropriate trees are merged together until no more conflicts exist.  The\n * resulting trees are then put into the root list.  A clever analysis using\n * the potential method can be used to show that the amortized cost of this\n * operation is O(lg n), see \"Introduction to Algorithms, Second Edition\" by\n * Cormen, Rivest, Leiserson, and Stein for more details.\n *\n * The other hard operation is decreaseKey, which works as follows.  First, we\n * update the key of the node to be the new value.  If this leaves the node\n * smaller than its parent, we're done.  Otherwise, we cut the node from its\n * parent, add it as a root, and then mark its parent.  If the parent was\n * already marked, we cut that node as well, recursively mark its parent,\n * and continue this process.  This can be shown to run in O(1) amortized time\n * using yet another clever potential function.  Finally, given this function,\n * we can implement delete by decreasing a key to -\\infty, then calling\n * dequeueMin to extract it.\n *\n * <p><b>Hipster author's note: This implementation was taken\n * from http://www.keithschwarz.com/interesting/code/?dir=fibonacci-heap</b></p>\n *\n * @param <T></T> The type of elements to store in the heap.\n * @author Keith Schwarz (htiek@cs.stanford.edu)\n *\n */\npublic final class FibonacciHeap<T> {\n    /* In order for all of the Fibonacci heap operations to complete in O(1),\n     * clients need to have O(1) access to any element in the heap.  We make\n     * this work by having each insertion operation produce a handle to the\n     * node in the tree.  In actuality, this handle is the node itself, but\n     * we guard against external modification by marking the internal fields\n     * private.\n     */\n    public static final class Entry<T> {\n        private int mDegree = 0;       // Number of children\n        private boolean mIsMarked = false; // Whether this node is marked\n\n        private Entry<T> mNext;   // Next and previous elements in the list\n        private Entry<T> mPrev;\n\n        private Entry<T> mParent; // Parent in the tree, if any.\n\n        private Entry<T> mChild;  // Child node, if any.\n\n        private T mElem;     // Element being stored here\n        private double mPriority; // Its priority\n\n        /**\n         * Returns the element represented by this heap entry.\n         *\n         * @return The element represented by this heap entry.\n         */\n        public T getValue() {\n            return mElem;\n        }\n\n        /**\n         * Sets the element associated with this heap entry.\n         *\n         * @param value The element to associate with this heap entry.\n         */\n        public void setValue(T value) {\n            mElem = value;\n        }\n\n        /**\n         * Returns the priority of this element.\n         *\n         * @return The priority of this element.\n         */\n        public double getPriority() {\n            return mPriority;\n        }\n\n        /**\n         * Constructs a new Entry that holds the given element with the indicated\n         * priority.\n         *\n         * @param elem     The element stored in this node.\n         * @param priority The priority of this element.\n         */\n        private Entry(T elem, double priority) {\n            mNext = mPrev = this;\n            mElem = elem;\n            mPriority = priority;\n        }\n    }\n\n    /* Pointer to the minimum element in the heap. */\n    private Entry<T> mMin = null;\n\n    /* Cached size of the heap, so we don't have to recompute this explicitly. */\n    private int mSize = 0;\n\n    /**\n     * Inserts the specified element into the Fibonacci heap with the specified\n     * priority.  Its priority must be a valid double, so you cannot set the\n     * priority to NaN.\n     *\n     * @param value    The value to insert.\n     * @param priority Its priority, which must be valid.\n     * @return An Entry representing that element in the tree.\n     */\n    public Entry<T> enqueue(T value, double priority) {\n        checkPriority(priority);\n\n        /* Create the entry object, which is a circularly-linked list of length\n         * one.\n         */\n        Entry<T> result = new Entry<T>(value, priority);\n\n        /* Merge this singleton list with the tree list. */\n        mMin = mergeLists(mMin, result);\n\n        /* Increase the size of the heap; we just added something. */\n        ++mSize;\n\n        /* Return the reference to the new element. */\n        return result;\n    }\n\n    /**\n     * Returns an Entry object corresponding to the minimum element of the\n     * Fibonacci heap, throwing a NoSuchElementException if the heap is\n     * empty.\n     *\n     * @return The smallest element of the heap.\n     * @throws java.util.NoSuchElementException If the heap is empty.\n     */\n    public Entry<T> min() {\n        if (isEmpty())\n            throw new NoSuchElementException(\"Heap is empty.\");\n        return mMin;\n    }\n\n    /**\n     * Returns whether the heap is empty.\n     *\n     * @return Whether the heap is empty.\n     */\n    public boolean isEmpty() {\n        return mMin == null;\n    }\n\n    /**\n     * Returns the number of elements in the heap.\n     *\n     * @return The number of elements in the heap.\n     */\n    public int size() {\n        return mSize;\n    }\n\n    /**\n     * Given two Fibonacci heaps, returns a new Fibonacci heap that contains\n     * all of the elements of the two heaps.  Each of the input heaps is\n     * destructively modified by having all its elements removed.  You can\n     * continue to use those heaps, but be aware that they will be empty\n     * after this call completes.\n     *\n     * @param one The first Fibonacci heap to merge.\n     * @param two The second Fibonacci heap to merge.\n     * @return A new FibonacciHeap containing all of the elements of both\n     *         heaps.\n     */\n    public static <T> FibonacciHeap<T> merge(FibonacciHeap<T> one, FibonacciHeap<T> two) {\n        /* Create a new FibonacciHeap to hold the result. */\n        FibonacciHeap<T> result = new FibonacciHeap<T>();\n\n        /* Merge the two Fibonacci heap root lists together.  This helper function\n         * also computes the min of the two lists, so we can store the result in\n         * the mMin field of the new heap.\n         */\n        result.mMin = mergeLists(one.mMin, two.mMin);\n\n        /* The size of the new heap is the sum of the sizes of the input heaps. */\n        result.mSize = one.mSize + two.mSize;\n\n        /* Clear the old heaps. */\n        one.mSize = two.mSize = 0;\n        one.mMin = null;\n        two.mMin = null;\n\n        /* Return the newly-merged heap. */\n        return result;\n    }\n\n    /**\n     * Dequeues and returns the minimum element of the Fibonacci heap.  If the\n     * heap is empty, this throws a NoSuchElementException.\n     *\n     * @return The smallest element of the Fibonacci heap.\n     * @throws java.util.NoSuchElementException If the heap is empty.\n     */\n    public Entry<T> dequeueMin() {\n        /* Check for whether we're empty. */\n        if (isEmpty())\n            throw new NoSuchElementException(\"Heap is empty.\");\n\n        /* Otherwise, we're about to lose an element, so decrement the number of\n         * entries in this heap.\n         */\n        --mSize;\n\n        /* Grab the minimum element so we know what to return. */\n        Entry<T> minElem = mMin;\n\n        /* Now, we need to get rid of this element from the list of roots.  There\n         * are two cases to consider.  First, if this is the only element in the\n         * list of roots, we set the list of roots to be null by clearing mMin.\n         * Otherwise, if it's not null, then we write the elements next to the\n         * min element around the min element to remove it, then arbitrarily\n         * reassign the min.\n         */\n        if (mMin.mNext == mMin) { // Case one\n            mMin = null;\n        } else { // Case two\n            mMin.mPrev.mNext = mMin.mNext;\n            mMin.mNext.mPrev = mMin.mPrev;\n            mMin = mMin.mNext; // Arbitrary element of the root list.\n        }\n\n        /* Next, clear the parent fields of all of the min element's children,\n         * since they're about to become roots.  Because the elements are\n         * stored in a circular list, the traversal is a bit complex.\n         */\n        if (minElem.mChild != null) {\n            /* Keep track of the first visited node. */\n            Entry<?> curr = minElem.mChild;\n            do {\n                curr.mParent = null;\n\n                /* Walk to the next node, then stop if this is the node we\n                 * started at.\n                 */\n                curr = curr.mNext;\n            } while (curr != minElem.mChild);\n        }\n\n        /* Next, splice the children of the root node into the topmost list,\n         * then set mMin to point somewhere in that list.\n         */\n        mMin = mergeLists(mMin, minElem.mChild);\n\n        /* If there are no entries left, we're done. */\n        if (mMin == null) return minElem;\n\n        /* Next, we need to coalsce all of the roots so that there is only one\n         * tree of each degree.  To track trees of each size, we allocate an\n         * ArrayList where the entry at position i is either null or the\n         * unique tree of degree i.\n         */\n        List<Entry<T>> treeTable = new ArrayList<Entry<T>>();\n\n        /* We need to traverse the entire list, but since we're going to be\n         * messing around with it we have to be careful not to break our\n         * traversal order mid-stream.  One major challenge is how to detect\n         * whether we're visiting the same node twice.  To do this, we'll\n         * spent a bit of overhead adding all of the nodes to a list, and\n         * then will visit each element of this list in order.\n         */\n        List<Entry<T>> toVisit = new ArrayList<Entry<T>>();\n\n        /* To add everything, we'll iterate across the elements until we\n         * find the first element twice.  We check this by looping while the\n         * list is empty or while the current element isn't the first element\n         * of that list.\n         */\n        for (Entry<T> curr = mMin; toVisit.isEmpty() || toVisit.get(0) != curr; curr = curr.mNext)\n            toVisit.add(curr);\n\n        /* Traverse this list and perform the appropriate unioning steps. */\n        for (Entry<T> curr : toVisit) {\n            /* Keep merging until a match arises. */\n            while (true) {\n                /* Ensure that the list is long enough to hold an element of this\n                 * degree.\n                 */\n                while (curr.mDegree >= treeTable.size())\n                    treeTable.add(null);\n\n                /* If nothing's here, we're can record that this tree has this size\n                 * and are done processing.\n                 */\n                if (treeTable.get(curr.mDegree) == null) {\n                    treeTable.set(curr.mDegree, curr);\n                    break;\n                }\n\n                /* Otherwise, merge with what's there. */\n                Entry<T> other = treeTable.get(curr.mDegree);\n                treeTable.set(curr.mDegree, null); // Clear the slot\n\n                /* Determine which of the two trees has the smaller root, storing\n                 * the two tree accordingly.\n                 */\n                Entry<T> min = (other.mPriority < curr.mPriority) ? other : curr;\n                Entry<T> max = (other.mPriority < curr.mPriority) ? curr : other;\n\n                /* Break max out of the root list, then merge it into min's child\n                 * list.\n                 */\n                max.mNext.mPrev = max.mPrev;\n                max.mPrev.mNext = max.mNext;\n\n                /* Make it a singleton so that we can merge it. */\n                max.mNext = max.mPrev = max;\n                min.mChild = mergeLists(min.mChild, max);\n\n                /* Reparent max appropriately. */\n                max.mParent = min;\n\n                /* Clear max's mark, since it can now lose another child. */\n                max.mIsMarked = false;\n\n                /* Increase min's degree; it now has another child. */\n                ++min.mDegree;\n\n                /* Continue merging this tree. */\n                curr = min;\n            }\n\n            /* Update the global min based on this node.  Note that we compare\n             * for <= instead of < here.  That's because if we just did a\n             * reparent operation that merged two different trees of equal\n             * priority, we need to make sure that the min pointer points to\n             * the root-level one.\n             */\n            if (curr.mPriority <= mMin.mPriority) mMin = curr;\n        }\n        return minElem;\n    }\n\n    /**\n     * Decreases the key of the specified element to the new priority.  If the\n     * new priority is greater than the old priority, this function throws an\n     * IllegalArgumentException.  The new priority must be a finite double,\n     * so you cannot set the priority to be NaN, or +/- infinity.  Doing\n     * so also throws an IllegalArgumentException.\n     * <p/>\n     * It is assumed that the entry belongs in this heap.  For efficiency\n     * reasons, this is not checked at runtime.\n     *\n     * @param entry       The element whose priority should be decreased.\n     * @param newPriority The new priority to associate with this entry.\n     * @throws IllegalArgumentException If the new priority exceeds the old\n     *                                  priority, or if the argument is not a finite double.\n     */\n    public void decreaseKey(Entry<T> entry, double newPriority) {\n        checkPriority(newPriority);\n        if (newPriority > entry.mPriority)\n            throw new IllegalArgumentException(\"New priority exceeds old.\");\n\n        /* Forward this to a helper function. */\n        decreaseKeyUnchecked(entry, newPriority);\n    }\n\n    /**\n     * Deletes this Entry from the Fibonacci heap that contains it.\n     * <p/>\n     * It is assumed that the entry belongs in this heap.  For efficiency\n     * reasons, this is not checked at runtime.\n     *\n     * @param entry The entry to delete.\n     */\n    public void delete(Entry<T> entry) {\n        /* Use decreaseKey to drop the entry's key to -infinity.  This will\n         * guarantee that the node is cut and set to the global minimum.\n         */\n        decreaseKeyUnchecked(entry, Double.NEGATIVE_INFINITY);\n\n        /* Call dequeueMin to remove it. */\n        dequeueMin();\n    }\n\n    /**\n     * Utility function which, given a user-specified priority, checks whether\n     * it's a valid double and throws an IllegalArgumentException otherwise.\n     *\n     * @param priority The user's specified priority.\n     * @throws IllegalArgumentException If it is not valid.\n     */\n    private void checkPriority(double priority) {\n        if (Double.isNaN(priority))\n            throw new IllegalArgumentException(priority + \" is invalid.\");\n    }\n\n    /**\n     * Utility function which, given two pointers into disjoint circularly-\n     * linked lists, merges the two lists together into one circularly-linked\n     * list in O(1) time.  Because the lists may be empty, the return value\n     * is the only pointer that's guaranteed to be to an element of the\n     * resulting list.\n     * <p/>\n     * This function assumes that one and two are the minimum elements of the\n     * lists they are in, and returns a pointer to whichever is smaller.  If\n     * this condition does not hold, the return value is some arbitrary pointer\n     * into the doubly-linked list.\n     *\n     * @param one A pointer into one of the two linked lists.\n     * @param two A pointer into the other of the two linked lists.\n     * @return A pointer to the smallest element of the resulting list.\n     */\n    private static <T> Entry<T> mergeLists(Entry<T> one, Entry<T> two) {\n        /* There are four cases depending on whether the lists are null or not.\n         * We consider each separately.\n         */\n        if (one == null && two == null) { // Both null, resulting list is null.\n            return null;\n        } else if (one != null && two == null) { // Two is null, result is one.\n            return one;\n        } else if (one == null && two != null) { // One is null, result is two.\n            return two;\n        } else { // Both non-null; actually do the splice.\n            /* This is actually not as easy as it seems.  The idea is that we'll\n             * have two lists that look like this:\n             *\n             * +----+     +----+     +----+\n             * |    |--N->|one |--N->|    |\n             * |    |<-P--|    |<-P--|    |\n             * +----+     +----+     +----+\n             *\n             *\n             * +----+     +----+     +----+\n             * |    |--N->|two |--N->|    |\n             * |    |<-P--|    |<-P--|    |\n             * +----+     +----+     +----+\n             *\n             * And we want to relink everything to get\n             *\n             * +----+     +----+     +----+---+\n             * |    |--N->|one |     |    |   |\n             * |    |<-P--|    |     |    |<+ |\n             * +----+     +----+<-\\  +----+ | |\n             *                  \\  P        | |\n             *                   N  \\       N |\n             * +----+     +----+  \\->+----+ | |\n             * |    |--N->|two |     |    | | |\n             * |    |<-P--|    |     |    | | P\n             * +----+     +----+     +----+ | |\n             *              ^ |             | |\n             *              | +-------------+ |\n             *              +-----------------+\n             *\n             */\n            Entry<T> oneNext = one.mNext; // Cache this since we're about to overwrite it.\n            one.mNext = two.mNext;\n            one.mNext.mPrev = one;\n            two.mNext = oneNext;\n            two.mNext.mPrev = two;\n\n            /* Return a pointer to whichever's smaller. */\n            return one.mPriority < two.mPriority ? one : two;\n        }\n    }\n\n    /**\n     * Decreases the key of a node in the tree without doing any checking to ensure\n     * that the new priority is valid.\n     *\n     * @param entry    The node whose key should be decreased.\n     * @param priority The node's new priority.\n     */\n    private void decreaseKeyUnchecked(Entry<T> entry, double priority) {\n        /* First, change the node's priority. */\n        entry.mPriority = priority;\n\n        /* If the node no longer has a higher priority than its parent, cut it.\n         * Note that this also means that if we try to run a delete operation\n         * that decreases the key to -infinity, it's guaranteed to cut the node\n         * from its parent.\n         */\n        if (entry.mParent != null && entry.mPriority <= entry.mParent.mPriority)\n            cutNode(entry);\n\n        /* If our new value is the new min, mark it as such.  Note that if we\n         * ended up decreasing the key in a way that ties the current minimum\n         * priority, this will change the min accordingly.\n         */\n        if (entry.mPriority <= mMin.mPriority)\n            mMin = entry;\n    }\n\n    /**\n     * Cuts a node from its parent.  If the parent was already marked, recursively\n     * cuts that node from its parent as well.\n     *\n     * @param entry The node to cut from its parent.\n     */\n    private void cutNode(Entry<T> entry) {\n        /* Begin by clearing the node's mark, since we just cut it. */\n        entry.mIsMarked = false;\n\n        /* Base case: If the node has no parent, we're done. */\n        if (entry.mParent == null) return;\n\n        /* Rewire the node's siblings around it, if it has any siblings. */\n        if (entry.mNext != entry) { // Has siblings\n            entry.mNext.mPrev = entry.mPrev;\n            entry.mPrev.mNext = entry.mNext;\n        }\n\n        /* If the node is the one identified by its parent as its child,\n         * we need to rewrite that pointer to point to some arbitrary other\n         * child.\n         */\n        if (entry.mParent.mChild == entry) {\n            /* If there are any other children, pick one of them arbitrarily. */\n            if (entry.mNext != entry) {\n                entry.mParent.mChild = entry.mNext;\n            }\n            /* Otherwise, there aren't any children left and we should clear the\n             * pointer and drop the node's degree.\n             */\n            else {\n                entry.mParent.mChild = null;\n            }\n        }\n\n        /* Decrease the degree of the parent, since it just lost a child. */\n        --entry.mParent.mDegree;\n\n        /* Splice this tree into the root list by converting it to a singleton\n         * and invoking the merge subroutine.\n         */\n        entry.mPrev = entry.mNext = entry;\n        mMin = mergeLists(mMin, entry);\n\n        /* Mark the parent and recursively cut it if it's already been\n         * marked.\n         */\n        if (entry.mParent.mIsMarked)\n            cutNode(entry.mParent);\n        else\n            entry.mParent.mIsMarked = true;\n\n        /* Clear the relocated node's parent; it's now a root. */\n        entry.mParent = null;\n    }\n}"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/lab/hipster/collections/HashQueue.java",
    "content": "package es.usc.citius.lab.hipster.collections;\n\nimport java.util.AbstractQueue;\nimport java.util.Iterator;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\n\n/**\n * Implementation of a {@link java.util.Queue} backed by a {@link java.util.LinkedHashSet}\n *\n * @param <S> the type of elements held in this collection\n */\npublic class HashQueue<S> extends AbstractQueue<S> {\n\n    private final Set<S> elements = new LinkedHashSet<S>();\n    private S first = null;\n\n    @Override\n    public boolean offer(S e) {\n        elements.add(e);\n        if (first == null) {\n            first = e;\n        }\n        return true;\n    }\n\n    @Override\n    public S poll() {\n        // Remove the first element\n        elements.remove(first);\n        S out = first;\n        // Reasign first\n        first = (elements.isEmpty()) ? null : elements.iterator().next();\n        return out;\n    }\n\n    @Override\n    public S peek() {\n        return first;\n    }\n\n    @Override\n    public Iterator<S> iterator() {\n        return elements.iterator();\n    }\n\n    @Override\n    public int size() {\n        return elements.size();\n    }\n\n    @Override\n    public boolean contains(Object o) {\n        return this.elements.contains(o);\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/lab/hipster/collections/adapter/HeuristicNodePriorityEvaluator.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.lab.hipster.collections.adapter;\n\n\nimport es.usc.citius.hipster.model.HeuristicNode;\n\n/**\n * Calculates the priority (double) of a {@link es.usc.citius.hipster.model.HeuristicNode}\n * based translating on a cost extending {@link java.lang.Number}.\n *\n * @param <A> type of the actions ({@code Void} if actions are not explicit).\n * @param <S> type of the states\n * @param <C> type of the cost\n * @param <N> type of the nodes\n *\n * @author Pablo Rodríguez Mier\n */\npublic class HeuristicNodePriorityEvaluator<A, S, C extends Comparable<C>, N extends HeuristicNode<A,S,C,N>> implements PriorityEvaluator<N> {\n    @Override\n    public double getPriority(N n) {\n        C cost = n.getScore();\n        if (cost instanceof Number) {\n            return ((Number) cost).doubleValue();\n        }\n        throw new ClassCastException(\"Automatic cast to double of the HeuristicNode score failed. HeuristicNode#getScore() is not returning a Number. Please \" +\n                \"use a different PriorityEvaluator to evaluate properly the custom type used by HeuristicNode.\");\n\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/lab/hipster/collections/adapter/PriorityEvaluator.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.lab.hipster.collections.adapter;\n\n/**\n * This interface is intended for the definition of evaluators to calculate\n * the priority (double) of a concrete element. This can be used to adapt different\n * data structures (like the most implementations of heaps for java) which use\n * doubles to sort the elements instead of defining comparable types (as used by\n * {@link java.util.Queue}.\n *\n * @param <N> type of the nodes\n *\n * @author Pablo Rodríguez Mier\n */\npublic interface PriorityEvaluator<N> {\n\n    /**\n     * Retrieve the priority of the node.\n     *\n     * @param n node\n     * @return priority as double value\n     */\n    double getPriority(N n);\n\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/lab/hipster/collections/adapter/PriorityFibonacciQueue.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.lab.hipster.collections.adapter;\n\nimport es.usc.citius.lab.hipster.collections.FibonacciHeap;\n\nimport java.util.AbstractQueue;\nimport java.util.Iterator;\n\n/**\n * Implementation of {@link java.util.Queue} based on the Fibonacci heap\n * concept, described in http://en.wikipedia.org/wiki/Fibonacci_heap.\n *\n * @param <N> type of the nodes\n *\n * @author Pablo Rodríguez Mier\n */\npublic class PriorityFibonacciQueue<N> extends AbstractQueue<N> {\n    private final FibonacciHeap<N> heap = new FibonacciHeap<N>();\n    private PriorityEvaluator<N> evaluator;\n\n    public PriorityFibonacciQueue(PriorityEvaluator<N> evaluator) {\n        this.evaluator = evaluator;\n    }\n\n    @Override\n    public Iterator<N> iterator() {\n        return new Iterator<N>() {\n            @Override\n            public boolean hasNext() {\n                return heap.size() > 0;\n            }\n\n            @Override\n            public N next() {\n                return heap.dequeueMin().getValue();\n            }\n\n            @Override\n            public void remove() {\n                throw new UnsupportedOperationException();\n            }\n        };\n    }\n\n    @Override\n    public int size() {\n        return heap.size();\n    }\n\n    @Override\n    public boolean offer(N n) {\n        heap.enqueue(n, this.evaluator.getPriority(n));\n        return true;\n    }\n\n    @Override\n    public N poll() {\n        return heap.dequeueMin().getValue();\n    }\n\n    @Override\n    public N peek() {\n        return heap.min().getValue();\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/lab/hipster/collections/adapter/package-info.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Includes some adapters to adapt the original data structures to\n * different interfaces, like {@link java.util.Queue}.\n */\npackage es.usc.citius.lab.hipster.collections.adapter;"
  },
  {
    "path": "hipster-core/src/main/java/es/usc/citius/lab/hipster/collections/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Custom collections and data structures.\n */\npackage es.usc.citius.lab.hipster.collections;"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/algorithm/problem/romanian/ADStarRomaniaProblemOptimalSearchTest.java",
    "content": "package es.usc.citius.hipster.algorithm.problem.romanian;\n\nimport es.usc.citius.hipster.algorithm.ADStarForward;\nimport es.usc.citius.hipster.algorithm.Algorithm;\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.model.problem.SearchComponents;\nimport es.usc.citius.hipster.util.examples.RomanianProblem;\n\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Implementation of the Romania problem test for the AD* algorithm.\n *\n * @author Adrián González Sieira <adrian.gonzalez@usc.es>\n * @since 22/07/2014\n */\npublic class ADStarRomaniaProblemOptimalSearchTest extends RomaniaProblemOptimalHeuristicSearchTest{\n\n    @Override\n    public Algorithm<Void, RomanianProblem.City, ? extends Node<Void, RomanianProblem.City, ?>> createAlgorithm() {\n        //initialize search problem\n        SearchComponents components = GraphSearchProblem.startingFrom(RomanianProblem.City.Arad)\n                .goalAt(RomanianProblem.City.Bucharest)\n                .in(graph)\n                .takeCostsFromEdges()\n                .useHeuristicFunction(RomanianProblem.heuristicFunction())\n                .components();\n\n        //create AD* algorithm\n        return Hipster.createADStar(components);\n    }\n\n    @Override\n    public List<? extends Node<Void, RomanianProblem.City, ?>> iterativeSearch(Iterator<? extends Node<Void, RomanianProblem.City, ?>> iterator) {\n        //find optimal solution\n        Node<Void, RomanianProblem.City, ?> node = null;\n        do{\n            node = iterator.next();\n        }while(iterator.hasNext() && !node.state().equals(GOAL));\n        //set variable of expanded nodes\n        this.expandedNodesTested = ((ADStarForward.Iterator) iterator).getClosed().values();\n        //return optimal path\n        return node.path();\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/algorithm/problem/romanian/AStarRomaniaProblemOptimalSearchTest.java",
    "content": "package es.usc.citius.hipster.algorithm.problem.romanian;\n\nimport es.usc.citius.hipster.algorithm.AStar;\nimport es.usc.citius.hipster.algorithm.Algorithm;\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\nimport es.usc.citius.hipster.util.examples.RomanianProblem;\n\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Implementation of the Romania problem test for the A* algorithm.\n *\n * @author Adrián González Sieira <adrian.gonzalez@usc.es>\n * @since 22/07/2014\n */\npublic class AStarRomaniaProblemOptimalSearchTest extends RomaniaProblemOptimalHeuristicSearchTest {\n\n    @Override\n    public Algorithm<Void, RomanianProblem.City, ? extends Node<Void, RomanianProblem.City, ?>> createAlgorithm() {\n        //initialize search problem\n        SearchProblem p = GraphSearchProblem\n                .startingFrom(RomanianProblem.City.Arad)\n                .in(graph)\n                .takeCostsFromEdges()\n                .useHeuristicFunction(RomanianProblem.heuristicFunction())\n                .build();\n\n        //create A* algorithm\n        return Hipster.createAStar(p);\n    }\n\n    @Override\n    public List<? extends Node<Void, RomanianProblem.City, ?>> iterativeSearch(Iterator<? extends Node<Void, RomanianProblem.City, ?>> iterator) {\n        //find optimal solution\n        Node<Void, RomanianProblem.City, ?> node = null;\n        do{\n            node = iterator.next();\n        }while(iterator.hasNext() && !node.state().equals(GOAL));\n        //set variables of expanded nodes\n        this.expandedNodesTested = ((AStar.Iterator) iterator).getClosed().values();\n        //return optimal path\n        return node.path();\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/algorithm/problem/romanian/BellmanFordRomaniaProblemOptimalSearchTest.java",
    "content": "package es.usc.citius.hipster.algorithm.problem.romanian;\n\nimport es.usc.citius.hipster.algorithm.Algorithm;\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\nimport es.usc.citius.hipster.util.examples.RomanianProblem;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Implementation of the Romania problem test for the Bellman-Ford algorithm.\n *\n * @author Adrián González Sieira <adrian.gonzalez@usc.es>\n * @since 08/06/2015\n */\npublic class BellmanFordRomaniaProblemOptimalSearchTest extends RomaniaProblemOptimalSearchTest{\n\n    @Override\n    public Algorithm<Void, RomanianProblem.City, ? extends Node<Void, RomanianProblem.City, ?>> createAlgorithm() {\n        SearchProblem p = GraphSearchProblem\n                .startingFrom(RomanianProblem.City.Arad)\n                .in(graph)\n                .takeCostsFromEdges()\n                .build();\n\n        //create iterator\n        return Hipster.createBellmanFord(p);\n    }\n\n    @Override\n    public List<? extends Node<Void, RomanianProblem.City, ?>> iterativeSearch(Iterator<? extends Node<Void, RomanianProblem.City, ?>> iterator) {\n        HashMap<RomanianProblem.City, Node<Void, RomanianProblem.City, ?>> expanded\n                = new HashMap<RomanianProblem.City, Node<Void, RomanianProblem.City, ?>>();\n        //find optimal solution\n        Node<Void, RomanianProblem.City, ?> node = null;\n        Node<Void, RomanianProblem.City, ?> goalNode = null;\n        do{\n            node = iterator.next();\n            if(expanded.containsKey(node.state())) expanded.remove(node);\n            expanded.put(node.state(), node);\n            //update solution found\n            if(node.state().equals(GOAL)){\n                goalNode = node;\n            }\n        }while(iterator.hasNext());\n        //set variables\n        this.expandedNodesTested = expanded.values();\n        //return optimal path\n        return goalNode.path();\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/algorithm/problem/romanian/DijkstraRomaniaProblemOptimalSearchTest.java",
    "content": "package es.usc.citius.hipster.algorithm.problem.romanian;\n\nimport es.usc.citius.hipster.algorithm.AStar;\nimport es.usc.citius.hipster.algorithm.Algorithm;\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\nimport es.usc.citius.hipster.util.examples.RomanianProblem;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n * Implementation of the Romania problem test for the Dijkstra algorithm.\n *\n * @author Adrián González Sieira <adrian.gonzalez@usc.es>\n * @since 31/07/2014\n */\npublic class DijkstraRomaniaProblemOptimalSearchTest extends RomaniaProblemOptimalSearchTest{\n\n    @Override\n    public Algorithm<Void, RomanianProblem.City, ? extends Node<Void, RomanianProblem.City, ?>> createAlgorithm() {\n        //initialize search problem\n        SearchProblem p = GraphSearchProblem\n                .startingFrom(RomanianProblem.City.Arad)\n                .in(graph)\n                .takeCostsFromEdges()\n                .build();\n        //create Dijkstra algorithm\n        return Hipster.createAStar(p);\n    }\n\n    @Override\n    public List<? extends Node<Void, RomanianProblem.City, ?>> iterativeSearch(Iterator<? extends Node<Void, RomanianProblem.City, ?>> iterator) {\n        //find optimal solution\n        Node<Void, RomanianProblem.City, ?> node = null;\n        do{\n            node = iterator.next();\n        }while(iterator.hasNext() && !node.state().equals(GOAL));\n        //set variables\n        this.expandedNodesTested = ((AStar.Iterator) iterator).getClosed().values();\n        //return optimal path\n        return node.path();\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/algorithm/problem/romanian/IDAStarRomaniaProblemOptimalSearchTest.java",
    "content": "package es.usc.citius.hipster.algorithm.problem.romanian;\n\nimport es.usc.citius.hipster.algorithm.Algorithm;\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\nimport es.usc.citius.hipster.util.examples.RomanianProblem;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Implementation of the Romania problem test for the IDA* algorithm.\n *\n * @author Adrián González Sieira <adrian.gonzalez@usc.es>\n * @since 31/07/2014\n */\npublic class IDAStarRomaniaProblemOptimalSearchTest extends RomaniaProblemOptimalHeuristicSearchTest{\n\n    @Override\n    public Algorithm<Void, RomanianProblem.City, ? extends Node<Void, RomanianProblem.City, ?>> createAlgorithm() {\n        //initialize search problem\n        SearchProblem p = GraphSearchProblem\n                .startingFrom(RomanianProblem.City.Arad)\n                .in(graph)\n                .takeCostsFromEdges()\n                .useHeuristicFunction(RomanianProblem.heuristicFunction())\n                .build();\n\n        //create IDA* algorithm\n        return Hipster.createIDAStar(p);\n    }\n\n    @Override\n    public List<? extends Node<Void, RomanianProblem.City, ?>> iterativeSearch(Iterator<? extends Node<Void, RomanianProblem.City, ?>> iterator) {\n        List<Node<Void, RomanianProblem.City, ?>> expanded\n                = new ArrayList<Node<Void, RomanianProblem.City, ?>>();\n        //find optimal solution\n        Node<Void, RomanianProblem.City, ?> node = null;\n        do{\n            node = iterator.next();\n            expanded.add(node);\n        }while(iterator.hasNext() && !node.state().equals(GOAL));\n        this.expandedNodesTested = expanded;\n        //return optimal path\n        return node.path();\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/algorithm/problem/romanian/RomaniaProblemOptimalHeuristicSearchTest.java",
    "content": "package es.usc.citius.hipster.algorithm.problem.romanian;\n\nimport es.usc.citius.hipster.model.HeuristicNode;\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.util.examples.RomanianProblem;\nimport org.junit.Test;\n\nimport java.util.HashMap;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n * Created by adrian.gonzalez on 8/06/15.\n */\npublic abstract class RomaniaProblemOptimalHeuristicSearchTest extends RomaniaProblemOptimalSearchTest {\n\n    protected final HashMap<RomanianProblem.City, Double> scoresFromArad;\n\n    public RomaniaProblemOptimalHeuristicSearchTest(){\n        super();\n        //obtain score map for expanding nodes to Bucharest\n        scoresFromArad = new HashMap<RomanianProblem.City, Double>();\n        scoresFromArad.put(RomanianProblem.City.Arad, 366d);\n        scoresFromArad.put(RomanianProblem.City.Zerind, 449d);\n        scoresFromArad.put(RomanianProblem.City.Timisoara, 447d);\n        scoresFromArad.put(RomanianProblem.City.Sibiu, 393d);\n        scoresFromArad.put(RomanianProblem.City.Oradea, 526d);\n        scoresFromArad.put(RomanianProblem.City.Fagaras, 415d);\n        scoresFromArad.put(RomanianProblem.City.Rimnicu_Vilcea, 413d);\n        scoresFromArad.put(RomanianProblem.City.Craiova, 526d);\n        scoresFromArad.put(RomanianProblem.City.Pitesti, 417d);\n        scoresFromArad.put(RomanianProblem.City.Bucharest, 418d);\n        scoresFromArad.put(RomanianProblem.City.Lugoj, 473d);\n        scoresFromArad.put(RomanianProblem.City.Mehadia, 540d);\n        scoresFromArad.put(RomanianProblem.City.Drobeta, 616d);\n    }\n\n    /**\n     * Check the scores of the elements expanded by the algorithm.\n     */\n    @Test\n    public void scoresFromAradToBucharest() {\n        for(Node<Void, RomanianProblem.City, ?> node : expandedNodesTested){\n            HeuristicNode<Void, RomanianProblem.City, Double, ?> heuristicNode =\n                    (HeuristicNode<Void, RomanianProblem.City, Double, ?>) node;\n            //compare returned score with expected\n            assertEquals(\n                    \"Failed checking score of \" + heuristicNode.state().toString(),\n                    scoresFromArad.get(heuristicNode.state()), heuristicNode.getScore()\n            );\n        }\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/algorithm/problem/romanian/RomaniaProblemOptimalSearchTest.java",
    "content": "package es.usc.citius.hipster.algorithm.problem.romanian;\n\nimport es.usc.citius.hipster.algorithm.Algorithm;\nimport es.usc.citius.hipster.model.CostNode;\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.util.examples.RomanianProblem;\nimport es.usc.citius.hipster.graph.HipsterGraph;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport java.util.*;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n * Generic test suite for algorithms that order the OPEN queue in a similar way that A* (using the score of a node).\n * The test cases implemented in this class are the following:\n * <ul>\n * <li>Cost of the nodes expanded by the algorithm.</li>\n * <li>Score of the nodes expanded by the algorithm.</li>\n * <li>Optimal path retrieved.</li>\n * </ul>\n * Different algorithms need to test these situations when performing optimal search (this means: not anytime search nor\n * replanning).\n * This test case suite uses the Romania problem searching from Arad to Bucharest.\n *\n * @author Adrián González Sieira <adrian.gonzalez@usc.es>\n * @since 0.1.0\n */\npublic abstract class RomaniaProblemOptimalSearchTest {\n\n    protected final HipsterGraph<RomanianProblem.City, Double> graph = RomanianProblem.graph();\n    protected Collection<Node<Void, RomanianProblem.City, ?>> expandedNodesTested;\n    protected List<? extends Node<Void, RomanianProblem.City, ?>> optimalPathIterator;\n    protected List<? extends Node<Void, RomanianProblem.City, ?>> optimalPathSearchMethod;\n    protected List<RomanianProblem.City> optimalPath;\n    protected final HashMap<RomanianProblem.City, Double> costsFromArad;\n    protected static final RomanianProblem.City GOAL = RomanianProblem.City.Bucharest;\n\n    public RomaniaProblemOptimalSearchTest(){\n        costsFromArad = new HashMap<RomanianProblem.City, Double>();\n        costsFromArad.put(RomanianProblem.City.Arad, 0d);\n        costsFromArad.put(RomanianProblem.City.Zerind, 75d);\n        costsFromArad.put(RomanianProblem.City.Timisoara, 118d);\n        costsFromArad.put(RomanianProblem.City.Sibiu, 140d);\n        costsFromArad.put(RomanianProblem.City.Oradea, 146d);\n        costsFromArad.put(RomanianProblem.City.Fagaras, 239d);\n        costsFromArad.put(RomanianProblem.City.Rimnicu_Vilcea, 220d);\n        costsFromArad.put(RomanianProblem.City.Craiova, 366d);\n        costsFromArad.put(RomanianProblem.City.Pitesti, 317d);\n        costsFromArad.put(RomanianProblem.City.Bucharest, 418d);\n        costsFromArad.put(RomanianProblem.City.Lugoj, 229d);\n        costsFromArad.put(RomanianProblem.City.Mehadia, 299d);\n        costsFromArad.put(RomanianProblem.City.Drobeta, 374d);\n        costsFromArad.put(RomanianProblem.City.Giurgiu, 508d);\n        costsFromArad.put(RomanianProblem.City.Urziceni, 503d);\n        costsFromArad.put(RomanianProblem.City.Hirsova, 601d);\n        costsFromArad.put(RomanianProblem.City.Eforie, 687d);\n        costsFromArad.put(RomanianProblem.City.Vaslui, 645d);\n        costsFromArad.put(RomanianProblem.City.Iasi, 737d);\n        costsFromArad.put(RomanianProblem.City.Neamt, 824d);\n\n        optimalPath =\n                Arrays.asList(\n                        RomanianProblem.City.Arad,\n                        RomanianProblem.City.Sibiu,\n                        RomanianProblem.City.Rimnicu_Vilcea,\n                        RomanianProblem.City.Pitesti,\n                        RomanianProblem.City.Bucharest\n                );\n    }\n\n    /**\n     * Check the returned path of the algorithm to be the optimal for the problem definition.\n     */\n    @Test\n    public void optimalPathFromAradToBucharest() {\n        //check elements returned by the search algorithm\n        assertEquals(\"Solutions have not the same size\", optimalPathIterator.size(), optimalPath.size());\n        for(int i = 0; i < optimalPath.size(); i++){\n            //check if current element of the path is equals to the\n            assertEquals(\n                    \"Failed checking element \" + i + \" of the path. Expected: \" +\n                            optimalPath.get(i) + \", found: \" + optimalPathIterator.get(i).state(),\n                    optimalPath.get(i),\n                    optimalPathIterator.get(i).state()\n            );\n        }\n    }\n\n    /**\n     * Check the returned path of the algorithm to be the optimal for the problem definition.\n     */\n    @Test\n    public void optimalPathFromAradToBucharestSearchMethod() {\n        //check elements returned by the search algorithm\n        assertEquals(\"Solutions have not the same size\", optimalPathSearchMethod.size(), optimalPath.size());\n        for(int i = 0; i < optimalPath.size(); i++){\n            //check if current element of the path is equals to the\n            assertEquals(\n                    \"Failed checking element \" + i + \" of the path. Expected: \" +\n                            optimalPath.get(i) + \", found: \" + optimalPathSearchMethod.get(i).state(),\n                    optimalPath.get(i),\n                    optimalPathSearchMethod.get(i).state()\n            );\n        }\n    }\n\n    /**\n     * Check the costs of the elements expanded by the algorithm finding the optimal path.\n     */\n    @Test\n    public void costsFromAradToBucharest() {\n        for(Node<Void, RomanianProblem.City, ?> node : expandedNodesTested){\n            CostNode<Void, RomanianProblem.City, Double, ?> costNode\n                    = (CostNode<Void, RomanianProblem.City, Double, ?>) node;\n            //compare returned cost with expected\n            assertEquals(\n                    \"Failed checking cost of \" + node.state().toString() + \". Expected: \" +\n                            costsFromArad.get(node.state()) + \", found: \" + costNode.getCost(),\n                    costNode.getCost(),\n                    costsFromArad.get(node.state())\n            );\n        }\n    }\n\n    /**\n     * Definition of abstract method to use the same test suite with different algorithms.\n     * This method fills the list of explored nodes and obtains the optimal path, wihch\n     * are stored in \"expandedNodesTested\" and \"optmalPath\" variables.\n     */\n    @Before\n    public void doSearch(){\n        Algorithm<Void, RomanianProblem.City, ? extends Node<Void, RomanianProblem.City, ?>> algorithm = createAlgorithm();\n        //execute iterative search\n        this.optimalPathIterator = iterativeSearch(algorithm.iterator());\n        this.optimalPathSearchMethod = algorithm.search(RomanianProblem.City.Bucharest).getGoalNode().path();\n    };\n\n    /**\n     * Method to execute the iterative search from a search iterator.\n     *\n     * @param iterator instance of {@link Iterator<? extends Node<Void, RomanianProblem.City, ?>>} to search\n     * @return solution list obtained by sarching step-by-step\n     */\n    public abstract List<? extends Node<Void, RomanianProblem.City, ?>> iterativeSearch(Iterator<? extends Node<Void, RomanianProblem.City, ?>> iterator);\n\n    /**\n     * Method to initialize the search algorithm.\n     *\n     * @return instance of {@link Algorithm} to search over the graph\n     */\n    public abstract Algorithm<Void, RomanianProblem.City, ? extends Node<Void, RomanianProblem.City, ?>> createAlgorithm();\n\n}"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/graph/HashBasedHipsterDirectedGraphTest.java",
    "content": "package es.usc.citius.hipster.graph;\n\nimport com.google.common.collect.Sets;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport java.util.Set;\n\nimport static org.junit.Assert.*;\n\n\npublic class HashBasedHipsterDirectedGraphTest {\n\n    protected HipsterDirectedGraph graph;\n    protected int size = 10;\n\n    @Before\n    public void setUp(){\n        graph = createStarGraph(size);\n    }\n\n    protected HashBasedHipsterDirectedGraph createStarGraph(int vertices){\n        HashBasedHipsterDirectedGraph g = new HashBasedHipsterDirectedGraph();\n        for(int i = 0; i < vertices; i++){\n            g.add(\"v\"+i);\n            for(int j=0; j<i; j++){\n                g.connect(\"v\"+j, \"v\"+i, Math.random());\n            }\n        }\n        return g;\n    }\n\n    @Test\n    public void testOutgoingEdgesOf() throws Exception {\n        for(int i=0; i<size; i++) {\n            Set edges = Sets.newHashSet(graph.outgoingEdgesOf(\"v\"+i));\n            assertEquals(size-(i+1), edges.size());\n        }\n    }\n\n    @Test\n    public void testIncomingEdgesOf() throws Exception {\n        for(int i=0; i<size; i++) {\n            Set edges = Sets.newHashSet(graph.incomingEdgesOf(\"v\"+i));\n            assertEquals(i, edges.size());\n        }\n    }\n\n    @Test\n    public void testEdges() throws Exception {\n        Set edges = Sets.newHashSet(graph.edges());\n        assertEquals(size*(size-1)/2, edges.size());\n    }\n}"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/graph/HashBasedHipsterGraphTest.java",
    "content": "package es.usc.citius.hipster.graph;\n\nimport com.google.common.collect.Sets;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport java.util.Set;\n\nimport static org.junit.Assert.*;\n\n\npublic class HashBasedHipsterGraphTest {\n    protected HashBasedHipsterGraph graph;\n    protected int size = 10;\n\n    protected HashBasedHipsterGraph createStarGraph(int vertices){\n        HashBasedHipsterGraph g = new HashBasedHipsterGraph();\n        for(int i = 0; i < vertices; i++){\n            g.add(\"v\"+i);\n            for(int j=0; j<i; j++){\n                g.connect(\"v\"+j, \"v\"+i, Math.random());\n            }\n        }\n        return g;\n    }\n\n    @Before\n    public void setUp(){\n        graph = createStarGraph(size);\n    }\n\n    private void testGraphEdges(){\n        Iterable<GraphEdge> edges = graph.edges();\n        int countEdgesV1 = 0;\n        int countAllEdges = 0;\n        for(GraphEdge e : edges){\n            if (e.getVertex1().equals(\"v1\") || e.getVertex2().equals(\"v1\")) countEdgesV1++;\n            countAllEdges++;\n        }\n        assertEquals((size-1)*2, countEdgesV1);\n        assertEquals(size*(size-1), countAllEdges);\n    }\n\n    @Test\n    public void testEdges() throws Exception {\n        testGraphEdges();\n    }\n\n    @Test\n    public void testEdgesWithDisconnectedVertices() throws Exception {\n        graph.add(\"X\");\n        graph.add(\"Y\");\n        testGraphEdges();\n    }\n\n    @Test\n    public void testAdd() throws Exception {\n        graph.add(\"X\");\n        Set vertices = Sets.newHashSet(graph.vertices());\n        assertTrue(vertices.contains(\"X\"));\n        assertTrue(vertices.size()==size+1);\n    }\n\n    @Test\n    public void testRemove() throws Exception {\n        graph.remove(\"v1\");\n        assertFalse(Sets.newHashSet(graph.vertices()).contains(\"v1\"));\n    }\n\n    @Test\n    public void testRemoveAndCheckEdges() throws Exception {\n        graph.remove(\"v1\");\n        assertFalse(Sets.newHashSet(graph.vertices()).contains(\"v1\"));\n        Iterable<GraphEdge> edges = graph.edges();\n        int countEdges = 0;\n        for(GraphEdge e : edges){\n            assertFalse(e.getVertex1().equals(\"v1\") || e.getVertex2().equals(\"v1\"));\n            countEdges++;\n        }\n        assertEquals((size-1)*(size-2), countEdges);\n    }\n\n    @Test\n    public void testConnect() throws Exception {\n        graph.add(\"X\");\n        graph.add(\"Y\");\n        graph.connect(\"X\",\"Y\",1.0d);\n        assertTrue(Sets.newHashSet(graph.vertices()).contains(\"X\"));\n        assertTrue(Sets.newHashSet(graph.vertices()).contains(\"Y\"));\n    }\n\n\n    @Test\n    public void testVertices() throws Exception {\n        Set vertices = Sets.newHashSet(graph.vertices());\n        assertEquals(size, vertices.size());\n    }\n\n    @Test\n    public void testEdgesOf() throws Exception {\n        Set edges = Sets.newHashSet(graph.edgesOf(\"v1\"));\n        assertEquals(size-1, edges.size());\n    }\n\n\n}"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/graph/UndirectedEdgeTest.java",
    "content": "package es.usc.citius.hipster.graph;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.*;\n\npublic class UndirectedEdgeTest {\n\n    @Test\n    public void testEqualsWithUndirectedEdgeSwapped() throws Exception {\n        UndirectedEdge e1 = new UndirectedEdge(\"a\", \"b\", 1);\n        UndirectedEdge e2 = new UndirectedEdge(\"b\", \"a\", 1);\n        assertEquals(e1, e2);\n    }\n\n    @Test\n    public void testEqualsWithUndirectedEdge() throws Exception {\n        UndirectedEdge e1 = new UndirectedEdge(\"a\", \"b\", 1);\n        UndirectedEdge e2 = new UndirectedEdge(\"a\", \"b\", 1);\n        assertEquals(e1, e2);\n    }\n\n    @Test\n    public void testNotEqualsWithUndirectedEdge() throws Exception {\n        UndirectedEdge e1 = new UndirectedEdge(\"a\", \"b\", 1);\n        UndirectedEdge e2 = new UndirectedEdge(\"a\", \"c\", 1);\n        assertNotEquals(e1, e2);\n    }\n}"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/util/graph/GraphBuilderTest.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.util.graph;\n\n\nimport es.usc.citius.hipster.graph.GraphBuilder;\nimport es.usc.citius.hipster.graph.GraphEdge;\nimport es.usc.citius.hipster.graph.HashBasedHipsterDirectedGraph;\nimport es.usc.citius.hipster.graph.HipsterDirectedGraph;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport static org.junit.Assert.assertEquals;\n\npublic class GraphBuilderTest {\n    private static HipsterDirectedGraph<String, Double> testGraph;\n    private static HipsterDirectedGraph<String, Double> testGraph2;\n\n    @BeforeClass\n    public static void setUp() throws Exception {\n\n        testGraph = GraphBuilder.<String,Double>create()\n                .connect(\"A\").to(\"B\").withEdge(4d)\n                .connect(\"A\").to(\"C\").withEdge(2d)\n                .connect(\"B\").to(\"C\").withEdge(5d)\n                .connect(\"B\").to(\"D\").withEdge(10d)\n                .connect(\"C\").to(\"E\").withEdge(3d)\n                .connect(\"D\").to(\"F\").withEdge(11d)\n                .connect(\"E\").to(\"D\").withEdge(4d)\n                .createDirectedGraph();\n\n        testGraph2 = GraphBuilder.<String,Double>create()\n                .connect(\"A\",\"B\")\n                .connect(\"A\",\"C\")\n                .connect(\"B\",\"C\")\n                .connect(\"B\",\"D\")\n                .connect(\"C\",\"E\")\n                .connect(\"D\",\"F\")\n                .connect(\"E\",\"D\")\n                .createDirectedGraph();\n    }\n\n    @Test\n    public void testVertices() {\n        Set<String> vertices = new HashSet<String>(Arrays.asList(\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"));\n        assertEquals(vertices, testGraph.vertices());\n        assertEquals(vertices, testGraph2.vertices());\n    }\n\n    @Test\n    public void testEdges() {\n        Set<Double> expectedValues = new HashSet<Double>(Arrays.asList(4d, 2d, 5d, 10d, 3d, 11d, 4d));\n        Set<Double> valuesGraph1 = new HashSet<Double>();\n        Set<Double> valuesGraph2 = new HashSet<Double>();\n        int countEdges1 = 0;\n        int countEdges2 = 0;\n        for(GraphEdge<String,Double> edge : testGraph.edges()){\n            valuesGraph1.add(edge.getEdgeValue());\n            countEdges1++;\n        }\n\n        for(GraphEdge<String,Double> edge : testGraph2.edges()){\n            valuesGraph2.add(edge.getEdgeValue());\n            countEdges2++;\n        }\n\n        assertEquals(7, countEdges1);\n        assertEquals(expectedValues, valuesGraph1);\n        assertEquals(7, countEdges2);\n    }\n\n    @Test\n    public void testIncomingEdges(){\n        Set<GraphEdge<String, Double>> edgesGraph1 = new HashSet<GraphEdge<String, Double>>();\n        Set<GraphEdge<String, Double>> edgesGraph2 = new HashSet<GraphEdge<String, Double>>();\n        for(GraphEdge<String, Double> current : testGraph.incomingEdgesOf(\"D\")){\n            edgesGraph1.add(current);\n        }\n        for(GraphEdge<String, Double> current : testGraph2.incomingEdgesOf(\"D\")){\n            edgesGraph2.add(current);\n        }\n        Set<Double> values = new HashSet<Double>();\n        for(GraphEdge<String,Double> e : edgesGraph1){\n            values.add(e.getEdgeValue());\n        }\n        assertEquals(2, edgesGraph1.size());\n        assertEquals(values, new HashSet<Double>(Arrays.asList(4.0d, 10.0d)));\n        assertEquals(2, edgesGraph2.size());\n    }\n\n    @Test\n    public void testOutgoingEdges(){\n        Set<GraphEdge<String, Double>> edgesGraph1 = new HashSet<GraphEdge<String, Double>>();\n        Set<GraphEdge<String, Double>> edgesGraph2 = new HashSet<GraphEdge<String, Double>>();\n        for(GraphEdge<String, Double> current : testGraph.outgoingEdgesOf(\"B\")){\n            edgesGraph1.add(current);\n        }\n        for(GraphEdge<String, Double> current : testGraph2.outgoingEdgesOf(\"B\")){\n            edgesGraph2.add(current);\n        }\n        Set<Double> values = new HashSet<Double>();\n        for(GraphEdge<String,Double> e : edgesGraph1){\n            values.add(e.getEdgeValue());\n        }\n        assertEquals(2, edgesGraph1.size());\n        assertEquals(values, new HashSet<Double>(Arrays.asList(5.0d, 10.0d)));\n        assertEquals(2, edgesGraph2.size());\n    }\n\n    @Test\n    public void testEdgeSetter() {\n        Set<GraphEdge<String, Double>> edgesGraph = new HashSet<GraphEdge<String, Double>>();\n        Set<Double> expectedValues = new HashSet<Double>(Arrays.asList(4d, 2d, 5d, 10d, 3d, 11d, 4d));\n        Set<Double> valuesGraph = new HashSet<Double>();\n        Set<Object> values = new HashSet<Object>();\n        for(GraphEdge<String, Double> current : testGraph2.outgoingEdgesOf(\"B\")){\n            edgesGraph.add(current);\n        }\n        for(GraphEdge<String,Double> e : edgesGraph){\n            values.add(e.getEdgeValue());\n        }\n        assertEquals(2, edgesGraph.size());\n\n        ((HashBasedHipsterDirectedGraph) testGraph2).buildEdge(\"A\", \"B\", 4d);\n        ((HashBasedHipsterDirectedGraph) testGraph2).buildEdge(\"A\", \"C\", 2d);\n        ((HashBasedHipsterDirectedGraph) testGraph2).buildEdge(\"B\", \"C\", 5d);\n        ((HashBasedHipsterDirectedGraph) testGraph2).buildEdge(\"B\", \"D\", 10d);\n        ((HashBasedHipsterDirectedGraph) testGraph2).buildEdge(\"C\", \"E\", 3d);\n        ((HashBasedHipsterDirectedGraph) testGraph2).buildEdge(\"D\", \"F\", 11d);\n        ((HashBasedHipsterDirectedGraph) testGraph2).buildEdge(\"E\", \"D\", 4d);\n\n        for(GraphEdge<String,Double> edge : testGraph.edges()){\n            valuesGraph.add(edge.getEdgeValue());\n        }\n        assertEquals(expectedValues, valuesGraph);\n\n\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/hipster/util/graph/RomanianProblemGraph.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.util.graph;\n\n\nimport com.google.common.collect.Sets;\nimport es.usc.citius.hipster.graph.GraphEdge;\nimport es.usc.citius.hipster.graph.HipsterGraph;\nimport es.usc.citius.hipster.graph.UndirectedEdge;\nimport es.usc.citius.hipster.util.examples.RomanianProblem;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport static org.junit.Assert.assertEquals;\n\npublic class RomanianProblemGraph {\n    private HipsterGraph<RomanianProblem.City, Double> graph;\n\n    @Before\n    public void setUp() {\n        graph = RomanianProblem.graph();\n    }\n\n    @Test\n    public void testAradRoads() {\n        Set<GraphEdge<RomanianProblem.City, Double>> roads = Sets.newHashSet(graph.edgesOf(RomanianProblem.City.Arad));\n        Set<GraphEdge<RomanianProblem.City, Double>> expected = new HashSet<>();\n        expected.add(new UndirectedEdge<RomanianProblem.City, Double>(RomanianProblem.City.Arad, RomanianProblem.City.Zerind, 75d));\n        expected.add(new UndirectedEdge<RomanianProblem.City, Double>(RomanianProblem.City.Arad, RomanianProblem.City.Sibiu, 140d));\n        expected.add(new UndirectedEdge<RomanianProblem.City, Double>(RomanianProblem.City.Arad, RomanianProblem.City.Timisoara, 118d));\n        assertEquals(expected, roads);\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/lab/hipster/algorithm/BellmanFordTest.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.lab.hipster.algorithm;\n\nimport es.usc.citius.hipster.algorithm.Algorithm;\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.algorithm.NegativeCycleException;\nimport es.usc.citius.hipster.graph.GraphBuilder;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.graph.HashBasedHipsterGraph;\nimport es.usc.citius.hipster.graph.HipsterDirectedGraph;\nimport es.usc.citius.hipster.model.impl.WeightedNode;\nimport org.junit.Test;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class BellmanFordTest {\n\n    @Test(expected = NegativeCycleException.class)\n    public void negativeCycleTest(){\n        // Create a simple graph with negative cycles\n        HipsterDirectedGraph<Integer,Integer> g =\n                GraphBuilder.<Integer, Integer>create()\n                .connect(1).to(2).withEdge(1)\n                .connect(2).to(3).withEdge(1)\n                .connect(3).to(1).withEdge(-3)\n                .connect(3).to(4).withEdge(2)\n                .createDirectedGraph();\n\n        // Test search\n        Hipster.createBellmanFord(GraphSearchProblem.startingFrom(1).in(g).takeCostsFromEdges().build()).search(4);\n    }\n\n    @Test\n    public void negativeWeightedGraphTest(){\n        HipsterDirectedGraph<String,Integer> g =\n                GraphBuilder.<String, Integer>create()\n                        .connect(\"s\").to(\"A\").withEdge(5)\n                        .connect(\"s\").to(\"C\").withEdge(-2)\n                        .connect(\"A\").to(\"B\").withEdge(1)\n                        .connect(\"B\").to(\"C\").withEdge(2)\n                        .connect(\"B\").to(\"t\").withEdge(3)\n                        .connect(\"B\").to(\"D\").withEdge(7)\n                        .connect(\"C\").to(\"A\").withEdge(2)\n                        .connect(\"D\").to(\"C\").withEdge(3)\n                        .connect(\"D\").to(\"t\").withEdge(10)\n                        .createDirectedGraph();\n        // Test search\n        Algorithm<Integer, String, WeightedNode<Integer, String, Double>>.SearchResult result =\n                Hipster.createBellmanFord(GraphSearchProblem.startingFrom(\"s\").in(g).takeCostsFromEdges().build())\n                .search(\"t\");\n\n        List<String> path = result.getOptimalPaths().get(0);\n        int cost = result.getGoalNode().getCost().intValue();\n\n        assertEquals(Arrays.asList(\"s\", \"C\", \"A\", \"B\", \"t\"), path);\n        assertEquals(4, cost);\n    }\n\n\n\n    public static HashBasedHipsterGraph<Integer, Integer> completeRandomGraph(int vertices){\n        HashBasedHipsterGraph<Integer, Integer> graph = new HashBasedHipsterGraph<>();\n        for(int i=0; i<vertices; i++){\n            graph.add(i);\n            for(int j=0; j<i; j++){\n                int cost = (int)(Math.random() * 10);\n                graph.connect(j, i, cost);\n            }\n        }\n        return graph;\n    }\n\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/lab/hipster/algorithm/DepthFirstSearchTest.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.lab.hipster.algorithm;\n\nimport es.usc.citius.hipster.algorithm.DepthLimitedSearch;\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphBuilder;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.model.impl.UnweightedNode;\nimport es.usc.citius.hipster.graph.HipsterDirectedGraph;\nimport org.junit.Test;\n\nimport java.util.Iterator;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class DepthFirstSearchTest {\n\n    @Test\n    public void testTree(){\n        HipsterDirectedGraph<String, String> tree =\n                GraphBuilder.<String,String>create()\n                .connect(\"A\").to(\"B\").withEdge(\"1\")\n                .connect(\"A\").to(\"C\").withEdge(\"2\")\n                .connect(\"B\").to(\"D\").withEdge(\"3\")\n                .connect(\"B\").to(\"E\").withEdge(\"4\")\n                .connect(\"D\").to(\"H\").withEdge(\"5\")\n                .connect(\"D\").to(\"I\").withEdge(\"6\")\n                .connect(\"E\").to(\"J\").withEdge(\"7\")\n                .connect(\"E\").to(\"K\").withEdge(\"8\")\n                .connect(\"C\").to(\"F\").withEdge(\"9\")\n                .connect(\"C\").to(\"G\").withEdge(\"10\")\n                .connect(\"F\").to(\"L\").withEdge(\"11\")\n                .connect(\"F\").to(\"M\").withEdge(\"12\")\n                .connect(\"G\").to(\"N\").withEdge(\"13\")\n                .connect(\"G\").to(\"O\").withEdge(\"14\")\n                .createDirectedGraph();\n\n        Iterator<UnweightedNode<String, String>> iterator =\n                Hipster.createDepthFirstSearch(GraphSearchProblem.startingFrom(\"A\").in(tree).build()).iterator();\n\n        verify(iterator, new String[]{\"A\", \"B\", \"D\", \"H\", \"I\", \"E\", \"J\", \"K\", \"C\", \"F\", \"L\", \"M\", \"G\", \"N\", \"O\"});\n    }\n\n    @Test\n    public void testGraphWithoutCycles(){\n        HipsterDirectedGraph<String, String> graph =\n                GraphBuilder.<String,String>create()\n                        .connect(\"A\").to(\"B\").withEdge(\"1\")\n                        .connect(\"A\").to(\"C\").withEdge(\"2\")\n                        .connect(\"B\").to(\"D\").withEdge(\"3\")\n                        .connect(\"B\").to(\"E\").withEdge(\"4\")\n                        .connect(\"E\").to(\"C\").withEdge(\"5\")\n                        .createDirectedGraph();\n\n        Iterator<UnweightedNode<String, String>> iterator =\n                Hipster.createDepthFirstSearch(GraphSearchProblem.startingFrom(\"A\").in(graph).build()).iterator();\n\n        verify(iterator, new String[]{\"A\", \"B\", \"D\", \"E\", \"C\"});\n    }\n\n    @Test\n    public void testGraph(){\n        HipsterDirectedGraph<String, String> graph =\n                GraphBuilder.<String,String>create()\n                .connect(\"A\").to(\"B\").withEdge(\"1\")\n                .connect(\"A\").to(\"C\").withEdge(\"2\")\n                .connect(\"B\").to(\"D\").withEdge(\"3\")\n                .connect(\"B\").to(\"E\").withEdge(\"4\")\n                .connect(\"E\").to(\"C\").withEdge(\"5\")\n                .connect(\"C\").to(\"A\").withEdge(\"6\")\n                .createDirectedGraph();\n\n        Iterator<UnweightedNode<String, String>> iterator =\n                Hipster.createDepthFirstSearch(GraphSearchProblem.startingFrom(\"A\").in(graph).build()).iterator();\n\n        verify(iterator, new String[]{\"A\", \"B\", \"D\", \"E\", \"C\"});\n    }\n\n    private void verify(Iterator<UnweightedNode<String, String>> iterator, String[] expected){\n        int i=0;\n        while(iterator.hasNext()){\n            UnweightedNode<String,String> node = iterator.next();\n            assertEquals(expected[i++], node.state());\n        }\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/lab/hipster/algorithm/DepthLimitedSearchTest.java",
    "content": "package es.usc.citius.lab.hipster.algorithm;\n\nimport es.usc.citius.hipster.algorithm.DepthLimitedSearch;\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphBuilder;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.graph.HipsterDirectedGraph;\nimport org.junit.Test;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n *\n * Copyright 2015 Centro de Investigación en Tecnoloxías da Información (CITIUS),\n * University of Santiago de Compostela (USC).\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @author Gabriella Zekany\n */\npublic class DepthLimitedSearchTest {\n    @Test\n    public void testTreeStructureNotFound(){\n        HipsterDirectedGraph<String, String> tree =\n                GraphBuilder.<String,String>create()\n                        .connect(\"A\").to(\"B\").withEdge(\"0\")\n                        .connect(\"A\").to(\"C\").withEdge(\"0\")\n                        .connect(\"A\").to(\"D\").withEdge(\"0\")\n                        .connect(\"A\").to(\"E\").withEdge(\"0\")\n                        .connect(\"C\").to(\"F\").withEdge(\"0\")\n                        .connect(\"C\").to(\"G\").withEdge(\"0\")\n                        .connect(\"G\").to(\"L\").withEdge(\"0\")\n                        .connect(\"L\").to(\"M\").withEdge(\"0\")\n                        .connect(\"L\").to(\"N\").withEdge(\"0\")\n                        .connect(\"L\").to(\"O\").withEdge(\"0\")\n                        .connect(\"N\").to(\"P\").withEdge(\"0\")\n                        .connect(\"D\").to(\"H\").withEdge(\"0\")\n                        .connect(\"E\").to(\"I\").withEdge(\"0\")\n                        .connect(\"E\").to(\"J\").withEdge(\"0\")\n                        .connect(\"E\").to(\"K\").withEdge(\"0\")\n                        .createDirectedGraph();\n\n        DepthLimitedSearch dps =\n                Hipster.createDepthLimitedSearch(GraphSearchProblem.startingFrom(\"A\").goalAt(\"O\").in(tree).build(), 3);\n        boolean result = dps.execute();\n        assertEquals(3, dps.getMaximumDepth());\n        assertEquals(false, result);\n    }\n\n   @Test\n   public void testTreeStructureFound(){\n        HipsterDirectedGraph<String, String> tree =\n                GraphBuilder.<String,String>create()\n                        .connect(\"A\").to(\"B\").withEdge(\"0\")\n                        .connect(\"A\").to(\"C\").withEdge(\"0\")\n                        .connect(\"B\").to(\"D\").withEdge(\"0\")\n                        .connect(\"B\").to(\"E\").withEdge(\"0\")\n                        .connect(\"B\").to(\"F\").withEdge(\"0\")\n                        .connect(\"D\").to(\"G\").withEdge(\"0\")\n                        .connect(\"D\").to(\"H\").withEdge(\"0\")\n                        .connect(\"H\").to(\"I\").withEdge(\"0\")\n                        .connect(\"H\").to(\"J\").withEdge(\"0\")\n                        .connect(\"E\").to(\"K\").withEdge(\"0\")\n                        .connect(\"F\").to(\"L\").withEdge(\"0\")\n                        .connect(\"F\").to(\"M\").withEdge(\"0\")\n                        .connect(\"L\").to(\"N\").withEdge(\"0\")\n                        .connect(\"C\").to(\"O\").withEdge(\"0\")\n                        .connect(\"C\").to(\"P\").withEdge(\"0\")\n                        .connect(\"C\").to(\"Q\").withEdge(\"0\")\n                        .connect(\"P\").to(\"S\").withEdge(\"0\")\n                        .connect(\"P\").to(\"T\").withEdge(\"0\")\n                        .connect(\"P\").to(\"U\").withEdge(\"0\")\n                        .connect(\"S\").to(\"V\").withEdge(\"0\")\n                        .connect(\"S\").to(\"W\").withEdge(\"0\")\n                        .connect(\"S\").to(\"X\").withEdge(\"0\")\n                        .connect(\"Q\").to(\"Y\").withEdge(\"0\")\n                        .createDirectedGraph();\n\n        List pathDps1 = Arrays.asList(\"A\", \"C\", \"Q\", \"Y\", \"P\", \"U\", \"T\", \"S\", \"X\", \"W\", \"V\", \"O\", \"B\", \"F\", \"M\", \"L\", \"N\");\n        DepthLimitedSearch dps1 =\n                Hipster.createDepthLimitedSearch(GraphSearchProblem.startingFrom(\"A\").goalAt(\"N\").in(tree).build(), 20);\n        boolean result1 = dps1.execute();\n        assertEquals(true, result1);\n        assertEquals(16, dps1.getCurrentDepth());\n       assertEquals(pathDps1, dps1.getPath());\n\n        List pathDps2 = Arrays.asList(\"F\", \"M\", \"L\", \"N\");\n        DepthLimitedSearch dps2 =\n                Hipster.createDepthLimitedSearch(GraphSearchProblem.startingFrom(\"F\").goalAt(\"N\").in(tree).build(), 5);\n        boolean result2 = dps2.execute();\n        assertEquals(true, result2);\n        assertEquals(3, dps2.getCurrentDepth());\n        assertEquals(pathDps2, dps2.getPath());\n\n        List pathDps3 = Arrays.asList(\"S\", \"X\", \"W\");\n        DepthLimitedSearch dps3 =\n                Hipster.createDepthLimitedSearch(GraphSearchProblem.startingFrom(\"S\").goalAt(\"W\").in(tree).build(), 2);\n        boolean result3 = dps3.execute();\n        assertEquals(true, result3);\n        assertEquals(2, dps3.getCurrentDepth());\n        assertEquals(pathDps3, dps3.getPath());\n    }\n\n    @Test\n    public void testGraphFound() {\n        HipsterDirectedGraph<String, String> graph =\n                GraphBuilder.<String,String>create()\n                        .connect(\"A\").to(\"B\").withEdge(\"1\")\n                        .connect(\"A\").to(\"C\").withEdge(\"2\")\n                        .connect(\"B\").to(\"D\").withEdge(\"3\")\n                        .connect(\"B\").to(\"E\").withEdge(\"4\")\n                        .connect(\"E\").to(\"C\").withEdge(\"5\")\n                        .connect(\"C\").to(\"A\").withEdge(\"6\")\n                        .createDirectedGraph();\n        List path = Arrays.asList(\"A\",\"C\",\"B\",\"E\");\n        DepthLimitedSearch dps1 =\n                Hipster.createDepthLimitedSearch(GraphSearchProblem.startingFrom(\"A\").goalAt(\"E\").in(graph).build(), 6);\n        boolean result1 = dps1.execute();\n        assertEquals(true, result1);\n        assertEquals(3, dps1.getCurrentDepth());\n        assertEquals(path, dps1.getPath());\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/lab/hipster/algorithm/MultiobjectiveShortestPathTest.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.lab.hipster.algorithm;\n\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphBuilder;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.model.function.BinaryFunction;\nimport es.usc.citius.hipster.model.function.impl.BinaryOperation;\nimport es.usc.citius.hipster.graph.HipsterDirectedGraph;\nimport org.junit.Test;\n\n/**\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class MultiobjectiveShortestPathTest {\n\n    public static class Cost implements Comparable<Cost> {\n        private double c1;\n        private double c2;\n\n        public Cost(double c1, double c2) {\n            this.c1 = c1;\n            this.c2 = c2;\n        }\n\n        @Override\n        public String toString() {\n            return \"Cost{\" +\n                    \"c1=\" + c1 +\n                    \", c2=\" + c2 +\n                    '}';\n        }\n\n        @Override\n        public int compareTo(Cost o) {\n            // Lexicographical comparison\n            if (c1 < o.c1 && c2 < o.c2){\n                return -1;\n            } else if (o.c1 < c1 && o.c2 < c2){\n                return 1;\n            }\n            // Non-dominated\n            return 0;\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            if (this == o) return true;\n            if (o == null || getClass() != o.getClass()) return false;\n\n            Cost cost = (Cost) o;\n\n            if (Double.compare(cost.c1, c1) != 0) return false;\n            if (Double.compare(cost.c2, c2) != 0) return false;\n\n            return true;\n        }\n\n        @Override\n        public int hashCode() {\n            int result;\n            long temp;\n            temp = Double.doubleToLongBits(c1);\n            result = (int) (temp ^ (temp >>> 32));\n            temp = Double.doubleToLongBits(c2);\n            result = 31 * result + (int) (temp ^ (temp >>> 32));\n            return result;\n        }\n    }\n    @Test\n    public void test(){\n        // Create a multiobjective graph\n        final HipsterDirectedGraph<String, Cost> graph =\n                GraphBuilder.create()\n                        .connect(\"v1\").to(\"v2\").withEdge(new Cost(7d, 1d))\n                        .connect(\"v1\").to(\"v3\").withEdge(new Cost(1d, 7d))\n                        .connect(\"v1\").to(\"v4\").withEdge(new Cost(8d, 4d))\n                        .connect(\"v2\").to(\"v4\").withEdge(new Cost(2d, 1d))\n                        .connect(\"v2\").to(\"v6\").withEdge(new Cost(2d, 2d))\n                        .connect(\"v3\").to(\"v4\").withEdge(new Cost(1d, 1d))\n                        .connect(\"v4\").to(\"v5\").withEdge(new Cost(6d, 4d))\n                        .connect(\"v4\").to(\"v6\").withEdge(new Cost(2d, 2d))\n                        .buildDirectedGraph();\n\n        // Since we use a special cost, we need to define a BinaryOperation<Cost>\n        // that provides the required elements to work with our special cost type.\n        // These elements are: a BinaryFunction<Cost> that defines how to compute\n        // a new cost from two costs: C x C -> C, the identity element I of our\n        // cost (C + I = C, I + C = C), and the maximum value.\n\n        // Cost a + Cost b is defined as a new cost a.c1+b.c1, a.c2+b.c2\n        BinaryFunction<Cost> f = new BinaryFunction<Cost>() {\n            @Override\n            public Cost apply(Cost a, Cost b) {\n                Cost c = new Cost(a.c1 + b.c1, a.c2 + b.c2);\n                return c;\n            }\n        };\n        // The identity cost identity satisfy:\n        // f.apply(c, identity).equals(c)\n        // f.apply(identity, c).equals(c)\n        Cost identity = new Cost(0d, 0d);\n\n        // Maximum value of our costs\n        Cost max = new Cost(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n\n        // Create our custom binary operation:\n        BinaryOperation<Cost> bf = new BinaryOperation<Cost>(f, identity, max);\n\n        System.out.println(Hipster.createMultiobjectiveLS(GraphSearchProblem.startingFrom(\"v1\").in(graph).useGenericCosts(bf).build()).search(\"v6\"));\n\n        // TODO; Add solution verification\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/lab/hipster/collection/HashQueueTest.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.lab.hipster.collection;\n\n\nimport es.usc.citius.lab.hipster.collections.HashQueue;\nimport org.junit.Test;\n\nimport java.util.Iterator;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\n\npublic class HashQueueTest {\n    @Test\n    public void testOffer() throws Exception {\n        HashQueue<String> queue = new HashQueue<String>();\n        queue.offer(\"element\");\n        assertEquals(1, queue.size());\n    }\n\n    @Test\n    public void testPoll() throws Exception {\n        HashQueue<String> queue = new HashQueue<String>();\n        queue.offer(\"element\");\n        assertEquals(\"element\", queue.poll());\n        assertEquals(0, queue.size());\n    }\n\n    @Test\n    public void testPeek() throws Exception {\n        HashQueue<String> queue = new HashQueue<String>();\n        queue.offer(\"element\");\n        assertEquals(\"element\", queue.peek());\n        assertEquals(1, queue.size());\n    }\n\n    @Test\n    public void testIterator() throws Exception {\n        HashQueue<String> queue = new HashQueue<String>();\n        String[] elements = new String[]{\"element-1\",\"element-2\",\"element-3\"};\n        queue.offer(elements[0]);\n        queue.offer(elements[1]);\n        queue.offer(elements[2]);\n        Iterator<String> it = queue.iterator();\n        assertTrue(it.hasNext());\n        int i=0;\n        while(it.hasNext()){\n            assertEquals(elements[i++],it.next());\n        }\n        assertEquals(3, queue.size());\n    }\n\n    @Test\n    public void testContains() throws Exception {\n        HashQueue<String> queue = new HashQueue<String>();\n        String[] elements = new String[]{\"element-1\",\"element-2\",\"element-3\"};\n        queue.offer(elements[0]);\n        queue.offer(elements[1]);\n        queue.offer(elements[2]);\n        assertTrue(queue.contains(\"element-1\"));\n        assertTrue(queue.contains(\"element-2\"));\n        assertTrue(queue.contains(\"element-3\"));\n    }\n}\n"
  },
  {
    "path": "hipster-core/src/test/java/es/usc/citius/lab/hipster/maze/Maze2DTest.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS).\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage es.usc.citius.lab.hipster.maze;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertTrue;\n\nimport java.awt.Point;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.Collection;\nimport java.util.HashSet;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\n\nimport es.usc.citius.hipster.util.examples.maze.Maze2D;\n\npublic class Maze2DTest {\n\n    private static final String[] obstacleMaze = {\n            \"XX                             G\",\n            \"          XXXXXXXX              \",\n            \"          XXXXXXXX              \",\n            \"          XXXXXXXX              \",\n            \"                                \",\n            \"                                \",\n            \" S                            XX\"};\n\n    private static final String[] refMaze = {\n            \"XX                             G\",\n            \"                                \",\n            \"                                \",\n            \"                                \",\n            \"                                \",\n            \"                                \",\n            \"S                             XX\"};\n\n    private static final String[] testMaze = {\n            \"XXSXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",\n            \"XX XXXXXXXXXXXXX     XXXXXXXXXXX\",\n            \"XX    XXXXXXXXXX XXX XX     XXXX\",\n            \"XXXXX  XXXXXX    XXX XX XXX XXXX\",\n            \"XXX XX XXXXXX XX XXX XX  XX XXXX\",\n            \"XXX     XXXXX XXXXXX XXXXXX XXXX\",\n            \"XXXXXXX       XXXXXX        XXXX\",\n            \"XXXXXXXXXX XXXXX XXXXXXXXXXXXXXX\",\n            \"XXXXXXXXXX XX    XXXXX      XXXX\",\n            \"XXXXXXXXXX    XXXXXXXX XXXX XXXX\",\n            \"XXXXXXXXXXX XXXXXXXXXX XXXX XXXX\",\n            \"XXXXXXXXXXX            XXXX XXXX\",\n            \"XXXXXXXXXXXXXXXXXXXXXXXX XX XXXX\",\n            \"XXXXXX              XXXX XX XXXX\",\n            \"XXXXXX XXXXXXXXXXXX XX      XXXX\",\n            \"XXXXXX XXG   XXXXXX XXXX XXXXXXX\",\n            \"XXXXXX XXXXX   XXX            XX\",\n            \"XXXXXX XXXXXXX XXXXXXXXXXX XXXXX\",\n            \"XXXXXX XXXXXXX XXXXXXXXXXXXXXXXX\",\n            \"XXXXXX           XXXXXXXXXXXXXXX\"};\n\n    // (10,0), (11,0), (23,16), (24,16)\n    private static final String[] testMaze2 = {\n            \"XXSXXXXXXX  XXXXXXXXXXXXXXXXXXXX\",\n            \"XX XXXXXXXXXXXXX     XXXXXXXXXXX\",\n            \"XX    XXXXXXXXXX XXX XX     XXXX\",\n            \"XXXXX  XXXXXX    XXX XX XXX XXXX\",\n            \"XXX XX XXXXXX XX XXX XX  XX XXXX\",\n            \"XXX     XXXXX XXXXXX XXXXXX XXXX\",\n            \"XXXXXXX       XXXXXX        XXXX\",\n            \"XXXXXXXXXX XXXXX XXXXXXXXXXXXXXX\",\n            \"XXXXXXXXXX XX    XXXXX      XXXX\",\n            \"XXXXXXXXXX    XXXXXXXX XXXX XXXX\",\n            \"XXXXXXXXXXX XXXXXXXXXX XXXX XXXX\",\n            \"XXXXXXXXXXX            XXXX XXXX\",\n            \"XXXXXXXXXXXXXXXXXXXXXXXX XX XXXX\",\n            \"XXXXXX              XXXX XX XXXX\",\n            \"XXXXXX XXXXXXXXXXXX XX      XXXX\",\n            \"XXXXXX XXG   XXXXXX XXXX XXXXXXX\",\n            \"XXXXXX XXXXX   XXX     XX     XX\",\n            \"XXXXXX XXXXXXX XXXXXXXXXXX XXXXX\",\n            \"XXXXXX XXXXXXX XXXXXXXXXXXXXXXXX\",\n            \"XXXXXX            XXXXXXXXXXXXXX\"};\n\n    @Ignore(\"To be fixed\")\n    @Test\n    public void testDiff() {\n        Maze2D maze = new Maze2D(testMaze);\n        Maze2D maze2 = new Maze2D(testMaze2);\n        Collection<Point> diffs = maze.diff(maze2);\n        Collection<Point> result = new HashSet<Point>();\n        result.add(new Point(10, 0));\n        result.add(new Point(11, 0));\n        result.add(new Point(23, 16));\n        result.add(new Point(24, 16));\n        assertEquals(diffs, result);\n    }\n\n    @Test\n    public void testPoints() {\n        Maze2D maze = new Maze2D(testMaze);\n        // Valid cells\n        assertTrue(maze.validLocation(new Point(2, 1)));\n        assertTrue(maze.validLocation(new Point(2, 0)));\n        assertTrue(maze.validLocation(new Point(4, 5)));\n        // Invalid cells\n        assertTrue(!maze.validLocation(new Point(0, 0)));\n        assertTrue(!maze.validLocation(new Point(1, 1)));\n        assertTrue(!maze.validLocation(new Point(12, 5)));\n        // Initial loc\n        assertEquals(maze.getInitialLoc(), new Point(2, 0));\n        assertEquals(maze.getGoalLoc(), new Point(9, 15));\n    }\n\n    @Ignore(\"To be fixed\")\n    @Test\n    public void testObstacles() {\n        Maze2D maze = new Maze2D(refMaze);\n        Maze2D goal = new Maze2D(obstacleMaze);\n        maze.putObstacleRectangle(new Point(10, 1), new Point(17, 3));\n        assertTrue(maze.diff(goal).isEmpty());\n        maze.removeObstacleRectangle(new Point(10, 1), new Point(17, 3));\n        assertTrue(maze.diff(new Maze2D(refMaze)).isEmpty());\n        assertTrue(!maze.diff(goal).isEmpty());\n    }\n    \n\t@Test\n    public void testPointInBounds() {\n    \tMaze2D maze = new Maze2D(testMaze);\n    \tassertFalse(maze.pointInBounds(new Point(-1,0)));\n    \tassertFalse(maze.pointInBounds(new Point(0,-1)));\n    \t\n    \tint colLength = maze.getMaze()[0].length;\n    \tint rowLength = maze.getMaze().length;\n    \tassertFalse(maze.pointInBounds(new Point(colLength,0)));\n    \tassertFalse(maze.pointInBounds(new Point(0,rowLength)));\n    \t\n    \tassertTrue(maze.pointInBounds(new Point(0,0)));\n    \tassertTrue(maze.pointInBounds(new Point(0,0)));\n    \tassertTrue(maze.pointInBounds(new Point(colLength-1,0)));\n    \tassertTrue(maze.pointInBounds(new Point(0,rowLength-1)));\n    }\n\t\n\t@Test\n\tpublic void testCharToPoint(){\n\t\ttry{\n\t\t\tMaze2D maze = new Maze2D(testMaze);\n\t\t\tMethod method = maze.getClass().getDeclaredMethod(\"charToPoint\", char.class);\n\t\t\tmethod.setAccessible(true);\n\t\t\tchar c = ' ';\n\t\t\tPoint point = (Point) method.invoke(maze, c);\n\t\t\tassertEquals(new Point(2, 1), point);\n\t\t}catch(NoSuchMethodException e){\n\t\t\tassertTrue(false);\n\t\t}catch(InvocationTargetException e){\n\t\t\tassertTrue(false);\n\t\t}catch(IllegalAccessException e){\n\t\t\tassertTrue(false);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "hipster-examples/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n  ~ Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n  ~\n  ~    Licensed under the Apache License, Version 2.0 (the \"License\");\n  ~    you may not use this file except in compliance with the License.\n  ~    You may obtain a copy of the License at\n  ~\n  ~        http://www.apache.org/licenses/LICENSE-2.0\n  ~\n  ~    Unless required by applicable law or agreed to in writing, software\n  ~    distributed under the License is distributed on an \"AS IS\" BASIS,\n  ~    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  ~    See the License for the specific language governing permissions and\n  ~    limitations under the License.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <parent>\n        <groupId>es.usc.citius.hipster</groupId>\n        <artifactId>hipster-pom</artifactId>\n        <version>1.0.2-SNAPSHOT</version>\n    </parent>\n    <modelVersion>4.0.0</modelVersion>\n    <artifactId>hipster-examples</artifactId>\n\n    <properties>\n        <hipster.root.dir>${project.basedir}/..</hipster.root.dir>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>es.usc.citius.hipster</groupId>\n            <artifactId>hipster-core</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>es.usc.citius.hipster</groupId>\n            <artifactId>hipster-third-party-graphs</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>com.google.guava</groupId>\n            <artifactId>guava</artifactId>\n            <version>29.0-jre</version>\n        </dependency>\n        <dependency>\n            <groupId>com.intellij</groupId>\n            <artifactId>forms_rt</artifactId>\n            <version>7.0.3</version>\n        </dependency>\n    </dependencies>\n\n\n</project>"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/ASCIIMazeVisualizer.form",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<form xmlns=\"http://www.intellij.com/uidesigner/form/\" version=\"1\" bind-to-class=\"es.usc.citius.hipster.examples.ASCIIMazeVisualizer\">\n  <grid id=\"27dc6\" binding=\"mainPanel\" layout-manager=\"BorderLayout\" hgap=\"0\" vgap=\"0\">\n    <constraints>\n      <xy x=\"20\" y=\"20\" width=\"532\" height=\"445\"/>\n    </constraints>\n    <properties/>\n    <border type=\"none\"/>\n    <children>\n      <grid id=\"267b9\" binding=\"optionPanel\" layout-manager=\"GridLayoutManager\" row-count=\"4\" column-count=\"1\" same-size-horizontally=\"false\" same-size-vertically=\"false\" hgap=\"-1\" vgap=\"-1\">\n        <margin top=\"0\" left=\"0\" bottom=\"0\" right=\"0\"/>\n        <constraints border-constraint=\"North\"/>\n        <properties>\n          <enabled value=\"true\"/>\n        </properties>\n        <border type=\"none\"/>\n        <children>\n          <component id=\"b7a4c\" class=\"javax.swing.JLabel\" binding=\"loadMazeLabel\">\n            <constraints>\n              <grid row=\"0\" column=\"0\" row-span=\"1\" col-span=\"1\" vsize-policy=\"0\" hsize-policy=\"0\" anchor=\"8\" fill=\"0\" indent=\"0\" use-parent-layout=\"false\"/>\n            </constraints>\n            <properties>\n              <text value=\"Load ASCII Maze:\"/>\n            </properties>\n          </component>\n          <component id=\"fb876\" class=\"javax.swing.JComboBox\" binding=\"comboMazes\">\n            <constraints>\n              <grid row=\"1\" column=\"0\" row-span=\"1\" col-span=\"1\" vsize-policy=\"0\" hsize-policy=\"2\" anchor=\"8\" fill=\"1\" indent=\"0\" use-parent-layout=\"false\"/>\n            </constraints>\n            <properties>\n              <model/>\n            </properties>\n          </component>\n          <grid id=\"c0fa3\" binding=\"algoContainerPanel\" layout-manager=\"GridLayoutManager\" row-count=\"2\" column-count=\"1\" same-size-horizontally=\"false\" same-size-vertically=\"false\" hgap=\"-1\" vgap=\"-1\">\n            <margin top=\"0\" left=\"0\" bottom=\"0\" right=\"0\"/>\n            <constraints>\n              <grid row=\"3\" column=\"0\" row-span=\"1\" col-span=\"1\" vsize-policy=\"3\" hsize-policy=\"3\" anchor=\"0\" fill=\"3\" indent=\"0\" use-parent-layout=\"false\"/>\n            </constraints>\n            <properties/>\n            <border type=\"none\"/>\n            <children>\n              <component id=\"6a93e\" class=\"javax.swing.JComboBox\" binding=\"comboAlgorithm\">\n                <constraints>\n                  <grid row=\"0\" column=\"0\" row-span=\"1\" col-span=\"1\" vsize-policy=\"0\" hsize-policy=\"2\" anchor=\"8\" fill=\"1\" indent=\"0\" use-parent-layout=\"false\"/>\n                </constraints>\n                <properties>\n                  <model/>\n                </properties>\n              </component>\n              <grid id=\"7efc3\" binding=\"configAlgorithmPanel\" layout-manager=\"BorderLayout\" hgap=\"0\" vgap=\"0\">\n                <constraints>\n                  <grid row=\"1\" column=\"0\" row-span=\"1\" col-span=\"1\" vsize-policy=\"3\" hsize-policy=\"3\" anchor=\"0\" fill=\"3\" indent=\"0\" use-parent-layout=\"false\"/>\n                </constraints>\n                <properties/>\n                <border type=\"none\"/>\n                <children>\n                  <grid id=\"5274\" binding=\"refreshPanel\" layout-manager=\"GridLayoutManager\" row-count=\"1\" column-count=\"3\" same-size-horizontally=\"false\" same-size-vertically=\"false\" hgap=\"-1\" vgap=\"-1\">\n                    <margin top=\"0\" left=\"0\" bottom=\"0\" right=\"0\"/>\n                    <constraints border-constraint=\"West\"/>\n                    <properties/>\n                    <border type=\"none\"/>\n                    <children>\n                      <component id=\"60a1e\" class=\"javax.swing.JSpinner\" binding=\"refreshSpinner\">\n                        <constraints>\n                          <grid row=\"0\" column=\"2\" row-span=\"1\" col-span=\"1\" vsize-policy=\"0\" hsize-policy=\"6\" anchor=\"8\" fill=\"1\" indent=\"0\" use-parent-layout=\"false\">\n                            <preferred-size width=\"80\" height=\"-1\"/>\n                          </grid>\n                        </constraints>\n                        <properties/>\n                      </component>\n                      <component id=\"b310e\" class=\"javax.swing.JLabel\" binding=\"refreshLabel\">\n                        <constraints>\n                          <grid row=\"0\" column=\"1\" row-span=\"1\" col-span=\"1\" vsize-policy=\"0\" hsize-policy=\"0\" anchor=\"8\" fill=\"0\" indent=\"0\" use-parent-layout=\"false\"/>\n                        </constraints>\n                        <properties>\n                          <text value=\"Refresh interval (ms):\"/>\n                        </properties>\n                      </component>\n                      <component id=\"69e94\" class=\"javax.swing.JCheckBox\" binding=\"realtimePrintingCheckBox\">\n                        <constraints>\n                          <grid row=\"0\" column=\"0\" row-span=\"1\" col-span=\"1\" vsize-policy=\"0\" hsize-policy=\"3\" anchor=\"8\" fill=\"0\" indent=\"0\" use-parent-layout=\"false\"/>\n                        </constraints>\n                        <properties>\n                          <selected value=\"true\"/>\n                          <text value=\"Realtime printing (slow)\"/>\n                        </properties>\n                      </component>\n                    </children>\n                  </grid>\n                  <grid id=\"87149\" binding=\"buttonPanel\" layout-manager=\"GridLayoutManager\" row-count=\"1\" column-count=\"2\" same-size-horizontally=\"false\" same-size-vertically=\"false\" hgap=\"-1\" vgap=\"-1\">\n                    <margin top=\"0\" left=\"0\" bottom=\"0\" right=\"0\"/>\n                    <constraints border-constraint=\"East\"/>\n                    <properties/>\n                    <border type=\"none\"/>\n                    <children>\n                      <component id=\"921f4\" class=\"javax.swing.JButton\" binding=\"runButton\" default-binding=\"true\">\n                        <constraints>\n                          <grid row=\"0\" column=\"0\" row-span=\"1\" col-span=\"1\" vsize-policy=\"0\" hsize-policy=\"0\" anchor=\"0\" fill=\"1\" indent=\"0\" use-parent-layout=\"false\"/>\n                        </constraints>\n                        <properties>\n                          <horizontalAlignment value=\"4\"/>\n                          <text value=\"Start\"/>\n                        </properties>\n                      </component>\n                      <component id=\"83b0f\" class=\"javax.swing.JButton\" binding=\"resetButton\">\n                        <constraints>\n                          <grid row=\"0\" column=\"1\" row-span=\"1\" col-span=\"1\" vsize-policy=\"0\" hsize-policy=\"3\" anchor=\"0\" fill=\"1\" indent=\"0\" use-parent-layout=\"false\"/>\n                        </constraints>\n                        <properties>\n                          <horizontalAlignment value=\"4\"/>\n                          <text value=\"Reset\"/>\n                        </properties>\n                      </component>\n                    </children>\n                  </grid>\n                </children>\n              </grid>\n            </children>\n          </grid>\n          <component id=\"43a8e\" class=\"javax.swing.JLabel\">\n            <constraints>\n              <grid row=\"2\" column=\"0\" row-span=\"1\" col-span=\"1\" vsize-policy=\"0\" hsize-policy=\"0\" anchor=\"8\" fill=\"0\" indent=\"0\" use-parent-layout=\"false\"/>\n            </constraints>\n            <properties>\n              <text value=\"Select algorithm:\"/>\n            </properties>\n          </component>\n        </children>\n      </grid>\n      <grid id=\"1a5b0\" binding=\"textContainerPanel\" layout-manager=\"GridLayoutManager\" row-count=\"1\" column-count=\"1\" same-size-horizontally=\"false\" same-size-vertically=\"false\" hgap=\"-1\" vgap=\"-1\">\n        <margin top=\"10\" left=\"1\" bottom=\"1\" right=\"1\"/>\n        <constraints border-constraint=\"Center\"/>\n        <properties/>\n        <border type=\"none\"/>\n        <children>\n          <component id=\"5b77f\" class=\"javax.swing.JTextArea\" binding=\"mazeTextArea\">\n            <constraints>\n              <grid row=\"0\" column=\"0\" row-span=\"1\" col-span=\"1\" vsize-policy=\"6\" hsize-policy=\"6\" anchor=\"0\" fill=\"3\" indent=\"0\" use-parent-layout=\"false\"/>\n            </constraints>\n            <properties>\n              <font name=\"Monospaced\" size=\"20\"/>\n            </properties>\n          </component>\n        </children>\n      </grid>\n      <grid id=\"278d9\" binding=\"statusBarPanel\" layout-manager=\"FlowLayout\" hgap=\"5\" vgap=\"5\" flow-align=\"0\">\n        <constraints border-constraint=\"South\"/>\n        <properties/>\n        <border type=\"bevel-lowered\"/>\n        <children>\n          <component id=\"ba4cf\" class=\"javax.swing.JLabel\" binding=\"labelInfoSteps\">\n            <constraints/>\n            <properties>\n              <text value=\"Steps:\"/>\n            </properties>\n          </component>\n          <component id=\"b840e\" class=\"javax.swing.JLabel\" binding=\"labelSteps\">\n            <constraints/>\n            <properties>\n              <text value=\"0\"/>\n            </properties>\n          </component>\n          <component id=\"15b9b\" class=\"javax.swing.JSeparator\">\n            <constraints/>\n            <properties>\n              <orientation value=\"1\"/>\n            </properties>\n          </component>\n          <component id=\"e9642\" class=\"javax.swing.JLabel\" binding=\"labelInfoCost\">\n            <constraints/>\n            <properties>\n              <text value=\"Distance:\"/>\n            </properties>\n          </component>\n          <component id=\"82a32\" class=\"javax.swing.JLabel\" binding=\"labelCost\">\n            <constraints/>\n            <properties>\n              <text value=\"0\"/>\n            </properties>\n          </component>\n        </children>\n      </grid>\n    </children>\n  </grid>\n</form>\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/ASCIIMazeVisualizer.java",
    "content": "package es.usc.citius.hipster.examples;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Lists;\nimport com.intellij.uiDesigner.core.GridConstraints;\nimport com.intellij.uiDesigner.core.GridLayoutManager;\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.model.CostNode;\nimport es.usc.citius.hipster.model.Node;\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.CostFunction;\nimport es.usc.citius.hipster.model.function.HeuristicFunction;\nimport es.usc.citius.hipster.model.function.impl.StateTransitionFunction;\nimport es.usc.citius.hipster.model.impl.WeightedNode;\nimport es.usc.citius.hipster.model.problem.ProblemBuilder;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\nimport es.usc.citius.hipster.util.examples.maze.Maze2D;\nimport es.usc.citius.hipster.util.examples.maze.Mazes;\n\nimport javax.swing.*;\nimport javax.swing.Timer;\nimport javax.swing.event.ChangeEvent;\nimport javax.swing.event.ChangeListener;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.text.DecimalFormat;\nimport java.util.*;\nimport java.util.List;\n\n/**\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class ASCIIMazeVisualizer {\n    private JPanel mainPanel;\n    private JPanel optionPanel;\n    private JComboBox comboMazes;\n    private JLabel loadMazeLabel;\n    private JPanel algoContainerPanel;\n    private JPanel textContainerPanel;\n    private JTextArea mazeTextArea;\n    private JComboBox comboAlgorithm;\n    private JButton resetButton;\n    private JButton runButton;\n    private JPanel configAlgorithmPanel;\n    private JSpinner refreshSpinner;\n    private JPanel refreshPanel;\n    private JPanel buttonPanel;\n    private JLabel refreshLabel;\n    private JCheckBox realtimePrintingCheckBox;\n    private JPanel statusBarPanel;\n    private JLabel labelInfoSteps;\n    private JLabel labelSteps;\n    private JLabel labelInfoCost;\n    private JLabel labelCost;\n    private JFrame mainFrame;\n    private String lastMaze;\n\n    {\n// GUI initializer generated by IntelliJ IDEA GUI Designer\n// >>> IMPORTANT!! <<<\n// DO NOT EDIT OR ADD ANY CODE HERE!\n        $$$setupUI$$$();\n    }\n\n    /**\n     * Method generated by IntelliJ IDEA GUI Designer\n     * >>> IMPORTANT!! <<<\n     * DO NOT edit this method OR call it in your code!\n     *\n     * @noinspection ALL\n     */\n    private void $$$setupUI$$$() {\n        mainPanel = new JPanel();\n        mainPanel.setLayout(new BorderLayout(0, 0));\n        optionPanel = new JPanel();\n        optionPanel.setLayout(new GridLayoutManager(4, 1, new Insets(0, 0, 0, 0), -1, -1));\n        optionPanel.setEnabled(true);\n        mainPanel.add(optionPanel, BorderLayout.NORTH);\n        loadMazeLabel = new JLabel();\n        loadMazeLabel.setText(\"Load ASCII Maze:\");\n        optionPanel.add(loadMazeLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));\n        comboMazes = new JComboBox();\n        final DefaultComboBoxModel defaultComboBoxModel1 = new DefaultComboBoxModel();\n        comboMazes.setModel(defaultComboBoxModel1);\n        optionPanel.add(comboMazes, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));\n        algoContainerPanel = new JPanel();\n        algoContainerPanel.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1));\n        optionPanel.add(algoContainerPanel, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));\n        comboAlgorithm = new JComboBox();\n        final DefaultComboBoxModel defaultComboBoxModel2 = new DefaultComboBoxModel();\n        comboAlgorithm.setModel(defaultComboBoxModel2);\n        algoContainerPanel.add(comboAlgorithm, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));\n        configAlgorithmPanel = new JPanel();\n        configAlgorithmPanel.setLayout(new BorderLayout(0, 0));\n        algoContainerPanel.add(configAlgorithmPanel, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));\n        refreshPanel = new JPanel();\n        refreshPanel.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));\n        configAlgorithmPanel.add(refreshPanel, BorderLayout.WEST);\n        refreshSpinner = new JSpinner();\n        refreshPanel.add(refreshSpinner, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(80, -1), null, 0, false));\n        refreshLabel = new JLabel();\n        refreshLabel.setText(\"Refresh interval (ms):\");\n        refreshPanel.add(refreshLabel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));\n        realtimePrintingCheckBox = new JCheckBox();\n        realtimePrintingCheckBox.setSelected(true);\n        realtimePrintingCheckBox.setText(\"Realtime printing (slow)\");\n        refreshPanel.add(realtimePrintingCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));\n        buttonPanel = new JPanel();\n        buttonPanel.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));\n        configAlgorithmPanel.add(buttonPanel, BorderLayout.EAST);\n        runButton = new JButton();\n        runButton.setHorizontalAlignment(4);\n        runButton.setText(\"Start\");\n        buttonPanel.add(runButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));\n        resetButton = new JButton();\n        resetButton.setHorizontalAlignment(4);\n        resetButton.setText(\"Reset\");\n        buttonPanel.add(resetButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));\n        final JLabel label1 = new JLabel();\n        label1.setText(\"Select algorithm:\");\n        optionPanel.add(label1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));\n        textContainerPanel = new JPanel();\n        textContainerPanel.setLayout(new GridLayoutManager(1, 1, new Insets(10, 1, 1, 1), -1, -1));\n        mainPanel.add(textContainerPanel, BorderLayout.CENTER);\n        mazeTextArea = new JTextArea();\n        mazeTextArea.setFont(new Font(\"Monospaced\", mazeTextArea.getFont().getStyle(), 20));\n        textContainerPanel.add(mazeTextArea, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));\n        statusBarPanel = new JPanel();\n        statusBarPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));\n        mainPanel.add(statusBarPanel, BorderLayout.SOUTH);\n        statusBarPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLoweredBevelBorder(), null));\n        labelInfoSteps = new JLabel();\n        labelInfoSteps.setText(\"Steps:\");\n        statusBarPanel.add(labelInfoSteps);\n        labelSteps = new JLabel();\n        labelSteps.setText(\"0\");\n        statusBarPanel.add(labelSteps);\n        final JSeparator separator1 = new JSeparator();\n        separator1.setOrientation(1);\n        statusBarPanel.add(separator1);\n        labelInfoCost = new JLabel();\n        labelInfoCost.setText(\"Distance:\");\n        statusBarPanel.add(labelInfoCost);\n        labelCost = new JLabel();\n        labelCost.setText(\"0\");\n        statusBarPanel.add(labelCost);\n    }\n\n    /**\n     * @noinspection ALL\n     */\n    public JComponent $$$getRootComponent$$$() {\n        return mainPanel;\n    }\n\n    private enum State {STOPPED, STARTED, PAUSED}\n\n    // Global execution state\n    private State state = State.STOPPED;\n    // Current algorithm used\n    private Iterator<? extends Node<?, Point, ?>> algorithmIterator;\n    // Listener to update the text area\n    private ExecutionHandler executionHandler;\n    // Move all to the algorithm executor\n    private Set<Point> explored = new HashSet<Point>();\n    private int steps = 0;\n    private Timer timer;\n    private Maze2D maze;\n\n    public static void main(String[] args) {\n\n        try {\n            UIManager.setLookAndFeel(\"javax.swing.plaf.nimbus.NimbusLookAndFeel\");\n        } catch (Exception ex) {\n        }\n\n        JFrame frame = new JFrame(\"Hipster Maze Shortest Path Visualizer\");\n        frame.setContentPane(new ASCIIMazeVisualizer(frame).mainPanel);\n        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n        frame.pack();\n        frame.setLocationRelativeTo(null);\n        frame.setVisible(true);\n    }\n\n    public ASCIIMazeVisualizer(final JFrame frame) {\n        this.mainFrame = frame;\n        // Use double buffer for smooth updates\n        mazeTextArea.setDoubleBuffered(true);\n        refreshSpinner.setValue(50);\n\n        // Default values\n        comboMazes.addItem(\"Maze example 1\");\n        comboMazes.addItem(\"Maze example 2\");\n        comboMazes.addItem(\"Maze example 3\");\n        comboMazes.addItem(\"Maze example 4\");\n        comboMazes.addItem(\"Maze example 5\");\n\n        comboAlgorithm.addItem(\"Depth First Search (DFS, non-optimal)\");\n        comboAlgorithm.addItem(\"Breadth First Search (BFS, non-optimal) \");\n        comboAlgorithm.addItem(\"Bellman Ford\");\n        comboAlgorithm.addItem(\"Dijkstra\");\n        comboAlgorithm.addItem(\"A*\");\n        comboAlgorithm.addItem(\"IDA*\");\n\n        loadSelectedMaze();\n\n        // Listener to process run/pause button\n        runButton.addActionListener(new ActionListener() {\n            @Override\n            public void actionPerformed(ActionEvent e) {\n                switch (state) {\n                    case STARTED:\n                        pause();\n                        break;\n                    case STOPPED:\n                        start();\n                        break;\n                    case PAUSED:\n                        continueExecution();\n                        break;\n                }\n            }\n        });\n\n        resetButton.addActionListener(new ActionListener() {\n            @Override\n            public void actionPerformed(ActionEvent e) {\n                stop();\n                loadSelectedMaze();\n            }\n        });\n\n        comboMazes.addActionListener(new ActionListener() {\n            @Override\n            public void actionPerformed(ActionEvent e) {\n                loadSelectedMaze();\n                // Resize to adapt the window\n                frame.pack();\n            }\n        });\n\n\n        refreshSpinner.addChangeListener(new ChangeListener() {\n            @Override\n            public void stateChanged(ChangeEvent e) {\n                timer.setDelay((Integer) refreshSpinner.getValue());\n            }\n        });\n\n        // Initialize the thread / listener for the execution\n        executionHandler = new ExecutionHandler();\n        timer = new Timer((Integer) refreshSpinner.getValue(), executionHandler);\n        new Thread(executionHandler).start();\n        timer.start();\n    }\n\n    private void continueExecution() {\n        if (state.equals(State.PAUSED)) {\n            runButton.setText(\"Pause\");\n            state = State.STARTED;\n        }\n    }\n\n    private synchronized Node<?, Point, ?> executeSearchStep() {\n        Node<?, Point, ?> node = null;\n        if (algorithmIterator.hasNext()) {\n            node = algorithmIterator.next();\n            steps++;\n            explored.add(node.state());\n            if (realtimePrintingCheckBox.isSelected()) updateVisualizer(node, maze, explored);\n            if (node.state().equals(maze.getGoalLoc())) {\n                updateVisualizer(node, maze, explored);\n                stop();\n            }\n        } else {\n            updateVisualizer(node, maze, explored);\n            stop();\n        }\n        return node;\n    }\n\n    private void start() {\n        // Create a new maze and run the selected algorithm\n        steps = 0;\n        try {\n            maze = new Maze2D(mazeTextArea.getText().split(\"\\\\r?\\\\n\"));\n        } catch (Exception ex) {\n            JOptionPane.showMessageDialog(mainFrame, ex.getMessage() + \". Try to reset the map.\", \"Maze parse exception\", JOptionPane.ERROR_MESSAGE);\n            return;\n        }\n        // Create a new algorithm\n        algorithmIterator = createAlgorithm(maze);\n        // Reset explored tiles\n        this.explored = new HashSet<Point>();\n        runButton.setText(\"Pause\");\n        state = State.STARTED;\n    }\n\n    private void stop() {\n        runButton.setText(\"Start\");\n        state = State.STOPPED;\n    }\n\n    private void pause() {\n        runButton.setText(\"Resume\");\n        state = State.PAUSED;\n    }\n\n    private synchronized void updateVisualizer(final Node<?, Point, ?> node, Maze2D maze, Collection<Point> explored) {\n        if (node != null && maze != null) {\n            List<Point> statePath = Lists.transform(node.path(), new Function<Node<?, Point, ?>, Point>() {\n                @Override\n                public Point apply(Node<?, Point, ?> pointNode) {\n                    return pointNode.state();\n                }\n            });\n\n            String mazeStr = getMazeStringSolution(maze, explored, statePath);\n            mazeTextArea.setText(mazeStr);\n            // Update the status bar\n            SwingUtilities.invokeLater(new Runnable() {\n                @Override\n                public void run() {\n                    labelSteps.setText(Integer.toString(steps));\n                    if (node instanceof CostNode) {\n                        CostNode n = (CostNode) node;\n                        labelCost.setText(new DecimalFormat(\"#.00\").format(n.getCost()));\n                    }\n                }\n            });\n        }\n    }\n\n\n    private class ExecutionHandler implements ActionListener, Runnable {\n\n        private ExecutionHandler() {\n        }\n\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            if (realtimePrintingCheckBox.isSelected() && state.equals(State.STARTED)) {\n                executeSearchStep();\n            }\n        }\n\n        @Override\n        public void run() {\n            while (!Thread.currentThread().isInterrupted()) {\n                try {\n                    if (!realtimePrintingCheckBox.isSelected() && state.equals(State.STARTED)) {\n                        executeSearchStep();\n                    } else {\n                        Thread.sleep(100);\n                        Thread.yield();\n                    }\n                } catch (InterruptedException ex) {\n                    Thread.currentThread().interrupt();\n                }\n            }\n        }\n    }\n\n    private Iterator<? extends Node<?, Point, ?>> createAlgorithm(Maze2D maze) {\n        final Iterator<? extends Node<?, Point, ?>> iterator;\n        switch (comboAlgorithm.getSelectedIndex()) {\n\n            case 0:\n                iterator = Hipster.createDepthFirstSearch(buildProblem(maze, false)).iterator();\n                break;\n            case 1:\n                iterator = Hipster.createBreadthFirstSearch(buildProblem(maze, false)).iterator();\n                break;\n            case 2:\n                iterator = Hipster.createBellmanFord(buildProblem(maze, false)).iterator();\n                break;\n            case 3:\n                iterator = Hipster.createDijkstra(buildProblem(maze, false)).iterator();\n                break;\n            case 4:\n                iterator = Hipster.createAStar(buildProblem(maze, true)).iterator();\n                break;\n            case 5:\n                iterator = Hipster.createIDAStar(buildProblem(maze, true)).iterator();\n                break;\n            default:\n                throw new IllegalStateException(\"Invalid algorithm\");\n        }\n        return iterator;\n    }\n\n    private void loadSelectedMaze() {\n        switch (comboMazes.getSelectedIndex()) {\n            case 0:\n                mazeTextArea.setText(Joiner.on('\\n').join(Mazes.exampleMaze1));\n                break;\n            case 1:\n                mazeTextArea.setText(Joiner.on('\\n').join(Mazes.testMaze4));\n                break;\n            case 2:\n                mazeTextArea.setText(Joiner.on('\\n').join(Mazes.testMaze3));\n                break;\n            case 3:\n                mazeTextArea.setText(Joiner.on('\\n').join(Mazes.testMaze2));\n                break;\n            case 4:\n                mazeTextArea.setText(Joiner.on('\\n').join(Mazes.testMaze5));\n                break;\n        }\n    }\n\n    private String getMazeStringSolution(Maze2D maze, Collection<Point> explored, Collection<Point> path) {\n        List<Map<Point, Character>> replacements = new ArrayList<Map<Point, Character>>();\n        Map<Point, Character> replacement = new HashMap<Point, Character>();\n        for (Point p : explored) {\n            replacement.put(p, '.');\n        }\n        replacements.add(replacement);\n        replacement = new HashMap<Point, Character>();\n        for (Point p : path) {\n            replacement.put(p, '*');\n        }\n        replacements.add(replacement);\n        return maze.getReplacedMazeString(replacements);\n    }\n\n    private SearchProblem<Void, Point, WeightedNode<Void, Point, Double>> buildProblem(final Maze2D maze, final boolean heuristic) {\n        return ProblemBuilder.create()\n                .initialState(maze.getInitialLoc())\n                .defineProblemWithoutActions()\n                .useTransitionFunction(new StateTransitionFunction<Point>() {\n                    @Override\n                    public Iterable<Point> successorsOf(Point state) {\n                        return maze.validLocationsFrom(state);\n                    }\n                })\n                .useCostFunction(new CostFunction<Void, Point, Double>() {\n                    @Override\n                    public Double evaluate(Transition<Void, Point> transition) {\n                        Point source = transition.getFromState();\n                        Point destination = transition.getState();\n                        double distance = source.distance(destination);\n                        double roundedDistance = (double) Math.round(distance * 1e5) / 1e5;\n                        return roundedDistance;\n                    }\n                })\n                .useHeuristicFunction(new HeuristicFunction<Point, Double>() {\n                    @Override\n                    public Double estimate(Point state) {\n                        if (heuristic) {\n                            double distance = state.distance(maze.getGoalLoc());\n                            double roundedDistance = (double) Math.round(distance * 1e5) / 1e5;\n                            return roundedDistance;\n                        }\n                        return 0d;\n                    }\n                })\n                .build();\n    }\n}\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/BlueprintsGraphMultiobjectiveSearch.java",
    "content": "package es.usc.citius.hipster.examples;\n\nimport com.tinkerpop.blueprints.Direction;\nimport com.tinkerpop.blueprints.Edge;\nimport com.tinkerpop.blueprints.Graph;\nimport com.tinkerpop.blueprints.Vertex;\nimport com.tinkerpop.blueprints.impls.tg.TinkerGraph;\nimport com.tinkerpop.blueprints.util.io.graphml.GraphMLReader;\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.ActionFunction;\nimport es.usc.citius.hipster.model.function.ActionStateTransitionFunction;\nimport es.usc.citius.hipster.model.function.BinaryFunction;\nimport es.usc.citius.hipster.model.function.CostFunction;\nimport es.usc.citius.hipster.model.function.impl.BinaryOperation;\nimport es.usc.citius.hipster.model.problem.ProblemBuilder;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\n\nimport java.io.IOException;\nimport java.net.URL;\n\n/**\n * <p>Simple example that loads a GraphML example graph from GitHub, loads it with the\n * Blueprints API and then solves the multiobjective problem with Hipster</p>\n *\n * A full description of the problem is published on\n * <a href=\"https://github.com/citiususc/hipster/wiki/Multiobjective-Search-with-Hipster-and-TinkerPop-Blueprints\">Hipster's wiki</a>.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class BlueprintsGraphMultiobjectiveSearch {\n\n    public static void main(String[] args) throws IOException {\n\n        Graph g = new TinkerGraph();\n        GraphMLReader.inputGraph(g, new URL(\"https://gist.githubusercontent.com/pablormier/5d52543b4dcae297ab14/raw/multiobjective-graph.graphml\").openStream());\n\n        // Since we use a special cost, we need to define a BinaryOperation<Cost>\n        // that provides the required elements to work with our special cost type.\n        // These elements are: a BinaryFunction<Cost> that defines how to compute\n        // a new cost from two costs: C x C -> C, the identity element I of our\n        // cost (C + I = C, I + C = C), and the maximum value.\n\n        // Cost a + Cost b is defined as a new cost a.c1+b.c1, a.c2+b.c2\n        BinaryFunction<Cost> f = new BinaryFunction<Cost>() {\n            @Override\n            public Cost apply(Cost a, Cost b) {\n                Cost c = new Cost(a.c1 + b.c1, a.c2 + b.c2);\n                return c;\n            }\n        };\n\n        // The identity cost identity satisfy:\n        // f.apply(c, identity).equals(c)\n        // f.apply(identity, c).equals(c)\n        Cost identity = new Cost(0d, 0d);\n\n        // Maximum value of our costs\n        Cost max = new Cost(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n\n        // Create our custom binary operation:\n        BinaryOperation<Cost> bf = new BinaryOperation<Cost>(f, identity, max);\n\n\n        // Define a problem\n        SearchProblem p = ProblemBuilder.create()\n                .initialState(g.getVertex(\"v1\"))\n                .defineProblemWithExplicitActions()\n                .useActionFunction(new ActionFunction<Edge, Vertex>() {\n                    @Override\n                    public Iterable<Edge> actionsFor(Vertex state) {\n                        return state.getEdges(Direction.OUT);\n                    }\n                }).useTransitionFunction(new ActionStateTransitionFunction<Edge, Vertex>() {\n                    @Override\n                    public Vertex apply(Edge action, Vertex state) {\n                        return action.getVertex(Direction.IN);\n                    }\n                }).useGenericCostFunction(new CostFunction<Edge, Vertex, Cost>() {\n                    @Override\n                    public Cost evaluate(Transition<Edge, Vertex> transition) {\n                        Double cost1 = Double.valueOf(transition.getAction().getProperty(\"c1\").toString());\n                        Double cost2 = Double.valueOf(transition.getAction().getProperty(\"c2\").toString());\n                        return new Cost(cost1, cost2);\n                    }\n                }, bf).build();\n\n        System.out.println(Hipster.createMultiobjectiveLS(p).search(g.getVertex(\"v6\")));\n\n\n    }\n\n    /**\n     * Build an example graph to execute in this example.\n     *\n     * @return example graph\n     */\n    private static Graph buildGraph() {\n        Graph g = new TinkerGraph();\n        //add vertices\n        Vertex v1 = g.addVertex(\"v1\");\n        Vertex v2 = g.addVertex(\"v2\");\n        Vertex v3 = g.addVertex(\"v3\");\n        Vertex v4 = g.addVertex(\"v4\");\n        Vertex v5 = g.addVertex(\"v5\");\n        Vertex v6 = g.addVertex(\"v6\");\n\n        //add edges labeled with costs\n        Edge e1 = g.addEdge(\"e1\", v1, v2, \"(7, 1)\");\n        e1.setProperty(\"c1\", 7);\n        e1.setProperty(\"c2\", 1);\n\n        Edge e2 = g.addEdge(\"e2\", v1, v3, \"(1, 4)\");\n        e2.setProperty(\"c1\", 1);\n        e2.setProperty(\"c2\", 4);\n\n        Edge e3 = g.addEdge(\"e3\", v1, v4, \"(2, 1)\");\n        e3.setProperty(\"c1\", 2);\n        e3.setProperty(\"c2\", 1);\n\n        Edge e4 = g.addEdge(\"e4\", v2, v4, \"(1, 1)\");\n        e4.setProperty(\"c1\", 1);\n        e4.setProperty(\"c2\", 1);\n\n        Edge e5 = g.addEdge(\"e5\", v2, v6, \"(2, 1)\");\n        e5.setProperty(\"c1\", 2);\n        e5.setProperty(\"c2\", 1);\n\n        Edge e6 = g.addEdge(\"e6\", v3, v4, \"(1, 1)\");\n        e6.setProperty(\"c1\", 1);\n        e6.setProperty(\"c2\", 1);\n\n        Edge e7 = g.addEdge(\"e7\", v4, v5, \"(3, 2)\");\n        e7.setProperty(\"c1\", 3);\n        e7.setProperty(\"c2\", 2);\n\n        Edge e8 = g.addEdge(\"e8\", v4, v6, \"(4, 8)\");\n        e8.setProperty(\"c1\", 4);\n        e8.setProperty(\"c2\", 8);\n\n        Edge e9 = g.addEdge(\"e9\", v5, v6, \"(1, 1)\");\n        e9.setProperty(\"c1\", 1);\n        e9.setProperty(\"c2\", 1);\n\n        return g;\n    }\n\n    /**\n     * Inner class to define a multi-objective cost.\n     */\n    static class Cost implements Comparable<Cost> {\n        private double c1;\n        private double c2;\n\n        /**\n         * Creation of multi-objective cost from two double values.\n         *\n         * @param c1 first element of the cost\n         * @param c2 second element of the cost\n         */\n        public Cost(double c1, double c2) {\n            this.c1 = c1;\n            this.c2 = c2;\n        }\n\n        @Override\n        public String toString() {\n            return \"Cost{\" +\n                    \"c1=\" + c1 +\n                    \", c2=\" + c2 +\n                    '}';\n        }\n\n        /**\n         * A cost is lower/higher than other if both components\n         * are (dominated cost). Returns 0 in the rest of the cases\n         * (non-dominated).\n         *\n         * @param o other cost element\n         * @return comparison result: -1/1 (dominated) or 0 (non-dominated)\n         */\n        @Override\n        public int compareTo(Cost o) {\n\n            if (c1 <= o.c1 && c2 <= o.c2){\n                if (c1 < o.c1 || c2 < o.c2){\n                    return -1;\n                }\n            } else if (o.c1 <= c1 && o.c2 <= o.c2){\n                if (o.c1 < c1 || o.c2 < c2){\n                    return 1;\n                }\n            }\n\n            // Non-dominated\n            return 0;\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            if (this == o) return true;\n            if (o == null || getClass() != o.getClass()) return false;\n\n            Cost cost = (Cost) o;\n\n            if (Double.compare(cost.c1, c1) != 0) return false;\n            if (Double.compare(cost.c2, c2) != 0) return false;\n\n            return true;\n        }\n\n        @Override\n        public int hashCode() {\n            int result;\n            long temp;\n            temp = Double.doubleToLongBits(c1);\n            result = (int) (temp ^ (temp >>> 32));\n            temp = Double.doubleToLongBits(c2);\n            result = 31 * result + (int) (temp ^ (temp >>> 32));\n            return result;\n        }\n    }\n}\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/DirectedGraphSearchExample.java",
    "content": "package es.usc.citius.hipster.examples;\n\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphBuilder;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.graph.HipsterDirectedGraph;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\n\n/**\n * Example that creates a {@link es.usc.citius.hipster.graph.HipsterDirectedGraph},\n * creates a search problem to be used with Hipster search iterators and performs\n * a search using the Dijkstra algorithm.\n *\n * The starting node is set in the creation of a {@link es.usc.citius.hipster.model.problem.SearchProblem},\n * which also specifies the source of the search (a graph in this case) and the cost function (costs taken\n * from the edges of the graph). The goal node is specified after creating the problem, in the\n * search method. As it is not required to create the search iterator.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class DirectedGraphSearchExample {\n\n    public static void main(String[] args){\n        // Create a simple weighted directed graph with Hipster where\n        // vertices are Strings and edge values are just doubles\n        HipsterDirectedGraph<String,Double> graph =\n                GraphBuilder.<String,Double>create()\n                .connect(\"A\").to(\"B\").withEdge(4d)\n                .connect(\"A\").to(\"C\").withEdge(2d)\n                .connect(\"B\").to(\"C\").withEdge(5d)\n                .connect(\"B\").to(\"D\").withEdge(10d)\n                .connect(\"C\").to(\"E\").withEdge(3d)\n                .connect(\"D\").to(\"F\").withEdge(11d)\n                .connect(\"E\").to(\"D\").withEdge(4d)\n                .createDirectedGraph();\n\n\n        // Create the search problem. For graph problems, just use\n        // the GraphSearchProblem util class to generate the problem with ease.\n        //If you want to use the costs of the edges as cost function of the problem,\n        //use {@link GraphSearchProblem#takeCostsFromEdges} as in this example. If your\n        //graph does not specify edge cost or you want avoid using them on the search,\n        //use {@link GraphSearchProblem#useGenericCosts} and a unitary cost will be assigned\n        //to each arc.\n        SearchProblem p = GraphSearchProblem\n                .startingFrom(\"A\")\n                .in(graph)\n                .takeCostsFromEdges()\n                .build();\n\n        // Search the shortest path from \"A\" to \"F\". The search will stop when the goal state\n        //is reached.\n        System.out.println(Hipster.createDijkstra(p).search(\"F\"));\n    }\n}\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/EightPuzzleProblemExample.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.examples;\n\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.ActionFunction;\nimport es.usc.citius.hipster.model.function.ActionStateTransitionFunction;\nimport es.usc.citius.hipster.model.function.CostFunction;\nimport es.usc.citius.hipster.model.function.HeuristicFunction;\nimport es.usc.citius.hipster.model.impl.WeightedNode;\nimport es.usc.citius.hipster.model.problem.ProblemBuilder;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\n\nimport java.awt.*;\nimport java.util.LinkedList;\n\nimport static es.usc.citius.hipster.examples.problem.NPuzzle.Puzzle;\nimport static es.usc.citius.hipster.examples.problem.NPuzzle.PuzzleMove;\n\n\n/**\n * Example of the N-Puzzle (3x3 tiles) search problem solved with the A* algorithm.\n *\n * This example defines first the initial and goal states, and a\n * {@link es.usc.citius.hipster.model.function.ActionFunction} which decides in each\n * state which actions can be applied to reach another state.\n *\n * The {@link es.usc.citius.hipster.model.function.ActionStateTransitionFunction} takes\n * as input an initial state and an action, generating the {@link es.usc.citius.hipster.model.Transition}\n * between them.\n *\n * The {@link es.usc.citius.hipster.model.function.CostFunction} returns always a unitary\n * cost, so A* will minimize the number of actions applied. As\n * {@link es.usc.citius.hipster.model.function.HeuristicFunction} the Manhattan distance between states\n * is used.\n *\n * @see {@link es.usc.citius.hipster.examples.problem.NPuzzle}\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class EightPuzzleProblemExample {\n\n    public static void main(String[] args){\n\n        final Puzzle initialState = new Puzzle(new int[]{0,8,7,6,5,4,3,2,1});\n        final Puzzle goalState = new Puzzle(new int[]{0,1,2,3,4,5,6,7,8});\n        //final int[][] goal = goalState.getMatrixBoard();\n\n        //Definition of the action function. Taking as input an state, determine the\n        //actions which can be applied to reach other state.\n        ActionFunction<PuzzleMove, Puzzle> af = new ActionFunction<PuzzleMove, Puzzle>() {\n            @Override\n            public Iterable<PuzzleMove> actionsFor(Puzzle state) {\n                LinkedList<PuzzleMove> movements = new LinkedList<PuzzleMove>();\n                // Get which place the gap tile is in\n                Point gap = state.getTile(0);\n                // side size of the board\n                int boardSize = state.getMatrixBoard().length;\n\n                // Check valid movements. There are always maximum\n                // 4 tiles around the gap (left, right, top, down)\n                if (gap.getX() > 0 && gap.getX() < boardSize){\n                    movements.add(PuzzleMove.UP);\n                }\n                if (gap.getX() >= 0 && gap.getX() < boardSize-1){\n                    movements.add(PuzzleMove.DOWN);\n                }\n                if (gap.getY() >= 0 && gap.getY() < boardSize-1){\n                    movements.add(PuzzleMove.RIGHT);\n                }\n                if (gap.getY() > 0 && gap.getY() < boardSize){\n                    movements.add(PuzzleMove.LEFT);\n                }\n                return movements;\n            }\n        };\n\n        //Definition of the transition function (taking as input the current state and\n        //current action). It generates following state after applying the action.\n        ActionStateTransitionFunction<PuzzleMove, Puzzle> atf = new ActionStateTransitionFunction<PuzzleMove, Puzzle>() {\n            @Override\n            public Puzzle apply(PuzzleMove action, Puzzle state) {\n                // Generate the next board\n                Point gap = state.getTile(0);\n                int[][] board = state.copyBoard();\n                //System.out.println(\"Applying \" + action + \" to \" + state + \" gap: \" + gap.toString());\n                // x=row, y=column\n                switch (action){\n                    case UP:\n                        board[gap.x][gap.y]=state.getMatrixBoard()[gap.x-1][gap.y];\n                        board[gap.x-1][gap.y]=0;\n                        break;\n                    case DOWN:\n                        board[gap.x][gap.y]=state.getMatrixBoard()[gap.x+1][gap.y];\n                        board[gap.x+1][gap.y]=0;\n                        break;\n                    case LEFT:\n                        board[gap.x][gap.y]=state.getMatrixBoard()[gap.x][gap.y-1];\n                        board[gap.x][gap.y-1]=0;\n                        break;\n                    case RIGHT:\n                        board[gap.x][gap.y]=state.getMatrixBoard()[gap.x][gap.y+1];\n                        board[gap.x][gap.y+1]=0;\n                        break;\n                }\n                Puzzle successor = new Puzzle(board);\n                return successor;\n            }\n        };\n\n        //definition of an unitary cost function\n        CostFunction<PuzzleMove, Puzzle, Double> cf = new CostFunction<PuzzleMove, Puzzle, Double>() {\n            @Override\n            public Double evaluate(Transition<PuzzleMove, Puzzle> transition) {\n                return 1d;\n            }\n        };\n\n        //definition of an heuristic, the Manhattan distance between states\n        HeuristicFunction<Puzzle, Double> hf = new HeuristicFunction<Puzzle, Double>() {\n            @Override\n            public Double estimate(Puzzle state) {\n                // Compute the manhattan distance\n                int mdistance = 0;\n                int[][] board = state.getMatrixBoard();\n                int size = board.length;\n                for (int x = 0; x < size; x++)\n                    for (int y = 0; y < size; y++) {\n                        int value = board[x][y];\n                        Point goalTile = goalState.getTile(value);\n                        // Compute diff\n                        if (value != 0) {\n                            int dx = x - goalTile.x;\n                            int dy = y - goalTile.y;\n                            mdistance += Math.abs(dx) + Math.abs(dy);\n                        }\n                    }\n                return (double)mdistance;\n            }\n        };\n\n        //here the search problem is instantiated defining all the components\n        //to be used in the search: the initial state,\n        //the action and transition function and the cost and heuristic\n        //functions to be used in the evaluation.\n        SearchProblem<PuzzleMove, Puzzle, WeightedNode<PuzzleMove, Puzzle, Double>> p =\n            ProblemBuilder.create()\n                .initialState(initialState)\n                .defineProblemWithExplicitActions()\n                    .useActionFunction(af)\n                    .useTransitionFunction(atf)\n                    .useCostFunction(cf)\n                    .useHeuristicFunction(hf)\n                    .build();\n\n\n        //Here we create the search iterator, A* in this case, and\n        //we launch the search process until the goal state is reached.\n        //More algorithms are available in the Hipster class to be used with\n        //any search problem.\n        //There are many ways to use a search iterator, but this is the\n        //simplest one.\n        System.out.println(Hipster.createAStar(p).search(goalState));\n\n    }\n}\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/EightQueensProblemExample.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.examples;\n\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.algorithm.localsearch.HillClimbing;\nimport es.usc.citius.hipster.examples.problem.NQueens;\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.CostFunction;\nimport es.usc.citius.hipster.model.function.HeuristicFunction;\nimport es.usc.citius.hipster.model.function.impl.StateTransitionFunction;\nimport es.usc.citius.hipster.model.impl.WeightedNode;\nimport es.usc.citius.hipster.model.problem.ProblemBuilder;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\nimport es.usc.citius.hipster.util.Predicate;\n\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Set;\n\n/**\n * Example using the N-Queens problem (size 8x8) solved using the Hill Climbing\n * and Enforced Hill Climbing algorithms.\n *\n * This example is a search problem with no explicit actions, only using a\n * transition function which generates from a state a set of\n * successor states. The cost function in this case is constant, and\n * we assume it has no cost to move a queen. As heuristic for this problem\n * we use the number of attacked queens. These components are defined\n * as the same time the problem is being built (using a\n * {@link es.usc.citius.hipster.model.problem.ProblemBuilder}.\n *\n * Once the problem is defined, in this example the Hill Climbing iterator\n * is created, and the usage of the iterator is shown: we keep expanding\n * new nodes (using {@link java.util.Iterator#next()}) until a solution is\n * found, considering a solution as a state where no queens are attacked.\n * This is a problem where we do not know the goal states a-priori. In\n * situations like this we might need more control on the search\n * process and stop it according of our needs, as we show in the\n * search loop.\n *\n * @see {@link es.usc.citius.hipster.examples.problem.NQueens}\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class EightQueensProblemExample {\n\n    public static void main(String[] args) {\n        // Solve the 8-Queen problem with Hill Climbing and Enforced Hill Climbing\n        final int size = 8;\n        //search problem definition, here we define also\n        //the transition function between states\n        //and the cost (always 0)\n        //and heuristic function (number of attacked queens)\n        SearchProblem<Void,NQueens,WeightedNode<Void,NQueens,Double>> p = ProblemBuilder.create()\n                .initialState(new NQueens(size))\n                //problem without explicit actions, only a transition function is needed\n                .defineProblemWithoutActions()\n                .useTransitionFunction(new StateTransitionFunction<NQueens>() {\n                    @Override\n                    public Iterable<NQueens> successorsOf(NQueens state) {\n                        // Generate all possible movements of one queen\n                        // There are size*(size-1) available movements\n                        Set<NQueens> states = new HashSet<NQueens>();\n                        for (int i = 0; i < size; i++) {\n                            for (int j = 0; j < size; j++) {\n                                // Change the queen at row i to column j\n                                // If i is already in j, then do not add the state\n                                if (state.getQueens()[i] != j) {\n                                    int[] queens = Arrays.copyOf(state.getQueens(), size);\n                                    queens[i] = j;\n                                    states.add(new NQueens(queens));\n                                }\n                            }\n                        }\n                        return states;\n                    }\n                })\n                .useCostFunction(new CostFunction<Void, NQueens, Double>() {\n                    @Override\n                    public Double evaluate(Transition<Void, NQueens> transition) {\n                        // We assume that the cost of moving a queen is 0\n                        return 0d;\n                    }\n                })\n                .useHeuristicFunction(new HeuristicFunction<NQueens, Double>() {\n                    @Override\n                    public Double estimate(NQueens state) {\n                        return (double) state.attackedQueens();\n                    }\n                }).build();\n\n        //print some information about the search that will be executed\n        System.out.println(\"Random initial state (\" + p.getInitialNode().state().attackedQueens() + \" attacked queens):\");\n        System.out.println(p.getInitialNode().state());\n\n        System.out.println(\"Running 8-Queens problem with Enforced Hill Climbing and a custom goal test predicate\");\n        //To execute the algorithm we have two options:\n        // Option 1 - Run the algorithm until the predicate is satisfied (until we find a state with score 0, that is, no attacked queens)\n        System.out.println(Hipster.createHillClimbing(p, true).search(new Predicate<WeightedNode<Void,NQueens,Double>>() {\n            @Override\n            public boolean apply(WeightedNode<Void, NQueens, Double> node) {\n                return node.getScore().equals(0d);\n            }\n        }));\n\n\n        System.out.println(\"Running 8-Queens problem with Enforced Hill Climbing using fine-grained iteration capabilities\");\n        // Option 2 - Manual execution. Expand nodes until we find a state that meets the requirements (no attacked queens)\n        HillClimbing<Void, NQueens, Double, WeightedNode<Void, NQueens, Double>>.EHCIterator it =\n                Hipster.createHillClimbing(p, true).iterator();\n        int iteration = 0;\n        Double best = it.getBestScore();\n        while (it.hasNext()) {\n            iteration++;\n            WeightedNode<Void, NQueens, Double> node = it.next();\n            //System.out.println(node);\n            if (node.getScore().compareTo(best) < 0) {\n                best = node.getScore();\n                System.out.println(\"New local minimum found with value \" + best + \" at iteration \" + iteration);\n            }\n            int attacked = node.state().attackedQueens();\n            //same stop condition than in the Option 1\n            if (attacked == 0) {\n                System.out.println(\"Solution found: \");\n                System.out.println(node);\n                break;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/EightQueensProblemExampleWithAnnealingSearch.java",
    "content": "/*\r\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\r\n *\r\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *    you may not use this file except in compliance with the License.\r\n *    You may obtain a copy of the License at\r\n *\r\n *        http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n *    Unless required by applicable law or agreed to in writing, software\r\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *    See the License for the specific language governing permissions and\r\n *    limitations under the License.\r\n */\r\n\r\npackage es.usc.citius.hipster.examples;\r\n\r\nimport java.util.Arrays;\r\nimport java.util.HashSet;\r\nimport java.util.Set;\r\n\r\nimport es.usc.citius.hipster.algorithm.Hipster;\r\nimport es.usc.citius.hipster.examples.problem.NQueens;\r\nimport es.usc.citius.hipster.model.Transition;\r\nimport es.usc.citius.hipster.model.function.CostFunction;\r\nimport es.usc.citius.hipster.model.function.HeuristicFunction;\r\nimport es.usc.citius.hipster.model.function.impl.StateTransitionFunction;\r\nimport es.usc.citius.hipster.model.impl.WeightedNode;\r\nimport es.usc.citius.hipster.model.problem.ProblemBuilder;\r\nimport es.usc.citius.hipster.model.problem.SearchProblem;\r\nimport es.usc.citius.hipster.util.Predicate;\r\n\r\n/**\r\n * Example using the N-Queens problem (size 8x8) solved using the Annealing search.\r\n *\r\n * This example is a search problem with no explicit actions, only using a\r\n * transition function which generates from a state a set of\r\n * successor states. The cost function in this case is constant, and\r\n * we assume it has no cost to move a queen. As heuristic for this problem\r\n * we use the number of attacked queens. These components are defined\r\n * as the same time the problem is being built (using a\r\n * {@link es.usc.citius.hipster.model.problem.ProblemBuilder}.\r\n *\r\n *\r\n * @see {@link es.usc.citius.hipster.examples.problem.NQueens}\r\n *\r\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\r\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\r\n */\r\npublic class EightQueensProblemExampleWithAnnealingSearch {\r\n\r\n    public static void main(String[] args) {\r\n        // Solve the 8-Queen problem with Hill Climbing and Enforced Hill Climbing\r\n        final int size = 8;\r\n        //search problem definition, here we define also\r\n        //the transition function between states\r\n        //and the cost (always 0)\r\n        //and heuristic function (number of attacked queens)\r\n        SearchProblem<Void,NQueens,WeightedNode<Void,NQueens,Double>> p = ProblemBuilder.create()\r\n                .initialState(new NQueens(size))\r\n                //problem without explicit actions, only a transition function is needed\r\n                .defineProblemWithoutActions()\r\n                .useTransitionFunction(new StateTransitionFunction<NQueens>() {\r\n                    @Override\r\n                    public Iterable<NQueens> successorsOf(NQueens state) {\r\n                        // Generate all possible movements of one queen\r\n                        // There are size*(size-1) available movements\r\n                        Set<NQueens> states = new HashSet<NQueens>();\r\n                        for (int i = 0; i < size; i++) {\r\n                            for (int j = 0; j < size; j++) {\r\n                                // Change the queen at row i to column j\r\n                                // If i is already in j, then do not add the state\r\n                                if (state.getQueens()[i] != j) {\r\n                                    int[] queens = Arrays.copyOf(state.getQueens(), size);\r\n                                    queens[i] = j;\r\n                                    states.add(new NQueens(queens));\r\n                                }\r\n                            }\r\n                        }\r\n                        return states;\r\n                    }\r\n                })\r\n                .useCostFunction(new CostFunction<Void, NQueens, Double>() {\r\n                    @Override\r\n                    public Double evaluate(Transition<Void, NQueens> transition) {\r\n                        // We assume that the cost of moving a queen is 0\r\n                        return 0d;\r\n                    }\r\n                })\r\n                .useHeuristicFunction(new HeuristicFunction<NQueens, Double>() {\r\n                    @Override\r\n                    public Double estimate(NQueens state) {\r\n                        return (double) state.attackedQueens();\r\n                    }\r\n                }).build();\r\n\r\n        //print some information about the search that will be executed\r\n        System.out.println(\"Random initial state (\" + p.getInitialNode().state().attackedQueens() + \" attacked queens):\");\r\n        System.out.println(p.getInitialNode().state());\r\n\r\n        System.out.println(\"Running 8-Queens problem with Annealing search and a custom goal test predicate\");\r\n        //To execute the algorithm we have two options:\r\n        // Option 1 - Run the algorithm until the predicate is satisfied (until we find a state with score 0, that is, no attacked queens)\r\n        System.out.println(Hipster.createAnnealingSearch(p, null,null,null,null).search(new Predicate<WeightedNode<Void,NQueens,Double>>() {\r\n            @Override\r\n            public boolean apply(WeightedNode<Void, NQueens, Double> node) {\r\n                return node.getScore().equals(0d);\r\n            }\r\n        }));       \r\n    }\r\n}\r\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/MazeShortestPathExample.java",
    "content": "/*\n* Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n*\n*    Licensed under the Apache License, Version 2.0 (the \"License\");\n*    you may not use this file except in compliance with the License.\n*    You may obtain a copy of the License at\n*\n*        http://www.apache.org/licenses/LICENSE-2.0\n*\n*    Unless required by applicable law or agreed to in writing, software\n*    distributed under the License is distributed on an \"AS IS\" BASIS,\n*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n*    See the License for the specific language governing permissions and\n*    limitations under the License.\n*/\n\npackage es.usc.citius.hipster.examples;\n\n\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.CostFunction;\nimport es.usc.citius.hipster.model.function.HeuristicFunction;\nimport es.usc.citius.hipster.model.function.impl.StateTransitionFunction;\nimport es.usc.citius.hipster.model.problem.ProblemBuilder;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\nimport es.usc.citius.hipster.util.examples.maze.Maze2D;\nimport es.usc.citius.hipster.util.examples.maze.Mazes;\n\nimport java.awt.*;\n\n/**\n * Example using a bidimensional maze, solved using the A* algorithm.\n * <p>\n * This example consists in a search problem in a {@link Maze2D}. This problem is characterized by:\n * <ul>\n *      <li>The problem is defined without explicit actions</li>\n *      <li>It uses a transition function implemented in the class {@link Maze2D}, which returns the accessible states from the current.</li>\n *      <li>The cost functions is the Euclidean distance between points.</li>\n *      <li>Heuristic function is also Euclidean Distance.</li>\n * </ul>\n * This example illustrates how to instantiate a {@link SearchProblem} and each one of the components\n * required for search, explaining what they do.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class MazeShortestPathExample {\n\n    public static void main(String[] args) throws InterruptedException {\n        /*\n            First, create a maze. There is a class called Maze2D\n            that allows the creation of labyrinths using ascii.\n\n            For this example, we use the MAZE5 example defined in\n            class Mazes.\n         */\n        Mazes.TestMaze example = Mazes.TestMaze.MAZE1;\n\n        System.out.println(\"Maze example:\");\n        System.out.println(example.getMaze());\n\n        /*\n            Now create the search problem. We have to define\n            how to move from one tile to another tile, what's the\n            cost of each movement (top/down/left/right and diagonal movements)\n            the heuristic to estimate the distance to the goal (optional, and\n            not used in this example).\n\n            There is a good A* tutorial that explains some important concepts\n            here http://www.policyalmanac.org/games/aStarTutorial.htm\n        */\n        final Maze2D maze = example.getMaze();\n\n        /*\n            In order to search, we need at least the origin and the goal destination.\n            For this example, this information is stored in the Maze, so we use\n            it as follows:\n        */\n        final Point origin = maze.getInitialLoc();\n        final Point goal = maze.getGoalLoc();\n\n        /*\n            SearchProblem is the structure used by Hipster to store all the\n            information about the search query, like: start, goals, transition function,\n            cost function, etc. Once created it is used to instantiate the search\n            iterators which provide the results.\n         */\n        SearchProblem p = ProblemBuilder.create()\n                /*\n                    Initial state of the search.\n                 */\n                .initialState(origin)\n\n                /*\n                    Search problems can be defined with or without actions. In this example\n                     a problem without actions is defined, as we do not require this information\n                     in the results, although it is interesting to use actions when the solution\n                     is highly more informative with them, like in the 8-puzzle or the N-queens\n                     problems.\n                 */\n                .defineProblemWithoutActions()\n\n                /*\n                    The transition\n                    function tells the algorithm which are the available motions from\n                    a concrete tile point.\n\n                    The transition function returns a collection of transitions.\n                    A transition is defined by a class Transition which has two attributes:\n                    source point (from) and destination point (to). The source point\n                    is the current state that we are exploring, and the destination point\n                    is a reachable location from that state.\n                */\n                .useTransitionFunction(new StateTransitionFunction<Point>() {\n                    @Override\n                    public Iterable<Point> successorsOf(Point state) {\n                        /*\n                            The maze is a 2D map, where each tile defined by 2D coordinates x and y\n                            can be empty or occupied by an obstacle.\n\n                            We have to compute which are the\n                            available movements (destination points) from the current point.\n                            Class Maze has a helper method that tell us the empty points\n                            (where we can move) available:\n                        */\n                        return maze.validLocationsFrom(state);\n                    }\n                })\n\n                /*\n                    The cost function defines the effort moving between states.\n                    The CostFunction is an interface with three generic types: S - the state,\n                    A - the action type and T - the cost type.\n                    In this example we use Point instances as states, Double values for the cost and the\n                    actions are not defined (so we use Void for them).\n                 */\n                .useCostFunction(new CostFunction<Void, Point, Double>() {\n\n                    @Override\n                    public Double evaluate(Transition<Void, Point> transition) {\n                        /*\n                            We use the Euclidean Distance (http://en.wikipedia.org/wiki/Euclidean_distance)\n                            to define the cost between Points. This allows to represent properly the difference\n                            of cost between straight motions (up/down/left/right) and diagonal\n                            motions (which cost is higher, as it is the distance between those points). You can\n                            read more about this policy in http://www.policyalmanac.org/games/aStarTutorial.htm.\n                         */\n                        Point source = transition.getFromState();\n                        Point destination = transition.getState();\n                        return source.distance(destination);\n                    }\n                })\n\n                /*\n                    The heuristic function estimates the cost between each state and the goal\n                    in order to guide the search more directly to the goal.\n                    The HeuristicFunction is an interface with two generic types: S - the state type, and\n                    T - the cost type.\n                    In this example the state type is Point and the cost type is Double.\n                    This method is optional, If you do not specify a heuristic, A* will behave as the\n                    Dijkstra's algorithm (https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm).\n                 */\n                .useHeuristicFunction(new HeuristicFunction<Point, Double>() {\n                    @Override\n                    public Double estimate(Point state) {\n                        /*\n                            It is very common to use Euclidean Distance as heuristic for maze problems.\n                            This estimator fulfills the optimistic (never overestimates the real cost between\n                            a state and the goal) and consistency (the closer is a state to the goal, the lower is\n                            the estimated cost) which define a good heuristic\n                            (https://en.wikipedia.org/wiki/Heuristic_(computer_science)).\n                         */\n                        return state.distance(goal);\n                    }                    \n                })\n\n                /*\n                    With this method the SearchProblem is instantiated using the data introduced with the methods\n                    above.\n                 */\n                .build();\n\n        /*\n            Alternatively, if you want to print the results as the search algorithm executes the\n            search, you can use the following statement:\n         */\n        //MazeSearch.printSearch(Hipster.createAStar(p).iterator(), maze);\n\n        /**\n         * Search is executed with until \"goal\" is explored.\n         */\n        System.out.println(Hipster.createAStar(p).search(goal));\n    }\n}\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/RomanianProblemDFSExample.java",
    "content": "package es.usc.citius.hipster.examples;\n\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\nimport es.usc.citius.hipster.util.examples.RomanianProblem;\n\n/**\n * Example of graph search using the Romania problem described\n * <a href =http://www.pearsonhighered.com/assets/hip/us/hip_us_pearsonhighered/samplechapter/0136042597.pdf>here</a>.\n * <p>\n * This example consists in a search problem based on a {@link es.usc.citius.hipster.graph.HipsterGraph} which\n * is traversed in lexicographical order. Main\n * characteristics of this example are:\n * <ul>\n *      <li>Uses {@link GraphSearchProblem}, a subclass of {@link SearchProblem} specially designed to facilitate\n *      working with graph search problems.</li>\n *      <li>The nodes of the graph are different cities in Romania.</li>\n *      <li>Nodes are traversed in lexicographical order.</li>\n *      <li>Graph nodes and edges are defined in {@link RomanianProblem}</li>\n *      <li>Finds the a path between the Arad and Bucharest using Depth First Search (DFS) algorithm.</li>\n * </ul>\n *\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class RomanianProblemDFSExample {\n\n    public static void main(String[] args) throws InterruptedException {\n\n        /*\n            SearchProblem is the structure used by Hipster to store all the\n            information about the search query, like: start, goals, transition function,\n            cost function, etc. Once created it is used to instantiate the search\n            iterators which provide the results.\n\n            GraphSearchProblem is a subclass of SearchProblem which provides implementations for TransitionFunction\n            which directly extract the information of connectivity between node from a HipsterGraph.\n         */\n        SearchProblem problem = GraphSearchProblem\n\n                /*\n                    Here we set the start of the search problem to the city Arad.\n                 */\n                .startingFrom(RomanianProblem.City.Arad)\n\n                /*\n                    Defines the graph which is used as source to instantiate this GraphSearchProblem. Here\n                    is where all the information of nodes and arcs is stored. This sets a TransitionFunction\n                    which creates the Transitions between states from the information stored in this HipsterGraph.\n                    With this method the transition function traverses the nodes in lexicographical order. Depending\n                    on the algorithm you use for the search this might be relevant or not. For example, Depth First\n                    Search will return a different solution if the order in which the nodes are navigated changes. But for\n                    other algorithms which find the optimal solution (like Dijkstra, A*, or AD*) this has no impact.\n                 */\n                .inGraphWithLexicographicalOrder(RomanianProblem.graph())\n\n                /*\n                    With this method the SearchProblem is instantiated using the data introduced with the methods\n                    above.\n                 */\n                .build();\n\n\n        /**\n         * Search iterators can be easily created using the methods in the Hipster class. This allows\n         * you to instantiate several search algorithms using the information stored in SearchProblem created\n         * above.\n         *\n         * In this example the search is executed using Depth First Search (DFS) with the goal Bucharest.\n         * Search will stop when the algorithm explores that node. Results of the search are printed.\n         */\n        System.out.println(Hipster.createDepthFirstSearch(problem).search(RomanianProblem.City.Bucharest));\n    }\n\n}\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/RomanianProblemExample.java",
    "content": "package es.usc.citius.hipster.examples;\n\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\nimport es.usc.citius.hipster.util.examples.RomanianProblem;\n\n/**\n * Example of graph search using the Romania problem described\n * <a href =http://www.pearsonhighered.com/assets/hip/us/hip_us_pearsonhighered/samplechapter/0136042597.pdf>here</a>.\n * <p>\n * This example consists in a search problem based on a {@link es.usc.citius.hipster.graph.HipsterGraph}. Main\n * characteristics of this example are:\n * <ul>\n *      <li>Uses {@link GraphSearchProblem}, a subclass of {@link SearchProblem} specially designed to facilitate\n *      working with graph search problems.</li>\n *      <li>The nodes of the graph are different cities in Romania.</li>\n *      <li>Edges of the graph (connectivity between cities) are defined in the link above.</li>\n *      <li>Graph nodes and edges are defined in {@link es.usc.citius.hipster.util.examples.RomanianProblem}</li>\n *      <li>Finds the shortest path between the cities Arad and Bucharest.</li>\n *      <li>Cost function takes the cost of moving between cities from the arcs of the graph.</li>\n * </ul>\n *\n * Although a heuristic is not used in this example (so A* behaves as Dijkstra's algorithm), it is defined in\n * {@link RomanianProblem#heuristicFunction()}. This heuristic stores the Euclidean Distance between each city and\n * Bucharest.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class RomanianProblemExample {\n\n    public static void main(String[] args) throws InterruptedException {\n\n        /*\n            SearchProblem is the structure used by Hipster to store all the\n            information about the search query, like: start, goals, transition function,\n            cost function, etc. Once created it is used to instantiate the search\n            iterators which provide the results.\n\n            GraphSearchProblem is a subclass of SearchProblem which provides implementations for TransitionFunction and\n            CostFunction which directly extract the information of connectivity between node and cost of the arcs from\n            a HipsterGraph.\n         */\n        SearchProblem problem = GraphSearchProblem\n\n                /*\n                    Here we set the start of the search problem to the city Arad.\n                 */\n                .startingFrom(RomanianProblem.City.Arad)\n\n                /*\n                    Defines the graph which is used as source to instantiate this GraphSearchProblem. Here\n                    is where all the information of nodes and arcs is stored. This sets a TransitionFunction\n                    which creates the Transitions between states from the information stored in this HipsterGraph.\n                 */\n                .in(RomanianProblem.graph())\n\n                /*\n                    The graph that we use in this example contains the weights of the arcs. These weights are\n                    the cost of moving between each pair of cities. Function {@link GraphSearchProblem#takeCostsFromEdges}\n                    creates a CostFunction that extracts the costs of each Transition from the HipsterGraph.\n\n                    Alternatively you can use the method extractCostsFromEdges if you need to apply any operation over\n                    the costs labeled in the edges of the graph.\n                 */\n                .takeCostsFromEdges()\n\n                /*\n                    With this method the SearchProblem is instantiated using the data introduced with the methods\n                    above.\n                 */\n                .build();\n\n\n        /**\n         * Search iterators can be easily created using the methods in the Hipster class. This allows\n         * you to instantiate several search algorithms using the information stored in SearchProblem created\n         * above.\n         *\n         * In this example the search is executed using A* with with the goal set to Bucharest.\n         * Search will stop when the algorithm explores that node. Results of the search are printed.\n         */\n        System.out.println(Hipster.createAStar(problem).search(RomanianProblem.City.Bucharest));\n    }\n\n}\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/SimpleEightPuzzleExample.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\npackage es.usc.citius.hipster.examples;\n\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.model.Transition;\nimport es.usc.citius.hipster.model.function.ActionFunction;\nimport es.usc.citius.hipster.model.function.ActionStateTransitionFunction;\nimport es.usc.citius.hipster.model.function.CostFunction;\nimport es.usc.citius.hipster.model.problem.ProblemBuilder;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * Example of using Hipster to solve the 8-puzzle search problem problem using the\n * Dijkstra's algorithm.\n * <p>\n * In this example a {@link SearchProblem} is used to define the components of the search, and\n * the search iterator is later instantiated using this structure. This summarizes the content\n * of this example:\n * <ul>\n *     <li>Uses {@link SearchProblem}, a structure created to facilitate organizing and storing the components\n *     of the search.</li>\n *     <li>The state of the 8-puzzle problem is modeled as an array. Each position of the array stores the number\n *     of each piece of the puzzle at the given position, meaning the 0 the empty space.</li>\n *     <li>This problem is modeled with actions, so an {@link ActionFunction} is used.\n *     This function analyzes which actions are applicable in each state. Valid actions for this problem are moving the\n *     empty space in each of the following directions: UP, DOWN, LEFT, RIGHT.</li>\n *     <li>The {@link es.usc.citius.hipster.model.function.TransitionFunction}\n *     creates the {@link Transition} resulting from apply the given actions to the current state.</li>\n *     <li>The {@link CostFunction} for this problem is unitary. All actions have unitary cost.</li>\n * </ul>\n *\n * The objective of this search problem is to minimize the number of actions to solve the 8-puzzle.\n *\n * @see {@link es.usc.citius.hipster.examples.EightPuzzleProblemExample}\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class SimpleEightPuzzleExample {\n\n    enum Action { UP, DOWN, LEFT, RIGHT } // Possible actions of our problem\n\n    public static void main(String[] args){\n\n        /*\n            SearchProblem is the structure used by Hipster to store all the\n            information about the search query, like: start, goals, transition function,\n            cost function, etc. Once created it is used to instantiate the search\n            iterators which provide the results.\n         */\n        SearchProblem p = ProblemBuilder.create()\n\n                /*\n                    Initial state of the search. Defined as an array.\n                 */\n                .initialState(Arrays.asList(5,4,0,7,2,6,8,1,3))\n\n                /*\n                    Search problems can be defined with or without actions. In this example\n                    we use actions, as the solution results more informative if includes the\n                    motions followed to order the pieces of the puzzle (i.e. LEFT, DOWN, DOWN...).\n                    But problems without explicit actions can also be defined using the method\n                    defineProblemWithoutActions. This is useful when the sequence of actions is not\n                    interesting for the solution of the search, like in the 2D maze search\n                    problem that you can find in this module.\n                 */\n                .defineProblemWithExplicitActions()\n\n                /*\n                    The action function is the component which calculates for each state the\n                    actions that are available to reach other state. In this example the action\n                    function discards all motions that are not possible due to the bounds of the\n                    puzzle. This code is in the function validMovementsFor of this same class.\n                 */\n                .useActionFunction(new ActionFunction<Action, List<Integer>>() {\n                    @Override\n                    public Iterable<Action> actionsFor(List<Integer> state) {\n                        // Here we compute the valid movements for the state\n                        return validMovementsFor(state);\n                    }\n                })\n\n                /*\n                    The transition\n                    function takes the available actions given by the actionFunction defined\n                    above and computes the new state that results from applying to the current state\n                    each one of the available actions.\n\n                    The transition function returns a collection of transitions.\n                    A transition is defined by a class Transition which has two attributes:\n                    source point (from) and destination point (to). The source point\n                    is the current state that we are exploring, and the destination point\n                    is a reachable location from that state.\n                */\n                .useTransitionFunction(new ActionStateTransitionFunction<Action, List<Integer>>() {\n                    @Override\n                    public List<Integer> apply(Action action, List<Integer> state) {\n                        // Here we compute the state that results from doing an action A to the current state\n                        return applyActionToState(action, state);\n                    }\n                })\n\n                /*\n                    The cost function defines the effort moving between states.\n                    The CostFunction is an interface with three generic types: S - the state,\n                    A - the action type and T - the cost type.\n                    In this example we consider an unitary cost for each motion.\n                 */\n                .useCostFunction(new CostFunction<Action, List<Integer>, Double>() {\n                    @Override\n                    public Double evaluate(Transition<Action, List<Integer>> transition) {\n                        // Every movement has the same cost, 1\n                        return 1d;\n                    }\n                })\n\n                /*\n                    With this method the SearchProblem is instantiated using the data introduced with the methods\n                    above.\n                 */\n                .build();\n\n        /**\n         * Here the search iterator (Dijkstra's algorithm) is created. Search is executed with until the goal\n         * state is explored and the results are printed by console.\n         */\n        System.out.println(Hipster.createDijkstra(p).search(Arrays.asList(0,1,2,3,4,5,6,7,8)));\n\n    }\n\n    /**\n     * Generates a new state that results from applying action Action to the state State.\n     * Example: {5,4,0,7,2,6,8,1,3} x LEFT -> {5,0,4,7,2,6,8,1,3}\n     *\n     * @param action action to apply (UP, DOWN, LEFT, RIGHT)\n     * @param board List of integers that represents the board\n     * @return new state\n     */\n    private static List<Integer> applyActionToState(Action action, List<Integer> board) {\n        // We copy the original board and we swap the 0 (empty tile) with the corresponding\n        // tile, depending on the action to apply.\n        List<Integer> successor = new ArrayList<Integer>(board);\n        int tileToSwap = 0;\n        switch (action){\n            case UP:\n                tileToSwap = board.indexOf(0) - 3;\n                break;\n            case DOWN:\n                tileToSwap = board.indexOf(0) + 3;\n                break;\n            case LEFT:\n                tileToSwap = board.indexOf(0) - 1;\n                break;\n            case RIGHT:\n                tileToSwap = board.indexOf(0) + 1;\n                break;\n        }\n        successor.set(board.indexOf(0), board.get(tileToSwap));\n        successor.set(tileToSwap, 0);\n        return successor;\n    }\n\n    /**\n     * Computes the valid movements for a particular board (it depends\n     * on the position of the empty tile).\n     *\n     * Example:\n     *\n     * | 2 0 1 |  0 1 2 3 4 5 6 7 8 <- indexes of the array\n     * | 4 3 5 | {2,0,1,4,3,5,7,6,8}\n     * | 7 6 8 |\n     *\n     * Valid movements for the empty tile 0 (array index 1): LEFT, RIGHT, DOWN.\n     *\n     * @param state List of integers that represents the board state\n     * @return iterable with the valid actions.\n     */\n    private static Iterable<Action> validMovementsFor(List<Integer> state) {\n\n        int emptyTile = state.indexOf(0); // array index which corresponds to the empty tile of the board\n        switch(emptyTile){\n            // Ad-hoc computation of the available movements for a fixed 3x3 board.\n            // NOTE: There are better ways to compute the valid actions for a general case NxN board!\n            case 0: return Arrays.asList(Action.RIGHT, Action.DOWN);\n            case 1: return Arrays.asList(Action.RIGHT, Action.DOWN, Action.LEFT);\n            case 2: return Arrays.asList(Action.LEFT, Action.DOWN);\n            case 3: return Arrays.asList(Action.UP, Action.DOWN, Action.RIGHT);\n            case 4: return Arrays.asList(Action.UP, Action.DOWN, Action.RIGHT, Action.LEFT);\n            case 5: return Arrays.asList(Action.UP, Action.DOWN, Action.LEFT);\n            case 6: return Arrays.asList(Action.UP, Action.RIGHT);\n            case 7: return Arrays.asList(Action.UP, Action.LEFT, Action.RIGHT);\n            case 8: return Arrays.asList(Action.UP, Action.LEFT);\n            default: throw new IllegalStateException(\"Invalid position\");\n        }\n    }\n}\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/UndirectedGraphSearchExample.java",
    "content": "package es.usc.citius.hipster.examples;\n\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphBuilder;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.graph.HipsterDirectedGraph;\nimport es.usc.citius.hipster.graph.HipsterGraph;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\n\n/**\n * Example of graph search with manual creation of the graph structure.\n * <p>\n * In this example an undirected {@link HipsterGraph} is created, and then\n * a search using DFS is executed. Summarized characteristics of this\n * example are:\n * <ul>\n *      <li>Uses {@link GraphSearchProblem}, a subclass of {@link SearchProblem} specially designed to facilitate\n *      working with graph search problems.</li>\n *      <li>An undirected graph is created introducing manually the data in the {@link HipsterGraph}.</li>\n *      <li>Cost function takes the cost of moving between cities from the arcs of the graph.</li>\n * </ul>\n *\n * In this example the search problem is defined from the initial state, extracting the costs from the arcs\n * of the graph. The goal is set after creating the search problem, at the end.\n * <p>\n * Since DFS is an uninformed search algorithm an heuristic is not needed to be defined.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n * @author Adrián González Sieira <<a href=\"adrian.gonzalez@usc.es\">adrian.gonzalez@usc.es</a>>\n */\npublic class UndirectedGraphSearchExample {\n\n\tpublic static void main(String args[]) {\n\n\t\t/*\n\t\t    Here a HipsterGraph is created. The builder allows to specify both nodes connected by each\n\t\t    arc and its cost.\n         */\n        HipsterGraph<String,Double> graph =\n                GraphBuilder.<String,Double>create() \n                .connect(\"A\").to(\"B\").withEdge(2d)\n                .connect(\"A\").to(\"C\").withEdge(2d)\n                .connect(\"A\").to(\"D\").withEdge(2d)\n                .connect(\"B\").to(\"E\").withEdge(5d)\n                .connect(\"B\").to(\"F\").withEdge(10d)\n                .connect(\"B\").to(\"G\").withEdge(5d)\n                .connect(\"B\").to(\"H\").withEdge(10d)\n                .connect(\"C\").to(\"I\").withEdge(5d)\n                .connect(\"C\").to(\"J\").withEdge(10d)\n                .connect(\"C\").to(\"K\").withEdge(5d)\n                .connect(\"K\").to(\"L\").withEdge(5d)\n                /*\n                    Finally the graph is instantiated with the methods createDirectedGraph or\n                    createUndirectedGraph, like in this example.\n                 */\n                .createUndirectedGraph();\n\n        /*\n            SearchProblem is the structure used by Hipster to store all the\n            information about the search query, like: start, goals, transition function,\n            cost function, etc. Once created it is used to instantiate the search\n            iterators which provide the results.\n\n            GraphSearchProblem is a subclass of SearchProblem which provides implementations for TransitionFunction and\n            CostFunction which directly extract the information of connectivity between node and cost of the arcs from\n            a HipsterGraph.\n         */\n\t\tSearchProblem p = GraphSearchProblem\n\n                /*\n                    Here we set the start of the search problem to the node \"A\".\n                 */\n\t\t\t\t.startingFrom(\"A\")\n\n                /*\n                    Defines the graph which is used as source to instantiate this GraphSearchProblem. Here\n                    is where all the information of nodes and arcs is stored. This sets a TransitionFunction\n                    which creates the Transitions between states from the information stored in this HipsterGraph.\n                 */\n\t\t\t\t.in(graph)\n\n                /*\n                    The graph that we use in this example contains the weights of the arcs. These weights are\n                    the stored in the arcs. Function {@link GraphSearchProblem#takeCostsFromEdges}\n                    creates a CostFunction that extracts the costs of each Transition from the HipsterGraph.\n\n                    Alternatively you can use the method extractCostsFromEdges if you need to apply any operation over\n                    the costs labeled in the edges of the graph.\n                 */\n\t\t\t\t.takeCostsFromEdges()\n\n                /*\n                    With this method the SearchProblem is instantiated using the data introduced with the methods\n                    above.\n                 */\n\t\t\t\t.build();\n\n        /**\n         * Search iterators can be easily created using the methods in the Hipster class. This allows\n         * you to instantiate several search algorithms using the information stored in SearchProblem created\n         * above.\n         *\n         * In this example the search is executed using DFS with with the goal set to \"L\". Search will stop\n         * when the algorithm explores that node. Results of the search are printed.\n         */\n\t\tSystem.out.println(Hipster.createDepthFirstSearch(p).search(\"L\"));\n\t}\n}\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Module with different toy examples solved with Hipster.\n */\npackage es.usc.citius.hipster.examples;"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/problem/NPuzzle.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.examples.problem;\n\nimport java.awt.*;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * <p>General N-Puzzle problem.</p>\n *\n * See the description of the N-Puzzle in\n * <a href=\"http://heuristicswiki.wikispaces.com/N+-+Puzzle\">Heuristics Wiki</a>\n */\npublic final class NPuzzle {\n\n    private NPuzzle(){}\n\n    /**\n     * Prints a search path in a readable form.\n     *\n     * @param path List of puzzle states of the path.\n     * @param size Size of the puzzle state (8 for 8-puzzle)\n     * @return String representing all the transitions from initial to goal.\n     */\n    public static String getPrettyPath(List<Puzzle> path, int size) {\n        // Print each row of all states\n        StringBuffer output = new StringBuffer();\n        for (int y = 0; y < size; y++) {\n            String row = \"\";\n            for (Puzzle state : path) {\n                int[][] board = state.getMatrixBoard();\n                row += \"| \";\n                for (int x = 0; x < size; x++) {\n                    row += board[y][x] + \" \";\n                }\n                row += \"|  \";\n            }\n            row += \"\\n\";\n            output.append(row);\n        }\n        return output.toString();\n    }\n\n    /**\n     * Actions that can be used in the N-Puzzle game. In the particular\n     * case of the 8-Puzzle, we have a 3x3 board with eight numbers and\n     * an empty grid square. Each tile next to the empty grid square can\n     * be moved to fill it. This is equivalent to consider the empty square\n     * as the tile that can be moved up, down, left or right in the board.\n     * Therefore, the actions that we can apply in the board are: moving\n     * the empty square up, down, left or right (depending on the position\n     * of the gap).\n     */\n    public enum PuzzleMove {\n        UP, DOWN, LEFT, RIGHT\n    }\n\n    /**\n     * Puzzle class represents the state codification for this game.\n     * It is represented as a plain array of numbers, where 0 represents\n     * the empty square.\n     * <p/>\n     * Note that the performance of the search algorithm strongly depends\n     * on the chosen representation of the state, as well as\n     * the performance of the transition and evaluation functions.\n     * This representation for a state of the 8-puzzle problem is not\n     * the most efficient one, but enough to solve the problem fast\n     * and clearly enough.\n     */\n    public static final class Puzzle {\n\n        // This is the attribute used to compute\n        // the hash and the equality test between puzzles.\n        private final int[] plainBoard;\n\n        private int[][] matrix = null;\n        // Used to optimize the search\n        private Puzzle previousBoard;\n\n        // Matrix board\n        public Puzzle(int[][] board) {\n            // Check if the board is square\n            int size = board.length;\n            if (!isSquare(board)) {\n                throw new IllegalArgumentException(\"Board is not square\");\n            }\n            this.plainBoard = new int[size * size];\n            for (int x = 0; x < size; x++) {\n                for (int y = 0; y < size; y++) {\n                    this.plainBoard[x * size + y] = board[x][y];\n                }\n            }\n            this.matrix = board;\n        }\n\n        // Plain board representation {0,1,2,3,4,5,6,7,8}\n        public Puzzle(int[] plainBoard) {\n            this.plainBoard = plainBoard;\n        }\n\n        int[][] matrixBoard(int[] plainBoard) {\n            // Generate a squared board. If the array size is not\n            // a perfect square, truncate size.\n            int size = (int) Math.sqrt(plainBoard.length);\n            int[][] board = new int[size][size];\n            for (int x = 0; x < size; x++) {\n                for (int y = 0; y < size; y++) {\n                    board[x][y] = plainBoard[x * size + y];\n                }\n            }\n            return board;\n        }\n\n        public int[][] copyBoard() {\n            return matrixBoard(this.plainBoard);\n        }\n\n        public int[][] getMatrixBoard() {\n            if (matrix == null) {\n                matrix = matrixBoard(this.plainBoard);\n            }\n            return matrix;\n        }\n\n        boolean isSquare(int[][] board) {\n            int rows = board.length;\n            for (int row = 0; row < rows; row++) {\n                if (board[row].length != rows) {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        public Point getTile(int number) {\n            int[][] matrixBoard = this.getMatrixBoard();\n            int size = matrixBoard.length;\n            for (int x = 0; x < size; x++) {\n                for (int y = 0; y < size; y++) {\n                    if (matrixBoard[x][y] == number) {\n                        return new Point(x, y);\n                    }\n                }\n            }\n            return null;\n        }\n\n        public Puzzle getPreviousBoard() {\n            return previousBoard;\n        }\n\n        public void setPreviousBoard(Puzzle previousBoard) {\n            this.previousBoard = previousBoard;\n        }\n\n        @Override\n        public String toString() {\n            return Arrays.toString(this.plainBoard);\n        }\n\n        // IMPORTANT NOTE: Since we are creating a state class (the basic unit search)\n        // we have to override equals & hashcode to guarantee that two states with\n        // the same tiles in the same position ARE EQUAL.\n\n        @Override\n        public boolean equals(Object o) {\n            if (this == o) return true;\n            if (o == null || getClass() != o.getClass()) return false;\n\n            Puzzle puzzle = (Puzzle) o;\n\n            if (!Arrays.equals(plainBoard, puzzle.plainBoard)) return false;\n\n            return true;\n        }\n\n        @Override\n        public int hashCode() {\n            return Arrays.hashCode(plainBoard);\n        }\n    }\n\n\n}\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/problem/NQueens.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.examples.problem;\n\n\nimport java.util.Arrays;\nimport java.util.Random;\n\n/**\n * <p>\n * General N-Queens problem. The goal is to place N-Queens in a N-Chess Board\n * without any queen attacking each other.\n * </p>\n *\n * There is a good description of the problem\n * <a href=\"http://www.math.utah.edu/~alfeld/queens/queens.html\">in Peter Alfeld's Web Page (University of Utah)</a>\n */\npublic class NQueens {\n    private static final String LS = System.getProperty(\"line.separator\");\n\n\n    // if N = 8:\n    // board[0] means queen at row 0.\n    // Example: if board[0] == 2 then there is a queen in\n    // the third column of the first row:\n    //\n    //   0 1 2 3 4 5 6 7\n    // 0     Q           <- row 0\n    // 1\n    // 2\n    // ...\n\n    private int queens[];\n\n    public NQueens(int size) {\n        this.queens = new int[size];\n        // Initialize randomly\n        Random r = new Random();\n        for (int i = 0; i < size; i++) {\n            this.queens[i] = r.nextInt(size);\n        }\n    }\n\n    public NQueens(int queens[]) {\n        this.queens = queens;\n    }\n\n    @Override\n    public String toString() {\n        String output = \"\" + LS;\n        // Build string row by row\n        for (int i = 0; i < queens.length; i++) {\n            // Check if there is a queen in this row\n            for (int j = 0; j < queens.length; j++) {\n                // if queens[i]==j then row i has a queen in column j\n                output += queens[i] == j ? \" O \" : \" . \";\n            }\n            output += LS;\n        }\n        return output;\n    }\n\n    public boolean isAttacked(int row, int column) {\n        for (int i = 0; i < queens.length; i++) {\n            if (i != row) {\n                // Same column\n                if (queens[i] == column) return true;\n                // Same major diagonal\n                if ((queens[i] - column) == (row - i)) return true;\n                // Same minor diagonal\n                if ((column - queens[i]) == (row - i)) return true;\n            }\n        }\n        return false;\n    }\n\n    public boolean isAttacked(int row) {\n        return isAttacked(row, queens[row]);\n    }\n\n    public int attackedQueens() {\n        int attacked = 0;\n        // Explore each row\n        for (int i = 0; i < queens.length; i++) {\n            if (isAttacked(i)) attacked++;\n        }\n        return attacked;\n    }\n\n\n    // Implement equals & hashcode using queens array attribute\n\n\n    @Override\n    public boolean equals(Object o) {\n        if (this == o) return true;\n        if (o == null || getClass() != o.getClass()) return false;\n\n        NQueens state = (NQueens) o;\n\n        if (!Arrays.equals(queens, state.queens)) return false;\n\n        return true;\n    }\n\n    @Override\n    public int hashCode() {\n        return Arrays.hashCode(queens);\n    }\n\n    public int[] getQueens() {\n        return queens;\n    }\n}\n\n\n"
  },
  {
    "path": "hipster-examples/src/main/java/es/usc/citius/hipster/examples/problem/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Game example models.\n */\npackage es.usc.citius.hipster.examples.problem;"
  },
  {
    "path": "hipster-examples/src/test/java/es/usc/citius/hipster/search/local/NQueensEHCTest.java",
    "content": "///*\n// * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n// *\n// *    Licensed under the Apache License, Version 2.0 (the \"License\");\n// *    you may not use this file except in compliance with the License.\n// *    You may obtain a copy of the License at\n// *\n// *        http://www.apache.org/licenses/LICENSE-2.0\n// *\n// *    Unless required by applicable law or agreed to in writing, software\n// *    distributed under the License is distributed on an \"AS IS\" BASIS,\n// *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// *    See the License for the specific language governing permissions and\n// *    limitations under the License.\n// */\n//\n//package es.usc.citius.hipster.search.local;\n//\n//\n//import es.usc.citius.hipster.examples.problem.NQueens;\n//import es.usc.citius.lab.hipster.function.HeuristicFunction;\n//import es.usc.citius.lab.hipster.function.TransitionFunction;\n//import es.usc.citius.lab.hipster.node.Node;\n//import es.usc.citius.lab.hipster.node.Transition;\n//import es.usc.citius.hipster.algorithm.localsearch.HillClimbing;\n//import org.junit.Test;\n//\n//import java.util.*;\n//\n//public class NQueensEHCTest {\n//\n//    @Test\n//    public void testSearch8Queens() throws Exception {\n//        // Transition: Interchange two positions randomly\n//        final int size=8;\n//        TransitionFunction<NQueens> tf = new TransitionFunction<NQueens>() {\n//            @Override\n//            public Iterable<? extends Transition<NQueens>> from(NQueens current) {\n//                // Generate all possible movements of one queen\n//                // There are size*(size-1) available movements\n//                Set<NQueens> states = new HashSet<NQueens>();\n//                for(int i=0; i < size; i++){\n//                    for(int j=0; j < size; j++){\n//                        // Change the queen at row i to column j\n//                        // If i is already in j, then do not add the state\n//                        if (current.getQueens()[i]!=j){\n//                            int[] queens = Arrays.copyOf(current.getQueens(), size);\n//                            queens[i]=j;\n//                            states.add(new NQueens(queens));\n//                        }\n//                    }\n//                }\n//                return Transition.map(current, states);\n//            }\n//        };\n//\n//        HeuristicFunction<NQueens, Integer> hf = new HeuristicFunction<NQueens, Integer>() {\n//            @Override\n//            public Integer estimate(NQueens state) {\n//                return state.attackedQueens();\n//            }\n//        };\n//\n//        NQueens initial = new NQueens(size);\n//        HillClimbing<NQueens, Integer> ehc = new HillClimbing<NQueens, Integer>(initial, tf,hf);\n//\n//        System.out.println(\"Initial state: \");\n//        System.out.println(initial.toString());\n//\n//        int iteration=0;\n//        Integer best = ehc.getBestScore();\n//        while(ehc.hasNext()){\n//            iteration++;\n//            Node<NQueens> node = ehc.next();\n//            if (ehc.getBestScore() < best){\n//                best = ehc.getBestScore();\n//                System.out.println(\"New local minimum found with value \" + best + \" at iteration \" + iteration);\n//            }\n//            int attacked = node.transition().to().attackedQueens();\n//            if (attacked == 0){\n//                System.out.println(\"Solution found: \");\n//                System.out.println(node.transition().to().toString());\n//                break;\n//            }\n//        }\n//    }\n//}\n"
  },
  {
    "path": "hipster-examples/src/test/java/es/usc/citius/lab/hipster/examples/NQueensTest.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.lab.hipster.examples;\n\n\nimport es.usc.citius.hipster.examples.problem.NQueens;\nimport org.junit.Test;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport static org.junit.Assert.assertEquals;\n\npublic class NQueensTest {\n\n    @Test\n    public void test8QueenZeroAttacked() throws Exception {\n        int solution[]={3,6,2,7,1,4,0,5};\n        assertEquals(0, new NQueens(solution).attackedQueens());\n    }\n\n    @Test\n    public void test8QueenSameColumnDiagonalAttacked() throws Exception {\n        int solution[]={3,6,3,7,1,4,0,5};\n        assertEquals(3, new NQueens(solution).attackedQueens());\n    }\n\n    @Test\n    public void test8QueenSameColumnAttacked() throws Exception {\n        int solution[]={3,6,2,7,1,4,2,5};\n        assertEquals(2, new NQueens(solution).attackedQueens());\n    }\n\n    @Test\n    public void test8QueenEqualsHashCode() throws Exception {\n        Set<NQueens> states = new HashSet<NQueens>();\n        // Two different instances with the same queens are the same state!\n        states.add(new NQueens(new int[]{0,1,2,3,4,5,6,7}));\n        states.add(new NQueens(new int[]{0,1,2,3,4,5,6,7}));\n        assertEquals(1, states.size());\n    }\n}\n"
  },
  {
    "path": "hipster-extensions/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <parent>\n        <artifactId>hipster-pom</artifactId>\n        <groupId>es.usc.citius.hipster</groupId>\n        <version>1.0.2-SNAPSHOT</version>\n    </parent>\n\n    <modelVersion>4.0.0</modelVersion>\n    <artifactId>hipster-extensions</artifactId>\n\n    <properties>\n        <hipster.root.dir>${project.basedir}/..</hipster.root.dir>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>es.usc.citius.hipster</groupId>\n            <artifactId>hipster-core</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>es.usc.citius.hipster</groupId>\n            <artifactId>hipster-third-party-graphs</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>com.google.guava</groupId>\n            <artifactId>guava</artifactId>\n            <version>29.0-jre</version>\n        </dependency>\n        <!-- Using Guava annotations require this dependency-->\n        <dependency>\n            <groupId>com.google.code.findbugs</groupId>\n            <artifactId>jsr305</artifactId>\n            <version>3.0.0</version>\n        </dependency>\n\n    </dependencies>\n\n</project>"
  },
  {
    "path": "hipster-extensions/src/main/java/es/usc/citius/hipster/extensions/graph/HashTableHipsterDirectedGraph.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\npackage es.usc.citius.hipster.extensions.graph;\n\nimport com.google.common.base.Preconditions;\nimport es.usc.citius.hipster.graph.DirectedEdge;\nimport es.usc.citius.hipster.graph.GraphEdge;\nimport es.usc.citius.hipster.graph.HipsterDirectedGraph;\n\n/**\n * Implementation of a HipsterDirectedGraph using a Guava Hash Table.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class HashTableHipsterDirectedGraph<V,E> extends HashTableHipsterGraph<V,E> implements HipsterDirectedGraph<V,E> {\n\n    @Override\n    public GraphEdge<V,E> connect(V v1, V v2, E value){\n        Preconditions.checkArgument(v1 != null && v2 != null, \"Vertices cannot be null\");\n        GraphEdge<V,E> edge = new DirectedEdge<V, E>(v1, v2, value);\n        graphTable.put(v1, v2, edge);\n        disconnected.remove(v1);\n        disconnected.remove(v2);\n        return edge;\n    }\n\n    @Override\n    public Iterable<GraphEdge<V, E>> outgoingEdgesOf(V vertex) {\n        return graphTable.row(vertex).values();\n    }\n\n    @Override\n    public Iterable<GraphEdge<V, E>> incomingEdgesOf(V vertex) {\n        return graphTable.column(vertex).values();\n    }\n\n    public static <V,E> HashTableHipsterDirectedGraph<V, E> create() {\n        return new HashTableHipsterDirectedGraph<V, E>();\n    }\n}\n"
  },
  {
    "path": "hipster-extensions/src/main/java/es/usc/citius/hipster/extensions/graph/HashTableHipsterGraph.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\npackage es.usc.citius.hipster.extensions.graph;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.HashBasedTable;\nimport com.google.common.collect.Sets;\nimport es.usc.citius.hipster.graph.GraphEdge;\nimport es.usc.citius.hipster.graph.HipsterGraph;\nimport es.usc.citius.hipster.graph.UndirectedEdge;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\n/**\n * Implementation of a HipsterGraph using a Guava Hash Table.\n *\n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class HashTableHipsterGraph<V,E> implements HipsterGraph<V,E> {\n    protected HashBasedTable<V,V,GraphEdge<V,E>> graphTable = HashBasedTable.create();\n    // keep extra info for all those disconnected vertices\n    protected Set<V> disconnected = new HashSet<V>();\n\n    public void add(V v){\n        if (!graphTable.containsColumn(v) && !graphTable.containsRow(v)){\n            disconnected.add(v);\n        }\n    }\n\n    private <T> boolean greaterThan(int size, Iterable<T> iterable){\n        int elems = 0;\n        for(T t : iterable){\n            elems++;\n            if (elems > size){\n                return true;\n            }\n        }\n        return false;\n    }\n\n    public void remove(V v){\n        // Get vertices connected with this one\n        for(GraphEdge<V,E> edge : edgesOf(v)){\n            V connectedVertex = edge.getVertex1().equals(v) ? edge.getVertex2() : edge.getVertex1();\n            // Is this vertex connected with a different vertex?\n            if (!greaterThan(1, edgesOf(connectedVertex))){\n                disconnected.add(connectedVertex);\n            }\n        }\n        if (graphTable.containsRow(v)){\n            graphTable.row(v).clear();\n        }\n        if (graphTable.containsColumn(v)){\n            graphTable.column(v).clear();\n        }\n        // Check for disconnected vertices\n        disconnected.remove(v); // v no longer exists\n\n    }\n\n    public void remove(V v, GraphEdge<V,E> edge){\n        // Try to remove vertex from row/columns\n        Preconditions.checkArgument(edge.getVertex1().equals(v) || edge.getVertex2().equals(v), \"Edge is not connected with the vertex\");\n        V opposite = edge.getVertex1().equals(v) ? edge.getVertex2() : edge.getVertex1();\n        graphTable.row(v).remove(opposite);\n    }\n\n    public GraphEdge<V,E> connect(V v1, V v2, E value){\n        Preconditions.checkArgument(v1 != null && v2 != null, \"Vertices cannot be null\");\n        GraphEdge<V,E> edge = new UndirectedEdge<V, E>(v1, v2, value);\n        graphTable.put(v1, v2, edge);\n        graphTable.put(v2, v1, edge);\n        disconnected.remove(v1);\n        disconnected.remove(v2);\n        return edge;\n    }\n\n    @Override\n    public Iterable<GraphEdge<V, E>> edges() {\n        return graphTable.values();\n    }\n\n    @Override\n    public Iterable<V> vertices() {\n        return Sets.union(Sets.union(graphTable.rowKeySet(), graphTable.columnKeySet()), disconnected);\n    }\n\n    @Override\n    public Iterable<GraphEdge<V, E>> edgesOf(V vertex) {\n        return Sets.union(Sets.newHashSet(graphTable.row(vertex).values()), Sets.newHashSet(graphTable.column(vertex).values()));\n    }\n\n    public static <V,E> HashTableHipsterGraph<V, E> create() {\n        return new HashTableHipsterGraph<V, E>();\n    }\n}\n"
  },
  {
    "path": "hipster-extensions/src/test/java/es/usc/citius/hipster/extensions/graph/HashTableHipsterDirectedGraphTest.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.extensions.graph;\n\nimport com.google.common.collect.Sets;\nimport es.usc.citius.hipster.graph.DirectedEdge;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport static org.junit.Assert.assertEquals;\n\n\npublic class HashTableHipsterDirectedGraphTest extends HashTableHipsterGraphTest {\n    private HashTableHipsterDirectedGraph<String, Double> directedGraph;\n\n    @Before\n    @Override\n    public void setUp() {\n        directedGraph = HashTableHipsterDirectedGraph.create();\n        directedGraph.connect(\"A\", \"B\", 4d);\n        directedGraph.connect(\"A\", \"C\", 2d);\n        directedGraph.connect(\"B\", \"C\", 5d);\n        directedGraph.connect(\"B\", \"D\", 10d);\n        directedGraph.connect(\"C\", \"E\", 3d);\n        directedGraph.connect(\"D\", \"F\", 11d);\n        directedGraph.connect(\"E\", \"D\", 4d);\n        graph = directedGraph;\n    }\n\n    @Test\n    public void testConnect() throws Exception {\n        directedGraph.connect(\"F\", \"G\", 1d);\n        assertEquals(\"F\", directedGraph.incomingEdgesOf(\"G\").iterator().next().getVertex1());\n    }\n\n    @Test\n    public void testOutgoingEdgesOf() throws Exception {\n        Set<DirectedEdge<String, Double>> expected = new HashSet<DirectedEdge<String, Double>>();\n        expected.add(new DirectedEdge<String, Double>(\"B\", \"C\", 5d));\n        expected.add(new DirectedEdge<String, Double>(\"B\", \"D\", 10d));\n        assertEquals(expected, Sets.newHashSet(directedGraph.outgoingEdgesOf(\"B\")));\n    }\n\n    @Test\n    public void testIncomingEdgesOf() throws Exception {\n        Set<DirectedEdge<String, Double>> expected = new HashSet<DirectedEdge<String, Double>>();\n        expected.add(new DirectedEdge<String, Double>(\"B\", \"C\", 5d));\n        expected.add(new DirectedEdge<String, Double>(\"A\", \"C\", 2d));\n        assertEquals(expected, Sets.newHashSet(directedGraph.incomingEdgesOf(\"C\")));\n    }\n\n    @Test\n    @Override\n    public void testEdges() throws Exception {\n        Set<DirectedEdge<String, Double>> expected = new HashSet<DirectedEdge<String, Double>>();\n        expected.add(new DirectedEdge<String, Double>(\"A\", \"B\", 4d));\n        expected.add(new DirectedEdge<String, Double>(\"A\", \"C\", 2d));\n        expected.add(new DirectedEdge<String, Double>(\"B\", \"C\", 5d));\n        expected.add(new DirectedEdge<String, Double>(\"B\", \"D\", 10d));\n        expected.add(new DirectedEdge<String, Double>(\"C\", \"E\", 3d));\n        expected.add(new DirectedEdge<String, Double>(\"D\", \"F\", 11d));\n        expected.add(new DirectedEdge<String, Double>(\"E\", \"D\", 4d));\n        assertEquals(expected, Sets.newHashSet(graph.edges()));\n    }\n\n    @Test\n    @Override\n    public void testEdgesOf() throws Exception {\n        Set<DirectedEdge<String,Double>> expected = new HashSet<DirectedEdge<String, Double>>();\n        expected.add(new DirectedEdge<String, Double>(\"B\", \"D\", 10d));\n        expected.add(new DirectedEdge<String, Double>(\"A\", \"B\", 4d));\n        expected.add(new DirectedEdge<String, Double>(\"B\", \"C\", 5d));\n        assertEquals(expected, graph.edgesOf(\"B\"));\n    }\n}\n"
  },
  {
    "path": "hipster-extensions/src/test/java/es/usc/citius/hipster/extensions/graph/HashTableHipsterGraphTest.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.extensions.graph;\n\nimport com.google.common.collect.Sets;\nimport es.usc.citius.hipster.graph.GraphEdge;\nimport es.usc.citius.hipster.graph.UndirectedEdge;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertTrue;\n\n\npublic class HashTableHipsterGraphTest {\n    protected HashTableHipsterGraph<String, Double> graph;\n\n    @Before\n    public void setUp(){\n        graph = HashTableHipsterGraph.create();\n        graph.connect(\"A\", \"B\", 4d);\n        graph.connect(\"A\", \"C\", 2d);\n        graph.connect(\"B\", \"C\", 5d);\n        graph.connect(\"B\", \"D\", 10d);\n        graph.connect(\"C\", \"E\", 3d);\n        graph.connect(\"D\", \"F\", 11d);\n        graph.connect(\"E\", \"D\", 4d);\n    }\n\n    @Test\n    public void testAdd() throws Exception {\n        graph.add(\"G\");\n        assertTrue(Sets.newHashSet(graph.vertices()).contains(\"G\"));\n    }\n\n    @Test\n    public void testRemove() throws Exception {\n        graph.remove(\"B\");\n        assertFalse(Sets.newHashSet(graph.vertices()).contains(\"B\"));\n    }\n\n    @Test\n    public void testRemoveEdge() throws Exception {\n\n    }\n\n    @Test\n    public void testConnect() throws Exception {\n        graph.connect(\"X\",\"Y\",1.0d);\n        assertTrue(Sets.newHashSet(graph.vertices()).contains(\"X\"));\n        assertTrue(Sets.newHashSet(graph.vertices()).contains(\"Y\"));\n    }\n\n    @Test\n    public void testEdges() throws Exception {\n        Set<GraphEdge<String,Double>> expected = new HashSet<GraphEdge<String, Double>>();\n        expected.add(new UndirectedEdge<String, Double>(\"A\",\"B\",4d));\n        expected.add(new UndirectedEdge<String, Double>(\"A\",\"C\",2d));\n        expected.add(new UndirectedEdge<String, Double>(\"B\",\"C\",5d));\n        expected.add(new UndirectedEdge<String, Double>(\"B\",\"D\",10d));\n        expected.add(new UndirectedEdge<String, Double>(\"C\",\"E\",3d));\n        expected.add(new UndirectedEdge<String, Double>(\"D\",\"F\",11d));\n        expected.add(new UndirectedEdge<String, Double>(\"E\",\"D\",4d));\n        assertEquals(expected, Sets.newHashSet(graph.edges()));\n    }\n\n    @Test\n    public void testVertices() throws Exception {\n        Set<String> expected = Sets.newHashSet(\"A\",\"B\",\"C\",\"D\",\"E\",\"F\");\n        assertEquals(expected, graph.vertices());\n    }\n\n    @Test\n    public void testEdgesOf() throws Exception {\n        Set<GraphEdge<String,Double>> expected = new HashSet<GraphEdge<String, Double>>();\n        expected.add(new UndirectedEdge<String, Double>(\"B\",\"D\",10d));\n        expected.add(new UndirectedEdge<String, Double>(\"A\",\"B\",4d));\n        expected.add(new UndirectedEdge<String, Double>(\"B\",\"C\",5d));\n        assertEquals(expected, graph.edgesOf(\"B\"));\n    }\n\n    @Test\n    public void testDisconnectedVertices(){\n        graph.connect(\"H\", \"L\", 1d);\n        graph.connect(\"I\", \"L\", 1d);\n        graph.connect(\"J\", \"L\", 1d);\n        graph.connect(\"K\", \"L\", 1d);\n        assertTrue(graph.disconnected.isEmpty());\n        graph.remove(\"L\");\n        assertEquals(4, graph.disconnected.size());\n    }\n}"
  },
  {
    "path": "hipster-test/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n  ~ Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n  ~\n  ~    Licensed under the Apache License, Version 2.0 (the \"License\");\n  ~    you may not use this file except in compliance with the License.\n  ~    You may obtain a copy of the License at\n  ~\n  ~        http://www.apache.org/licenses/LICENSE-2.0\n  ~\n  ~    Unless required by applicable law or agreed to in writing, software\n  ~    distributed under the License is distributed on an \"AS IS\" BASIS,\n  ~    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  ~    See the License for the specific language governing permissions and\n  ~    limitations under the License.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <parent>\n        <groupId>es.usc.citius.hipster</groupId>\n        <artifactId>hipster-pom</artifactId>\n        <version>1.0.2-SNAPSHOT</version>\n    </parent>\n    <modelVersion>4.0.0</modelVersion>\n    <artifactId>hipster-test</artifactId>\n\n    <properties>\n        <hipster.root.dir>${project.basedir}/..</hipster.root.dir>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>com.google.code.findbugs</groupId>\n            <artifactId>jsr305</artifactId>\n        </dependency>\n        <dependency>\n            <groupId>com.google.guava</groupId>\n            <artifactId>guava</artifactId>\n        </dependency>\n        <dependency>\n            <groupId>es.usc.citius.hipster</groupId>\n            <artifactId>hipster-core</artifactId>\n            <version>${project.version}</version>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n\n</project>"
  },
  {
    "path": "hipster-third-party-graphs/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n  ~ Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n  ~\n  ~    Licensed under the Apache License, Version 2.0 (the \"License\");\n  ~    you may not use this file except in compliance with the License.\n  ~    You may obtain a copy of the License at\n  ~\n  ~        http://www.apache.org/licenses/LICENSE-2.0\n  ~\n  ~    Unless required by applicable law or agreed to in writing, software\n  ~    distributed under the License is distributed on an \"AS IS\" BASIS,\n  ~    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  ~    See the License for the specific language governing permissions and\n  ~    limitations under the License.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <parent>\n        <groupId>es.usc.citius.hipster</groupId>\n        <artifactId>hipster-pom</artifactId>\n        <version>1.0.2-SNAPSHOT</version>\n    </parent>\n    <modelVersion>4.0.0</modelVersion>\n\n    <artifactId>hipster-third-party-graphs</artifactId>\n\n    <dependencies>\n        <dependency>\n            <groupId>com.tinkerpop.blueprints</groupId>\n            <artifactId>blueprints-graph-jung</artifactId>\n            <version>2.4.0</version>\n        </dependency>\n        <dependency>\n            <groupId>com.tinkerpop.blueprints</groupId>\n            <artifactId>blueprints-core</artifactId>\n            <version>2.4.0</version>\n        </dependency>\n        <dependency>\n            <groupId>es.usc.citius.hipster</groupId>\n            <artifactId>hipster-core</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>net.sf.jung</groupId>\n            <artifactId>jung-graph-impl</artifactId>\n            <version>2.0.1</version>\n        </dependency>\n        <dependency>\n            <groupId>net.sf.jung</groupId>\n            <artifactId>jung-algorithms</artifactId>\n            <version>2.0.1</version>\n        </dependency>\n        <dependency>\n            <groupId>net.sf.jung</groupId>\n            <artifactId>jung-io</artifactId>\n            <version>2.0.1</version>\n        </dependency>\n    </dependencies>\n</project>"
  },
  {
    "path": "hipster-third-party-graphs/src/main/java/es/usc/citius/hipster/thirdparty/graphs/blueprints/BlueprintsHipsterDirectedGraphAdapter.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.thirdparty.graphs.blueprints;\n\n\nimport com.tinkerpop.blueprints.Direction;\nimport com.tinkerpop.blueprints.Edge;\nimport com.tinkerpop.blueprints.Graph;\nimport com.tinkerpop.blueprints.Vertex;\nimport es.usc.citius.hipster.graph.GraphEdge;\nimport es.usc.citius.hipster.graph.HipsterDirectedGraph;\n\n/**\n * Simple adapter implementation between a Hipster graph and a Blueprints graph.\n */\npublic class BlueprintsHipsterDirectedGraphAdapter extends BlueprintsHipsterGraphAdapter implements HipsterDirectedGraph<Vertex, Edge> {\n\n    public BlueprintsHipsterDirectedGraphAdapter(Graph graph) {\n        super(graph);\n    }\n\n    @Override\n    public Iterable<GraphEdge<Vertex, Edge>> outgoingEdgesOf(Vertex vertex) {\n        return convertEdges(vertex.getEdges(Direction.OUT));\n    }\n\n    @Override\n    public Iterable<GraphEdge<Vertex, Edge>> incomingEdgesOf(Vertex vertex) {\n        return convertEdges(vertex.getEdges(Direction.IN));\n    }\n}\n"
  },
  {
    "path": "hipster-third-party-graphs/src/main/java/es/usc/citius/hipster/thirdparty/graphs/blueprints/BlueprintsHipsterGraphAdapter.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.thirdparty.graphs.blueprints;\n\n\nimport com.tinkerpop.blueprints.Direction;\nimport com.tinkerpop.blueprints.Edge;\nimport com.tinkerpop.blueprints.Graph;\nimport com.tinkerpop.blueprints.Vertex;\nimport es.usc.citius.hipster.graph.GraphEdge;\nimport es.usc.citius.hipster.graph.HipsterGraph;\nimport es.usc.citius.hipster.graph.UndirectedEdge;\nimport es.usc.citius.hipster.util.Function;\nimport es.usc.citius.hipster.util.F;\n\nimport java.util.Iterator;\n\n/**\n * Simple graph adapter between a Blueprints graph and a HipsterGraph.\n */\npublic class BlueprintsHipsterGraphAdapter implements HipsterGraph<Vertex, Edge> {\n    private Graph graph;\n\n    public BlueprintsHipsterGraphAdapter(Graph graph) {\n        this.graph = graph;\n    }\n\n    @Override\n    public Iterable<GraphEdge<Vertex, Edge>> edges() {\n        return convertEdges(graph.getEdges());\n    }\n\n    @Override\n    public Iterable<Vertex> vertices() {\n        return graph.getVertices();\n    }\n\n    @Override\n    public Iterable<GraphEdge<Vertex, Edge>> edgesOf(Vertex vertex) {\n        return convertEdges(vertex.getEdges(Direction.BOTH));\n    }\n\n    protected static Iterable<GraphEdge<Vertex,Edge>> convertEdges(final Iterable<Edge> edges){\n        return new Iterable<GraphEdge<Vertex, Edge>>() {\n            @Override\n            public Iterator<GraphEdge<Vertex, Edge>> iterator() {\n                return F.map(edges.iterator(), new Function<Edge, GraphEdge<Vertex, Edge>>() {\n                    @Override\n                    public GraphEdge<Vertex, Edge> apply(Edge edge) {\n                        return new UndirectedEdge<Vertex, Edge>(edge.getVertex(Direction.OUT), edge.getVertex(Direction.IN), edge);\n                    }\n                });\n            }\n        };\n    }\n}\n"
  },
  {
    "path": "hipster-third-party-graphs/src/main/java/es/usc/citius/hipster/thirdparty/graphs/blueprints/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Adapter classes and interfaces to work with the <a href=\"https://github.com/tinkerpop/blueprints/wiki\">Blueprints API</a>.\n */\npackage es.usc.citius.hipster.thirdparty.graphs.blueprints;"
  },
  {
    "path": "hipster-third-party-graphs/src/main/java/es/usc/citius/hipster/thirdparty/graphs/jung/JUNGHipsterDirectedGraphAdapter.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.thirdparty.graphs.jung;\n\n\nimport edu.uci.ics.jung.graph.Graph;\nimport es.usc.citius.hipster.graph.GraphEdge;\nimport es.usc.citius.hipster.graph.HipsterDirectedGraph;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\n\n/**\n * An adapter class to adapt a JUNG graph to the Hipster Graph interface.\n * @param <V> vertex type.\n * @param <E> edge type.\n */\npublic class JUNGHipsterDirectedGraphAdapter<V,E> extends JUNGHipsterGraphAdapter<V,E> implements HipsterDirectedGraph<V,E> {\n\n    public JUNGHipsterDirectedGraphAdapter(Graph<V, E> graph) {\n        super(graph);\n    }\n\n    @Override\n    public Iterable<GraphEdge<V, E>> outgoingEdgesOf(V vertex) {\n        try {\n            // getOutEdges blueprints impl throws null pointer exception\n            final Collection<E> outEdges = graph.getOutEdges(vertex);\n            if (outEdges == null || outEdges.isEmpty()) {\n                return Collections.emptyList();\n            }\n            return adapt(outEdges);\n        } catch (NullPointerException e){\n            return Collections.emptyList();\n        }\n    }\n\n    @Override\n    public Iterable<GraphEdge<V, E>> incomingEdgesOf(V vertex) {\n        try {\n            // getInEdges blueprints impl throws null pointer exception\n            final Collection<E> inEdges = graph.getInEdges(vertex);\n            if (inEdges == null || inEdges.isEmpty()) {\n                return Collections.emptyList();\n            }\n            return adapt(inEdges);\n        }catch(NullPointerException e){\n            return Collections.emptyList();\n        }\n    }\n}\n"
  },
  {
    "path": "hipster-third-party-graphs/src/main/java/es/usc/citius/hipster/thirdparty/graphs/jung/JUNGHipsterGraphAdapter.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.thirdparty.graphs.jung;\n\nimport edu.uci.ics.jung.graph.Graph;\nimport edu.uci.ics.jung.graph.util.EdgeType;\nimport es.usc.citius.hipster.graph.DirectedEdge;\nimport es.usc.citius.hipster.graph.GraphEdge;\nimport es.usc.citius.hipster.graph.HipsterGraph;\nimport es.usc.citius.hipster.graph.UndirectedEdge;\nimport es.usc.citius.hipster.util.Function;\nimport es.usc.citius.hipster.util.F;\n\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Iterator;\n\n/**\n * An adapter to adapt a JUNG graph to a general HipsterGraph interface.\n * \n * @author Pablo Rodríguez Mier <<a href=\"mailto:pablo.rodriguez.mier@usc.es\">pablo.rodriguez.mier@usc.es</a>>\n */\npublic class JUNGHipsterGraphAdapter<V,E> implements HipsterGraph<V,E> {\n    protected Graph<V,E> graph;\n\n    public JUNGHipsterGraphAdapter(Graph<V, E> graph) {\n        this.graph = graph;\n    }\n\n    protected Iterable<GraphEdge<V,E>> adapt(final Iterable<E> iterable){\n        return new Iterable<GraphEdge<V, E>>() {\n            @Override\n            public Iterator<GraphEdge<V, E>> iterator() {\n                return F.map(iterable.iterator(), new Function<E, GraphEdge<V, E>>() {\n                    @Override\n                    public GraphEdge<V, E> apply(E edge) {\n                        if (graph.getEdgeType(edge).equals(EdgeType.DIRECTED)) {\n                            return new DirectedEdge<V, E>(graph.getSource(edge), graph.getDest(edge), edge);\n                        }\n                        return new UndirectedEdge<V, E>(graph.getSource(edge), graph.getDest(edge), edge);\n                    }\n                });\n            }\n        };\n    }\n    @Override\n    public Iterable<GraphEdge<V, E>> edges() {\n        final Collection<E> edges = graph.getEdges();\n        if (edges == null || edges.isEmpty()){\n            return Collections.emptyList();\n        }\n        return adapt(edges);\n    }\n\n    @Override\n    public Iterable<V> vertices() {\n        return graph.getVertices();\n    }\n\n    @Override\n    public Iterable<GraphEdge<V, E>> edgesOf(V vertex) {\n        final Collection<E> edges = graph.getIncidentEdges(vertex);\n        if (edges == null || edges.isEmpty()){\n            return Collections.emptyList();\n        }\n        return adapt(edges);\n    }\n\n}\n"
  },
  {
    "path": "hipster-third-party-graphs/src/main/java/es/usc/citius/hipster/thirdparty/graphs/jung/package-info.java",
    "content": "/*\n * Copyright 2013 Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela (USC).\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\n/**\n * Adapter classes and interfaces to work with the <a href=\"http://jung.sourceforge.net/\">JUNG API</a>.\n */\npackage es.usc.citius.hipster.thirdparty.graphs.jung;"
  },
  {
    "path": "hipster-third-party-graphs/src/test/java/es/usc/citius/hipster/thirdparty/graphs/JUNGHipsterGraphAdapterTest.java",
    "content": "/*\n * Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\npackage es.usc.citius.hipster.thirdparty.graphs;\n\n\nimport com.tinkerpop.blueprints.Edge;\nimport com.tinkerpop.blueprints.Graph;\nimport com.tinkerpop.blueprints.Vertex;\nimport com.tinkerpop.blueprints.impls.tg.TinkerGraph;\nimport com.tinkerpop.blueprints.oupls.jung.GraphJung;\nimport com.tinkerpop.blueprints.util.io.graphml.GraphMLReader;\nimport es.usc.citius.hipster.algorithm.Hipster;\nimport es.usc.citius.hipster.graph.GraphSearchProblem;\nimport es.usc.citius.hipster.graph.HipsterDirectedGraph;\nimport es.usc.citius.hipster.model.impl.WeightedNode;\nimport es.usc.citius.hipster.model.problem.SearchProblem;\nimport es.usc.citius.hipster.thirdparty.graphs.jung.JUNGHipsterDirectedGraphAdapter;\nimport es.usc.citius.hipster.util.Function;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport java.io.InputStream;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.zip.GZIPInputStream;\n\nimport static org.junit.Assert.assertEquals;\n\npublic class JUNGHipsterGraphAdapterTest {\n\n    private static Graph graph;\n\n    public static final String GRAPH_FILE = \"lesmiserables.graphml.gz\";\n\n\n    @BeforeClass\n    public static void setUp() throws Exception {\n        graph = new TinkerGraph();\n        // Get the stream associated with the example graph\n        InputStream fileStream = JUNGHipsterGraphAdapterTest.class.getClassLoader().getResourceAsStream(GRAPH_FILE);\n        // Check if the file was located successfully\n        if (fileStream == null){\n            throw new NullPointerException(GRAPH_FILE + \" cannot be found\");\n        }\n        // Use a GZip stream\n        InputStream ungzippedStream = new GZIPInputStream(fileStream);\n        // populate it\n        GraphMLReader.inputGraph(graph, ungzippedStream);\n        // Close opened streams\n        ungzippedStream.close();\n        fileStream.close();\n    }\n\n    @Test\n    public void testUniformShortestPathSearch(){\n        // Create a graph search problem\n        Vertex origin = graph.query().has(\"label\",\"Cochepaille\").vertices().iterator().next();\n        Vertex dest = graph.query().has(\"label\",\"Tholomyes\").vertices().iterator().next();\n        // Create an adapted graph\n        HipsterDirectedGraph<Vertex,Edge> adaptedGraph = new JUNGHipsterDirectedGraphAdapter<Vertex, Edge>(new GraphJung(graph));\n        // Search a path from origin to dest\n        SearchProblem<Edge, Vertex, WeightedNode<Edge, Vertex, Double>> p = GraphSearchProblem.startingFrom(origin).in(adaptedGraph).takeCostsFromEdges().build();\n        // Shortest path solution\n        List<String> expectedPath = Arrays.asList(\"Cochepaille\", \"Bamatabois\", \"Fantine\", \"Tholomyes\");\n        List<Vertex> shortestPath = Hipster.createAStar(p).search(dest).getOptimalPaths().get(0);\n        for(int i=0; i < shortestPath.size(); i++){\n            assertEquals(expectedPath.get(i), shortestPath.get(i).getProperty(\"label\"));\n        }\n    }\n\n    @Test\n    public void testWeightedShortestPathSearch(){\n        // Take origin and dest vertices from the graph.\n        // Origin: Vertex with label Cochepaille\n        // Destination: Vertex with label Tholomyes\n        Vertex origin = graph.query().has(\"label\",\"Cochepaille\").vertices().iterator().next();\n        Vertex dest = graph.query().has(\"label\",\"Tholomyes\").vertices().iterator().next();\n        // Create a Hipster Directed Graph from a JUNG graph\n        HipsterDirectedGraph<Vertex,Edge> adaptedGraph = new JUNGHipsterDirectedGraphAdapter<Vertex, Edge>(new GraphJung(graph));\n        // Search a path from origin to dest\n        SearchProblem<Edge, Vertex, WeightedNode<Edge, Vertex, Double>> p =\n                GraphSearchProblem\n                        .startingFrom(origin)\n                        .in(adaptedGraph)\n                        .extractCostFromEdges(new Function<Edge, Double>() {\n                            @Override\n                            public Double apply(Edge edge) {\n                                return edge.getProperty(\"weight\");\n                            }\n                        })\n                        .build();\n        List<String> expectedPath = Arrays.asList(\"Cochepaille\", \"Bamatabois\", \"Javert\", \"Cosette\", \"Tholomyes\");\n        // There is only one optimal path.\n        List<Vertex> shortestPath = Hipster.createAStar(p).search(dest).getOptimalPaths().get(0);\n        for(int i=0; i < shortestPath.size(); i++){\n            assertEquals(expectedPath.get(i), shortestPath.get(i).getProperty(\"label\"));\n        }\n    }\n}\n"
  },
  {
    "path": "pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n    \n    <properties>\n        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n        <!-- Point to the root dir to locate custom templates for javadoc -->\n        <hipster.root.dir>${project.basedir}</hipster.root.dir>\n        <!-- Site config -->\n        <site.url>http://hipster4j.org</site.url>\n        <!-- Hipster version -->\n        <hipster.version>1.0.2-SNAPSHOT</hipster.version>\n    </properties>\n\n    <groupId>es.usc.citius.hipster</groupId>\n    <artifactId>hipster-pom</artifactId>\n    <packaging>pom</packaging>\n    <version>1.0.2-SNAPSHOT</version>\n\n    <name>hipster-pom</name>\n    <url>${site.url}</url>\n    <inceptionYear>2013-2020</inceptionYear>\n\n    <modules>\n        <module>hipster-core</module>\n        <module>hipster-examples</module>\n        <module>hipster-all</module>\n        <module>hipster-test</module>\n        <module>hipster-third-party-graphs</module>\n        <module>hipster-extensions</module>\n    </modules>\n\n    <organization>\n        <name>Centro de Investigación en Tecnoloxías da Información (CITIUS), University of Santiago de Compostela</name>\n        <url>http://citius.usc.es</url>\n    </organization>\n\n    <issueManagement>\n        <system>GitHub</system>\n        <url>http://github.com/citiususc/hipster/issues</url>\n    </issueManagement>\n\n    <description>\n        Hipster4j is a lightweight and powerful heuristic search library for Java and Android. It contains common, fully customizable algorithms such as Dijkstra, A* (A-Star), DFS, BFS, Bellman-Ford and more.\n    </description>\n\n    <licenses>\n        <license>\n            <name>The Apache Software License, Version 2.0</name>\n            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>\n            <distribution>repo</distribution>\n        </license>\n    </licenses>\n\n    <prerequisites>\n        <maven>3.0.3</maven>\n    </prerequisites>\n\n    <scm>\n        <connection>scm:git:git@github.com:citiususc/hipster.git</connection>\n        <developerConnection>scm:git:git@github.com:citiususc/hipster.git</developerConnection>\n        <url>scm:git:git@github.com:citiususc/hipster.git</url>\n    </scm>\n\n    <developers>\n        <developer>\n            <id>pablormier</id>\n            <name>Pablo Rodríguez Mier</name>\n            <email>pablo.rodriguez.mier@usc.es</email>\n            <roles>\n                <role>owner</role>\n                <role>developer</role>\n            </roles>\n        </developer>\n        <developer>\n            <id>adrian_gonzalez</id>\n            <name>Adrián González Sieira</name>\n            <email>adrian.gonzalez@usc.es</email>\n            <roles>\n                <role>owner</role>\n                <role>developer</role>\n            </roles>\n        </developer>\n    </developers>\n\n    <dependencyManagement>\n        <dependencies>\n            <dependency>\n                <groupId>junit</groupId>\n                <artifactId>junit</artifactId>\n                <version>4.13.1</version>\n                <scope>test</scope>\n            </dependency>\n            <dependency>\n                <groupId>com.google.guava</groupId>\n                <artifactId>guava</artifactId>\n                <version>29.0-jre</version>\n            </dependency>\n            <dependency>\n                <groupId>com.google.code.findbugs</groupId>\n                <artifactId>jsr305</artifactId>\n                <version>3.0.0</version>\n            </dependency>\n        </dependencies>\n    </dependencyManagement>\n\n    <dependencies>\n        <!-- Test dependencies -->\n        <dependency>\n            <groupId>junit</groupId>\n            <artifactId>junit</artifactId>\n        </dependency>\n    </dependencies>\n\n    <build>\n        <pluginManagement>\n            <plugins>\n                <plugin>\n                    <groupId>org.apache.maven.plugins</groupId>\n                    <artifactId>maven-javadoc-plugin</artifactId>\n                    <version>3.2.0</version>\n                    <configuration>\n                        <encoding>UTF-8</encoding>\n                        <docencoding>UTF-8</docencoding>\n                        <charset>UTF-8</charset>\n                        <!-- Doclava specific configuration -->\n                        <docletArtifact>\n                            <groupId>com.google.doclava</groupId>\n                            <artifactId>doclava</artifactId>\n                            <version>1.0.6</version>\n                        </docletArtifact>\n                        <doclet>com.google.doclava.Doclava</doclet>\n                        <bootclasspath>${sun.boot.class.path}</bootclasspath>\n                        <additionalparam>\n                            -federate JDK http://download.oracle.com/javase/6/docs/api/index.html?\n                            -federationxml JDK http://doclava.googlecode.com/svn/static/api/openjdk-6.xml\n                            -hdf project.name \"${project.name}\"\n                            -templatedir ${hipster.root.dir}/src/main/doclava/custom/assets/hipster-template/\n                            -d ${project.build.directory}/apidocs\n                        </additionalparam>\n                        <useStandardDocletOptions>false</useStandardDocletOptions>\n                        <additionalJOption>-J-Xmx1024m</additionalJOption>\n                        <docfilessubdirs>true</docfilessubdirs>\n                    </configuration>\n                </plugin>\n                <plugin>\n                    <groupId>org.apache.maven.plugins</groupId>\n                    <artifactId>maven-site-plugin</artifactId>\n                    <version>3.3</version>\n                    <configuration>\n                        <generateReports>true</generateReports>\n                        <inputEncoding>UTF-8</inputEncoding>\n                        <outputEncoding>UTF-8</outputEncoding>\n                        <skipDeploy>true</skipDeploy>\n                    </configuration>\n                </plugin>\n\n                <plugin>\n                    <groupId>org.apache.maven.plugins</groupId>\n                    <artifactId>maven-assembly-plugin</artifactId>\n                    <version>2.4</version>\n                </plugin>\n            </plugins>\n        </pluginManagement>\n\n        <plugins>\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-jar-plugin</artifactId>\n                <version>2.4</version>\n                <configuration>\n                    <archive>\n                        <manifest>\n                            <addClasspath>true</addClasspath>\n                        </manifest>\n                    </archive>\n                </configuration>\n            </plugin>\n\n            <plugin>\n                <artifactId>maven-compiler-plugin</artifactId>\n                <version>3.3</version>\n                <configuration>\n                    <source>1.7</source>\n                    <target>1.7</target>\n                </configuration>\n            </plugin>\n\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-source-plugin</artifactId>\n                <version>2.2.1</version>\n                <executions>\n                    <execution>\n                        <id>attach-sources</id>\n                        <phase>verify</phase>\n                        <goals>\n                            <goal>jar-no-fork</goal>\n                            <goal>test-jar-no-fork</goal>\n                        </goals>\n                    </execution>\n                </executions>\n            </plugin>\n\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-javadoc-plugin</artifactId>\n                <version>3.2.0</version>\n                <executions>\n                    <execution>\n                        <id>attach-javadocs</id>\n                        <goals>\n                            <goal>jar</goal>\n                        </goals>\n                    </execution>\n                    <execution>\n                        <id>aggregate</id>\n                        <goals>\n                            <goal>aggregate</goal>\n                        </goals>\n                        <phase>site</phase>\n                    </execution>\n                </executions>\n            </plugin>\n\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-release-plugin</artifactId>\n                <version>2.5</version>\n            </plugin>\n\n\n            <!-- Generate site documentation using reflow-maven-skin -->\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-site-plugin</artifactId>\n            </plugin>\n\n            <plugin>\n                <groupId>org.eluder.coveralls</groupId>\n                <artifactId>coveralls-maven-plugin</artifactId>\n                <version>3.1.0</version>\n            </plugin>\n\n            <!-- Plugin to generate reports of test coverage -->\n            <plugin>\n                <groupId>org.jacoco</groupId>\n                <artifactId>jacoco-maven-plugin</artifactId>\n                <version>0.8.5</version>\n                <executions>\n                    <execution>\n                        <goals>\n                            <goal>prepare-agent</goal>\n                        </goals>\n                    </execution>\n                    <execution>\n                        <id>report</id>\n                        <phase>test</phase>\n                        <goals>\n                            <goal>report</goal>\n                        </goals>\n                    </execution>\n                </executions>\n            </plugin>\n        </plugins>\n    </build>\n\n    <distributionManagement>\n        <repository>\n            <id>bintray-hipster4j-maven</id>\n            <name>hipster4j-maven</name>\n            <url>https://api.bintray.com/maven/hipster4j/maven/hipster4j/;publish=1</url>\n        </repository>\n    </distributionManagement>\n</project>"
  },
  {
    "path": "src/main/doclava/custom/assets/hipster-template/assets/customizations.css",
    "content": "#header {\n    border-bottom: 3px solid #0767a4;\n}\n\n#search_filtered .jd-selected {\n    background-color: #0767a4;\n}\n\n/************* Customizations for Hipster *************/\n\nbody {\n    background-image: none;\n    font: 14px/19px Roboto, sans-serif;\n}\n\nth {\n    background-color: #E2E2E2;\n}\n\n#header {\n    border-bottom: 3px solid #F36126;\n    height: 80px;\n}\n\n#masthead-title {\n    color: #E56B3C;\n}\n\n#jd-header {\n    background-color: transparent;\n}\n\n.jd-sumtable a:hover {\n    text-decoration:none;\n    color: #F36126;\n}\n\n.ui-resizable-s {\n    background: none;\n    background-color: #F1F1F1;\n}\n.ui-resizable-e {\n    background: none;\n    background-color: #F1F1F1;\n}\n\n#search-button {\n    border: 0;\n    background: url(images/icon_search.png) no-repeat;\n    width: 50px;\n    height: 28px;\n    color: transparent;\n}\n\n#search-button:hover {\n    background-position: 0 -28px;\n}\n\na:active,\na:active code {\n  color:#F36126;\n}\n\n/* Scrollbar replacement. Original snippet from https://gist.github.com/devinrhode2/2573411 */\n::-webkit-scrollbar {\n    height: 5px;\n    overflow: visible;\n    width: 5px;\n    background-color: rgba(0,0,0,0);\n}\n/* 243,97,38 */\n\n::-webkit-scrollbar:hover {\n    background-color: rgba(0,0,0,0.1);\n}\n::-webkit-scrollbar-thumb:vertical {\n    background: rgba(0,0,0,0.3);\n}\n::-webkit-scrollbar-thumb:vertical:hover {\n    background: rgba(243,97,38,0.6);\n}\n::-webkit-scrollbar-thumb:vertical:active {\n    background: rgba(243,97,38,0.8);\n}\n::-webkit-scrollbar-thumb:horizontal {\n    background: rgba(0,0,0,0.3);\n}\n::-webkit-scrollbar-thumb:horizontal:hover {\n    background: rgba(243,97,38,0.6);\n}\n::-webkit-scrollbar-thumb:horizontal:active {\n    background: rgba(243,97,38,0.8);\n}\n\n/* Google roboto font */\n@font-face {\n    font-family: 'Roboto';\n    font-style: normal;\n    font-weight: 100;\n    src: local('Roboto Thin'), local('Roboto-Thin'), url(https://themes.googleusercontent.com/static/fonts/roboto/v9/vzIUHo9z-oJ4WgkpPOtg1_esZW2xOQ-xsNqO47m55DA.woff) format('woff');\n}\n@font-face {\n    font-family: 'Roboto';\n    font-style: normal;\n    font-weight: 400;\n    src: local('Roboto Regular'), local('Roboto-Regular'), url(https://themes.googleusercontent.com/static/fonts/roboto/v9/2UX7WLTfW3W8TclTUvlFyQ.woff) format('woff');\n}\n@font-face {\n    font-family: 'Roboto';\n    font-style: normal;\n    font-weight: 500;\n    src: local('Roboto Medium'), local('Roboto-Medium'), url(https://themes.googleusercontent.com/static/fonts/roboto/v9/RxZJdnzeo3R5zSexge8UUT8E0i7KZn-EPnyo3HZu7kw.woff) format('woff');\n}\n@font-face {\n    font-family: 'Roboto';\n    font-style: normal;\n    font-weight: 700;\n    src: local('Roboto Bold'), local('Roboto-Bold'), url(https://themes.googleusercontent.com/static/fonts/roboto/v9/d-6IYplOFocCacKzxwXSOD8E0i7KZn-EPnyo3HZu7kw.woff) format('woff');\n}\n@font-face {\n    font-family: 'Roboto';\n    font-style: italic;\n    font-weight: 400;\n    src: local('Roboto Italic'), local('Roboto-Italic'), url(https://themes.googleusercontent.com/static/fonts/roboto/v9/1pO9eUAp8pSF8VnRTP3xnvesZW2xOQ-xsNqO47m55DA.woff) format('woff');\n}\n@font-face {\n    font-family: 'Roboto';\n    font-style: italic;\n    font-weight: 500;\n    src: local('Roboto Medium Italic'), local('Roboto-MediumItalic'), url(https://themes.googleusercontent.com/static/fonts/roboto/v9/OLffGBTaF0XFOW1gnuHF0YbN6UDyHWBl620a-IRfuBk.woff) format('woff');\n}"
  },
  {
    "path": "src/main/doclava/custom/assets/hipster-template/assets/customizations.js",
    "content": ""
  },
  {
    "path": "src/main/doclava/custom/assets/hipster-template/components/api_filter.cs",
    "content": "<?cs # The default API filter selector that goes in the header ?><?cs\ndef:default_api_filter() ?><?cs\n  if:reference.apilevels ?>\n  <div id=\"api-level-toggle\">\n    <input type=\"checkbox\" id=\"apiLevelCheckbox\" onclick=\"toggleApiLevelSelector(this)\" />\n    <label for=\"apiLevelCheckbox\" class=\"disabled\">Filter by API Level: </label>\n    <select id=\"apiLevelSelector\">\n      <!-- option elements added by buildApiLevelSelector() -->\n    </select>\n  </div>\n  <script>\n   var SINCE_DATA = [ <?cs \n      each:since = since ?>'<?cs \n        var:since.key ?>'<?cs \n        if:!last(since) ?>, <?cs /if ?><?cs\n      /each \n    ?> ];\n    \n    var SINCE_LABELS = [ <?cs \n      each:since = since ?>'<?cs \n        var:since.name ?>'<?cs \n        if:!last(since) ?>, <?cs /if ?><?cs\n      /each \n    ?> ];\n    buildApiLevelSelector();\n    addLoadEvent(changeApiLevel);\n  </script>\n<?cs /if ?>\n<?cs /def ?>"
  },
  {
    "path": "src/main/doclava/custom/assets/hipster-template/components/left_nav.cs",
    "content": "<?cs # The default side navigation for the reference docs ?><?cs \ndef:custom_left_nav() ?>\n  <div class=\"g-section g-tpl-240\" id=\"body-content\">\n    <div class=\"g-unit g-first side-nav-resizable\" id=\"side-nav\">\n      <div id=\"swapper\">\n        <div id=\"nav-panels\">\n          <div id=\"resize-packages-nav\">\n            <div id=\"packages-nav\">\n              <div id=\"index-links\"><nobr>\n                <a href=\"<?cs var:toroot ?>packages.html\" <?cs if:(page.title == \"Package Index\") ?>class=\"selected\"<?cs /if ?> >Package Index</a> | \n                <a href=\"<?cs var:toroot ?>classes.html\" <?cs if:(page.title == \"Class Index\") ?>class=\"selected\"<?cs /if ?>>Class Index</a></nobr>\n              </div>\n              <ul>\n                <?cs call:package_link_list(docs.packages) ?>\n              </ul><br/>\n            </div> <!-- end packages -->\n          </div> <!-- end resize-packages -->\n          <div id=\"classes-nav\"><?cs \n            if:subcount(class.package) ?>\n            <ul>\n              <?cs call:list(\"Interfaces\", class.package.interfaces) ?>\n              <?cs call:list(\"Classes\", class.package.classes) ?>\n              <?cs call:list(\"Annotations\", class.package.annotations) ?>\n              <?cs call:list(\"Enums\", class.package.enums) ?>\n              <?cs call:list(\"Exceptions\", class.package.exceptions) ?>\n              <?cs call:list(\"Errors\", class.package.errors) ?>\n            </ul><?cs \n            elif:subcount(package) ?>\n            <ul>\n              <?cs call:class_link_list(\"Interfaces\", package.interfaces) ?>\n              <?cs call:class_link_list(\"Classes\", package.classes) ?>\n              <?cs call:class_link_list(\"Annotations\", package.annotations) ?>\n              <?cs call:class_link_list(\"Enums\", package.enums) ?>\n              <?cs call:class_link_list(\"Exceptions\", package.exceptions) ?>\n              <?cs call:class_link_list(\"Errors\", package.errors) ?>\n            </ul><?cs \n            else ?>\n              <script>\n                /*addLoadEvent(maxPackageHeight);*/\n              </script>\n              <p style=\"padding:10px\">Select a package to view its members</p><?cs \n            /if ?><br/>\n          </div><!-- end classes -->\n        </div><!-- end nav-panels -->\n        <div id=\"nav-tree\" style=\"display:none\">\n          <div id=\"index-links\"><nobr>\n            <a href=\"<?cs var:toroot ?>packages.html\" <?cs if:(page.title == \"Package Index\") ?>class=\"selected\"<?cs /if ?> >Package Index</a> | \n            <a href=\"<?cs var:toroot ?>classes.html\" <?cs if:(page.title == \"Class Index\") ?>class=\"selected\"<?cs /if ?>>Class Index</a></nobr>\n          </div>\n        </div><!-- end nav-tree -->\n      </div><!-- end swapper -->\n    </div> <!-- end side-nav -->\n    <script>\n      if (!isMobile) {\n        $(\"<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>\").appendTo(\"#side-nav\");\n        chooseDefaultNav();\n        if ($(\"#nav-tree\").is(':visible')) {\n          init_default_navtree(\"<?cs var:toroot ?>\");\n        } else {\n          addLoadEvent(function() {\n            scrollIntoView(\"packages-nav\");\n            scrollIntoView(\"classes-nav\");\n          });\n        }\n        $(\"#swapper\").css({borderBottom:\"2px solid #aaa\"});\n      } else {\n        swapNav(); // tree view should be used on mobile\n      }\n    </script><?cs \n/def ?>"
  },
  {
    "path": "src/main/doclava/custom/assets/hipster-template/components/masthead.cs",
    "content": "<?cs def:custom_masthead() ?>\n<div id=\"header\">\n    <div id=\"headerLeft\">\n    <?cs if:project.name ?>\n      <span id=\"masthead-title\"><?cs var:project.name ?></span>\n    <?cs /if ?>\n    </div>\n    <div id=\"headerRight\">\n      <?cs call:default_search_box() ?>\n      <?cs if:reference && reference.apilevels ?>\n        <?cs call:default_api_filter() ?>\n      <?cs /if ?>\n    </div>\n</div><!-- header -->\n<?cs /def ?>"
  },
  {
    "path": "src/main/doclava/custom/assets/hipster-template/components/search_box.cs",
    "content": "<?cs # The default search box that goes in the header ?><?cs \ndef:default_search_box() ?>\n  <div id=\"search\" >\n      <div id=\"searchForm\">\n          <form accept-charset=\"utf-8\" class=\"gsc-search-box\" \n                onsubmit=\"return submit_search()\">\n            <table class=\"gsc-search-box\" cellpadding=\"0\" cellspacing=\"0\"><tbody>\n                <tr>\n                  <td class=\"gsc-input\">\n                    <input id=\"search_autocomplete\" class=\"gsc-input\" type=\"text\" size=\"33\" autocomplete=\"off\"\n                      title=\"search developer docs\" name=\"q\"\n                      value=\"search developer docs\"\n                      onFocus=\"search_focus_changed(this, true)\"\n                      onBlur=\"search_focus_changed(this, false)\"\n                      onkeydown=\"return search_changed(event, true, '<?cs var:toroot?>')\"\n                      onkeyup=\"return search_changed(event, false, '<?cs var:toroot?>')\" />\n                  <div id=\"search_filtered_div\" class=\"no-display\">\n                      <table id=\"search_filtered\" cellspacing=0>\n                      </table>\n                  </div>\n                  </td>\n                  <td class=\"gsc-search-button\">\n                    <input type=\"submit\" value=\"Search\" title=\"search\" id=\"search-button\" class=\"gsc-search-button\" />\n                  </td>\n                  <td class=\"gsc-clear-button\">\n                    <div title=\"clear results\" class=\"gsc-clear-button\">&nbsp;</div>\n                  </td>\n                </tr></tbody>\n              </table>\n          </form>\n      </div><!-- searchForm -->\n  </div><!-- search --><?cs \n/def ?>"
  },
  {
    "path": "src/main/doclava/custom/assets/hipster-template/customizations.cs",
    "content": "<?cs # placeholder for custom clearsilver code. ?>\n<?cs def:custom_masthead() ?>\n<div id=\"header\">\n    <div id=\"headerLeft\">\n      <a href=\"http://citius.usc.es\" tabindex=\"-1\"><img src=\"<?cs var:toassets ?>images/header-logo.png\" alt=\"\" border=\"0\"></a>\n    </div>\n    <div id=\"headerRight\">\n      <?cs call:default_search_box() ?>\n      <?cs if:reference && reference.apilevels ?>\n        <?cs call:default_api_filter() ?>\n      <?cs /if ?>\n    </div>\n</div><!-- header -->\n<?cs /def ?>"
  },
  {
    "path": "src/main/doclava/custom/assets/hipster-template/footer.cs",
    "content": "<div id=\"footer\">\n<!--Generated by <a href=\"http://code.google.com/p/doclava/\">Doclava</a>-->\nCopyrigth &copy Centro de Investigación en Tecnoloxías da Información (<a href=\"http://citius.usc.es\">CITIUS</a>).\n</div> <!-- end footer -->\n"
  },
  {
    "path": "src/main/javadoc/overview.html",
    "content": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html>\n<head>\n    <title>Hipster - A heuristic search library for java</title>\n</head>\n<body>\nHipster is a heuristic iterative search library implemented in pure java.\nThe aim of this project is to provide a easy to use, well-designed object-oriented\nlibrary that lets you use and extend the most common search algorithms to solve from\ngraph problems to more advanced state-space search problems.\n</body>\n</html>"
  },
  {
    "path": "src/main/javadoc/stylesheet.css",
    "content": "/* Javadoc style sheet */\n/*\nOverall document style\n*/\nbody {\n    background-color:#ffffff;\n    color:#353833;\n    font-family:Helvetica, Arial, sans-serif;\n    font-size:76%;\n    margin:0;\n}\na:link, a:visited {\n    text-decoration:none;\n    color:#4c6b87;    \n}\n\na:hover, a:focus {\n    text-decoration:none;\n    color:#bb7a2a;\n}\na:active {\n    text-decoration:none;\n    color:#4c6b87;\n}\na[name] {\n    color:#353833;\n}\na[name]:hover {\n    text-decoration:none;\n    color:#353833;\n}\npre {\n    font-size:1.3em;\n}\nh1 {\n    font-size:1.8em;\n}\nh2 {\n    font-size:1.5em;\n}\nh3 {\n    font-size:1.4em;\n}\nh4 {\n    font-size:1.3em;\n}\nh5 {\n    font-size:1.2em;\n}\nh6 {\n    font-size:1.1em;\n}\nul {\n    list-style-type:disc;\n}\ncode, tt {\n    font-size:1.125em;\n}\ndt code {\n    font-size:1.125em;\n}\ntable tr td dt code {\n    font-size:1.125em;\n    vertical-align:top;\n}\nsup {\n    font-size:.6em;\n}\n/*\nDocument title and Copyright styles\n*/\n.clear {\n    clear:both;\n    height:0px;\n    overflow:hidden;\n}\n.aboutLanguage {\n    float:right;\n    padding:0px 21px;\n    font-size:.8em;\n    z-index:200;\n    margin-top:-7px;\n}\n.legalCopy {\n    margin-left:.5em;\n}\n.bar a, .bar a:link, .bar a:visited, .bar a:active {\n    color:#FFFFFF;\n    text-decoration:none;\n}\n.bar a:hover, .bar a:focus {\n    color:#bb7a2a;\n}\n.tab {\n    background-color:#0066FF;\n    background-image:url(resources/titlebar.gif);\n    background-position:left top;\n    background-repeat:no-repeat;\n    color:#ffffff;\n    padding:8px;\n    width:5em;\n    font-weight:bold;\n}\n/*\nNavigation bar styles\n*/\n.bar {\n    background-image:url(resources/background.gif);\n    background-repeat:repeat-x;\n    color:#FFFFFF;\n    padding:.8em .5em .4em .8em;\n    height:auto;/*height:1.8em;*/\n    font-size:1em;\n    margin:0;\n}\n.topNav {\n    background-image:url(resources/background.gif);\n    background-repeat:repeat-x;\n    color:#FFFFFF;\n    float:left;\n    padding:0;\n    width:100%;\n    clear:right;\n    height:2.8em;\n    padding-top:10px;\n    overflow:hidden;\n}\n.bottomNav {\n    margin-top:10px;\n    background-image:url(resources/background.gif);\n    background-repeat:repeat-x;\n    color:#FFFFFF;\n    float:left;\n    padding:0;\n    width:100%;\n    clear:right;\n    height:2.8em;\n    padding-top:10px;\n    overflow:hidden;\n}\n.subNav {\n    background-color:#dee3e9;\n    border-bottom:1px solid #9eadc0;\n    float:left;\n    width:100%;\n    overflow:hidden;\n}\n.subNav div {\n    clear:left;\n    float:left;\n    padding:0 0 5px 6px;\n}\nul.navList, ul.subNavList {\n    float:left;\n    margin:0 25px 0 0;\n    padding:0;\n}\nul.navList li{\n    list-style:none;\n    float:left;\n    padding:3px 6px;\n}\nul.subNavList li{\n    list-style:none;\n    float:left;\n    font-size:90%;\n}\n.topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited {\n    color:#FFFFFF;\n    text-decoration:none;\n}\n.topNav a:hover, .bottomNav a:hover {\n    text-decoration:none;\n    color:#bb7a2a;\n}\n.navBarCell1Rev {\n    background-image:url(resources/tab.gif);\n    background-color:#a88834;\n    color:#FFFFFF;\n    margin: auto 5px;\n    border:1px solid #c9aa44;\n}\n/*\nPage header and footer styles\n*/\n.header, .footer {\n    clear:both;\n    margin:0 20px;\n    padding:5px 0 0 0;\n}\n.indexHeader {\n    margin:10px;\n    position:relative;\n}\n.indexHeader h1 {\n    font-size:1.3em;\n}\n.title {\n    color:#2c4557;\n    margin:10px 0;\n}\n.subTitle {\n    margin:5px 0 0 0;\n}\n.header ul {\n    margin:0 0 25px 0;\n    padding:0;\n}\n.footer ul {\n    margin:20px 0 5px 0;\n}\n.header ul li, .footer ul li {\n    list-style:none;\n    font-size:1.2em;\n}\n/*\nHeading styles\n*/\ndiv.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 {\n    background-color:#dee3e9;\n    border-top:1px solid #9eadc0;\n    border-bottom:1px solid #9eadc0;\n    margin:0 0 6px -8px;\n    padding:2px 5px;\n}\nul.blockList ul.blockList ul.blockList li.blockList h3 {\n    background-color:#dee3e9;\n    border-top:1px solid #9eadc0;\n    border-bottom:1px solid #9eadc0;\n    margin:0 0 6px -8px;\n    padding:2px 5px;\n}\nul.blockList ul.blockList li.blockList h3 {\n    padding:0;\n    margin:15px 0;\n}\nul.blockList li.blockList h2 {\n    padding:0px 0 20px 0;\n}\n/*\nPage layout container styles\n*/\n.contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer {\n    clear:both;\n    padding:10px 20px;\n    position:relative;\n}\n.indexContainer {\n    margin:10px;\n    position:relative;\n    font-size:1.0em;\n}\n.indexContainer h2 {\n    font-size:1.1em;\n    padding:0 0 3px 0;\n}\n.indexContainer ul {\n    margin:0;\n    padding:0;\n}\n.indexContainer ul li {\n    list-style:none;\n}\n.contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt {\n    font-size:1.1em;\n    font-weight:bold;\n    margin:10px 0 0 0;\n    color:#4E4E4E;\n}\n.contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd {\n    margin:10px 0 10px 20px;\n}\n.serializedFormContainer dl.nameValue dt {\n    margin-left:1px;\n    font-size:1.1em;\n    display:inline;\n    font-weight:bold;\n}\n.serializedFormContainer dl.nameValue dd {\n    margin:0 0 0 1px;\n    font-size:1.1em;\n    display:inline;\n}\n/*\nList styles\n*/\nul.horizontal li {\n    display:inline;\n    font-size:0.9em;\n}\nul.inheritance {\n    margin:0;\n    padding:0;\n}\nul.inheritance li {\n    display:inline;\n    list-style:none;\n}\nul.inheritance li ul.inheritance {\n    margin-left:15px;\n    padding-left:15px;\n    padding-top:1px;\n}\nul.blockList, ul.blockListLast {\n    margin:10px 0 10px 0;\n    padding:0;\n}\nul.blockList li.blockList, ul.blockListLast li.blockList {\n    list-style:none;\n    margin-bottom:25px;\n}\nul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList {\n    padding:0px 20px 5px 10px;\n    border:1px solid #9eadc0;\n    background-color:#f9f9f9;\n}\nul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList {\n    padding:0 0 5px 8px;\n    background-color:#ffffff;\n    border:1px solid #9eadc0;\n    border-top:none;\n}\nul.blockList ul.blockList ul.blockList ul.blockList li.blockList {\n    margin-left:0;\n    padding-left:0;\n    padding-bottom:15px;\n    border:none;\n    border-bottom:1px solid #9eadc0;\n}\nul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast {\n    list-style:none;\n    border-bottom:none;\n    padding-bottom:0;\n}\ntable tr td dl, table tr td dl dt, table tr td dl dd {\n    margin-top:0;\n    margin-bottom:1px;\n}\n/*\nTable styles\n*/\n.contentContainer table, .classUseContainer table, .constantValuesContainer table {\n    border-bottom:1px solid #9eadc0;\n    width:100%;\n}\n.contentContainer ul li table, .classUseContainer ul li table, .constantValuesContainer ul li table {\n    width:100%;\n}\n.contentContainer .description table, .contentContainer .details table {\n    border-bottom:none;\n}\n.contentContainer ul li table th.colOne, .contentContainer ul li table th.colFirst, .contentContainer ul li table th.colLast, .classUseContainer ul li table th, .constantValuesContainer ul li table th, .contentContainer ul li table td.colOne, .contentContainer ul li table td.colFirst, .contentContainer ul li table td.colLast, .classUseContainer ul li table td, .constantValuesContainer ul li table td{\n    vertical-align:top;\n    padding-right:20px;\n}\n.contentContainer ul li table th.colLast, .classUseContainer ul li table th.colLast,.constantValuesContainer ul li table th.colLast,\n.contentContainer ul li table td.colLast, .classUseContainer ul li table td.colLast,.constantValuesContainer ul li table td.colLast,\n.contentContainer ul li table th.colOne, .classUseContainer ul li table th.colOne,\n.contentContainer ul li table td.colOne, .classUseContainer ul li table td.colOne {\n    padding-right:3px;\n}\n.overviewSummary caption, .packageSummary caption, .contentContainer ul.blockList li.blockList caption, .summary caption, .classUseContainer caption, .constantValuesContainer caption {\n    position:relative;\n    text-align:left;\n    background-repeat:no-repeat;\n    color:#FFFFFF;\n    font-weight:bold;\n    clear:none;\n    overflow:hidden;\n    padding:0px;\n    margin:0px;\n}\ncaption a:link, caption a:hover, caption a:active, caption a:visited {\n    color:#FFFFFF;\n}\n.overviewSummary caption span, .packageSummary caption span, .contentContainer ul.blockList li.blockList caption span, .summary caption span, .classUseContainer caption span, .constantValuesContainer caption span {\n    white-space:nowrap;\n    padding-top:8px;\n    padding-left:8px;\n    display:block;\n    float:left;\n    background-image:url(resources/titlebar.gif);\n    height:18px;\n}\n.overviewSummary .tabEnd, .packageSummary .tabEnd, .contentContainer ul.blockList li.blockList .tabEnd, .summary .tabEnd, .classUseContainer .tabEnd, .constantValuesContainer .tabEnd {\n    width:10px;\n    background-image:url(resources/titlebar_end.gif);\n    background-repeat:no-repeat;\n    background-position:top right;\n    position:relative;\n    float:left;\n}\nul.blockList ul.blockList li.blockList table {\n    margin:0 0 12px 0px;\n    width:100%;\n}\n.tableSubHeadingColor {\n    background-color: #EEEEFF;\n}\n.altColor {\n    background-color:#eeeeef;\n}\n.rowColor {\n    background-color:#ffffff;\n}\n.overviewSummary td, .packageSummary td, .contentContainer ul.blockList li.blockList td, .summary td, .classUseContainer td, .constantValuesContainer td {\n    text-align:left;\n    padding:3px 3px 3px 7px;\n}\nth.colFirst, th.colLast, th.colOne, .constantValuesContainer th {\n    background:#dee3e9;\n    border-top:1px solid #9eadc0;\n    border-bottom:1px solid #9eadc0;\n    text-align:left;\n    padding:3px 3px 3px 7px;\n}\ntd.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover {\n    font-weight:bold;\n}\ntd.colFirst, th.colFirst {\n    border-left:1px solid #9eadc0;\n    white-space:nowrap;\n}\ntd.colLast, th.colLast {\n    border-right:1px solid #9eadc0;\n}\ntd.colOne, th.colOne {\n    border-right:1px solid #9eadc0;\n    border-left:1px solid #9eadc0;\n}\ntable.overviewSummary  {\n    padding:0px;\n    margin-left:0px;\n}\ntable.overviewSummary td.colFirst, table.overviewSummary th.colFirst,\ntable.overviewSummary td.colOne, table.overviewSummary th.colOne {\n    width:25%;\n    vertical-align:middle;\n}\ntable.packageSummary td.colFirst, table.overviewSummary th.colFirst {\n    width:25%;\n    vertical-align:middle;\n}\n/*\nContent styles\n*/\n.description pre {\n    margin-top:0;\n}\n.deprecatedContent {\n    margin:0;\n    padding:10px 0;\n}\n.docSummary {\n    padding:0;\n}\n/*\nFormatting effect styles\n*/\n.sourceLineNo {\n    color:green;\n    padding:0 30px 0 0;\n}\nh1.hidden {\n    visibility:hidden;\n    overflow:hidden;\n    font-size:.9em;\n}\n.block {\n    display:block;\n    margin:3px 0 0 0;\n}\n.strong {\n    font-weight:bold;\n}\n\n\n\n/*\n *\n * Custom values added to the original javadoc jdk7 css.\n * This style is inspired in the original Mockito javadoc style.\n * The following rules have the same specificity as the original ones\n * defined previously, and only override the required properties\n * to change the basic color/design.\n *\n */\n\n\ncode { \n    /*color: #777;*/\n    line-height: 1.286em; \n    font-family: \"Consolas\", \"Lucida Console\", \"Droid Sans Mono\", \"Andale Mono\", \"Monaco\", \"Lucida Sans Typewriter\"; \n}\n\ncode, tt {\n    font-size: 1.0em;\n}\n\npre { \n    color: #555;\n    font-size:1.0em;\n    line-height: 1.2em; \n    font-family: \"Lucida Console\", \"Droid Sans Mono\", \"Andale Mono\", \"Monaco\", \"Consolas\", \"Lucida Sans Typewriter\"; \n}\n\n.topNav {\n    background-image:none;\n    background-color:#dee3e9;\n    padding-top:5px;\n    padding-bottom:2px;\n    margin-bottom:5px;\n    height:2.0em;\n    color:#666;\n}\n\n.topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited {\n    color:#16569A;\n}\n\n.subNav {\n    background-color:#ffffff;\n}\n\n.navBarCell1    { \n    background-color:#E0E6DF; \n}\n\n.navBarCell1Rev {\n    background-image:none; \n    background-color:#16569A; \n    border:none;\n    margin:0;\n}\n\n.bottomNav {\n    display:none;\n}\n\na:hover, a:focus { \n    color:#EEEEEE; \n    background-color:#16569A;\n}\n\na:link {\n    text-decoration:none;\n}\n\n/* Original color CC3300 */\na:visited { \n    color:#f36126;\n}\n\na:visited:hover { \n    color: #fff; \n    background-color:#f36126;\n}\n\n/* Remove blue bar */\n.bar {\n    background-image:none;\n    background-color:#fff;\n    color:#333;\n}\n\n.bar a:hover, .bar a:focus {\n    color:#eeeeee;\n}\n\n.bar a, .bar a:link, .bar a:visited, .bar a:active {\n    color:#333;\n    text-decoration:none;\n}\n\n/* Remove gold color links */\n.topNav a:hover, .bottomNav a:hover {\n    text-decoration:none;\n    color:#eeeeee;\n}\n\n/* Remove tab images */\n.tab {\n    background-image:none;\n}\n\n.overviewSummary caption span, .packageSummary caption span, .contentContainer ul.blockList li.blockList caption span, .summary caption span, .classUseContainer caption span, .constantValuesContainer caption span {\n    display:none;\n}\n.overviewSummary .tabEnd, .packageSummary .tabEnd, .contentContainer ul.blockList li.blockList .tabEnd, .summary .tabEnd, .classUseContainer .tabEnd, .constantValuesContainer .tabEnd {\n    display:none;\n}\n\n\n/* Fix footer bug (overflow p) and increment the size of the font by 20% */\n.legalCopy {\n    font-size:120%;\n    float:left;\n    clear:both;\n}\n"
  },
  {
    "path": "src/site/markdown/citation.md",
    "content": "### Citation\n\nThe project was also accepted in the 9th Iberian Conference on Information Systems and Technologies (CISTI), 2014. \nIf you use this library in your research projects, we encourage you to please cite our work. \n\n> Rodriguez-Mier, P., Gonzalez-Sieira, A., Mucientes, M., Lama, M. & Bugarin, A. (2014). \n[Hipster: An Open Source Java Library for Heuristic Search](#). \n*9th Iberian Conference on Information Systems and Technologies (CISTI)*.\n\n<script src=\"https://gist.github.com/pablormier/945a3c2a80da630f44b8.js\"></script>"
  },
  {
    "path": "src/site/markdown/index.md",
    "content": "<div class=\"jumbotron\">\n    <div class=\"container\">\n        <center>\n            <p><img alt=\"\" src=\"img/hipster-no-text.png\"></img></p>\n            <p>An Open Source Java Library for Heuristic Search</p>\n            <p>\n                <a class=\"btn btn-blue btn-lg\" href=\"http://goo.gl/eIPKas\" role=\"button\">Download Hipster</a>\n                <a class=\"btn btn-primary btn-lg\" href=\"http://goo.gl/KRwd50\" role=\"button\">Download Source</a>\n            </p>\n        </center>\n\n        <center>\n            <a class=\"media-icon\" href=\"https://twitter.com/hipster4j\" target=\"_blank\" title=\"Hipster on Twitter\"><img src=\"img/twitter.png\" alt=\"twitter\"/></a>\n            <a class=\"media-icon\" href=\"https://plus.google.com/103153744967420864206\" rel=\"publisher\" target=\"_blank\" title=\"Hipster on Google+\"><img src=\"img/googleplus.png\" alt=\"google plus\"/></a>\n            <a class=\"media-icon\" href=\"https://www.youtube.com/channel/UCJeACNvmSZCW9gevIIjXQ1w\" target=\"_blank\" title=\"Hipster on Youtube\"><img src=\"img/youtube.png\" alt=\"youtube\"/></a>\n        </center>\n    </div>\n</div>\n\n---\n\n## <i class=\"fa fa-rocket\"></i> Powerful\n\nHipster is an easy to use yet powerful and flexible type-safe library for\nheuristic search, written in pure Java. Hipster relies on a flexible model with generic operators that allow you to\nreuse and change the behavior of the algorithms very easily. Just define how your problem\nis and let Hipster do the job.\n\n## <i class=\"fa fa-cogs\"></i> Modular\n\nAll the components to define a search problem are clearly\ndefined and separated across different [Maven modules](http://maven.apache.org/). Just pick up\nthe components you need and create your algorithm from scratch or\nby reusing other algorithms included in Hipster.\n\n## <i class=\"fa fa-github-alt\"></i> Open Source\n\nHipster comes with a permissive [Apache 2.0 license](license.html) that allows you\nto use the library in a wide variety of commercial and\nnon-commercial projects. All the source code of this library\nis hosted in [GitHub](http://www.github.com/citiususc/hipster).\nPlease feel free to contribute to this project by\nreporting issues, requesting new features or by developing your own\nalgorithms.\n\n---\n\n## Quick Start\n\nThe easiest way to use Hipster is adding it as a dependency with your favourite dependency manager.\nMaven users can include the library using the following snippet:\n\n<script src=\"https://gist.github.com/pablormier/11350229.js\"></script>\n\nThis gives you the full features of Hipster to start using, extending and improving search\nalgorithms. Here you have a simple example of how to find the shortest path in a directed graph with Hipster:\n\n<script src=\"https://gist.github.com/pablormier/10107318.js\"></script>\n\nHipster comes also with different adapters to work with [Blueprints](https://github.com/tinkerpop/blueprints)\nand [JUNG](http://jung.sourceforge.net/) graph libraries. However,\nHipster is not limited to graph search. You can do much more!. Define your problem\nin terms of actions, states and transitions and apply different search strategies to solve them fast!.\nCheck out some examples included in Hipster, like the N-Puzzle, N-Queens or Maze Search.\n\n---\n\n### About this project\n\nDuring our PhD thesis, we have found that there is a lack of Java libraries\nthat implement search algorithms with an extensible, flexible and simple to use model.\nMoreover, most of the libraries rely on graph structures or recursive implementations \nwhich do not offer fine-grained control over the\nalgorithm. This is why we decided to make our little contribution in this field.\nAlthough Hipster is far from being perfect, we hope you find it useful.\n\nHipster was originally created and is currently maintained by:\n\n-   **Pablo Rodriguez-Mier** - Computer Science PhD student at CITIUS.\n-   **Adrian Gonzalez-Sieira** - Computer Science PhD student at CITIUS.\n\nThe scientific supervisors of this project are listed below:\n\n-   **Dr. Manuel Mucientes**\n-   **Dr. Manuel Lama**\n-   **Dr. Alberto Bugarín**\n\nThe project was also accepted in the\n[_9th Iberian Conference on Information Systems and Technologies (CISTI), 2014_](http://www.aisti.eu/cisti2014).\nIf you use this library in your research projects, we encourage you to please cite our\nwork :). Check the [citation](citation.html) page for more information.\n\n### Related projects\n\nHere you have a list of similar or complementary open source projects for Java which\nyou might find useful:\n\n-   [**AIMA-JAVA**](https://code.google.com/p/aima-java/) - A comprehensive collection of different algorithms from the book _\"Artificial Intelligence, A Modern Approach\"_.\n-   [**JUNG**](http://jung.sourceforge.net/) - A Java library for graph processing. It also includes shortest path algorithms such as Dijkstra or A\\*.\n\n<center>\n    <p>This software is tested and profiled using JProfiler</p>\n    <a href=\"http://www.ej-technologies.com/products/jprofiler/overview.html\"><img src = \"http://static-aws.ej-technologies.com/fSPWWYHqc7hE2dXygJb0KGSIf3TPEGUnaU62MxxGsIv.png\"></img></a>\n</center>\n"
  },
  {
    "path": "src/site/resources/css/site.css",
    "content": "@import url(\"http://fonts.googleapis.com/css?family=Lobster|Cabin:400,700\");\n\n.color-highlight {\n\tcolor: #225E9B;\n}\n\nbody {\n\tbackground-image:url(../images/bg.png);\n}\n\nbody[class*=\"page-themes-bootswatch\"] {\n\tbackground-image: none;\n}\n\nbody[class*=\"page-themes-bootswatch\"] .color-highlight {\n\tcolor: inherit;\n}\n\n.thumbnail-row {\n\tmargin-top: 10px;\n}\n\n/*h1, */h2 {\n  margin-top: 30px;\n}\n\nh3, h4, h5, h6 {\n  margin-top: 20px;\n}\n\n.carousel-caption a {\n  color: white;\n}\n\n\n/* Workarounds from http://andriusvelykis.github.io/reflow-maven-skin/css/site.css */\n\n.project-reflow-parent.page-index h2[id]:before {\n  height: 30px;\n  margin-top: -30px;\n}\n\n.project-reflow-parent.page-index .sidebar {\n  margin-top: 10px;\n}\n\n.project-reflow-parent.page-index .sidebar {\n  margin-top: 10px;\n}\n\n.project-reflow-parent.page-index .sidebar h3 {\n  margin-top: 10px;\n}\n\n\n@media (min-width: 980px) {\n  .page-themes-bootswatch-readable .navbar.affix {\n    top: 60px;\n  }\n\n  .page-themes-bootswatch-cerulean .navbar.affix {\n    top: 50px;\n  }\n\n  .page-themes-bootswatch-spruce .navbar.affix {\n    top: 55px;\n  }\n}\n\n/* Change fonts */\n\nh1,\nh2,\nh3,\nh4,\nh5,\nh6,\n.h1,\n.h2,\n.h3,\n.h4,\n.h5,\n.h6 {\n  font-family: 'Lobster', cursive;\n  font-weight: 500;\n  line-height: 1.1;\n}\n\nlegend {\n  font-family: 'Lobster', cursive;\n  font-size: 22.5px;\n}\n\n.navbar-brand {\n  font-family: 'Lobster', cursive;\n  font-size: 19px;\n  line-height: 21px;\n}\n\nbody {\n  font-family: \"Cabin\", Arial, sans-serif;\n  font-size: 14px;\n}\n\n/* Jumbotron style from Bootstrap 3 */\n\n.jumbotron {\n  padding: 30px;\n  margin-bottom: 30px;\n  color: inherit;\n  background-color: #eee;\n}\n.jumbotron h1,\n.jumbotron .h1 {\n  color: inherit;\n}\n.jumbotron p {\n  margin-bottom: 15px;\n  font-size: 21px;\n  font-weight: 200;\n}\n.container .jumbotron {\n  border-radius: 6px;\n}\n.jumbotron .container {\n  max-width: 100%;\n}\n@media screen and (min-width: 768px) {\n  .jumbotron {\n    padding-top: 48px;\n    padding-bottom: 48px;\n  }\n  .container .jumbotron {\n    padding-right: 60px;\n    padding-left: 60px;\n  }\n  .jumbotron h1,\n  .jumbotron .h1 {\n    font-size: 63px;\n  }\n}\n\n/* Custom style */\n\npre.clean {\n    padding: 0;\n    background-color: transparent;\n    border: 0;\n    border-color: transparent;\n}\n\n.main-body .fa {\n    margin-right: .5em;\n}\n\n.gist .gist-file .gist-data {\n    background-color: transparent !important;\n }\n\n .btn-blue {\n \tcolor: #FFFFFF;\n \ttext-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);\n \tbackground-color: #435A6E;\n \t*background-color: #435A6E;\n \tbackground-image: -moz-linear-gradient(top, #8EAFCC, #435A6E);\n \tbackground-image: -webkit-gradient(linear, 0 0, 0 100%, from(#8EAFCC), to(#435A6E));\n \tbackground-image: -webkit-linear-gradient(top, #8EAFCC, #435A6E);\n \tbackground-image: -o-linear-gradient(top, #8EAFCC, #435A6E);\n \tbackground-image: linear-gradient(to bottom, #8EAFCC, #435A6E);\n \tbackground-repeat: repeat-x;\n \tborder-color: #435A6E;\n \tborder-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);\n \tfilter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8EAFCC', endColorstr='#435A6E', GradientType=0);\n \tfilter: progid:DXImageTransform.Microsoft.gradient(enabled=false);\n }\n .btn-blue:hover,\n .btn-blue:focus,\n .btn-blue:active,\n .btn-blue.active,\n .btn-blue.disabled,\n .btn-blue[disabled] {\n \tcolor: #FFFFFF;\n \tbackground-color: #435A6E;\n \t*background-color: #003bb3;\n }\n\n .media-icon{\n      padding-left: 10px;\n      padding-right: 10px;\n }"
  },
  {
    "path": "src/site/site.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<!--\n  ~ Copyright 2014 CITIUS <http://citius.usc.es>, University of Santiago de Compostela.\n  ~\n  ~    Licensed under the Apache License, Version 2.0 (the \"License\");\n  ~    you may not use this file except in compliance with the License.\n  ~    You may obtain a copy of the License at\n  ~\n  ~        http://www.apache.org/licenses/LICENSE-2.0\n  ~\n  ~    Unless required by applicable law or agreed to in writing, software\n  ~    distributed under the License is distributed on an \"AS IS\" BASIS,\n  ~    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  ~    See the License for the specific language governing permissions and\n  ~    limitations under the License.\n  -->\n\n<project xmlns=\"http://maven.apache.org/DECORATION/1.3.0\"\n         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/DECORATION/1.3.0 http://maven.apache.org/xsd/decoration-1.3.0.xsd\">\n\n    <skin>\n        <groupId>lt.velykis.maven.skins</groupId>\n        <artifactId>reflow-maven-skin</artifactId>\n        <version>1.1.0</version>\n    </skin>\n\n    <publishDate position=\"bottom\" format=\"yyyy-MM-dd\" />\n    <version position=\"bottom\" />\n    <googleAnalyticsAccountId>UA-54364281-1</googleAnalyticsAccountId>\n\n    <custom>\n        <reflowSkin>\n            <smoothScroll>true</smoothScroll>\n            <theme>bootswatch-united</theme>\n\n            <brand>\n                <name>Hipster</name>\n                <href>http://www.github.com/citiususc/hipster</href>\n            </brand>\n            <slogan>An Open Source Java Library for Heuristic Search</slogan>\n            <titleTemplate>%2$s | %1$s</titleTemplate>\n            <!-- Use Table of Contents at the top of the page (max 6 elements) -->\n            <toc>top</toc>\n            <tocTopMax>6</tocTopMax>\n\n            <bottomDescription>\n                The Open Source Heuristic Search Library implemented in pure Java.\n            </bottomDescription>\n            <pages>\n                <index project=\"hipster-pom\">\n                    <!-- Override the title -->\n                    <titleTemplate>Hipster</titleTemplate>\n                    <!-- no breadcrumbs on the main index page -->\n                    <breadcrumbs>false</breadcrumbs>\n                    <!-- no ToC on the main index page -->\n                    <toc>false</toc>\n                    <markPageHeader>false</markPageHeader>\n                    <sections>\n                        <columns>1</columns>\n                        <columns>3</columns>\n                        <body />\n                        <sidebar />\n                    </sections>\n                </index>\n                <contribute>\n                    <breadcrumbs>false</breadcrumbs>\n                </contribute>\n                <issue-tracking>\n                    <highlightJs>false</highlightJs>\n                    <toc>false</toc>\n                </issue-tracking>\n                <license>\n                    <toc>false</toc>\n                </license>\n                <!-- Disable ToC for some Maven reports -->\n                <project-info>\n                    <toc>false</toc>\n                </project-info>\n                <github-report>\n                    <toc>false</toc>\n                </github-report>\n                <dependencies>\n                    <tocTopMax>4</tocTopMax>\n                </dependencies>\n            </pages>\n        </reflowSkin>\n    </custom>\n\n    <body>\n        <head>\n            <link href=\"http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css\" rel=\"stylesheet\"/>\n            <link rel=\"stylesheet\" href=\"http://yandex.st/highlightjs/8.0/styles/obsidian.min.css\" />\n        </head>\n\n        <links>\n            <item name=\"Hipster on GitHub\" href=\"http://www.github.com/citiususc/hipster\" />\n        </links>\n\n        <breadcrumbs>\n            <item name=\"Hipster\" href=\"/\" />\n        </breadcrumbs>\n\n        <menu name=\"Project info\" ref=\"reports\" inherit=\"bottom\"/>\n    </body>\n\n</project>"
  }
]