diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..ba0a163 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,97 @@ +root = true + +[*] +ij_continuation_indent_size = 8 +ij_formatter_off_tag = @formatter:off +ij_formatter_on_tag = @formatter:on +ij_formatter_tags_enabled = true +ij_smart_tabs = false +ij_wrap_on_typing = false + +[{*.kt,*.kts}] +ktlint_code_style = intellij_idea +ktlint_standard_multiline-if-else = disabled +ktlint_standard_final-newline = disabled +ij_kotlin_align_in_columns_case_branch = false +ij_kotlin_align_multiline_binary_operation = false +ij_kotlin_align_multiline_extends_list = false +ij_kotlin_align_multiline_method_parentheses = false +ij_kotlin_align_multiline_parameters = true +ij_kotlin_align_multiline_parameters_in_calls = false +ij_kotlin_allow_trailing_comma = false +ij_kotlin_allow_trailing_comma_on_call_site = false +ij_kotlin_assignment_wrap = normal +ij_kotlin_blank_lines_after_class_header = 0 +ij_kotlin_blank_lines_around_block_when_branches = 0 +ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_line = 1 +ij_kotlin_block_comment_add_space = false +ij_kotlin_block_comment_at_first_column = true +ij_kotlin_call_parameters_new_line_after_left_paren = true +ij_kotlin_call_parameters_right_paren_on_new_line = true +ij_kotlin_call_parameters_wrap = on_every_item +ij_kotlin_catch_on_new_line = false +ij_kotlin_class_annotation_wrap = split_into_lines +ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL +ij_kotlin_continuation_indent_for_chained_calls = false +ij_kotlin_continuation_indent_for_expression_bodies = false +ij_kotlin_continuation_indent_in_argument_lists = false +ij_kotlin_continuation_indent_in_elvis = false +ij_kotlin_continuation_indent_in_if_conditions = false +ij_kotlin_continuation_indent_in_parameter_lists = false +ij_kotlin_continuation_indent_in_supertype_lists = false +ij_kotlin_else_on_new_line = false +ij_kotlin_enum_constants_wrap = off +ij_kotlin_extends_list_wrap = normal +ij_kotlin_field_annotation_wrap = split_into_lines +ij_kotlin_finally_on_new_line = false +ij_kotlin_if_rparen_on_new_line = true +ij_kotlin_import_nested_classes = false +ij_kotlin_imports_layout = *,java.**,javax.**,kotlin.**,^ +ij_kotlin_insert_whitespaces_in_simple_one_line_method = true +ij_kotlin_keep_blank_lines_before_right_brace = 2 +ij_kotlin_keep_blank_lines_in_code = 2 +ij_kotlin_keep_blank_lines_in_declarations = 2 +ij_kotlin_keep_first_column_comment = true +ij_kotlin_keep_indents_on_empty_lines = false +ij_kotlin_keep_line_breaks = true +ij_kotlin_lbrace_on_next_line = false +ij_kotlin_line_break_after_multiline_when_entry = true +ij_kotlin_line_comment_add_space = false +ij_kotlin_line_comment_add_space_on_reformat = false +ij_kotlin_line_comment_at_first_column = true +ij_kotlin_method_annotation_wrap = split_into_lines +ij_kotlin_method_call_chain_wrap = normal +ij_kotlin_method_parameters_new_line_after_left_paren = true +ij_kotlin_method_parameters_right_paren_on_new_line = true +ij_kotlin_method_parameters_wrap = on_every_item +ij_kotlin_name_count_to_use_star_import = 5 +ij_kotlin_name_count_to_use_star_import_for_members = 3 +ij_kotlin_packages_to_use_import_on_demand = java.util.*,kotlinx.android.synthetic.**,io.ktor.** +ij_kotlin_parameter_annotation_wrap = off +ij_kotlin_space_after_comma = true +ij_kotlin_space_after_extend_colon = true +ij_kotlin_space_after_type_colon = true +ij_kotlin_space_before_catch_parentheses = true +ij_kotlin_space_before_comma = false +ij_kotlin_space_before_extend_colon = true +ij_kotlin_space_before_for_parentheses = true +ij_kotlin_space_before_if_parentheses = true +ij_kotlin_space_before_lambda_arrow = true +ij_kotlin_space_before_type_colon = false +ij_kotlin_space_before_when_parentheses = true +ij_kotlin_space_before_while_parentheses = true +ij_kotlin_spaces_around_additive_operators = true +ij_kotlin_spaces_around_assignment_operators = true +ij_kotlin_spaces_around_equality_operators = true +ij_kotlin_spaces_around_function_type_arrow = true +ij_kotlin_spaces_around_logical_operators = true +ij_kotlin_spaces_around_multiplicative_operators = true +ij_kotlin_spaces_around_range = false +ij_kotlin_spaces_around_relational_operators = true +ij_kotlin_spaces_around_unary_operator = false +ij_kotlin_spaces_around_when_arrow = true +ij_kotlin_variable_annotation_wrap = off +ij_kotlin_while_on_new_line = false +ij_kotlin_wrap_elvis_expressions = 1 +ij_kotlin_wrap_expression_body_functions = 1 +ij_kotlin_wrap_first_method_in_call_chain = false diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..8337b80 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,9 @@ +#!/bin/bash +echo "Running git pre-commit hook" +./gradlew ktlintCheck +ktlintCheckStatus=$? +if [[ $ktlintCheckStatus -ne 0 ]]; then + exit 1 +else + exit 0 +fi \ No newline at end of file diff --git a/.github/mergeable.yml b/.github/mergeable.yml new file mode 100644 index 0000000..35a16f8 --- /dev/null +++ b/.github/mergeable.yml @@ -0,0 +1,15 @@ +version: 2 +mergeable: + - when: pull_request.* + name: 'Check decoration' + validate: + - do: title + must_exclude: + regex: ^\[WIP\] + - do: label + must_exclude: + regex: 'wip' + - do: description + no_empty: + enabled: true + message: Description matter and should not be empty. Provide detail with **what** was changed, **why** it was changed, and **how** it was changed. diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..bab44e1 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,36 @@ +name: Main +on: + pull_request: + branches: [ main,development ] + + push: + branches: [ main,development ] +jobs: + Lint: + name: Lint + runs-on: ubuntu-latest + steps: + - name: Checkout project sources + uses: actions/checkout@v4 + - name: Start lint + run: ./gradlew ktlintCheck + + Tests: + name: Tests and Coverage + runs-on: ubuntu-latest + steps: + - name: Checkout project sources + uses: actions/checkout@v4 + - name: Run test + id : runtest + run: ./gradlew test + continue-on-error: true + - name : Display tests results + run: python3 ./scripts/test-result-printer.py --dir ./build/test-results/test --all-failures + - name: Run jacoco coverage report + run: ./gradlew jacocoTestReport + - name: Display info about coverage + run: python3 ./scripts/csv-reports-printer.py --input ./build/reports/jacoco/test/jacocoTestReport.csv + - name : Failure at least one test fails + if: steps.runtest.outcome != 'success' + run: exit 1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c7828f5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/ +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..ce1c62c --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,16 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml new file mode 100644 index 0000000..fe63bb6 --- /dev/null +++ b/.idea/kotlinc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..9d5d112 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..5ba7916 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,11 @@ +# Contributing +Rules of contributing to our project. +1. If you want to add your own feature or fix something in our code, please create your own branch to do it. +2. Please avoid verbs in commits' names ("project initialization" instead of "initialize project" or "initialized project") +3. Once your branch is complete, you can make a pull request and wait for it to be reviewed. +4. Description of pull request is required to be written. +5. Your commits and pull requests must be named and described in English. +6. Your naming of commits and pull requests must be logical and reasonable. Use conventional commits, please. +7. Please use "git commit -s" option. +8. Don't merge your pull request before your code has been reviewed. +9. If you are in doubt what to do, it's better to text developers. \ No newline at end of file diff --git a/DOCS.md b/DOCS.md new file mode 100644 index 0000000..994cc99 --- /dev/null +++ b/DOCS.md @@ -0,0 +1,82 @@ +# Documentation + +You need to clone our repository and run the app using + +``` +./gradlew run +``` + +## How to use + +Firstly, you need to choose a graph + +![graph-choose](src/main/resources/graph-choose.png) + +## Undirected unweighted graph + +Here is the example of our graph window + +![graph](src/main/resources/graph.png) + +If you click "Reset", graph will become as it was before you started manipulating it. + +If you click "Algorithms", you will be suggested to use algorithms of this graph + +![graph-algos](src/main/resources/graph-algos.png) + +### Bridges + +Bridge edges are highlighted with red color. + +![bridge](src/main/resources/bridge.png) + +### Cycles search for given vertex + +You are suggested to put in a number of chosen vertex + +![cycles-vertex-choose.png](src/main/resources/cycle-vertex-choose.png) + +Then you receive highlighted cycle of this vertex, or vertex becomes highlighted with blue color if it doesn't belong to any cycle + +![cycle](src/main/resources/cycle.png) + +### Key vertices selection + +You receive highlighted key vertices of this graph + +![key-vertices](src/main/resources/key-vertices.png) + +## Directed unweighted graph + +Directed graph has some undirected graph algorithms, but also there is selection of strongly connected components. + +### Strongly connected components selection + +Each component is highlighted with its unique color. + +![scc](src/main/resources/scc.png) + +## Undirected weighted graph + +In weighted graph, you can see weights of edges + +![edges-weights](src/main/resources/edges-weights.png) + +### Minimal spanning tree construction + +Included edges are highlighted with red + +![mst](src/main/resources/mst.png) + +### Path finding + +To find a path, you need to pick source and destination vertices + +![path-vertices](src/main/resources/path-vertices.png) + +Path is highlighted. Notice that we don't support negative weights for path finding in undirected graph. + +![path](src/main/resources/path.png) + +## Weighted directed graph +All its algorithms are already explained above \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..16df502 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,9 @@ +# The MIT License (MIT) + +Copyright © 2024 Vyacheslav Kochergin, Vadim Marchenko, Dmitri Kuznetsov. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..29e0d0f --- /dev/null +++ b/README.md @@ -0,0 +1,179 @@ +# Graphs visualizer app + +This app is a graph visualizer with ability to analyze the graph. + +## Table of contents + +* [Functionality](#functionality) +* [File structure](#filestructure) +* [How to use](#howtouse) +* [Technologies used in the library](#technologies) +* [Our team and responsibility areas](#team) +* [Project status](#status) +* [Contributing](#contributing) +* [License](#license) + +## Functionality + +We provide the opportunity to solve these problems with our app: + +* Selecting key vertices of the graph. +* Selecting strongly connected components (directed graph). +* Searching for bridges (undirected graph). +* Search for cycles for a given vertex. +* Construction of a minimal spanning tree (weighted undirected graph). +* Finding the shortest path between a pair of vertices (weighted graph). We also support negative weights (only directed + graph). + +## File structure + +``` +src +├── main/kotlin +│ │ +│ ├── model +│ │ ├── algorithms +│ │ │ ├── bridgeFinder +│ │ │ │ ├── BridgeFinder.kt // bridge finding algorithm implementation +│ │ │ │ +│ │ │ ├── keyVerticesSelection +│ │ │ │ ├── KeyVerticesSelectionSolver.kt // key vertices selection algorithm implementation +│ │ │ │ +│ │ │ ├── kruskalAlgorithm +│ │ │ │ ├── KruskalALgorithmSolver.kt // minimal spanning tree building algorithm implementation +│ │ │ │ +│ │ │ ├── pathSearch +│ │ │ │ ├── djikstra +│ │ │ │ │ ├── DjikstraAlgorithm.kt // finding path between two vertices without negative weights for undirected graph algorithm implementation +│ │ │ │ │ +│ │ │ │ ├── fordBellman +│ │ │ │ │ ├── FordBellmanAlgorithm.kt // finding path between two vertices with negative weights for directed graph algorithm implementation +│ │ │ │ │ +│ │ │ │ ├── PathResult.kt // result of finding path class, same for both algorithms +│ │ │ │ +│ │ │ ├── searchCycle +│ │ │ │ ├── SearchCycleForVertexInDirectedGraphSolver.kt // searching cycle for given vertex in directed graph algorithm implementation +│ │ │ │ ├── SearchCycleForVertexInGraphSolver.kt // searching cycle for given vertex algorithm implementation +│ │ │ │ +│ │ │ ├── stronglyConnectedComponentsSelection +│ │ │ │ ├── StronglyConnectedComponentsSelectionSolver.kt // strongly connected components selection algorithm implementation +│ │ │ +│ │ ├── graphs +│ │ │ ├── edges +│ │ │ │ ├── Edge.kt // unweighted edge class +│ │ │ │ ├── WeightedEdge.kt // weighted edge class +│ │ │ │ +│ │ │ ├── graphs +│ │ │ │ ├── AbstractGraph.kt // abstract graph class +│ │ │ │ ├── DirectedGraph.kt // directed graph class +│ │ │ │ ├── Graph.kt // graph class +│ │ │ │ ├── WeightedDirectedGraph.kt // weighted directed graph class +│ │ │ │ ├── WeightedGraph.kt // weighted graph class +│ │ │ │ +│ │ │ ├── vertex +│ │ │ │ ├── Vertex.kt // vertex class +│ │ +│ ├── view +│ │ ├── graphView +│ │ │ ├── edgesView +│ │ │ │ ├── DirectedEdgeView.kt // directed edge view +│ │ │ │ ├── EdgeView.kt // edge view +│ │ │ │ +│ │ │ ├── graphsView +│ │ │ │ ├── GraphView.kt // graph view +│ │ │ │ ├── WeightedGraphView.kt // weighted graph view +│ │ │ │ +│ │ │ ├── VertexView.kt // vertex view +│ │ │ +│ │ ├── screens +│ │ │ ├── mainScreens +│ │ │ │ ├── MainScreen.kt // main screen +│ │ │ │ ├── MainScreenWeightedGraph.kt // main screen with weighted graph +│ │ │ │ +│ │ │ ├── GraphChooseScreen.kt // graph type choose screen +│ │ +│ ├── viewModel +│ │ ├── graphViewModel +│ │ │ ├── edgesViewModel +│ │ │ │ ├── EdgeViewModel.kt // edge viewmodel class +│ │ │ │ ├── WeightedEdgeViewModel.kt // edge viewmodel class +│ │ │ │ +│ │ │ ├── graphsViewModel +│ │ │ │ ├── GraphViewModel.kt // graph viewmodel class +│ │ │ │ ├── WeightedGraphViewModel.kt // weighted graph viewmodel class +│ │ │ │ +│ │ │ ├── CircularPlacementStrategy.kt // circular placement strategy class +│ │ │ ├── RepresentationStrategy.kt // representation strategy interface +│ │ │ ├── VertexViewModel.kt // vertex viewmodel class +│ │ │ +│ │ ├── screensViewModels +│ │ │ ├── mainScreensViewModels +│ │ │ │ ├── MainScreenViewModel.kt // main screen viewmodel class +│ │ │ │ ├── MainScreenViewModelWeightedGraph // main screen with weighted graph viewmodel class +│ │ │ │ +│ │ │ ├── GraphChooseViewModel.kt // graph choose window viewmodel class +│ │ +│ ├── Main.kt // entry point, main app file +│ +├── test/kotlin +│ ├── algorithmsTests +│ │ ├── BridgeFinderTests.kt // bridge finding tests +│ │ ├── DjikstraTests.kt.kt // Dijkstra algorithm tests +│ │ ├── FordBellmanTests.kt // Ford-Bellman algorithm tests +│ │ ├── KeyVerticesSelectionSolverDirectedGraphTests.kt // key vertices selection in directed graph +│ │ ├── KeyVerticesSelectionSolverTests.kt // key vertices selection tests +│ │ ├── KruskalAlgorithmSolverTests.kt // MST building tests +│ │ ├── SearchCycleForVertexInDirectedGraphSolverTests.kt // cycle search in directed graph tests +│ │ ├── SearchCycleForVertexInGraphSolverTests.kt // cycle search in graph tests +│ │ ├── StronglyConnectedComponentsSelectionSolverTests.kt // strongly connected components selection tests +│ │ +│ ├── graphsTests +│ │ ├── AbstractGraphTests.kt // abstract graph tests +│ │ ├── AbstractWeightedGraphTests.kt // abstract weighted graph tests +│ │ ├── DirectedGraphTests.kt // directed graph tests +│ │ ├── GraphTests.kt // graph tests +│ │ ├── WeightedDirectedGraphTests.kt // weighted directed graph tests +│ │ ├── WeightedGraphTests.kt // weighted graph tests +│ │ +``` + +## How to use + +See [DOCS.md](./DOCS.md) + +## Technologies used in the library + +* [Kotlin 1.9.23](https://kotlinlang.org) +* [Gradle 8.5](https://gradle.org) +* [JDK 17](https://openjdk.org) +* [Jetpack Compose](https://developer.android.com/develop/ui/compose) +* [ktlint](https://github.com/pinterest/ktlint) + +## Our team and responsibility areas + +* Vyacheslav Kochergin - key vertices selection, strongly connected components selection, finding the shortest path with + negative weights, GUI, + documentation. [GitHub](https://github.com/VyacheslavIurevich), [Contact](https://t.me/se4life). +* Vadim Marchenko - .json graph storage, searching for bridges, finding the shortest path without negative weights, + CI. [GitHub](https://github.com/elbananium), [Contact](https://t.me/elbananum). +* Dmitri Kuznetsov - searching cycles for given vertex, minimal spanning tree + construction. [GitHub](https://github.com/f1i3g3), [Contact](https://t.me/f1i3g3). + +## Project status + +Ready to be checked (as much as we managed to do in time). + +## Contributing + +See [CONTRIBUTING.md](./CONTRIBUTING.md) + +## License + +See [LICENSE.md](./LICENSE.md) + +## Acknowledgements + +Huge thanks to [@IliaSuponeff](https://github.com/IliaSuponeff) +from [Team 12](https://github.com/spbu-coding-2023/graphs-graphs-12/) for allowing us to use his scripts for CI ( +distributed under the MIT license). Also we have our GUI based on developments +from [gui-workshop](https://github.com/spbu-coding-2023/gui-workshop) repository (distributed under the MIT license). \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..9779e07 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,73 @@ +import org.jetbrains.compose.desktop.application.dsl.TargetFormat +import org.jlleitschuh.gradle.ktlint.reporter.ReporterType + +plugins { + kotlin("jvm") version "1.9.23" + id("org.jlleitschuh.gradle.ktlint") version "12.1.1" + kotlin("plugin.serialization") version "1.9.23" + id("org.jetbrains.compose") + jacoco +} + +group = "org.example" +version = "1.0-SNAPSHOT" + +repositories { + mavenCentral() + maven("https://maven.pkg.jetbrains.space/public/p/compose/dev") + google() +} + +dependencies { + implementation(files("libs/gephi-toolkit-0.10.0-all.jar")) + testImplementation(kotlin("test")) + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3") + implementation(compose.desktop.currentOs) +} + +compose.desktop { + application { + mainClass = "MainKt" + + nativeDistributions { + targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb) + packageName = "graph_demo" + packageVersion = "1.0.0" + } + } +} + +tasks.test { + useJUnitPlatform() +} +tasks.jacocoTestReport { + reports { + csv.required = true + xml.required = false + html.required = false + } +} + +configure { + debug.set(true) + verbose.set(true) + android.set(false) + outputToConsole.set(true) + outputColorName.set("RED") + enableExperimentalRules.set(true) + reporters { + reporter(ReporterType.PLAIN) + reporter(ReporterType.CHECKSTYLE) + } + kotlinScriptAdditionalPaths { + include(fileTree("scripts/")) + } + filter { + exclude("**/generated/**") + include("**/kotlin/**") + } +} + +kotlin { + jvmToolchain(17) +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..1179899 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,2 @@ +kotlin.code.style=official +compose.version=1.6.2 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..49cda23 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Apr 23 22:12:14 MSK 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/libs/gephi-toolkit-0.10.0-all.jar b/libs/gephi-toolkit-0.10.0-all.jar new file mode 100644 index 0000000..7489213 Binary files /dev/null and b/libs/gephi-toolkit-0.10.0-all.jar differ diff --git a/scripts/csv-reports-printer.py b/scripts/csv-reports-printer.py new file mode 100644 index 0000000..4ee0bbe --- /dev/null +++ b/scripts/csv-reports-printer.py @@ -0,0 +1,198 @@ +import argparse +import csv +import sys +import typing +from text_colorize import ANSIColors, TextStyle, colorize + + +COLUMNS_TYPES = [ + '_MISSED', + '_COVERED', +] + +CSV_COLUMNS = [ + 'PACKAGES', + 'CLASS', + 'BRANCH_MISSED', + 'BRANCH_COVERED', + 'LINE_MISSED', + 'LINE_COVERED', + 'METHOD_MISSED', + 'METHOD_COVERED', +] +DISPLAY_COLUMNS = [ + 'PACKAGES', + 'CLASS', + 'BRANCH', + 'LINE', + 'METHOD', +] +DEFAULT_LABEL_SIZE = 8 + + +def create_row_info() -> dict: + return { + key: 0 for key in CSV_COLUMNS + } + + +def is_valid_lib(group: str, lib_name: str) -> bool: + if len(lib_name) == 0: + return True + return group == lib_name + + +def parse_args(args: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser( + prog="CSV Jacoco Test Reports Printer", + description="Program read csv file with jacoco report and print it at terminal at stdin", + ) + + parser.add_argument( + "-i", "--input", required=True, + help="setup path to CSV file with jacoco report information", + metavar="" + ) + parser.add_argument( + "-l", "--lib", + help="setup library name to remove from package path", + default="", + metavar="" + ) + parser.add_argument( + "-p", "--package-print", + help="setup flag to 'ON' to print packages of files at report (default 'OFF')", + action='store_true', + default=False + ) + + return parser.parse_args(args) + + +def read_csv(namespace: argparse.Namespace) -> typing.Optional[dict]: + table = [] + max_packages_name_length = 20 + max_classes_name_length = 20 + + with open(getattr(namespace, "input"), 'r') as file: + reader = csv.reader(file) + for row in reader: + if len(row) == 0: + break + if (row[0] == "GROUP") or not is_valid_lib(row[0], getattr(namespace, "lib", "")): + continue + + row_info = create_row_info() + is_skipped = False + for key in row_info.keys(): + if key not in CSV_COLUMNS: + row_info.pop(key) + + index = CSV_COLUMNS.index(key) + 1 + row_info[key] = row[index] + + if key == "PACKAGES": + max_packages_name_length = max(max_packages_name_length, len(row_info[key])) + elif key == "CLASS": + if '(' in row_info[key] or ')' in row_info[key] or ' ' in row_info[key]: + is_skipped = True + break + elif '.' in row_info[key]: + row_info[key] = row_info[key].split('.')[-1] + + max_classes_name_length = max(max_classes_name_length, len(row_info[key])) + + if not is_skipped: + table.append(row_info) + return { + "table": table, + "max_packages_name_length": max_packages_name_length, + "max_classes_name_length": max_classes_name_length + } + + +def create_label(text: str, lbl_size: int, color: ANSIColors = ANSIColors.BLACK): + if len(text) >= lbl_size: + text = text[:lbl_size] + + if len(text) % 2 != 0: + text = ' ' + text + + color_text = colorize( + f"{{:^{lbl_size}}}".format(text), + color, + TextStyle.BOLD + ) + return f'| {color_text} |' + + +def colorize_percent_label(percent: int) -> str: + color = ANSIColors.RED + if 50 <= percent < 75: + color = ANSIColors.YELLOW + elif 75 <= percent <= 100: + color = ANSIColors.GREEN + + return create_label(f"{percent}%", DEFAULT_LABEL_SIZE, color) + + +def display_columns(max_packages_name_length: int, max_classes_name_length: int) -> int: + global DISPLAY_COLUMNS, DEFAULT_LABEL_SIZE + for column in DISPLAY_COLUMNS: + lbl_size = DEFAULT_LABEL_SIZE + if column == "CLASS": + lbl_size = max_classes_name_length + elif column == "PACKAGES": + lbl_size = max_packages_name_length + + lbl = create_label(column, lbl_size, ANSIColors.PURPLE) + print(lbl, end="") + print() + + +def display_csv_data(namespace: argparse.Namespace, csv_data_dict: dict) -> None: + global DISPLAY_COLUMNS, COLUMNS_TYPES + if not getattr(namespace, "package_print", False): + DISPLAY_COLUMNS.remove("PACKAGES") + + if getattr(namespace, 'lib'): + print(f"Jacoco Covered Report Info for module named '{getattr(namespace, 'lib')}':") + + max_packages_name_length = csv_data_dict.get("max_packages_name_length", 20) + max_classes_name_length = csv_data_dict.get("max_classes_name_length", 20) + table: list[dict] = csv_data_dict.get("table", []) + display_columns(max_packages_name_length, max_classes_name_length) + + for row in table: + for column in DISPLAY_COLUMNS: + lbl = "" + if column in ["PACKAGES", "CLASS"]: + lbl = create_label( + row[column], + max_packages_name_length if column == "PACKAGES" else max_classes_name_length, + ANSIColors.YELLOW + ) + else: + vals = [int(row[column + _type]) for _type in COLUMNS_TYPES] + percent = int(round((vals[1] - vals[0]) / vals[1], 2) * 100) if vals[1] != 0 else 100 + lbl = colorize_percent_label( + percent, + ) + + print(lbl, end="") + print() + + +if __name__ == "__main__": + ns = parse_args(sys.argv[1:]) + + try: + csv_data = read_csv(ns) + except Exception as e: + print( + f"Can't read csv file: '{getattr(ns, 'input')}', get exception: '{e}'", + file=sys.stderr + ) + sys.exit(-1) + + display_csv_data(ns, csv_data) diff --git a/scripts/test-result-printer.py b/scripts/test-result-printer.py new file mode 100644 index 0000000..5f9e987 --- /dev/null +++ b/scripts/test-result-printer.py @@ -0,0 +1,185 @@ +import argparse +import sys, os +import xml.etree.ElementTree as ET +from text_colorize import ANSIColors, TextStyle, colorize + + +class TestCase: + + def __init__(self, name: str, is_passed: bool) -> None: + self.name = str(name) + self.is_passed = bool(is_passed) + + def toString(self, indent: int = 0): + return "\t" * indent + f"{self.name} -> {self.result_type()}" + + def result_type(self) -> str: + return colorize( + 'PASSED' if self.is_passed else 'FAILURE', + ANSIColors.GREEN if self.is_passed else ANSIColors.RED, + TextStyle.ITALIC + ) + + def __bool__(self): + return self.is_passed + + +class ParametrisedTestCase(TestCase): + + def __init__(self, name: str, cases: list[TestCase]) -> None: + super().__init__(name, all(cases)) + self.cases = cases + + def add_case(self, case: TestCase): + self.is_passed = self.is_passed and case.is_passed + self.cases.append(case) + + def toString(self, indent: int = 0, also_failed: bool = False): + inline_cases = [] + for case in self.cases: + if (also_failed and case.is_passed): + continue + + inline_cases.append(case.toString(indent + 1)) + + inline_cases = '\n'.join(inline_cases).rstrip() + return super().toString(indent) + f"\n{inline_cases}" + + +def parse_args(args: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser( + prog="Test Result Printer", + description="Program read xml files with tests results and print it at terminal at stdin", + ) + parser.add_argument( + "-d", "--dir", required=True, + help="setup path to directory with xml files with tests information", + metavar="" + ) + parser.add_argument( + "-a", "--all", + action="store_true", + help="setup mode of diplay type to print all test information to ON (default OFF)", + ) + parser.add_argument( + "-f", "--all-failures", + action="store_true", + help="setup mode of diplay type to print also test information which failed to ON (default OFF)", + ) + return parser.parse_args(args) + + +def parse_test_result(test_path: str) -> tuple[ET.Element, dict[str, TestCase]]: + tree_root = ET.parse(test_path).getroot() + cases = dict() + for child in tree_root: + if child.tag != "testcase": + continue + + name = child.get("name", "uncknown test cases") + is_passed = child.find("failure") is None + if '[' in name: + primary_name = name.split('[')[0] + args = '[' + "[".join(name.split('[')[1:]) + + case: ParametrisedTestCase = cases.get(primary_name, ParametrisedTestCase(primary_name, [])) + case.add_case(TestCase(args, is_passed)) + cases[primary_name] = case + else: + cases[name] = TestCase(name, is_passed) + + return (tree_root, cases,) + + +def display_all_test_result(tree_root: ET.Element, cases: dict[str, TestCase]): + print( + "Tests of", + tree_root.attrib.get("name", "UncnownTestSuite").split('.')[-1].replace("Test", ":"), + sep=" " + ) + for name in sorted(cases.keys()): + print(cases[name].toString(indent=1)) + + passed_test_count = int(tree_root.attrib.get("tests", 0)) - int(tree_root.attrib.get("failures", 0)) + print( + colorize(f"Passed: {passed_test_count}", ANSIColors.GREEN, TextStyle.BOLD), + colorize(f"Failures: {tree_root.attrib.get('failures', 0)}", ANSIColors.RED, TextStyle.BOLD), + f"Time: {tree_root.attrib.get('time', 0.0)}", + sep=" ", + end=os.linesep * 2 + ) + + +def display_failures_test_result(tree_root: ET.Element, cases: dict[str, TestCase]): + failed_tests = [] + for name in sorted(cases.keys()): + if not cases[name].is_passed: + failed_tests.append(cases[name]) + + if len(failed_tests) == 0: + return + + print( + "Failed tests of", + tree_root.attrib.get("name", "UncnownTestSuite").split('.')[-1].replace("Test", ":"), + sep=" " + ) + for case in failed_tests: + if isinstance(case, ParametrisedTestCase): + print(case.toString(indent=1, also_failed=True)) + elif isinstance(case, TestCase): + print(case.toString(indent=1)) + + passed_test_count = int(tree_root.attrib.get("tests", 0)) - int(tree_root.attrib.get("failures", 0)) + print( + colorize(f"Passed: {passed_test_count}", ANSIColors.GREEN, TextStyle.BOLD), + colorize(f"Failures: {tree_root.attrib.get('failures', 0)}", ANSIColors.RED, TextStyle.BOLD), + f"Time: {tree_root.attrib.get('time', 0.0)}", + sep=" ", + end=os.linesep * 2 + ) + + +if __name__ == "__main__": + ns = parse_args(sys.argv[1:]) + + tests_result_dir = getattr(ns, "dir") + childs = os.listdir(tests_result_dir) + tests_results: list[tuple[ET.Element, dict[str, TestCase]]] = [] + for child in sorted(childs): + child_path = os.path.join(tests_result_dir, child) + if not os.path.isfile(child_path): + continue + + if not (child.startswith("TEST") and child.endswith(".xml")): + continue + + try: + tests_results.append(parse_test_result(child_path)) + except Exception as e: + print(f"Can't display ttest information at file '{child}': {e}", file=sys.stderr) + + tests_count = 0 + tests_failed_count = 0 + time_of_all_tests = 0 + for test_result in tests_results: + tree_root: ET.Element = test_result[0] + tests_count += int(tree_root.attrib.get("tests", 0)) + tests_failed_count += int(tree_root.attrib.get("failures", 0)) + time_of_all_tests += float(tree_root.attrib.get('time', 0.0)) + + + print( + colorize(f"Count of tests: {tests_count}", ANSIColors.YELLOW, TextStyle.BOLD), + colorize(f"Count of passed tests: {tests_count - tests_failed_count}", ANSIColors.GREEN, TextStyle.BOLD), + colorize(f"Count of failured tests: {tests_failed_count}", ANSIColors.RED, TextStyle.BOLD), + colorize(f"Time: {time_of_all_tests}", ANSIColors.BLUE, TextStyle.BOLD), + sep=os.linesep, + end=os.linesep * 2 + ) + + for test_result in tests_results: + if getattr(ns, "all", False): + display_all_test_result(test_result[0], test_result[1]) + elif getattr(ns, "all_failures", False): + display_failures_test_result(test_result[0], test_result[1]) diff --git a/scripts/text_colorize.py b/scripts/text_colorize.py new file mode 100644 index 0000000..ce38225 --- /dev/null +++ b/scripts/text_colorize.py @@ -0,0 +1,20 @@ +import enum + +class ANSIColors(enum.IntEnum): + PURPLE = 35 + BLUE = 34 + GREEN = 32 + YELLOW = 33 + RED = 31 + BLACK = 30 + WHITE = 37 + + +class TextStyle(enum.IntEnum): + SIMPLE = 0 + BOLD = 1 + ITALIC = 3 + + +def colorize(text: str, color: ANSIColors, style: TextStyle = TextStyle.SIMPLE) -> str: + return f"\033[{style};{color}m{text}\033[0m" diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..ee97c39 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,11 @@ +pluginManagement { + repositories { + gradlePluginPortal() + maven("https://maven.pkg.jetbrains.space/public/p/compose/dev") + } + plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0" + id("org.jetbrains.compose").version(extra["compose.version"] as String) + } +} +rootProject.name = "graphs-graphs-6" \ No newline at end of file diff --git a/src/main/kotlin/Main.kt b/src/main/kotlin/Main.kt new file mode 100644 index 0000000..3f911a6 --- /dev/null +++ b/src/main/kotlin/Main.kt @@ -0,0 +1,165 @@ +import androidx.compose.desktop.ui.tooling.preview.Preview +import androidx.compose.material.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.ui.window.Window +import androidx.compose.ui.window.application +import model.graphs.graphs.DirectedGraph +import model.graphs.graphs.Graph +import model.graphs.graphs.WeightedDirectedGraph +import model.graphs.graphs.WeightedGraph +import view.screens.graphChooseScreen +import view.screens.mainScreens.mainScreen +import view.screens.mainScreens.mainScreenWeightedGraph +import view.screens.placementStrategyScreen +import viewModel.screensViewModels.GraphChooseViewModel +import viewModel.screensViewModels.PlacementStrategyViewModel +import viewModel.screensViewModels.mainScreensViewModels.MainScreenViewModel +import viewModel.screensViewModels.mainScreensViewModels.MainScreenViewModelWeightedGraph + +var closeFirstWindow: MutableState = mutableStateOf(false) +var closePlacementStrategyWindow: MutableState = mutableStateOf(false) +val graphChooseVM = GraphChooseViewModel() +val placementStrategyVM = PlacementStrategyViewModel() + +@Composable +@Preview +fun app() { + MaterialTheme { + closeFirstWindow = remember { mutableStateOf(false) } + closePlacementStrategyWindow = remember { mutableStateOf(false) } + if (!closePlacementStrategyWindow.value) { + placementStrategyScreen(placementStrategyVM) { + closePlacementStrategyWindow.value = true + } + } + if (!closeFirstWindow.value) { + graphChooseScreen(graphChooseVM) { + closeFirstWindow.value = true + } + } + if (closeFirstWindow.value && closePlacementStrategyWindow.value) { + if (!graphChooseVM.isDirected && !graphChooseVM.isWeighted) { + val sampleGraph = Graph().apply { + addVertex("A") + addVertex("B") + addVertex("C") + addVertex("D") + addVertex("E") + addVertex("F") + addVertex("G") + addEdge(1, 0) + addEdge(0, 2) + addEdge(0, 3) + addEdge(3, 2) + addEdge(2, 1) + addEdge(1, 4) + addEdge(4, 5) + addEdge(5, 6) + addEdge(6, 4) + } + mainScreen(MainScreenViewModel(sampleGraph, placementStrategyVM.placementStrategy), false) + } else if (graphChooseVM.isDirected && !graphChooseVM.isWeighted) { + val sampleGraph = DirectedGraph().apply { + addVertex("A") + addVertex("B") + addVertex("C") + addVertex("D") + addVertex("E") + addVertex("F") + addVertex("G") + + addEdge(1, 0) + addEdge(0, 2) + addEdge(0, 3) + addEdge(3, 2) + addEdge(2, 1) + addEdge(1, 4) + addEdge(4, 5) + addEdge(5, 6) + addEdge(6, 4) + } + mainScreen(MainScreenViewModel(sampleGraph, placementStrategyVM.placementStrategy), true) + } else if (!graphChooseVM.isDirected) { + val sampleGraph = WeightedGraph().apply { + addVertex("A") + addVertex("B") + addVertex("C") + addVertex("D") + addVertex("E") + addVertex("F") + addVertex("G") + + addEdge(1, 0) + addEdge(0, 2) + addEdge(0, 3) + addEdge(3, 2) + addEdge(2, 1) + addEdge(1, 4) + addEdge(4, 5) + addEdge(5, 6) + addEdge(6, 4) + + changeEdgeWeight(0, 1) + changeEdgeWeight(1, 1) + changeEdgeWeight(2, 3) + changeEdgeWeight(3, 4) + changeEdgeWeight(4, 5) + changeEdgeWeight(5, 6) + changeEdgeWeight(6, 12) + changeEdgeWeight(7, 4) + changeEdgeWeight(8, 5) + } + mainScreenWeightedGraph( + MainScreenViewModelWeightedGraph(sampleGraph, placementStrategyVM.placementStrategy), + false + ) + } else { + val sampleGraph = WeightedDirectedGraph().apply { + addVertex("A") + addVertex("B") + addVertex("C") + addVertex("D") + addVertex("E") + addVertex("F") + addVertex("G") + + addEdge(1, 0) + addEdge(0, 2) + addEdge(0, 3) + addEdge(3, 2) + addEdge(2, 1) + addEdge(1, 4) + addEdge(4, 5) + addEdge(5, 6) + addEdge(6, 4) + + changeEdgeWeight(0, 1) + changeEdgeWeight(1, 1) + changeEdgeWeight(2, 3) + changeEdgeWeight(3, 4) + changeEdgeWeight(4, 5) + changeEdgeWeight(5, 6) + changeEdgeWeight(6, 12) + changeEdgeWeight(7, 4) + changeEdgeWeight(8, 5) + } + mainScreenWeightedGraph( + MainScreenViewModelWeightedGraph(sampleGraph, placementStrategyVM.placementStrategy), + true + ) + } + } + } +} + +fun main() = application { + val windowTitle by remember { mutableStateOf("Graphs visualizer by team 6") } + + Window(title = windowTitle, onCloseRequest = ::exitApplication) { + app() + } +} \ No newline at end of file diff --git a/src/main/kotlin/model/algorithms/bridgeFinder/BridgeFinder.kt b/src/main/kotlin/model/algorithms/bridgeFinder/BridgeFinder.kt new file mode 100644 index 0000000..47c73c8 --- /dev/null +++ b/src/main/kotlin/model/algorithms/bridgeFinder/BridgeFinder.kt @@ -0,0 +1,83 @@ +package model.algorithms.bridgeFinder + +import model.graphs.graphs.Graph +import java.util.Stack +import kotlin.math.min + +open class BridgeFinder(protected val graph: Graph) { + + private var verticesCount = 0 + private var timer = 0 + private lateinit var visited: BooleanArray + private lateinit var bridges: MutableList> + private lateinit var verticlsStack: Stack + private lateinit var enterTimeInVertex: Array + private lateinit var enterTimeInComponent: Array + private lateinit var adjencyMap: Map> + private fun updateInfo() { + timer = 0 + verticesCount = graph.vertices.size + visited = BooleanArray(verticesCount) + bridges = mutableListOf>() + verticlsStack = Stack() + enterTimeInVertex = Array(verticesCount) { -1 } + enterTimeInComponent = Array(verticesCount) { -1 } + adjencyMap = graph.toAdjacencyMap() + } + + open fun findBridges(): List> { + updateInfo() + for (vertexNumber in 0.. enterTimeInVertex[from]) bridges.add(Pair(from, to)) + vertex = from + parent = when (verticlsStack.isEmpty()) { + true -> -1 + else -> verticlsStack.peek() + } + verticlsStack.push(vertex) + } + } else { + visited[vertex] = true + enterTimeInVertex[vertex] = timer + enterTimeInComponent[vertex] = timer++ + } + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/model/algorithms/keyVerticesSelection/KeyVerticesSelectionSolver.kt b/src/main/kotlin/model/algorithms/keyVerticesSelection/KeyVerticesSelectionSolver.kt new file mode 100644 index 0000000..cb6a60c --- /dev/null +++ b/src/main/kotlin/model/algorithms/keyVerticesSelection/KeyVerticesSelectionSolver.kt @@ -0,0 +1,93 @@ +package model.algorithms.keyVerticesSelection + +import model.graphs.graphs.Graph +import java.util.Collections.max +import java.util.SortedMap +import kotlin.Double.Companion.MAX_VALUE +import kotlin.math.pow +import kotlin.math.sqrt + +open class KeyVerticesSelectionSolver(protected open val graph: Graph) { + private lateinit var graphMap: Map> + private var alpha = 0.15 + private val threshold = 0.00001 + private val stochasticMatrix: MutableMap> = mutableMapOf() + private val visited: MutableMap = mutableMapOf() + + private fun dfsStochasticMatrix(vertexNum: Int) { + if (visited[vertexNum] == true) return + visited[vertexNum] = true + val nextVertices = graphMap[vertexNum] ?: return + for (nextVertexNum in nextVertices) { + if (stochasticMatrix[vertexNum] == null) stochasticMatrix[vertexNum] = mutableMapOf() + stochasticMatrix[vertexNum]?.set( + nextVertexNum, + (1 - alpha) * (1 / nextVertices.size) + alpha / graph.vertices.keys.size + ) + dfsStochasticMatrix(nextVertexNum) + } + } + + private fun initializeStochasticMatrix() { + for (vertexNum in graph.vertices.keys) dfsStochasticMatrix(vertexNum) + } + + private fun initializeStartVector(): MutableMap { + val vector: MutableMap = mutableMapOf() + for (vertexNum in graph.vertices.keys) vector[vertexNum] = 1 / graph.vertices.keys.size.toDouble() + return vector + } + + private fun multiplyVectorByStochasticMatrix(vector: MutableMap): MutableMap { + val product: MutableMap = mutableMapOf() + for (vertexNum in graph.vertices.keys) { + for (vertexIt in graph.vertices.keys) { + val matrixProbability = stochasticMatrix[vertexIt]?.get(vertexNum) + val vectorProbability = vector[vertexIt] + if (matrixProbability == null || vectorProbability == null) continue + if (product[vertexNum] == null) product[vertexNum] = vectorProbability * matrixProbability + else { + val currValue = product[vertexNum] + if (currValue != null) { + product[vertexNum] = currValue + vectorProbability * matrixProbability + } + } + } + } + return product + } + + private fun countDistance(firstVector: MutableMap, secondVector: MutableMap): Double { + var distance = 0.0 + for (vertexNum in graph.vertices.keys) { + val firstValue = firstVector[vertexNum] + val secondValue = secondVector[vertexNum] + if (firstValue == null || secondValue == null) return 0.0 + distance += (firstValue - secondValue).pow(2) + } + return sqrt(distance) + } + + private fun findStationaryDistribution(): SortedMap { + var distance = MAX_VALUE + var vector = initializeStartVector() + while (distance > threshold) { + val nextVector = multiplyVectorByStochasticMatrix(vector) + distance = countDistance(vector, nextVector) + vector = nextVector + } + return vector.toSortedMap() + } + + fun selectKeyVertices(): List { + graphMap = graph.toAdjacencyMap() + initializeStochasticMatrix() + val stationaryDistribution = findStationaryDistribution() + val keyVertices: MutableList = mutableListOf() + for (vertexNum in graph.vertices.keys) { + val pageRank = stationaryDistribution[vertexNum] ?: continue + if (pageRank >= 0.5 * max(stationaryDistribution.values)) keyVertices.add(vertexNum) + } + return keyVertices + } +} diff --git a/src/main/kotlin/model/algorithms/kruskalAlgorithm/KruskalAlgorithmSolver.kt b/src/main/kotlin/model/algorithms/kruskalAlgorithm/KruskalAlgorithmSolver.kt new file mode 100644 index 0000000..a0a8043 --- /dev/null +++ b/src/main/kotlin/model/algorithms/kruskalAlgorithm/KruskalAlgorithmSolver.kt @@ -0,0 +1,69 @@ +package model.algorithms.kruskalAlgorithm + +import model.graphs.edges.WeightedEdge +import model.graphs.graphs.WeightedGraph + +class KruskalAlgorithmSolver(graph: WeightedGraph) { // non-directed weighted connected graphs + private var edges = graph.edges.values + private val numOfVertices = graph.lastVertexNumber + + private val disjointSet: MutableList = mutableListOf() + private val minimalSpanningTree = mutableListOf() + + fun doKruskalAlgorithm(): Pair> { + if (numOfVertices <= 1) { // empty graph or graph with one vertex + return Pair(false, minimalSpanningTree.toList()) + } + + initializeDisjointSet() + val sortedEdges = edges.sortedBy { it.weight } + + for (edge in sortedEdges) { + if (minimalSpanningTree.size == numOfVertices - 1) { + break + } + + if (findMST(disjointSet, edge.verticesNumbers.first) != + findMST(disjointSet, edge.verticesNumbers.second) + ) { + unionMST(disjointSet, edge.verticesNumbers.first, edge.verticesNumbers.second) + minimalSpanningTree.add(edge) + } + } + + if (minimalSpanningTree.size < numOfVertices - 1) { + return Pair(false, emptyList()) + } + + return Pair(true, minimalSpanningTree.toList()) + } + + private fun initializeDisjointSet() { + for (i in 0.., i: Int): Int { + if (parents[i] < 0) { + return i + } + + return findMST(parents, parents[i]).also { parents[i] = it } + } + + private fun unionMST(parents: MutableList, i: Int, j: Int) { + val root1 = findMST(parents, i) + val root2 = findMST(parents, j) + + if (root1 != root2) { + if (parents[root1] < parents[root2]) { + parents[root1] += parents[root2] + parents[root2] = root1 + } else { + parents[root2] += parents[root1] + parents[root1] = root2 + } + } + } +} diff --git a/src/main/kotlin/model/algorithms/pathSearch/PathResult.kt b/src/main/kotlin/model/algorithms/pathSearch/PathResult.kt new file mode 100644 index 0000000..4393acb --- /dev/null +++ b/src/main/kotlin/model/algorithms/pathSearch/PathResult.kt @@ -0,0 +1,9 @@ +package model.algorithms.pathSearch + +import model.graphs.graphs.WeightedGraph +import model.graphs.vertex.Vertex + +open class PathResult(val graph: WeightedGraph, val vertexList: List>) { + val sourceVertex = if (vertexList.isEmpty()) null else vertexList.first() + val endVertex = if (vertexList.isEmpty()) null else vertexList.last() +} \ No newline at end of file diff --git a/src/main/kotlin/model/algorithms/pathSearch/djikstra/DjikstraAlgorithm.kt b/src/main/kotlin/model/algorithms/pathSearch/djikstra/DjikstraAlgorithm.kt new file mode 100644 index 0000000..1facad9 --- /dev/null +++ b/src/main/kotlin/model/algorithms/pathSearch/djikstra/DjikstraAlgorithm.kt @@ -0,0 +1,64 @@ +package model.algorithms.pathSearch.djikstra + +import model.algorithms.pathSearch.PathResult +import model.graphs.graphs.WeightedGraph +import model.graphs.vertex.Vertex + +open class DjikstraAlgorithm(protected val graph: WeightedGraph) { + fun findNearestPath(startVertex: Vertex, endVertex: Vertex): PathResult { + if (!graph.vertices.containsValue(startVertex) || !graph.vertices.containsValue(endVertex)) throw IllegalArgumentException() + + val startVertexId = graph.vertices.keys.first { x -> graph.vertices[x] == startVertex } + val endVertexId = graph.vertices.keys.first { x -> graph.vertices[x] == endVertex } + + return findNearestPath(startVertexId, endVertexId) + } + fun findNearestPath(startVertexId: Int, endVertexId: Int): PathResult { + if (graph.vertices.isEmpty() || !graph.vertices.containsKey(startVertexId) || !graph.vertices.containsKey(endVertexId)) throw IllegalArgumentException() + + val verticesDistance = mutableMapOf() + val verticlesFrom = mutableMapOf() + val verticlesVisited = mutableMapOf() + for (i in graph.vertices.keys) { + verticesDistance[i] = Int.MAX_VALUE + verticlesFrom[i] = null + verticlesVisited[i] = false + } + verticesDistance[startVertexId] = 0 + for (i in graph.vertices.keys) { + var nearestId: Int? = null + + for (j in graph.vertices.keys) { + if (!verticlesVisited.getOrDefault(j, false) && (verticesDistance[j]!! < verticesDistance[i]!! || nearestId == null)) { + nearestId = j + } + } + if (nearestId == null || verticesDistance[nearestId] == Int.MAX_VALUE) break + verticlesVisited[nearestId] = true + + val edgesFromNearest = graph.edges.filter { x -> x.value.verticesNumbers.first == nearestId || x.value.verticesNumbers.second == nearestId }.values + + for (edge in edgesFromNearest) { + val to = if (nearestId == edge.verticesNumbers.first) edge.verticesNumbers.second else edge.verticesNumbers.first + if (verticesDistance[nearestId]!! + edge.weight < verticesDistance[to]!!) { + verticesDistance[to] = verticesDistance[nearestId]!! + edge.weight + verticlesFrom[to] = nearestId + } + } + } + + val resultPath = mutableListOf>() + var finish: Int? = endVertexId + while (finish != startVertexId) { + if (finish == null) { + resultPath.clear() + break + } + resultPath.add(graph.vertices[finish]!!) + finish = verticlesFrom[finish] + } + resultPath.add(graph.vertices[startVertexId]!!) + resultPath.reverse() + return PathResult(graph, resultPath) + } +} \ No newline at end of file diff --git a/src/main/kotlin/model/algorithms/pathSearch/fordBellman/FordBellmanAlgorithm.kt b/src/main/kotlin/model/algorithms/pathSearch/fordBellman/FordBellmanAlgorithm.kt new file mode 100644 index 0000000..4a65989 --- /dev/null +++ b/src/main/kotlin/model/algorithms/pathSearch/fordBellman/FordBellmanAlgorithm.kt @@ -0,0 +1,53 @@ +package model.algorithms.pathSearch.fordBellman + +import model.algorithms.pathSearch.PathResult +import model.graphs.graphs.WeightedDirectedGraph +import model.graphs.vertex.Vertex +import kotlin.Int.Companion.MAX_VALUE + +class FordBellmanAlgorithm(val graph: WeightedDirectedGraph) { + fun findPath(startVertexNum: Int, finishVertexNum: Int): PathResult { + val distances: MutableMap = mutableMapOf() + val parents: MutableMap = mutableMapOf() + if ((!(graph.vertices.keys.contains(startVertexNum))) || (!(graph.vertices.keys.contains(finishVertexNum)))) throw IllegalArgumentException("No such vertex in the graph") + for (vertexNum in graph.vertices.keys) { + distances[vertexNum] = MAX_VALUE + parents[vertexNum] = -1 + } + distances[startVertexNum] = 0 + var it = 0 + do { + var changesHappened = false + for (edge in graph.edges.values) { + val distanceFirst = distances[edge.verticesNumbers.first] + val distanceSecond = distances[edge.verticesNumbers.second] + if (distanceFirst != null && distanceSecond != null) { + if (distanceFirst < MAX_VALUE) { + if (distanceSecond > distanceFirst + edge.weight) { + distances[edge.verticesNumbers.second] = distanceFirst + edge.weight + parents[edge.verticesNumbers.second] = edge.verticesNumbers.first + changesHappened = true + } + } + } + } + ++it + if (it > graph.vertices.size) throw IllegalArgumentException("Negative cycle in the graph! Isn't supported by Ford-Bellman algorithm.") + } while (changesHappened) + + if (distances[finishVertexNum] == MAX_VALUE) throw IllegalArgumentException("No path between these vertices") + else { + val path: MutableList> = mutableListOf() + var currVertexNum = finishVertexNum + while (currVertexNum != -1) { + val currVertex = graph.vertices[currVertexNum] + if (currVertex == null) throw Exception() + else { + path.add(currVertex) + currVertexNum = parents[currVertexNum] ?: break + } + } + return PathResult(graph, path.reversed()) + } + } +} diff --git a/src/main/kotlin/model/algorithms/placement/YifanHuPlacement.kt b/src/main/kotlin/model/algorithms/placement/YifanHuPlacement.kt new file mode 100644 index 0000000..60024ed --- /dev/null +++ b/src/main/kotlin/model/algorithms/placement/YifanHuPlacement.kt @@ -0,0 +1,63 @@ +package model.algorithms.placement + +import model.graphs.edges.Edge +import model.graphs.graphs.AbstractGraph +import org.gephi.graph.api.GraphModel +import org.gephi.graph.api.Node +import org.gephi.layout.plugin.force.StepDisplacement +import org.gephi.layout.plugin.force.yifanHu.YifanHuLayout +import kotlin.random.Random + +open class YifanHuPlacement(val graph: AbstractGraph) { + fun getPlacement(width: Int, height: Int): Map> { + val random = Random(1L) + + val graphModel = GraphModel.Factory.newInstance() + val graphType = graphModel.undirectedGraph + + val nodes = mutableMapOf() + for (vertex in graph.vertices.values) { + val node: Node = graphModel.factory().newNode(vertex.value.toString()) + node.setX(random.nextFloat() * width) + node.setY(random.nextFloat() * height) + nodes[vertex.value] = node + + graphType.addNode(node) + } + + for (edge in graph.edges.values) { + val firstVertex = graph.getVertexValue(edge.verticesNumbers.first) + val secondVertex = graph.getVertexValue(edge.verticesNumbers.second) + val e: org.gephi.graph.api.Edge = graphModel.factory().newEdge( + nodes[firstVertex], + nodes[secondVertex], + 1, + false + ) + graphType.addEdge(e) + } + val layout = YifanHuLayout(null, StepDisplacement(1f)) + layout.setGraphModel(graphModel) + layout.initAlgo() + layout.resetPropertiesValues() + layout.optimalDistance = 300f + layout.relativeStrength = 0.2f + layout.initialStep = 20.0f + layout.stepRatio = 0.95f + layout.isAdaptiveCooling = true + + var i = 0 + while (i < 1000 && layout.canAlgo()) { + layout.goAlgo() + i++ + } + layout.endAlgo() + val placement = mutableMapOf>() + for (vertex in graph.vertices.values) { + val n = graphType.getNode(vertex.value.toString()) + placement[vertex.value] = Pair(n.x(), n.y()) + } + + return placement + } +} \ No newline at end of file diff --git a/src/main/kotlin/model/algorithms/searchCycle/SearchCycleForVertexInDirectedGraphSolver.kt b/src/main/kotlin/model/algorithms/searchCycle/SearchCycleForVertexInDirectedGraphSolver.kt new file mode 100644 index 0000000..b151183 --- /dev/null +++ b/src/main/kotlin/model/algorithms/searchCycle/SearchCycleForVertexInDirectedGraphSolver.kt @@ -0,0 +1,10 @@ +package model.algorithms.searchCycle + +import model.graphs.graphs.DirectedGraph + +class SearchCycleForVertexInDirectedGraphSolver(graph: DirectedGraph) : + SearchCycleForVertexInGraphSolver(graph) { + override fun parentsCheck(currVertex: Int, parentVertex: Int): Boolean { + return false + } +} \ No newline at end of file diff --git a/src/main/kotlin/model/algorithms/searchCycle/SearchCycleForVertexInGraphSolver.kt b/src/main/kotlin/model/algorithms/searchCycle/SearchCycleForVertexInGraphSolver.kt new file mode 100644 index 0000000..b961d7a --- /dev/null +++ b/src/main/kotlin/model/algorithms/searchCycle/SearchCycleForVertexInGraphSolver.kt @@ -0,0 +1,83 @@ +package model.algorithms.searchCycle + +import model.graphs.graphs.Graph + +open class SearchCycleForVertexInGraphSolver(val graph: Graph) { // non-negative numbers of vertices + protected enum class Color { + White, + Gray, + Black + } + + private val verticesAdjacencyList = graph.toAdjacencyMap() + private val cycleVertices = mutableListOf() + private val vertexColor = mutableMapOf() + + fun searchCycleForVertex(vertex: Int): Boolean { // only first cycle found + if (verticesAdjacencyList.isEmpty()) { + return false + } + + initializeUsageList() + + val result = dfs(vertex) + return result == -2 + } + + fun getCycle(): List { + val answer = cycleVertices + + if (cycleVertices.size > 0) { + answer.reverse() + } + + return answer.toList() // correct answer (reverse), first vertex included twice; if algorithm's result is false, empty list returned + } + + private fun initializeUsageList() { + for (vertex in verticesAdjacencyList.keys) { + vertexColor[vertex] = Color.White + } + } + + protected open fun parentsCheck(currVertex: Int, parentVertex: Int): Boolean { + return currVertex == parentVertex + } + + private fun dfs(currVertex: Int, prevVertex: Int = -1): Int { + if (vertexColor[currVertex] == Color.Gray) { // cycle of two in directed graphs + cycleVertices.add(currVertex) + return currVertex + } + vertexColor[currVertex] = Color.Gray + + val tempAdjacencyList = verticesAdjacencyList[currVertex] ?: return -1 // adjacency list is never empty + for (tempVertex in tempAdjacencyList) { + if (parentsCheck(tempVertex, prevVertex)) { + continue + } + + if (vertexColor[tempVertex] == Color.White) { + val result = dfs(tempVertex, currVertex) + + if (result >= 0) { + cycleVertices.add(currVertex) + + vertexColor[currVertex] = Color.Black + return if (result == currVertex) -2 else result + } + } + + if (vertexColor[tempVertex] == Color.Gray) { + cycleVertices.add(tempVertex) + cycleVertices.add(currVertex) + + vertexColor[currVertex] = Color.Black + return tempVertex + } + } + + vertexColor[currVertex] = Color.Black + return -1 + } +} diff --git a/src/main/kotlin/model/algorithms/stronglyConnectedComponentsSelection/StronglyConnectedComponentsSelectionSolver.kt b/src/main/kotlin/model/algorithms/stronglyConnectedComponentsSelection/StronglyConnectedComponentsSelectionSolver.kt new file mode 100644 index 0000000..f866203 --- /dev/null +++ b/src/main/kotlin/model/algorithms/stronglyConnectedComponentsSelection/StronglyConnectedComponentsSelectionSolver.kt @@ -0,0 +1,68 @@ +package model.algorithms.stronglyConnectedComponentsSelection + +import model.graphs.graphs.DirectedGraph + +class StronglyConnectedComponentsSelectionSolver(val graph: DirectedGraph) { + private val visited: MutableMap = mutableMapOf() + private val graphMap: MutableMap> = mutableMapOf() + private val reversedGraphMap: MutableMap> = mutableMapOf() + private val order: MutableList = mutableListOf() + private val components: MutableMap = mutableMapOf() + private var lastComponentNum = 1 + + private fun initializeGraphs() { + for (edge in graph.edges.values) { + val firstVertexNum = edge.verticesNumbers.first + val secondVertexNum = edge.verticesNumbers.second + if (graphMap.containsKey(firstVertexNum)) graphMap[firstVertexNum]?.add(secondVertexNum) + else graphMap[firstVertexNum] = mutableSetOf(secondVertexNum) + if (reversedGraphMap.containsKey(secondVertexNum)) reversedGraphMap[secondVertexNum]?.add( + firstVertexNum + ) + else reversedGraphMap[secondVertexNum] = mutableSetOf(firstVertexNum) + } + } + + private fun initializeVisited() { + for (vertexNum in graph.vertices.keys) visited[vertexNum] = false + } + + private fun dfsOrder(vertexNum: Int) { + visited[vertexNum] = true + val nextVertices = graphMap[vertexNum] + if (nextVertices != null) { + for (nextVertexNum in nextVertices) { + if (visited[nextVertexNum] == false) dfsOrder(nextVertexNum) + } + } + order.add(vertexNum) + } + + private fun dfsComponents(vertexNum: Int) { + visited[vertexNum] = true + components[vertexNum] = lastComponentNum + val nextVertices = reversedGraphMap[vertexNum] + if (nextVertices != null) { + for (nextVertexNum in nextVertices) { + if (visited[nextVertexNum] == false) dfsComponents(nextVertexNum) + } + } + } + + fun selectStronglyConnectedComponents(): MutableMap { + initializeGraphs() + initializeVisited() + for (vertexNum in graphMap.keys) { + if (visited[vertexNum] == false) dfsOrder(vertexNum) + } + initializeVisited() // we need visited[vertexNum] = false again for all vertices + for (vertexIndex in 0 until order.size) { + val vertexNum = order[order.size - 1 - vertexIndex] + if (visited[vertexNum] == false) { + dfsComponents(vertexNum) + ++lastComponentNum + } + } + return components + } +} diff --git a/src/main/kotlin/model/data/AbstractGraphSerializer.kt b/src/main/kotlin/model/data/AbstractGraphSerializer.kt new file mode 100644 index 0000000..e9212ad --- /dev/null +++ b/src/main/kotlin/model/data/AbstractGraphSerializer.kt @@ -0,0 +1,44 @@ +package model.data + +import model.graphs.edges.Edge +import model.graphs.graphs.AbstractGraph +import model.graphs.graphs.DirectedGraph +import model.graphs.graphs.WeightedDirectedGraph +import model.graphs.graphs.WeightedGraph + +abstract class AbstractGraphSerializer { + + abstract fun deserializeGraph(name: String): GraphRepresentation + protected abstract fun serializeGraphRepresentation(graph: GraphRepresentation) + + protected abstract fun getNameForNextGraph(): String + + abstract fun isGraphAlreadyStored(name: String): Boolean + + private fun initGraphSerialization(graphName: String?, graph: AbstractGraph, vertexDataSerializer: IVertexDataSerializer): GraphRepresentationBuilder { + var name = "" + name = graphName ?: getNameForNextGraph() + + if (isGraphAlreadyStored(name)) throw Exception(DataConstants.ALREADYEXIST_ERROR) + + return GraphRepresentationBuilder(vertexDataSerializer.getSerializableType(), name, graph, vertexDataSerializer) + } + fun serializeOrdinaryGraph(graphName: String?, graph: AbstractGraph, vertexDataSerializer: IVertexDataSerializer) = serializeGraphRepresentation(initGraphSerialization(graphName, graph, vertexDataSerializer).build()) + + fun serializeNotOrdinaryGraph(graphName: String?, graph: DirectedGraph, vertexDataSerializer: IVertexDataSerializer) { + val initResult = initGraphSerialization(graphName, graph, vertexDataSerializer) + initResult.makeDirected() + serializeGraphRepresentation(initResult.build()) + } + fun serializeNotOrdinaryGraph(graphName: String?, graph: WeightedGraph, vertexDataSerializer: IVertexDataSerializer) { + val initResult = initGraphSerialization(graphName, graph, vertexDataSerializer) + initResult.makeWeighted() + serializeGraphRepresentation(initResult.build()) + } + fun serializeNotOrdinaryGraph(graphName: String?, graph: WeightedDirectedGraph, vertexDataSerializer: IVertexDataSerializer) { + val initResult = initGraphSerialization(graphName, graph, vertexDataSerializer) + initResult.makeWeighted() + initResult.makeDirected() + return serializeGraphRepresentation(initResult.build()) + } +} \ No newline at end of file diff --git a/src/main/kotlin/model/data/DataConstants.kt b/src/main/kotlin/model/data/DataConstants.kt new file mode 100644 index 0000000..4c4a890 --- /dev/null +++ b/src/main/kotlin/model/data/DataConstants.kt @@ -0,0 +1,5 @@ +package model.data + +object DataConstants { + const val ALREADYEXIST_ERROR = "A graph with the same name is already stored." +} \ No newline at end of file diff --git a/src/main/kotlin/model/data/GraphRepresentation.kt b/src/main/kotlin/model/data/GraphRepresentation.kt new file mode 100644 index 0000000..783518d --- /dev/null +++ b/src/main/kotlin/model/data/GraphRepresentation.kt @@ -0,0 +1,76 @@ +package model.data + +import kotlinx.serialization.Serializable +import model.graphs.edges.Edge +import model.graphs.graphs.AbstractGraph +import model.graphs.graphs.DirectedGraph +import model.graphs.graphs.Graph +import model.graphs.graphs.WeightedDirectedGraph +import model.graphs.graphs.WeightedGraph +import java.lang.reflect.Type + +@Serializable +data class GraphRepresentation(val name: String, val vertexValueTypeName: String, val vertexValuesList: List, val edges: List>, val isDirected: Boolean, val isWeighted: Boolean, val weightEdgeList: List) { + + private fun initGraphCreation(graph: AbstractGraph, deserializer: IVertexDataSerializer) { + for (i in vertexValuesList) { + val value = deserializer.deserialize(i) + graph.addVertex(value) + } + + for (i in edges) { + graph.addEdge(i.first, i.second) + } + } + + fun createOrdinaryGraphByRepresentation(deserializer: IVertexDataSerializer): Graph { + val result = Graph() + initGraphCreation(result, deserializer) + return result + } + fun createDirectedWeightedGraphByRepresentation(deserializer: IVertexDataSerializer): WeightedDirectedGraph { + val result = WeightedDirectedGraph() + initGraphCreation(result, deserializer) + for ((index, value) in weightEdgeList.withIndex()) { + result.changeEdgeWeight(index, value) + } + return result + } + fun createDirectedGraphByRepresentation(deserializer: IVertexDataSerializer): DirectedGraph { + val result = DirectedGraph() + initGraphCreation(result, deserializer) + return result + } + fun createWeightedGraphByRepresentation(deserializer: IVertexDataSerializer): WeightedGraph { + val result = WeightedGraph() + initGraphCreation(result, deserializer) + for ((index, value) in weightEdgeList.withIndex()) { + result.changeEdgeWeight(index, value) + } + return result + } +} + +class GraphRepresentationBuilder(vertexDataType: Type, val name: String, val graph: AbstractGraph, vertexDataSerializer: IVertexDataSerializer) { + private val vertexValueTypeName: String = vertexDataType.typeName + private val vertexValuesList: List = graph.vertices.values.map { x -> vertexDataSerializer.serialize(x.value) }.toList() + private val edges = graph.edges.map { x -> x.value.verticesNumbers } + private var isDirected = false + private var isWeighted = false + private var weightEdgeList = listOf() + + fun makeDirected(): GraphRepresentationBuilder { + isDirected = true + return this + } + + fun makeWeighted(): GraphRepresentationBuilder { + isWeighted = true + weightEdgeList = (graph as WeightedGraph).edges.values.map { x -> x.weight } + return this + } + + fun build(): GraphRepresentation { + return GraphRepresentation(name, vertexValueTypeName, vertexValuesList, edges, isDirected, isWeighted, weightEdgeList) + } +} \ No newline at end of file diff --git a/src/main/kotlin/model/data/IVertexDataSerializer.kt b/src/main/kotlin/model/data/IVertexDataSerializer.kt new file mode 100644 index 0000000..7817e45 --- /dev/null +++ b/src/main/kotlin/model/data/IVertexDataSerializer.kt @@ -0,0 +1,11 @@ +package model.data + +import java.lang.reflect.Type + +interface IVertexDataSerializer { + fun serialize(data: V): String + + fun getSerializableType(): Type + + fun deserialize(data: String): V +} \ No newline at end of file diff --git a/src/main/kotlin/model/data/json/JsonGraphSerializer.kt b/src/main/kotlin/model/data/json/JsonGraphSerializer.kt new file mode 100644 index 0000000..908e143 --- /dev/null +++ b/src/main/kotlin/model/data/json/JsonGraphSerializer.kt @@ -0,0 +1,40 @@ +package model.data.json + +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import model.data.AbstractGraphSerializer +import model.data.GraphRepresentation +import java.io.File +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths +import java.time.LocalDate + +class JsonGraphSerializer : AbstractGraphSerializer() { + + private val storagePath = "./jsonGraphsStorage" + + init { + if (!Files.isDirectory(Paths.get(storagePath))) Files.createDirectory(Paths.get(storagePath)) + } + override fun deserializeGraph(name: String): GraphRepresentation { + val text = File("$storagePath/$name.json").readText() + return Json.decodeFromString(text) + } + + override fun serializeGraphRepresentation(graph: GraphRepresentation) { + val text = Json.encodeToString(graph) + File(storagePath + "/" + graph.name + ".json").writeText(text) + } + + override fun getNameForNextGraph(): String { + var name = LocalDate.now().toString() + while (isGraphAlreadyStored(name)) { + name += ",new" + } + return name + } + + override fun isGraphAlreadyStored(name: String): Boolean = Files.exists(Path.of("$storagePath/$name.json")) +} \ No newline at end of file diff --git a/src/main/kotlin/model/graphs/edges/Edge.kt b/src/main/kotlin/model/graphs/edges/Edge.kt new file mode 100644 index 0000000..c21702e --- /dev/null +++ b/src/main/kotlin/model/graphs/edges/Edge.kt @@ -0,0 +1,5 @@ +package model.graphs.edges + +open class Edge( + internal var verticesNumbers: Pair +) diff --git a/src/main/kotlin/model/graphs/edges/WeightedEdge.kt b/src/main/kotlin/model/graphs/edges/WeightedEdge.kt new file mode 100644 index 0000000..e5babde --- /dev/null +++ b/src/main/kotlin/model/graphs/edges/WeightedEdge.kt @@ -0,0 +1,5 @@ +package model.graphs.edges + +class WeightedEdge(verticesNumbers: Pair) : Edge(verticesNumbers) { + internal var weight: Int = 0 +} diff --git a/src/main/kotlin/model/graphs/graphs/AbstractGraph.kt b/src/main/kotlin/model/graphs/graphs/AbstractGraph.kt new file mode 100644 index 0000000..99fbc30 --- /dev/null +++ b/src/main/kotlin/model/graphs/graphs/AbstractGraph.kt @@ -0,0 +1,77 @@ +package model.graphs.graphs + +import model.graphs.edges.Edge +import model.graphs.vertex.Vertex + +abstract class AbstractGraph { + internal var vertices: MutableMap> = mutableMapOf() + internal open var edges: MutableMap = mutableMapOf() + internal var lastVertexNumber = 0 + internal var lastEdgeNumber = 0 + + open fun toAdjacencyMap(): Map> { + val graphMap: MutableMap> = mutableMapOf() + for (edge in edges.values) { + val firstVertexNum = edge.verticesNumbers.first + val secondVertexNum = edge.verticesNumbers.second + // we add 1-2 and 2-1 both edges in undirected case + if (graphMap.containsKey(firstVertexNum)) graphMap[firstVertexNum]?.add(secondVertexNum) + else graphMap[firstVertexNum] = mutableSetOf(secondVertexNum) + if (graphMap.containsKey(secondVertexNum)) graphMap[secondVertexNum]?.add( + firstVertexNum + ) + else graphMap[secondVertexNum] = mutableSetOf(firstVertexNum) + } + for (vertexNum in vertices.keys) { + if (!(graphMap.containsKey(vertexNum))) graphMap[vertexNum] = mutableSetOf() + } + return graphMap.toMap() + } + + // size of list "vertices" is index of our next vertex, same for edge further + fun addVertex(value: V) { + vertices[lastVertexNumber++] = Vertex(value) + } + + fun removeVertex(vertexNumber: Int): Vertex? = vertices.remove(vertexNumber) + + fun getVertexValue(vertexNumber: Int): V? = vertices[vertexNumber]?.value + + fun changeVertexValue(vertexNumber: Int, newValue: V): Boolean { + if (vertices[vertexNumber] == null) return false + vertices[vertexNumber]?.value = newValue + return true + } + + // edges are equivalent if their vertices are the same (direction doesn't make effect in general case) + protected open fun checkEdgesEquivalent(firstEdge: E, secondEdge: E): Boolean = + ( + (firstEdge.verticesNumbers == secondEdge.verticesNumbers) || ( + firstEdge.verticesNumbers == Pair( + secondEdge.verticesNumbers.second, + secondEdge.verticesNumbers.first + ) + ) + ) + + protected abstract fun createEdge(firstVertexNumber: Int, secondVertexNumber: Int): E + + fun addEdge(firstVertexNumber: Int, secondVertexNumber: Int): Boolean { + // if edge is a loop, we don't add it + if (firstVertexNumber == secondVertexNumber) return false + // if edge's vertex is not in graph, we don't add it + if ((!(vertices.containsKey(firstVertexNumber))) || (!(vertices.containsKey(secondVertexNumber)))) return false + val edge = createEdge(firstVertexNumber, secondVertexNumber) + for (currEdge in edges.values) { + // if edge is already in the graph, we don't add it + if (checkEdgesEquivalent(edge, currEdge)) return false + } + edges[lastEdgeNumber++] = edge + return true + } + + fun removeEdge(edgeNumber: Int): E? = edges.remove(edgeNumber) + + fun getEdgeVerticesNumbers(edgeNumber: Int): Pair? = + edges[edgeNumber]?.verticesNumbers +} diff --git a/src/main/kotlin/model/graphs/graphs/DirectedGraph.kt b/src/main/kotlin/model/graphs/graphs/DirectedGraph.kt new file mode 100644 index 0000000..32735fd --- /dev/null +++ b/src/main/kotlin/model/graphs/graphs/DirectedGraph.kt @@ -0,0 +1,24 @@ +package model.graphs.graphs + +import model.graphs.edges.Edge + +class DirectedGraph : Graph() { + override fun toAdjacencyMap(): Map> { + val graphMap: MutableMap> = mutableMapOf() + for (edge in edges.values) { + val firstVertexNum = edge.verticesNumbers.first + val secondVertexNum = edge.verticesNumbers.second + // we add only 1-2 in directed case + if (graphMap.containsKey(firstVertexNum)) graphMap[firstVertexNum]?.add(secondVertexNum) + else graphMap[firstVertexNum] = mutableSetOf(secondVertexNum) + } + for (vertexNum in vertices.keys) { + if (!(graphMap.containsKey(vertexNum))) graphMap[vertexNum] = mutableSetOf() + } + return graphMap.toMap() + } + + // edges are equivalent when both source and destination are the same + override fun checkEdgesEquivalent(firstEdge: Edge, secondEdge: Edge) = + (firstEdge.verticesNumbers == secondEdge.verticesNumbers) +} diff --git a/src/main/kotlin/model/graphs/graphs/Graph.kt b/src/main/kotlin/model/graphs/graphs/Graph.kt new file mode 100644 index 0000000..b996e00 --- /dev/null +++ b/src/main/kotlin/model/graphs/graphs/Graph.kt @@ -0,0 +1,8 @@ +package model.graphs.graphs + +import model.graphs.edges.Edge + +open class Graph : AbstractGraph() { + override fun createEdge(firstVertexNumber: Int, secondVertexNumber: Int): Edge = + Edge(Pair(firstVertexNumber, secondVertexNumber)) +} diff --git a/src/main/kotlin/model/graphs/graphs/WeightedDirectedGraph.kt b/src/main/kotlin/model/graphs/graphs/WeightedDirectedGraph.kt new file mode 100644 index 0000000..b017cb1 --- /dev/null +++ b/src/main/kotlin/model/graphs/graphs/WeightedDirectedGraph.kt @@ -0,0 +1,24 @@ +package model.graphs.graphs + +import model.graphs.edges.WeightedEdge + +class WeightedDirectedGraph : WeightedGraph() { + override fun toAdjacencyMap(): Map> { + val graphMap: MutableMap> = mutableMapOf() + for (edge in edges.values) { + val firstVertexNum = edge.verticesNumbers.first + val secondVertexNum = edge.verticesNumbers.second + // we add only 1-2 in directed case + if (graphMap.containsKey(firstVertexNum)) graphMap[firstVertexNum]?.add(secondVertexNum) + else graphMap[firstVertexNum] = mutableSetOf(secondVertexNum) + } + for (vertexNum in vertices.keys) { + if (!(graphMap.containsKey(vertexNum))) graphMap[vertexNum] = mutableSetOf() + } + return graphMap.toMap() + } + + // edges are equivalent when both source and destination are the same + override fun checkEdgesEquivalent(firstEdge: WeightedEdge, secondEdge: WeightedEdge) = + (firstEdge.verticesNumbers == secondEdge.verticesNumbers) +} diff --git a/src/main/kotlin/model/graphs/graphs/WeightedGraph.kt b/src/main/kotlin/model/graphs/graphs/WeightedGraph.kt new file mode 100644 index 0000000..d1bae1f --- /dev/null +++ b/src/main/kotlin/model/graphs/graphs/WeightedGraph.kt @@ -0,0 +1,16 @@ +package model.graphs.graphs + +import model.graphs.edges.WeightedEdge + +open class WeightedGraph : AbstractGraph() { + override fun createEdge(firstVertexNumber: Int, secondVertexNumber: Int): WeightedEdge = + WeightedEdge(Pair(firstVertexNumber, secondVertexNumber)) + + fun changeEdgeWeight(edgeNumber: Int, newWeight: Int): Boolean { + if (edges[edgeNumber] == null) return false + edges[edgeNumber]?.weight = newWeight + return true + } + + fun getEdgeWeight(edgeNumber: Int): Int? = edges[edgeNumber]?.weight +} diff --git a/src/main/kotlin/model/graphs/vertex/Vertex.kt b/src/main/kotlin/model/graphs/vertex/Vertex.kt new file mode 100644 index 0000000..6e4a89d --- /dev/null +++ b/src/main/kotlin/model/graphs/vertex/Vertex.kt @@ -0,0 +1,5 @@ +package model.graphs.vertex + +data class Vertex( + internal var value: V +) diff --git a/src/main/kotlin/view/graphView/VertexView.kt b/src/main/kotlin/view/graphView/VertexView.kt new file mode 100644 index 0000000..3bc0a2f --- /dev/null +++ b/src/main/kotlin/view/graphView/VertexView.kt @@ -0,0 +1,46 @@ +package view.graphView + +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.unit.dp +import viewModel.graphViewModel.VertexViewModel + +@Composable +fun vertexView( + viewModel: VertexViewModel, + modifier: Modifier = Modifier +) { + Box( + modifier = modifier + .size(viewModel.radius * 2, viewModel.radius * 2) + .offset(viewModel.x, viewModel.y) + .background( + color = viewModel.color, + shape = CircleShape + ) + .pointerInput(viewModel) { + detectDragGestures { change, dragAmount -> + change.consume() + viewModel.onDrag(dragAmount) + } + } + ) { + if (viewModel.labelVisible) { + Text( + modifier = Modifier + .align(Alignment.Center) + .offset(0.dp, -viewModel.radius - 10.dp), + text = viewModel.label + ) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/view/graphView/edgesView/DirectedEdgeView.kt b/src/main/kotlin/view/graphView/edgesView/DirectedEdgeView.kt new file mode 100644 index 0000000..6dba619 --- /dev/null +++ b/src/main/kotlin/view/graphView/edgesView/DirectedEdgeView.kt @@ -0,0 +1,71 @@ +package view.graphView.edgesView + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.unit.dp +import viewModel.graphViewModel.edgesViewModel.EdgeViewModel +import kotlin.math.PI +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.sin + +@Composable +fun directedEdgeView( + viewModel: EdgeViewModel, + modifier: Modifier = Modifier +) { + var edgeColor by remember { mutableStateOf(viewModel.color) } + + Canvas(modifier = modifier.fillMaxSize()) { + edgeColor = viewModel.color + val source = Offset( + viewModel.u.x.toPx() + viewModel.u.radius.toPx(), + viewModel.u.y.toPx() + viewModel.u.radius.toPx() + ) + val destination = Offset( + viewModel.v.x.toPx() + viewModel.v.radius.toPx(), + viewModel.v.y.toPx() + viewModel.v.radius.toPx() + ) + val arrowSize = 35f + val angle = atan2(destination.y - source.y, destination.x - source.x) + val rotationAngle = PI / 12 + val arrowSourceX = destination.x - arrowSize * cos(angle + rotationAngle) + val arrowSourceY = destination.y - arrowSize * sin(angle + rotationAngle) + val arrowDestinationX = destination.x - arrowSize * cos(angle - rotationAngle) + val arrowDestinationY = destination.y - arrowSize * sin(angle - rotationAngle) + val path = Path().apply { + moveTo(source.x, source.y) + lineTo(destination.x, destination.y) + moveTo(destination.x, destination.y) + lineTo(arrowSourceX.toFloat(), arrowSourceY.toFloat()) + moveTo(destination.x, destination.y) + lineTo(arrowDestinationX.toFloat(), arrowDestinationY.toFloat()) + } + drawPath( + path = path, + color = edgeColor, + style = Stroke(width = 1.3.dp.toPx()) + ) + } + if (viewModel.labelVisible) { + Text( + modifier = Modifier + .offset( + viewModel.u.x + (viewModel.v.x - viewModel.u.x) / 2, + viewModel.u.y + (viewModel.v.y - viewModel.u.y) / 2 + ), + text = viewModel.label + ) + } +} diff --git a/src/main/kotlin/view/graphView/edgesView/EdgeView.kt b/src/main/kotlin/view/graphView/edgesView/EdgeView.kt new file mode 100644 index 0000000..5e5e5aa --- /dev/null +++ b/src/main/kotlin/view/graphView/edgesView/EdgeView.kt @@ -0,0 +1,47 @@ +package view.graphView.edgesView + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import viewModel.graphViewModel.edgesViewModel.EdgeViewModel + +@Composable +fun edgeView( + viewModel: EdgeViewModel, + modifier: Modifier = Modifier +) { + var edgeColor by remember { mutableStateOf(viewModel.color) } + + Canvas(modifier = modifier.fillMaxSize()) { + edgeColor = viewModel.color + drawLine( + start = Offset( + viewModel.u.x.toPx() + viewModel.u.radius.toPx(), + viewModel.u.y.toPx() + viewModel.u.radius.toPx() + ), + end = Offset( + viewModel.v.x.toPx() + viewModel.v.radius.toPx(), + viewModel.v.y.toPx() + viewModel.v.radius.toPx() + ), + color = edgeColor + ) + } + if (viewModel.labelVisible) { + Text( + modifier = Modifier + .offset( + viewModel.u.x + (viewModel.v.x - viewModel.u.x) / 2, + viewModel.u.y + (viewModel.v.y - viewModel.u.y) / 2 + ), + text = viewModel.label + ) + } +} \ No newline at end of file diff --git a/src/main/kotlin/view/graphView/graphsView/GraphView.kt b/src/main/kotlin/view/graphView/graphsView/GraphView.kt new file mode 100644 index 0000000..20a2d6c --- /dev/null +++ b/src/main/kotlin/view/graphView/graphsView/GraphView.kt @@ -0,0 +1,29 @@ +package view.graphView.graphsView + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import model.graphs.graphs.DirectedGraph +import view.graphView.edgesView.directedEdgeView +import view.graphView.edgesView.edgeView +import view.graphView.vertexView +import viewModel.graphViewModel.graphsViewModel.GraphViewModel + +@Composable +fun graphView( + viewModel: GraphViewModel +) { + Box( + modifier = Modifier + .fillMaxSize() + + ) { + viewModel.vertices.forEach { v -> + vertexView(v, Modifier) + } + viewModel.edges.forEach { e -> + if (viewModel.graph is DirectedGraph) directedEdgeView(e, Modifier) else edgeView(e, Modifier) + } + } +} diff --git a/src/main/kotlin/view/graphView/graphsView/WeightedGraphView.kt b/src/main/kotlin/view/graphView/graphsView/WeightedGraphView.kt new file mode 100644 index 0000000..ec287b9 --- /dev/null +++ b/src/main/kotlin/view/graphView/graphsView/WeightedGraphView.kt @@ -0,0 +1,29 @@ +package view.graphView.graphsView + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import model.graphs.graphs.WeightedDirectedGraph +import view.graphView.edgesView.directedEdgeView +import view.graphView.edgesView.edgeView +import view.graphView.vertexView +import viewModel.graphViewModel.graphsViewModel.WeightedGraphViewModel + +@Composable +fun weightedGraphView( + viewModel: WeightedGraphViewModel +) { + Box( + modifier = Modifier + .fillMaxSize() + + ) { + viewModel.vertices.forEach { v -> + vertexView(v, Modifier) + } + viewModel.edges.forEach { e -> + if (viewModel.graph is WeightedDirectedGraph) directedEdgeView(e, Modifier) else edgeView(e, Modifier) + } + } +} diff --git a/src/main/kotlin/view/screens/GraphChooseScreen.kt b/src/main/kotlin/view/screens/GraphChooseScreen.kt new file mode 100644 index 0000000..0da3ae7 --- /dev/null +++ b/src/main/kotlin/view/screens/GraphChooseScreen.kt @@ -0,0 +1,64 @@ +package view.screens + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.material.Button +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.unit.dp +import viewModel.screensViewModels.GraphChooseViewModel + +@Composable +fun graphChooseScreen(viewModel: GraphChooseViewModel, onDismiss: () -> Unit) { + Row( + horizontalArrangement = Arrangement.spacedBy(20.dp) + ) { + Button( + onClick = { + viewModel.selectGraph() + onDismiss() + }, + enabled = true + ) { + Text( + text = "Graph" + ) + } + + Button( + onClick = { + viewModel.selectDirectedGraph() + onDismiss() + }, + enabled = true + ) { + Text( + text = "Directed graph" + ) + } + + Button( + onClick = { + viewModel.selectWeightedGraph() + onDismiss() + }, + enabled = true + ) { + Text( + text = "Weighted graph" + ) + } + + Button( + onClick = { + viewModel.selectWeightedDirectedGraph() + onDismiss() + }, + enabled = true + ) { + Text( + text = "Weighted directed graph" + ) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/view/screens/PlacementStrategyScreen.kt b/src/main/kotlin/view/screens/PlacementStrategyScreen.kt new file mode 100644 index 0000000..39956ca --- /dev/null +++ b/src/main/kotlin/view/screens/PlacementStrategyScreen.kt @@ -0,0 +1,40 @@ +package view.screens + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.material.Button +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.unit.dp +import viewModel.screensViewModels.PlacementStrategyViewModel + +@Composable +fun placementStrategyScreen(viewModel: PlacementStrategyViewModel, onDismiss: () -> Unit) { + Row( + horizontalArrangement = Arrangement.spacedBy(20.dp) + ) { + Button( + onClick = { + viewModel.selectYifanHu() + onDismiss() + }, + enabled = true + ) { + Text( + text = "YifanHu" + ) + } + + Button( + onClick = { + viewModel.selectCircular() + onDismiss() + }, + enabled = true + ) { + Text( + text = "Circular" + ) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/view/screens/mainScreens/MainScreen.kt b/src/main/kotlin/view/screens/mainScreens/MainScreen.kt new file mode 100644 index 0000000..655e814 --- /dev/null +++ b/src/main/kotlin/view/screens/mainScreens/MainScreen.kt @@ -0,0 +1,127 @@ +package view.screens.mainScreens + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.material.AlertDialog +import androidx.compose.material.Button +import androidx.compose.material.Checkbox +import androidx.compose.material.DropdownMenu +import androidx.compose.material.DropdownMenuItem +import androidx.compose.material.OutlinedTextField +import androidx.compose.material.Surface +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import view.graphView.graphsView.graphView +import viewModel.screensViewModels.mainScreensViewModels.MainScreenViewModel + +@Composable +fun mainScreen(viewModel: MainScreenViewModel, isDirected: Boolean) { + Row( + horizontalArrangement = Arrangement.spacedBy(20.dp) + ) { + Column(modifier = Modifier.width(370.dp)) { + Row { + Checkbox(checked = viewModel.showVerticesLabels.value, onCheckedChange = { + viewModel.showVerticesLabels.value = it + }) + Text("Show vertices labels", fontSize = 28.sp, modifier = Modifier.padding(4.dp)) + } + Button( + onClick = viewModel::resetGraphView, + enabled = true + ) { + Text( + text = "Reset" + ) + } + var expanded by remember { mutableStateOf(false) } + var dialogOpen by remember { mutableStateOf(false) } + var cycleVertex by remember { mutableStateOf(0) } + val items = + mutableListOf("Find cycles for a vertex", "Select key vertices") + if (isDirected) items.add("Select strongly connected components") + else items.add(0, "Find bridges") + fun onItemSelected(item: String) { + when (item) { + "Select key vertices" -> viewModel.selectKeyVertices() + "Select strongly connected components" -> viewModel.selectStronglyConnectedComponents() + "Find bridges" -> viewModel.findBridges() + "Find cycles for a vertex" -> { + dialogOpen = true + } + } + } + if (dialogOpen) { + AlertDialog( + onDismissRequest = { + dialogOpen = false + }, + title = { Text("Enter the vertex, please") }, + text = { + Column { + OutlinedTextField( + value = cycleVertex.toString(), + onValueChange = { cycleVertex = it.toIntOrNull() ?: 0 }, + label = { Text("Vertex") } + ) + } + }, + confirmButton = { + Button( + onClick = { + dialogOpen = false + viewModel.findCycle(cycleVertex) + } + ) { + Text("OK") + } + }, + dismissButton = { + Button( + onClick = { dialogOpen = false } + ) { + Text("Cancel") + } + } + ) + } + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false } + ) { + items.forEach { item -> + DropdownMenuItem(onClick = { + onItemSelected(item) + expanded = false + }) { + Text(item) + } + } + } + Button( + onClick = { expanded = true }, + enabled = true + ) { + Text( + text = "Algorithms" + ) + } + } + + Surface( + modifier = Modifier.weight(1f) + ) { + graphView(viewModel.graphViewModel) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/view/screens/mainScreens/MainScreenWeightedGraph.kt b/src/main/kotlin/view/screens/mainScreens/MainScreenWeightedGraph.kt new file mode 100644 index 0000000..9f28275 --- /dev/null +++ b/src/main/kotlin/view/screens/mainScreens/MainScreenWeightedGraph.kt @@ -0,0 +1,201 @@ +package view.screens.mainScreens + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.material.AlertDialog +import androidx.compose.material.Button +import androidx.compose.material.Checkbox +import androidx.compose.material.DropdownMenu +import androidx.compose.material.DropdownMenuItem +import androidx.compose.material.OutlinedTextField +import androidx.compose.material.Surface +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import view.graphView.graphsView.weightedGraphView +import viewModel.screensViewModels.mainScreensViewModels.MainScreenViewModelWeightedGraph + +@Composable +fun mainScreenWeightedGraph(viewModel: MainScreenViewModelWeightedGraph, isDirected: Boolean) { + Row( + horizontalArrangement = Arrangement.spacedBy(20.dp) + ) { + Column(modifier = Modifier.width(370.dp)) { + Row { + Checkbox(checked = viewModel.showVerticesLabels.value, onCheckedChange = { + viewModel.showVerticesLabels.value = it + }) + Text("Show vertices labels", fontSize = 28.sp, modifier = Modifier.padding(4.dp)) + } + Row { + Checkbox(checked = viewModel.showEdgesLabels.value, onCheckedChange = { + viewModel.showEdgesLabels.value = it + }) + Text("Show edges weights", fontSize = 28.sp, modifier = Modifier.padding(4.dp)) + } + Button( + onClick = viewModel::resetGraphView, + enabled = true + ) { + Text( + text = "Reset" + ) + } + var expanded by remember { mutableStateOf(false) } + var dialogOpen by remember { mutableStateOf(false) } + var dialogSecondOpen by remember { mutableStateOf(false) } + var pathFindStartVertex by remember { mutableStateOf(0) } + var pathFindFinishVertex by remember { mutableStateOf(0) } + var cycleVertex by remember { mutableStateOf(0) } + var isFordBellman by remember { mutableStateOf(false) } + val items = + mutableListOf( + "Find cycles for a vertex", + "Select key vertices" + ) + if (isDirected) items.apply { + items.add(1, "Find shortest path (Ford-Bellman)") + items.add("Select strongly connected components") + } + else items.apply { + items.add(1, "Find shortest path (Dijkstra)") + items.add(0, "Find bridges") + items.add(0, "Build a minimal spanning tree") + } + fun onItemSelected(item: String) { + when (item) { + "Select key vertices" -> viewModel.selectKeyVertices() + "Select strongly connected components" -> viewModel.selectStronglyConnectedComponents() + "Find bridges" -> viewModel.findBridges() + "Find cycles for a vertex" -> { + dialogSecondOpen = true + } + + "Build a minimal spanning tree" -> viewModel.buildMST() + "Find shortest path (Dijkstra)" -> { + isFordBellman = false + dialogOpen = true + } + + "Find shortest path (Ford-Bellman)" -> { + isFordBellman = true + dialogOpen = true + } + } + } + if (dialogOpen) { + AlertDialog( + onDismissRequest = { + dialogOpen = false + }, + title = { Text("Enter source and destination vertices, please") }, + text = { + Column { + OutlinedTextField( + value = pathFindStartVertex.toString(), + onValueChange = { pathFindStartVertex = it.toIntOrNull() ?: 0 }, + label = { Text("Source") } + ) + OutlinedTextField( + value = pathFindFinishVertex.toString(), + onValueChange = { pathFindFinishVertex = it.toIntOrNull() ?: 0 }, + label = { Text("Destination") } + ) + } + }, + confirmButton = { + Button( + onClick = { + dialogOpen = false + viewModel.findShortestPath( + isFordBellman, + pathFindStartVertex - 1, + pathFindFinishVertex - 1 + ) + } + ) { + Text("OK") + } + }, + dismissButton = { + Button( + onClick = { dialogOpen = false } + ) { + Text("Cancel") + } + } + ) + } + if (dialogSecondOpen) { + AlertDialog( + onDismissRequest = { + dialogOpen = false + }, + title = { Text("Enter the vertex, please") }, + text = { + Column { + OutlinedTextField( + value = cycleVertex.toString(), + onValueChange = { cycleVertex = it.toIntOrNull() ?: 0 }, + label = { Text("Vertex") } + ) + } + }, + confirmButton = { + Button( + onClick = { + dialogSecondOpen = false + viewModel.findCycle(cycleVertex) + } + ) { + Text("OK") + } + }, + dismissButton = { + Button( + onClick = { dialogSecondOpen = false } + ) { + Text("Cancel") + } + } + ) + } + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false } + ) { + items.forEach { item -> + DropdownMenuItem(onClick = { + onItemSelected(item) + expanded = false + }) { + Text(item) + } + } + } + Button( + onClick = { expanded = true }, + enabled = true + ) { + Text( + text = "Algorithms" + ) + } + } + + Surface( + modifier = Modifier.weight(1f) + ) { + weightedGraphView(viewModel.graphViewModel) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/graphViewModel/CircularPlacementStrategy.kt b/src/main/kotlin/viewModel/graphViewModel/CircularPlacementStrategy.kt new file mode 100644 index 0000000..bee0ac8 --- /dev/null +++ b/src/main/kotlin/viewModel/graphViewModel/CircularPlacementStrategy.kt @@ -0,0 +1,63 @@ +package viewModel.graphViewModel + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import model.graphs.edges.Edge +import model.graphs.graphs.AbstractGraph +import viewModel.graphViewModel.edgesViewModel.EdgeViewModel +import kotlin.math.cos +import kotlin.math.min +import kotlin.math.sin + +class CircularPlacementStrategy : RepresentationStrategy { + override fun place(width: Double, height: Double, graph: AbstractGraph, vertices: Collection>) { + if (vertices.isEmpty()) { + println("CircularPlacementStrategy.place: there is nothing to place 👐🏻") + return + } + + val center = Pair(width / 2, height / 2) + val angle = 2 * Math.PI / vertices.size + + val sorted = vertices.sortedBy { it.label } + val first = sorted.first() + var point = Pair(center.first, center.second - min(width, height) / 2) + first.x = point.first.dp + first.y = point.second.dp + first.color = Color.Gray + + sorted + .drop(1) + .onEach { + point = point.rotate(center, angle) + it.x = point.first.dp + it.y = point.second.dp + } + } + + override fun highlightVertices(vertices: Collection>, color: Color) { + vertices + .onEach { + it.color = color + } + } + + override fun highlightEdges(edges: Collection>, color: Color) { + edges + .onEach { + it.color = color + } + } + + private fun Pair.rotate(pivot: Pair, angle: Double): Pair { + val sin = sin(angle) + val cos = cos(angle) + + val diff = first - pivot.first to second - pivot.second + val rotated = Pair( + diff.first * cos - diff.second * sin, + diff.first * sin + diff.second * cos + ) + return rotated.first + pivot.first to rotated.second + pivot.second + } +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/graphViewModel/RepresentationStrategy.kt b/src/main/kotlin/viewModel/graphViewModel/RepresentationStrategy.kt new file mode 100644 index 0000000..d901b9c --- /dev/null +++ b/src/main/kotlin/viewModel/graphViewModel/RepresentationStrategy.kt @@ -0,0 +1,12 @@ +package viewModel.graphViewModel + +import androidx.compose.ui.graphics.Color +import model.graphs.edges.Edge +import model.graphs.graphs.AbstractGraph +import viewModel.graphViewModel.edgesViewModel.EdgeViewModel + +interface RepresentationStrategy { + fun place(width: Double, height: Double, graph: AbstractGraph, vertices: Collection>) + fun highlightVertices(vertices: Collection>, color: Color) + fun highlightEdges(edges: Collection>, color: Color) +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/graphViewModel/VertexViewModel.kt b/src/main/kotlin/viewModel/graphViewModel/VertexViewModel.kt new file mode 100644 index 0000000..d4679fc --- /dev/null +++ b/src/main/kotlin/viewModel/graphViewModel/VertexViewModel.kt @@ -0,0 +1,48 @@ +package viewModel.graphViewModel + +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import model.graphs.vertex.Vertex + +class VertexViewModel( + x: Dp = 0.dp, + y: Dp = 0.dp, + color: Color, + val v: Vertex, + private val _labelVisible: State, + val radius: Dp = 25.dp +) { + private var _x = mutableStateOf(x) + var x: Dp + get() = _x.value + set(value) { + _x.value = value + } + private var _y = mutableStateOf(y) + var y: Dp + get() = _y.value + set(value) { + _y.value = value + } + private var _color = mutableStateOf(color) + var color: Color + get() = _color.value + set(value) { + _color.value = value + } + + val label + get() = v.value.toString() + + val labelVisible + get() = _labelVisible.value + + fun onDrag(offset: Offset) { + _x.value += offset.x.dp + _y.value += offset.y.dp + } +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/graphViewModel/YifanHuPlacementStrategy.kt b/src/main/kotlin/viewModel/graphViewModel/YifanHuPlacementStrategy.kt new file mode 100644 index 0000000..be05713 --- /dev/null +++ b/src/main/kotlin/viewModel/graphViewModel/YifanHuPlacementStrategy.kt @@ -0,0 +1,38 @@ +package viewModel.graphViewModel + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import model.algorithms.placement.YifanHuPlacement +import model.graphs.edges.Edge +import model.graphs.graphs.AbstractGraph +import viewModel.graphViewModel.edgesViewModel.EdgeViewModel + +class YifanHuPlacementStrategy : RepresentationStrategy { + override fun place( + width: Double, + height: Double, + graph: AbstractGraph, + vertices: Collection> + ) { + val placemnt = YifanHuPlacement(graph).getPlacement(width.toInt(), height.toInt()) + + for (vertex in vertices) { + vertex.x = placemnt[vertex.v.value]?.first?.dp ?: 0f.dp + vertex.y = placemnt[vertex.v.value]?.second?.dp ?: 0f.dp + } + } + + override fun highlightVertices(vertices: Collection>, color: Color) { + vertices + .onEach { + it.color = color + } + } + + override fun highlightEdges(edges: Collection>, color: Color) { + edges + .onEach { + it.color = color + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/graphViewModel/edgesViewModel/EdgeViewModel.kt b/src/main/kotlin/viewModel/graphViewModel/edgesViewModel/EdgeViewModel.kt new file mode 100644 index 0000000..95b2e52 --- /dev/null +++ b/src/main/kotlin/viewModel/graphViewModel/edgesViewModel/EdgeViewModel.kt @@ -0,0 +1,20 @@ +package viewModel.graphViewModel.edgesViewModel + +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.graphics.Color +import viewModel.graphViewModel.VertexViewModel + +open class EdgeViewModel( + val u: VertexViewModel, + val v: VertexViewModel, + color: Color +) { + open val label: String = "" + open val labelVisible: Boolean = false + private var _color = mutableStateOf(color) + var color: Color + get() = _color.value + set(value) { + _color.value = value + } +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/graphViewModel/edgesViewModel/WeightedEdgeViewModel.kt b/src/main/kotlin/viewModel/graphViewModel/edgesViewModel/WeightedEdgeViewModel.kt new file mode 100644 index 0000000..16ebdf3 --- /dev/null +++ b/src/main/kotlin/viewModel/graphViewModel/edgesViewModel/WeightedEdgeViewModel.kt @@ -0,0 +1,19 @@ +package viewModel.graphViewModel.edgesViewModel + +import androidx.compose.runtime.State +import androidx.compose.ui.graphics.Color +import model.graphs.edges.WeightedEdge +import viewModel.graphViewModel.VertexViewModel + +class WeightedEdgeViewModel( + u: VertexViewModel, + v: VertexViewModel, + color: Color, + private val e: WeightedEdge, + private val _labelVisible: State +) : EdgeViewModel(u, v, color) { + override val label + get() = e.weight.toString() + override val labelVisible + get() = _labelVisible.value +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/graphViewModel/graphsViewModel/GraphViewModel.kt b/src/main/kotlin/viewModel/graphViewModel/graphsViewModel/GraphViewModel.kt new file mode 100644 index 0000000..d222ee9 --- /dev/null +++ b/src/main/kotlin/viewModel/graphViewModel/graphsViewModel/GraphViewModel.kt @@ -0,0 +1,31 @@ +package viewModel.graphViewModel.graphsViewModel + +import androidx.compose.runtime.State +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import model.graphs.graphs.Graph +import viewModel.graphViewModel.VertexViewModel +import viewModel.graphViewModel.edgesViewModel.EdgeViewModel + +class GraphViewModel( + val graph: Graph, + showVerticesLabels: State +) { + val verticesMap = graph.vertices.values.associateWith { v -> + VertexViewModel(0.dp, 0.dp, Color.Gray, v, showVerticesLabels) + } + + val edgesMap = graph.edges.values.associateWith { e -> + val fst = verticesMap[graph.vertices[e.verticesNumbers.first]] + ?: throw IllegalStateException("VertexView for ${graph.vertices[e.verticesNumbers.first]} not found") + val snd = verticesMap[graph.vertices[e.verticesNumbers.second]] + ?: throw IllegalStateException("VertexView for ${graph.vertices[e.verticesNumbers.first]} not found") + EdgeViewModel(fst, snd, Color.Black) + } + + val vertices: Collection> + get() = verticesMap.values + + val edges: Collection> + get() = edgesMap.values +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/graphViewModel/graphsViewModel/WeightedGraphViewModel.kt b/src/main/kotlin/viewModel/graphViewModel/graphsViewModel/WeightedGraphViewModel.kt new file mode 100644 index 0000000..ccc0ca4 --- /dev/null +++ b/src/main/kotlin/viewModel/graphViewModel/graphsViewModel/WeightedGraphViewModel.kt @@ -0,0 +1,33 @@ +package viewModel.graphViewModel.graphsViewModel + +import androidx.compose.runtime.State +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import model.graphs.graphs.WeightedGraph +import viewModel.graphViewModel.VertexViewModel +import viewModel.graphViewModel.edgesViewModel.WeightedEdgeViewModel + +class WeightedGraphViewModel( + val graph: WeightedGraph, + showVerticesLabels: State, + showEdgesLabels: State +) { + + val verticesMap = graph.vertices.values.associateWith { v -> + VertexViewModel(0.dp, 0.dp, Color.Gray, v, showVerticesLabels) + } + + val edgesMap = graph.edges.values.associateWith { e -> + val fst = verticesMap[graph.vertices[e.verticesNumbers.first]] + ?: throw IllegalStateException("VertexView for ${graph.vertices[e.verticesNumbers.first]} not found") + val snd = verticesMap[graph.vertices[e.verticesNumbers.second]] + ?: throw IllegalStateException("VertexView for ${graph.vertices[e.verticesNumbers.first]} not found") + WeightedEdgeViewModel(fst, snd, Color.Black, e, showEdgesLabels) + } + + val vertices: Collection> + get() = verticesMap.values + + val edges: Collection> + get() = edgesMap.values +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/screensViewModels/GraphChooseViewModel.kt b/src/main/kotlin/viewModel/screensViewModels/GraphChooseViewModel.kt new file mode 100644 index 0000000..2bfcf4e --- /dev/null +++ b/src/main/kotlin/viewModel/screensViewModels/GraphChooseViewModel.kt @@ -0,0 +1,26 @@ +package viewModel.screensViewModels + +class GraphChooseViewModel { + internal var isDirected = false + internal var isWeighted = false + + fun selectGraph() { + isDirected = false + isWeighted = false + } + + fun selectDirectedGraph() { + isDirected = true + isWeighted = false + } + + fun selectWeightedGraph() { + isDirected = false + isWeighted = true + } + + fun selectWeightedDirectedGraph() { + isDirected = true + isWeighted = true + } +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/screensViewModels/PlacementStrategyViewModel.kt b/src/main/kotlin/viewModel/screensViewModels/PlacementStrategyViewModel.kt new file mode 100644 index 0000000..da24295 --- /dev/null +++ b/src/main/kotlin/viewModel/screensViewModels/PlacementStrategyViewModel.kt @@ -0,0 +1,16 @@ +package viewModel.screensViewModels + +import viewModel.graphViewModel.CircularPlacementStrategy +import viewModel.graphViewModel.RepresentationStrategy +import viewModel.graphViewModel.YifanHuPlacementStrategy + +class PlacementStrategyViewModel { + internal var placementStrategy: RepresentationStrategy = CircularPlacementStrategy() + + fun selectYifanHu() { + placementStrategy = YifanHuPlacementStrategy() + } + fun selectCircular() { + placementStrategy = CircularPlacementStrategy() + } +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/screensViewModels/mainScreensViewModels/MainScreenViewModel.kt b/src/main/kotlin/viewModel/screensViewModels/mainScreensViewModels/MainScreenViewModel.kt new file mode 100644 index 0000000..559339d --- /dev/null +++ b/src/main/kotlin/viewModel/screensViewModels/mainScreensViewModels/MainScreenViewModel.kt @@ -0,0 +1,140 @@ +package viewModel.screensViewModels.mainScreensViewModels + +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.graphics.Color +import model.algorithms.bridgeFinder.BridgeFinder +import model.algorithms.keyVerticesSelection.KeyVerticesSelectionSolver +import model.algorithms.searchCycle.SearchCycleForVertexInDirectedGraphSolver +import model.algorithms.searchCycle.SearchCycleForVertexInGraphSolver +import model.algorithms.stronglyConnectedComponentsSelection.StronglyConnectedComponentsSelectionSolver +import model.graphs.graphs.DirectedGraph +import model.graphs.graphs.Graph +import viewModel.graphViewModel.RepresentationStrategy +import viewModel.graphViewModel.VertexViewModel +import viewModel.graphViewModel.edgesViewModel.EdgeViewModel +import viewModel.graphViewModel.graphsViewModel.GraphViewModel +import kotlin.random.Random + +class MainScreenViewModel(val graph: Graph, private val representationStrategy: RepresentationStrategy) { + + val showVerticesLabels = mutableStateOf(false) + val graphViewModel = GraphViewModel(graph, showVerticesLabels) + + init { + representationStrategy.place(800.0, 600.0, graph, graphViewModel.vertices) + } + + fun resetGraphView() { + representationStrategy.place(800.0, 600.0, graph, graphViewModel.vertices) + graphViewModel.vertices.forEach { v -> v.color = Color.Gray } + graphViewModel.edges.forEach { e -> e.color = Color.Black } + } + + private fun setVerticesColor(verticesToHighlight: List) { + val verticesList: MutableList> = mutableListOf() + for (vertexNum in verticesToHighlight) { + val vertex = graph.vertices[vertexNum] ?: throw IllegalArgumentException("No such vertex in a graph model") + val vertexViewModel = graphViewModel.verticesMap[vertex] + ?: throw IllegalArgumentException("No such vertex in a graph ViewModel") + verticesList.add(vertexViewModel) + } + representationStrategy.highlightVertices(verticesList, Color.Green) + } + + fun selectKeyVertices() { + val solver = KeyVerticesSelectionSolver(graph) + val keyVerticesList = solver.selectKeyVertices() + setVerticesColor(keyVerticesList) + } + + fun selectStronglyConnectedComponents() { + if (graph !is DirectedGraph) throw IllegalArgumentException("Only directed graph supported") + val solver = StronglyConnectedComponentsSelectionSolver(graph) + val componentsMap = solver.selectStronglyConnectedComponents() + val componentsColors: MutableMap = mutableMapOf() + val usedTriples: MutableList> = mutableListOf(Triple(0, 0, 0)) + for (componentNum in componentsMap.values) { + if (componentNum !in componentsColors.keys) { + var randomTriple = Triple(0, 0, 0) + while (randomTriple in usedTriples) randomTriple = + Triple(Random.nextInt(256), Random.nextInt(256), Random.nextInt(256)) + usedTriples.add(randomTriple) + val color = Color(randomTriple.first, randomTriple.second, randomTriple.third, 255) + componentsColors[componentNum] = color + } + } + for (vertexNum in componentsMap.keys) { + val vertex = graph.vertices[vertexNum] ?: throw IllegalArgumentException("No such vertex in a graph model") + val vertexViewModel = graphViewModel.verticesMap[vertex] + ?: throw IllegalArgumentException("No such vertex in a graph ViewModel") + val componentNum = + componentsMap[vertexNum] ?: throw IllegalArgumentException("No component found for this vertex") + val color = + componentsColors[componentNum] ?: throw IllegalArgumentException("No color found for this component") + representationStrategy.highlightVertices(listOf(vertexViewModel), color) + } + } + + fun findBridges() { + val solver = BridgeFinder(graph) + val bridges = solver.findBridges() + val toHighlightEdges: MutableList> = mutableListOf() + for (bridge in bridges) { + for (edge in graph.edges.values) { + if ((bridge == edge.verticesNumbers) || (Pair(bridge.second, bridge.first) == edge.verticesNumbers)) { + val edgeViewModel = + graphViewModel.edgesMap[edge] ?: throw IllegalArgumentException("No ViewModel for such edge") + toHighlightEdges.add(edgeViewModel) + } + } + } + representationStrategy.highlightEdges(toHighlightEdges, Color.Red) + } + + fun findCycle(cycleVertexNum: Int) { + val solver = + if (graph is DirectedGraph) SearchCycleForVertexInDirectedGraphSolver(graph) else SearchCycleForVertexInGraphSolver( + graph + ) + val vertexNum = cycleVertexNum - 1 + val resultHasCycle = solver.searchCycleForVertex(vertexNum) + val resultList = solver.getCycle() + val toHighlightVertices: MutableList> = mutableListOf() + val toHighlightEdges: MutableList> = mutableListOf() + var previousVertexNum = vertexNum + if (resultHasCycle) { + for (currVertexNum in resultList) { + val vertex = + graph.vertices[currVertexNum] ?: throw IllegalArgumentException("No such vertex in graph model") + val vertexViewModel = graphViewModel.verticesMap[vertex] + ?: throw IllegalArgumentException("No such vertex in a graph ViewModel") + toHighlightVertices.add(vertexViewModel) + for (edge in graph.edges.values) { + if (graph is DirectedGraph) { + if (edge.verticesNumbers == Pair(previousVertexNum, currVertexNum)) { + val edgeViewModel = graphViewModel.edgesMap[edge] + ?: throw IllegalArgumentException("No such edge in a graph ViewModel") + toHighlightEdges.add(edgeViewModel) + } + } else { + if ((edge.verticesNumbers == Pair(previousVertexNum, currVertexNum)) || (edge.verticesNumbers == Pair(currVertexNum, previousVertexNum))) { + val edgeViewModel = graphViewModel.edgesMap[edge] + ?: throw IllegalArgumentException("No such edge in a graph ViewModel") + toHighlightEdges.add(edgeViewModel) + } + } + } + previousVertexNum = currVertexNum + } + representationStrategy.highlightVertices(toHighlightVertices, Color.Green) + representationStrategy.highlightEdges(toHighlightEdges, Color.Red) + } else { + val vertex = + graph.vertices[vertexNum] ?: throw IllegalArgumentException("No such vertex in graph model") + val vertexViewModel = graphViewModel.verticesMap[vertex] + ?: throw IllegalArgumentException("No such vertex in a graph ViewModel") + toHighlightVertices.add(vertexViewModel) + representationStrategy.highlightVertices(toHighlightVertices, Color.Blue) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/viewModel/screensViewModels/mainScreensViewModels/MainScreenViewModelWeightedGraph.kt b/src/main/kotlin/viewModel/screensViewModels/mainScreensViewModels/MainScreenViewModelWeightedGraph.kt new file mode 100644 index 0000000..f67ae65 --- /dev/null +++ b/src/main/kotlin/viewModel/screensViewModels/mainScreensViewModels/MainScreenViewModelWeightedGraph.kt @@ -0,0 +1,224 @@ +package viewModel.screensViewModels.mainScreensViewModels + +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.graphics.Color +import model.algorithms.bridgeFinder.BridgeFinder +import model.algorithms.keyVerticesSelection.KeyVerticesSelectionSolver +import model.algorithms.kruskalAlgorithm.KruskalAlgorithmSolver +import model.algorithms.pathSearch.djikstra.DjikstraAlgorithm +import model.algorithms.pathSearch.fordBellman.FordBellmanAlgorithm +import model.algorithms.searchCycle.SearchCycleForVertexInDirectedGraphSolver +import model.algorithms.searchCycle.SearchCycleForVertexInGraphSolver +import model.algorithms.stronglyConnectedComponentsSelection.StronglyConnectedComponentsSelectionSolver +import model.graphs.graphs.DirectedGraph +import model.graphs.graphs.Graph +import model.graphs.graphs.WeightedDirectedGraph +import model.graphs.graphs.WeightedGraph +import model.graphs.vertex.Vertex +import viewModel.graphViewModel.RepresentationStrategy +import viewModel.graphViewModel.VertexViewModel +import viewModel.graphViewModel.edgesViewModel.EdgeViewModel +import viewModel.graphViewModel.edgesViewModel.WeightedEdgeViewModel +import viewModel.graphViewModel.graphsViewModel.WeightedGraphViewModel +import kotlin.random.Random + +class MainScreenViewModelWeightedGraph( + val graph: WeightedGraph, + private val representationStrategy: RepresentationStrategy +) { + val showVerticesLabels = mutableStateOf(false) + val showEdgesLabels = mutableStateOf(false) + val graphViewModel = WeightedGraphViewModel(graph, showVerticesLabels, showEdgesLabels) + + init { + representationStrategy.place(800.0, 600.0, graph, graphViewModel.vertices) + } + + fun resetGraphView() { + representationStrategy.place(800.0, 600.0, graph, graphViewModel.vertices) + graphViewModel.vertices.forEach { v -> v.color = Color.Gray } + graphViewModel.edges.forEach { e -> e.color = Color.Black } + } + + private fun setVerticesColor(verticesToHighlight: List) { + val verticesList: MutableList> = mutableListOf() + for (vertexNum in verticesToHighlight) { + val vertex = graph.vertices[vertexNum] ?: throw IllegalArgumentException("No such vertex in a graph model") + val vertexViewModel = graphViewModel.verticesMap[vertex] + ?: throw IllegalArgumentException("No such vertex in a graph ViewModel") + verticesList.add(vertexViewModel) + } + representationStrategy.highlightVertices(verticesList, Color.Green) + } + + fun selectKeyVertices() { + val sameGraphNoWeights: Graph = if (graph is WeightedDirectedGraph) DirectedGraph() else Graph() + for (vertex in graph.vertices.values) sameGraphNoWeights.addVertex(vertex.value) + for (edge in graph.edges.values) sameGraphNoWeights.addEdge( + edge.verticesNumbers.first, + edge.verticesNumbers.second + ) + val solver = KeyVerticesSelectionSolver(sameGraphNoWeights) + val keyVerticesList = solver.selectKeyVertices() + setVerticesColor(keyVerticesList) + } + + fun selectStronglyConnectedComponents() { + if (graph !is WeightedDirectedGraph) throw IllegalArgumentException("Only directed graph supported") + val sameGraphNoWeights: DirectedGraph = DirectedGraph() + for (vertex in graph.vertices.values) sameGraphNoWeights.addVertex(vertex.value) + for (edge in graph.edges.values) sameGraphNoWeights.addEdge( + edge.verticesNumbers.first, + edge.verticesNumbers.second + ) + val solver = StronglyConnectedComponentsSelectionSolver(sameGraphNoWeights) + val componentsMap = solver.selectStronglyConnectedComponents() + val componentsColors: MutableMap = mutableMapOf() + val usedTriples: MutableList> = mutableListOf(Triple(0, 0, 0)) + for (componentNum in componentsMap.values) { + if (componentNum !in componentsColors.keys) { + var randomTriple = Triple(0, 0, 0) + while (randomTriple in usedTriples) randomTriple = + Triple(Random.nextInt(256), Random.nextInt(256), Random.nextInt(256)) + usedTriples.add(randomTriple) + val color = Color(randomTriple.first, randomTriple.second, randomTriple.third, 255) + componentsColors[componentNum] = color + } + } + for (vertexNum in componentsMap.keys) { + val vertex = graph.vertices[vertexNum] ?: throw IllegalArgumentException("No such vertex in a graph model") + val vertexViewModel = graphViewModel.verticesMap[vertex] + ?: throw IllegalArgumentException("No such vertex in a graph ViewModel") + val componentNum = + componentsMap[vertexNum] ?: throw IllegalArgumentException("No component found for this vertex") + val color = + componentsColors[componentNum] ?: throw IllegalArgumentException("No color found for this component") + representationStrategy.highlightVertices(listOf(vertexViewModel), color) + } + } + + fun findShortestPath(isFordBellman: Boolean, startVertexNum: Int, finishVertexNum: Int) { + var previousVertex: Vertex? + val vertexList: List> + if (isFordBellman) { + if (graph !is WeightedDirectedGraph) throw IllegalArgumentException("Only directed graphs with negative weights are supported") + val solver = FordBellmanAlgorithm(graph) + val result = solver.findPath(startVertexNum, finishVertexNum) + previousVertex = result.sourceVertex + vertexList = result.vertexList + } else { + val solver = DjikstraAlgorithm(graph) + val result = solver.findNearestPath(startVertexNum, finishVertexNum) + previousVertex = result.sourceVertex + vertexList = result.vertexList + } + val toHighlightVertices: MutableList> = mutableListOf() + val toHighlightEdges: MutableList> = mutableListOf() + for (vertex in vertexList) { + val vertexViewModel = graphViewModel.verticesMap[vertex] + ?: throw IllegalArgumentException("No such vertex in a graph ViewModel") + toHighlightVertices.add(vertexViewModel) + for (edge in graph.edges.values) { + if ((isFordBellman && (Pair(graph.vertices[edge.verticesNumbers.first], graph.vertices[edge.verticesNumbers.second]) == Pair(previousVertex, vertex))) || (!isFordBellman && ((Pair(graph.vertices[edge.verticesNumbers.first], graph.vertices[edge.verticesNumbers.second]) == Pair(previousVertex, vertex)) || Pair(graph.vertices[edge.verticesNumbers.first], graph.vertices[edge.verticesNumbers.second]) == Pair(vertex, previousVertex)))) { + val edgeViewModel = + graphViewModel.edgesMap[edge] ?: throw IllegalArgumentException("No ViewModel for such edge") + toHighlightEdges.add(edgeViewModel) + } + } + previousVertex = vertex + } + representationStrategy.highlightVertices(toHighlightVertices, Color.Green) + representationStrategy.highlightEdges(toHighlightEdges, Color.Red) + } + + fun findBridges() { + val sameGraphNoWeights = Graph() + for (vertex in graph.vertices.values) sameGraphNoWeights.addVertex(vertex.value) + for (edge in graph.edges.values) sameGraphNoWeights.addEdge( + edge.verticesNumbers.first, + edge.verticesNumbers.second + ) + val solver = BridgeFinder(sameGraphNoWeights) + val bridges = solver.findBridges() + val toHighlightEdges: MutableList> = mutableListOf() + for (bridge in bridges) { + for (edge in graph.edges.values) { + if ((bridge == edge.verticesNumbers) || (Pair(bridge.second, bridge.first) == edge.verticesNumbers)) { + val edgeViewModel = + graphViewModel.edgesMap[edge] ?: throw IllegalArgumentException("No ViewModel for such edge") + toHighlightEdges.add(edgeViewModel) + } + } + } + representationStrategy.highlightEdges(toHighlightEdges, Color.Red) + } + + fun buildMST() { + val solver = KruskalAlgorithmSolver(graph) + val mst = solver.doKruskalAlgorithm() + val toHighlightNotIncludedEdges: MutableList> = mutableListOf() + val toHighlightIncludedEdges: MutableList> = mutableListOf() + for (edge in graph.edges.values) { + val edgeViewModel = + graphViewModel.edgesMap[edge] ?: throw IllegalArgumentException("No ViewModel for such edge") + if (edge in mst.second) toHighlightIncludedEdges.add(edgeViewModel) + else toHighlightNotIncludedEdges.add(edgeViewModel) + } + representationStrategy.highlightEdges(toHighlightIncludedEdges, Color.Red) + representationStrategy.highlightEdges(toHighlightNotIncludedEdges, Color.White) + } + + fun findCycle(cycleVertexNum: Int) { + val sameGraphNoWeights = if (graph is WeightedDirectedGraph) DirectedGraph() else Graph() + for (vertex in graph.vertices.values) sameGraphNoWeights.addVertex(vertex.value) + for (edge in graph.edges.values) sameGraphNoWeights.addEdge( + edge.verticesNumbers.first, + edge.verticesNumbers.second + ) + val solver = + if (sameGraphNoWeights is DirectedGraph) SearchCycleForVertexInDirectedGraphSolver(sameGraphNoWeights) else SearchCycleForVertexInGraphSolver( + sameGraphNoWeights + ) + val vertexNum = cycleVertexNum - 1 + val resultHasCycle = solver.searchCycleForVertex(vertexNum) + val resultList = solver.getCycle() + val toHighlightVertices: MutableList> = mutableListOf() + val toHighlightEdges: MutableList> = mutableListOf() + var previousVertexNum = vertexNum + if (resultHasCycle) { + for (currVertexNum in resultList) { + val vertex = + graph.vertices[currVertexNum] ?: throw IllegalArgumentException("No such vertex in graph model") + val vertexViewModel = graphViewModel.verticesMap[vertex] + ?: throw IllegalArgumentException("No such vertex in a graph ViewModel") + toHighlightVertices.add(vertexViewModel) + for (edge in graph.edges.values) { + if (sameGraphNoWeights is DirectedGraph) { + if (edge.verticesNumbers == Pair(previousVertexNum, currVertexNum)) { + val edgeViewModel = graphViewModel.edgesMap[edge] + ?: throw IllegalArgumentException("No such edge in a graph ViewModel") + toHighlightEdges.add(edgeViewModel) + } + } else { + if ((edge.verticesNumbers == Pair(previousVertexNum, currVertexNum)) || (edge.verticesNumbers == Pair(currVertexNum, previousVertexNum)) + ) { + val edgeViewModel = graphViewModel.edgesMap[edge] + ?: throw IllegalArgumentException("No such edge in a graph ViewModel") + toHighlightEdges.add(edgeViewModel) + } + } + } + previousVertexNum = currVertexNum + } + representationStrategy.highlightVertices(toHighlightVertices, Color.Green) + representationStrategy.highlightEdges(toHighlightEdges, Color.Red) + } else { + val vertex = + graph.vertices[vertexNum] ?: throw IllegalArgumentException("No such vertex in graph model") + val vertexViewModel = graphViewModel.verticesMap[vertex] + ?: throw IllegalArgumentException("No such vertex in a graph ViewModel") + toHighlightVertices.add(vertexViewModel) + representationStrategy.highlightVertices(toHighlightVertices, Color.Blue) + } + } +} \ No newline at end of file diff --git a/src/main/resources/bridge.png b/src/main/resources/bridge.png new file mode 100644 index 0000000..f04cb53 Binary files /dev/null and b/src/main/resources/bridge.png differ diff --git a/src/main/resources/cycle-vertex-choose.png b/src/main/resources/cycle-vertex-choose.png new file mode 100644 index 0000000..165ddd1 Binary files /dev/null and b/src/main/resources/cycle-vertex-choose.png differ diff --git a/src/main/resources/cycle.png b/src/main/resources/cycle.png new file mode 100644 index 0000000..83f76be Binary files /dev/null and b/src/main/resources/cycle.png differ diff --git a/src/main/resources/edges-weights.png b/src/main/resources/edges-weights.png new file mode 100644 index 0000000..c64aaf6 Binary files /dev/null and b/src/main/resources/edges-weights.png differ diff --git a/src/main/resources/graph-algos.png b/src/main/resources/graph-algos.png new file mode 100644 index 0000000..7039411 Binary files /dev/null and b/src/main/resources/graph-algos.png differ diff --git a/src/main/resources/graph-choose.png b/src/main/resources/graph-choose.png new file mode 100644 index 0000000..7ef1c5f Binary files /dev/null and b/src/main/resources/graph-choose.png differ diff --git a/src/main/resources/graph.png b/src/main/resources/graph.png new file mode 100644 index 0000000..3229044 Binary files /dev/null and b/src/main/resources/graph.png differ diff --git a/src/main/resources/key-vertices.png b/src/main/resources/key-vertices.png new file mode 100644 index 0000000..6bd87d0 Binary files /dev/null and b/src/main/resources/key-vertices.png differ diff --git a/src/main/resources/mst.png b/src/main/resources/mst.png new file mode 100644 index 0000000..2053e18 Binary files /dev/null and b/src/main/resources/mst.png differ diff --git a/src/main/resources/path-vertices.png b/src/main/resources/path-vertices.png new file mode 100644 index 0000000..483d912 Binary files /dev/null and b/src/main/resources/path-vertices.png differ diff --git a/src/main/resources/path.png b/src/main/resources/path.png new file mode 100644 index 0000000..2e49c92 Binary files /dev/null and b/src/main/resources/path.png differ diff --git a/src/main/resources/scc.png b/src/main/resources/scc.png new file mode 100644 index 0000000..a76736d Binary files /dev/null and b/src/main/resources/scc.png differ diff --git a/src/test/kotlin/algorithmsTests/BridgeFinderTests.kt b/src/test/kotlin/algorithmsTests/BridgeFinderTests.kt new file mode 100644 index 0000000..628e4db --- /dev/null +++ b/src/test/kotlin/algorithmsTests/BridgeFinderTests.kt @@ -0,0 +1,108 @@ +package algorithmsTests + +import model.algorithms.bridgeFinder.BridgeFinder +import model.graphs.graphs.Graph +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test +import kotlin.test.assertContentEquals + +class BridgeFinderTests { + private lateinit var graph: Graph + private lateinit var finder: BridgeFinder + + @BeforeEach + fun setup() { + graph = Graph() + finder = BridgeFinder(graph) + } + + @Test + @DisplayName("Empty graph") + fun emptyGraph() { + val result = finder.findBridges() + val expectedResult = listOf>() + assertContentEquals(result, expectedResult) + } + + @Test + @DisplayName("Graph with some vertex, but without edges") + fun withVertexWithoutEdges() { + graph.addVertex(0) + graph.addVertex(1) + graph.addVertex(2) + graph.addVertex(3) + graph.addVertex(4) + graph.addVertex(5) + graph.addVertex(6) + graph.addVertex(7) + + val result = finder.findBridges() + val expectedResult = listOf>() + assertContentEquals(result, expectedResult) + } + + @Test + @DisplayName("No bridges in graph") + fun noBridges() { + graph.addVertex(0) + graph.addVertex(1) + graph.addVertex(2) + graph.addVertex(3) + graph.addEdge(0, 1) + graph.addEdge(1, 3) + graph.addEdge(0, 2) + graph.addEdge(2, 3) + val result = finder.findBridges() + val expectedResult = listOf>() + assertContentEquals(result, expectedResult) + } + + @Test + @DisplayName("two components connected with bridge") + fun twoComponentsConnectedWithBriddge() { + graph.addVertex(0) + graph.addVertex(1) + graph.addVertex(2) + graph.addVertex(3) + graph.addVertex(4) + graph.addVertex(5) + graph.addVertex(6) + graph.addVertex(7) + graph.addEdge(0, 1) + graph.addEdge(1, 3) + graph.addEdge(0, 2) + graph.addEdge(2, 3) + graph.addEdge(4, 5) + graph.addEdge(4, 7) + graph.addEdge(7, 6) + graph.addEdge(5, 6) + graph.addEdge(3, 4) + val result = finder.findBridges() + val expectedResult = listOf(Pair(3, 4)) + assertContentEquals(result, expectedResult) + } + + @Test + @DisplayName("All edges are bridges") + fun allEdgesBridges() { + graph.addVertex(0) + graph.addVertex(1) + graph.addVertex(2) + graph.addVertex(3) + graph.addVertex(4) + graph.addVertex(5) + graph.addVertex(6) + graph.addVertex(7) + graph.addEdge(6, 7) + graph.addEdge(5, 6) + graph.addEdge(4, 5) + graph.addEdge(3, 4) + graph.addEdge(2, 3) + graph.addEdge(1, 2) + graph.addEdge(0, 1) + val result = finder.findBridges() + val expectedResult = listOf(Pair(6, 7), Pair(5, 6), Pair(4, 5), Pair(3, 4), Pair(2, 3), Pair(1, 2), Pair(0, 1)) + assertContentEquals(expectedResult, result) + } +} \ No newline at end of file diff --git a/src/test/kotlin/algorithmsTests/DjikstraTests.kt b/src/test/kotlin/algorithmsTests/DjikstraTests.kt new file mode 100644 index 0000000..47b12ca --- /dev/null +++ b/src/test/kotlin/algorithmsTests/DjikstraTests.kt @@ -0,0 +1,129 @@ +package algorithmsTests + +import model.algorithms.pathSearch.PathResult +import model.algorithms.pathSearch.djikstra.DjikstraAlgorithm +import model.graphs.graphs.WeightedGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +class DjikstraTests { + + private lateinit var graph: WeightedGraph + private lateinit var solver: DjikstraAlgorithm + + @BeforeEach + fun setup() { + graph = WeightedGraph() + solver = DjikstraAlgorithm(graph) + } + + private fun createExpectedPathResult(vararg ids: Int): PathResult { + val list = mutableListOf>() + + for (i in ids) { + if (!graph.vertices.containsKey(i)) throw IllegalArgumentException("Vertex with id $i not found") + list.add(graph.vertices[i]!!) + } + + return PathResult(graph, list) + } + private fun assertEqualsDjikstraPathResult(expected: PathResult, result: PathResult) { + assertEquals(expected.graph, result.graph) + assertEquals(expected.vertexList.size, result.vertexList.size) + for (i in 0.. 1") + fun firstSchema0to1() { + prepareGraphSchema_First() + + val result = solver.findNearestPath(0, 1) + val expresult = createExpectedPathResult(0, 1) + + assertEqualsDjikstraPathResult(expresult, result) + } + + @Test + @DisplayName("First Schema 0 -> 3") + fun firstSchema0to3() { + prepareGraphSchema_First() + + val result = solver.findNearestPath(0, 3) + val expresult = createExpectedPathResult(0, 3) + + assertEqualsDjikstraPathResult(expresult, result) + } + + @Test + @DisplayName("First Schema 0 -> 4") + fun firstSchema0to4() { + prepareGraphSchema_First() + + val result = solver.findNearestPath(0, 4) + val expresult = createExpectedPathResult(0, 3, 2, 4) + + assertEqualsDjikstraPathResult(expresult, result) + } + + @Test + @DisplayName("First Schema 4 -> 0") + fun firstSchema4to0() { + prepareGraphSchema_First() + + val result = solver.findNearestPath(4, 0) + val expresult = createExpectedPathResult(4, 2, 3, 0) + + assertEqualsDjikstraPathResult(expresult, result) + } + + @Test + @DisplayName("First Schema 1 -> 3") + fun firstSchema1to3() { + prepareGraphSchema_First() + + val result = solver.findNearestPath(1, 3) + val expresult = createExpectedPathResult(1, 0, 3) + + assertEqualsDjikstraPathResult(expresult, result) + } + + @Test + @DisplayName("First Schema 3 -> 1") + fun firstSchema3to1() { + prepareGraphSchema_First() + + val result = solver.findNearestPath(3, 1) + val expresult = createExpectedPathResult(3, 0, 1) + + assertEqualsDjikstraPathResult(expresult, result) + } +} \ No newline at end of file diff --git a/src/test/kotlin/algorithmsTests/FordBellmanTests.kt b/src/test/kotlin/algorithmsTests/FordBellmanTests.kt new file mode 100644 index 0000000..20b6c81 --- /dev/null +++ b/src/test/kotlin/algorithmsTests/FordBellmanTests.kt @@ -0,0 +1,118 @@ +package algorithmsTests + +import model.algorithms.pathSearch.fordBellman.FordBellmanAlgorithm +import model.graphs.edges.WeightedEdge +import model.graphs.graphs.WeightedDirectedGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +class FordBellmanTests { + private lateinit var graph: WeightedDirectedGraph + private lateinit var solver: FordBellmanAlgorithm + + @BeforeEach + fun setup() { + graph = WeightedDirectedGraph() + solver = FordBellmanAlgorithm(graph) + } + + @Test + @DisplayName("search path, graph consists of two vertices connected with one edge") + fun twoVerticesOneEdge() { + graph.vertices = mutableMapOf(Pair(1, Vertex(1)), Pair(2, Vertex(2))) + graph.edges = mutableMapOf(Pair(1, WeightedEdge(Pair(1, 2)))) + graph.edges[1]?.weight = 5 + val expectedPath = listOf(Vertex(1), Vertex(2)) + assertEquals(expectedPath, solver.findPath(1, 2).vertexList) + } + + @Test + @DisplayName("choose path between two variants") + fun twoPathVariants() { + graph.vertices = mutableMapOf(Pair(1, Vertex(1)), Pair(2, Vertex(2)), Pair(3, Vertex(3))) + graph.edges = mutableMapOf( + Pair(1, WeightedEdge(Pair(1, 2))), + Pair(2, WeightedEdge(Pair(2, 3))), + Pair(3, WeightedEdge(Pair(1, 3))) + ) + graph.edges[1]?.weight = 5 + graph.edges[2]?.weight = -10000 + graph.edges[3]?.weight = 1 + val expectedPath = listOf(Vertex(1), Vertex(2), Vertex(3)) + assertEquals(expectedPath, solver.findPath(1, 3).vertexList) + } + + @Test + @DisplayName("search path between non-existent vertices") + fun searchPathBetweenNonExistentVertices() { + graph.vertices = mutableMapOf(Pair(1, Vertex(1)), Pair(2, Vertex(2))) + graph.edges = mutableMapOf(Pair(1, WeightedEdge(Pair(1, 2)))) + graph.edges[1]?.weight = 5 + assertThrows(IllegalArgumentException::class.java) { + solver.findPath(3, 4) + } + } + + @Test + @DisplayName("search path between existent and non-existent vertices") + fun searchPathBetweenExistentAndNonExistentVertices() { + graph.vertices = mutableMapOf(Pair(1, Vertex(1)), Pair(2, Vertex(2))) + graph.edges = mutableMapOf(Pair(1, WeightedEdge(Pair(1, 2)))) + graph.edges[1]?.weight = 5 + assertThrows(IllegalArgumentException::class.java) { + solver.findPath(2, 4) + } + } + + @Test + @DisplayName("search path between two non-connected vertices") + fun searchPathNonConnectedVertices() { + graph.vertices = mutableMapOf(Pair(1, Vertex(1)), Pair(2, Vertex(2)), Pair(3, Vertex(3)), Pair(4, Vertex(4))) + graph.edges = mutableMapOf( + Pair(1, WeightedEdge(Pair(1, 2))), + Pair(2, WeightedEdge(Pair(3, 4))) + ) + graph.edges[1]?.weight = 5 + graph.edges[2]?.weight = 10 + assertThrows(IllegalArgumentException::class.java) { + solver.findPath(1, 3) + } + } + + @Test + @DisplayName("search path with positive cycle in graph") + fun searchPathPositiveCycle() { + graph.vertices = mutableMapOf(Pair(1, Vertex(1)), Pair(2, Vertex(2)), Pair(3, Vertex(3))) + graph.edges = mutableMapOf( + Pair(1, WeightedEdge(Pair(1, 2))), + Pair(2, WeightedEdge(Pair(2, 3))), + Pair(3, WeightedEdge(Pair(3, 1))) + ) + graph.edges[1]?.weight = 5 + graph.edges[2]?.weight = 10 + graph.edges[3]?.weight = 20 + val expectedPath = listOf(Vertex(1), Vertex(2), Vertex(3)) + assertEquals(expectedPath, solver.findPath(1, 3).vertexList) + } + + @Test + @DisplayName("try to search path with negative cycle in graph") + fun searchPathNegativeCycle() { + graph.vertices = mutableMapOf(Pair(1, Vertex(1)), Pair(2, Vertex(2)), Pair(3, Vertex(3))) + graph.edges = mutableMapOf( + Pair(1, WeightedEdge(Pair(1, 2))), + Pair(2, WeightedEdge(Pair(2, 3))), + Pair(3, WeightedEdge(Pair(3, 1))) + ) + graph.edges[1]?.weight = -5 + graph.edges[2]?.weight = -10 + graph.edges[3]?.weight = -20 + assertThrows(IllegalArgumentException::class.java) { + solver.findPath(1, 3) + } + } +} diff --git a/src/test/kotlin/algorithmsTests/KeyVerticesSelectionSolverDirectedGraphTests.kt b/src/test/kotlin/algorithmsTests/KeyVerticesSelectionSolverDirectedGraphTests.kt new file mode 100644 index 0000000..6bad6fb --- /dev/null +++ b/src/test/kotlin/algorithmsTests/KeyVerticesSelectionSolverDirectedGraphTests.kt @@ -0,0 +1,60 @@ +package algorithmsTests + +import model.algorithms.keyVerticesSelection.KeyVerticesSelectionSolver +import model.graphs.edges.Edge +import model.graphs.graphs.DirectedGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +class KeyVerticesSelectionSolverDirectedGraphTests : KeyVerticesSelectionSolverTests() { + @BeforeEach + override fun setup() { + graph = DirectedGraph() + solver = KeyVerticesSelectionSolver(graph) + } + + @Test + @DisplayName("select key vertices in a graph with two key vertices") + override fun selectKeyVerticesTwoKeyVertices() { + graph.vertices = mutableMapOf( + Pair(1, Vertex(1)), + Pair(2, Vertex(2)), + Pair(3, Vertex(3)), + Pair(4, Vertex(4)), + Pair(5, Vertex(5)), + Pair(6, Vertex(6)) + ) + graph.edges = mutableMapOf( + Pair(1, Edge(Pair(1, 3))), + Pair(2, Edge(Pair(2, 3))), + Pair(3, Edge(Pair(3, 4))), + Pair(4, Edge(Pair(4, 5))), + Pair(5, Edge(Pair(4, 6))) + ) + val expectedKeyVertices = listOf(3, 4) + assertEquals(expectedKeyVertices, solver.selectKeyVertices()) + } + + @Test + @DisplayName("select key vertices in a graph with one key vertex") + override fun selectKeyVerticesExpectingOneKeyVertex() { + graph.vertices = mutableMapOf( + Pair(1, Vertex(1)), + Pair(2, Vertex(2)), + Pair(3, Vertex(3)), + Pair(4, Vertex(4)), + Pair(5, Vertex(5)) + ) + graph.edges = mutableMapOf( + Pair(1, Edge(Pair(1, 3))), + Pair(2, Edge(Pair(2, 3))), + Pair(3, Edge(Pair(4, 3))), + Pair(4, Edge(Pair(5, 3))) + ) + val expectedKeyVertices = listOf(3) + assertEquals(expectedKeyVertices, solver.selectKeyVertices()) + } +} \ No newline at end of file diff --git a/src/test/kotlin/algorithmsTests/KeyVerticesSelectionSolverTests.kt b/src/test/kotlin/algorithmsTests/KeyVerticesSelectionSolverTests.kt new file mode 100644 index 0000000..77785f7 --- /dev/null +++ b/src/test/kotlin/algorithmsTests/KeyVerticesSelectionSolverTests.kt @@ -0,0 +1,92 @@ +package algorithmsTests + +import model.algorithms.keyVerticesSelection.KeyVerticesSelectionSolver +import model.graphs.edges.Edge +import model.graphs.graphs.Graph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +open class KeyVerticesSelectionSolverTests { + protected lateinit var graph: Graph + protected lateinit var solver: KeyVerticesSelectionSolver + + @BeforeEach + open fun setup() { + graph = Graph() + solver = KeyVerticesSelectionSolver(graph) + } + + @Test + @DisplayName("select key vertices in a graph with one key vertex") + open fun selectKeyVerticesExpectingOneKeyVertex() { + graph.vertices = mutableMapOf( + Pair(1, Vertex(1)), + Pair(2, Vertex(2)), + Pair(3, Vertex(3)), + Pair(4, Vertex(4)), + Pair(5, Vertex(5)) + ) + graph.edges = mutableMapOf( + Pair(1, Edge(Pair(3, 1))), + Pair(2, Edge(Pair(3, 2))), + Pair(3, Edge(Pair(3, 4))), + Pair(4, Edge(Pair(3, 5))) + ) + val expectedKeyVertices = listOf(3) + assertEquals(expectedKeyVertices, solver.selectKeyVertices()) + } + + @Test + @DisplayName("select key vertices in a cycle graph") + fun selectKeyVerticesCycle() { + graph.vertices = mutableMapOf( + Pair(1, Vertex(1)), + Pair(2, Vertex(2)), + Pair(3, Vertex(3)) + ) + graph.edges = mutableMapOf( + Pair(1, Edge(Pair(1, 2))), + Pair(2, Edge(Pair(2, 3))), + Pair(3, Edge(Pair(3, 1))) + ) + val expectedKeyVertices = listOf(1, 2, 3) + assertEquals(expectedKeyVertices, solver.selectKeyVertices()) + } + + @Test + @DisplayName("select key vertices in a graph with two key vertices") + open fun selectKeyVerticesTwoKeyVertices() { + graph.vertices = mutableMapOf( + Pair(1, Vertex(1)), + Pair(2, Vertex(2)), + Pair(3, Vertex(3)), + Pair(4, Vertex(4)), + Pair(5, Vertex(5)), + Pair(6, Vertex(6)) + ) + graph.edges = mutableMapOf( + Pair(1, Edge(Pair(1, 3))), + Pair(2, Edge(Pair(2, 3))), + Pair(3, Edge(Pair(3, 4))), + Pair(4, Edge(Pair(4, 5))), + Pair(5, Edge(Pair(4, 6))) + ) + val expectedKeyVertices = listOf(3, 4) + assertEquals(expectedKeyVertices, solver.selectKeyVertices()) + } + + @Test + @DisplayName("select key vertices in a graph with no edges") + fun selectKeyVerticesNoEdges() { + graph.vertices = mutableMapOf( + Pair(1, Vertex(1)), + Pair(2, Vertex(2)), + Pair(3, Vertex(3)) + ) + val expectedKeyVertices: MutableList = mutableListOf() + assertEquals(expectedKeyVertices, solver.selectKeyVertices()) + } +} \ No newline at end of file diff --git a/src/test/kotlin/algorithmsTests/KruskalAlgorithmSolverTests.kt b/src/test/kotlin/algorithmsTests/KruskalAlgorithmSolverTests.kt new file mode 100644 index 0000000..481f1ae --- /dev/null +++ b/src/test/kotlin/algorithmsTests/KruskalAlgorithmSolverTests.kt @@ -0,0 +1,241 @@ +package algorithmsTests + +import model.algorithms.kruskalAlgorithm.KruskalAlgorithmSolver +import model.graphs.edges.WeightedEdge +import model.graphs.graphs.WeightedGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertIterableEquals +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +class KruskalAlgorithmSolverTests { + + private lateinit var graph: WeightedGraph + private lateinit var solver: KruskalAlgorithmSolver + + @BeforeEach + fun setup() { + graph = WeightedGraph() + } + + @Test + @DisplayName("empty graph test") + fun emptyGraph() { + graph.lastVertexNumber = graph.vertices.size + + solver = KruskalAlgorithmSolver(graph) + + val expectedMST = emptyList() + val expectedResult = Pair(false, expectedMST) + + val actualResult = solver.doKruskalAlgorithm() + val actualMST = actualResult.second + + assertEquals(expectedResult.first, actualResult.first) + assertIterableEquals(expectedMST, actualMST) + } + + @Test + @DisplayName("graph with one vertex") + fun oneVertex() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)) + ) + graph.lastVertexNumber = graph.vertices.size + + solver = KruskalAlgorithmSolver(graph) + + val expectedMST = emptyList() + val expectedResult = Pair(false, expectedMST) + + val actualResult = solver.doKruskalAlgorithm() + val actualMST = actualResult.second + + assertEquals(expectedResult.first, actualResult.first) + assertIterableEquals(expectedMST, actualMST) + } + + @Test + @DisplayName("isolated vertices test") + fun isolatedVertices() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)), + Pair(3, Vertex(4)), + Pair(4, Vertex(5)) + ) + graph.lastVertexNumber = graph.vertices.size + + solver = KruskalAlgorithmSolver(graph) + + val expectedMST = emptyList() + val expectedResult = Pair(false, expectedMST) + + val actualResult = solver.doKruskalAlgorithm() + val actualMST = actualResult.second + + assertEquals(expectedResult.first, actualResult.first) + assertIterableEquals(expectedMST, actualMST) + } + + @Test + @DisplayName("not connected graph") + fun notConnectedGraph() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)), + Pair(3, Vertex(4)), + Pair(4, Vertex(5)) + ) + graph.lastVertexNumber = graph.vertices.size + + graph.edges = mutableMapOf( + Pair(1, WeightedEdge(Pair(0, 1))), + Pair(2, WeightedEdge(Pair(1, 2))), + Pair(3, WeightedEdge(Pair(3, 4))) + ) + graph.changeEdgeWeight(0, 5) + graph.changeEdgeWeight(1, 1) + graph.changeEdgeWeight(2, 3) + + solver = KruskalAlgorithmSolver(graph) + + val expectedMST = emptyList() + val expectedResult = Pair(false, expectedMST) + + val actualResult = solver.doKruskalAlgorithm() + val actualMST = actualResult.second + + assertEquals(expectedResult.first, actualResult.first) + assertIterableEquals(expectedMST, actualMST) + } + + @Test + @DisplayName("two vertices, one edge") + fun oneEdge() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)) + ) + graph.lastVertexNumber = graph.vertices.size + + graph.edges = mutableMapOf( + Pair(0, WeightedEdge(Pair(0, 1))) + ) + graph.changeEdgeWeight(0, 2) + + solver = KruskalAlgorithmSolver(graph) + + val expectedMST = listOf(graph.edges[0]) + val expectedResult = Pair(true, expectedMST) + + val actualResult = solver.doKruskalAlgorithm() + val actualMST = actualResult.second + + assertEquals(expectedResult.first, actualResult.first) + assertIterableEquals(expectedMST, actualMST) + } + + @Test + @DisplayName("big minimal spanning tree test") + fun bigMST() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)), + Pair(3, Vertex(4)), + Pair(4, Vertex(5)) + ) + graph.lastVertexNumber = graph.vertices.size + + graph.edges = mutableMapOf( + Pair(0, WeightedEdge(Pair(0, 1))), + Pair(1, WeightedEdge(Pair(2, 3))), + Pair(2, WeightedEdge(Pair(0, 3))), + Pair(3, WeightedEdge(Pair(3, 4))), + Pair(4, WeightedEdge(Pair(2, 3))), + Pair(5, WeightedEdge(Pair(1, 4))) + ) + graph.changeEdgeWeight(0, 3) + graph.changeEdgeWeight(1, 6) + graph.changeEdgeWeight(2, 5) + graph.changeEdgeWeight(3, 4) + graph.changeEdgeWeight(4, 8) + graph.changeEdgeWeight(5, 7) + + solver = KruskalAlgorithmSolver(graph) + + val expectedMST = listOf( + graph.edges[0], + graph.edges[3], + graph.edges[2], + graph.edges[1] + ) + val expectedResult = Pair(true, expectedMST) + + val actualResult = solver.doKruskalAlgorithm() + val actualMST = actualResult.second + + assertEquals(expectedResult.first, actualResult.first) + assertIterableEquals(expectedMST, actualMST) + } + + @Test + @DisplayName("another big minimal spanning tree test") + fun anotherBigMST() { + graph.vertices = mutableMapOf( + Pair(0, Vertex('A'.code)), + Pair(1, Vertex('B'.code)), + Pair(2, Vertex('C'.code)), + Pair(3, Vertex('D'.code)), + Pair(4, Vertex('E'.code)), + Pair(5, Vertex('F'.code)), + Pair(6, Vertex('G'.code)) + ) + graph.lastVertexNumber = graph.vertices.size + + graph.edges = mutableMapOf( + Pair(0, WeightedEdge(Pair(1, 0))), + Pair(1, WeightedEdge(Pair(0, 2))), + Pair(2, WeightedEdge(Pair(0, 3))), + Pair(3, WeightedEdge(Pair(3, 2))), + Pair(4, WeightedEdge(Pair(2, 1))), + Pair(5, WeightedEdge(Pair(1, 4))), + Pair(6, WeightedEdge(Pair(4, 5))), + Pair(7, WeightedEdge(Pair(5, 6))), + Pair(8, WeightedEdge(Pair(6, 4))) + ) + + graph.changeEdgeWeight(0, 1) + graph.changeEdgeWeight(1, 1) + graph.changeEdgeWeight(2, 3) + graph.changeEdgeWeight(3, 4) + graph.changeEdgeWeight(4, 5) + graph.changeEdgeWeight(5, 6) + graph.changeEdgeWeight(6, 12) + graph.changeEdgeWeight(7, 4) + graph.changeEdgeWeight(8, 5) + + solver = KruskalAlgorithmSolver(graph) + + val expectedMST = listOf( + graph.edges[0], + graph.edges[1], + graph.edges[2], + graph.edges[7], + graph.edges[8], + graph.edges[5] + ) + val expectedResult = Pair(true, expectedMST) + + val actualResult = solver.doKruskalAlgorithm() + val actualMST = actualResult.second + + assertEquals(expectedResult.first, actualResult.first) + assertIterableEquals(expectedMST, actualMST) + } +} \ No newline at end of file diff --git a/src/test/kotlin/algorithmsTests/SearchCycleForVertexInDirectedGraphSolverTests.kt b/src/test/kotlin/algorithmsTests/SearchCycleForVertexInDirectedGraphSolverTests.kt new file mode 100644 index 0000000..cbc51b8 --- /dev/null +++ b/src/test/kotlin/algorithmsTests/SearchCycleForVertexInDirectedGraphSolverTests.kt @@ -0,0 +1,190 @@ +package algorithmsTests + +import model.algorithms.searchCycle.SearchCycleForVertexInDirectedGraphSolver +import model.graphs.edges.Edge +import model.graphs.graphs.DirectedGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +class SearchCycleForVertexInDirectedGraphSolverTests : SearchCycleForVertexInGraphSolverTests() { + private var graph: DirectedGraph = DirectedGraph() + + @Test + @DisplayName("one cycle, different answer from undirected case") + override fun oneCycle() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)) + ) + graph.edges = mutableMapOf( + Pair(0, Edge(Pair(0, 1))), + Pair(1, Edge(Pair(2, 1))), + Pair(2, Edge(Pair(0, 2))) + ) + solver = SearchCycleForVertexInDirectedGraphSolver(graph) + + val expected = false + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val expectedCycle = listOf(0, 1, 2, 0) + val actualCycle = solver.getCycle() + assertNotEquals(expectedCycle, actualCycle) + assertEquals(emptyList(), actualCycle) + } + + @Test + @DisplayName("one cycle in directed case") + fun oneCycleDirected() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)) + ) + graph.edges = mutableMapOf( + Pair(0, Edge(Pair(0, 1))), + Pair(1, Edge(Pair(1, 2))), + Pair(2, Edge(Pair(2, 0))) + ) + solver = SearchCycleForVertexInDirectedGraphSolver(graph) + + val expected = true + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val expectedCycle = listOf(0, 1, 2, 0) + val actualCycle = solver.getCycle() + assertEquals(expectedCycle, actualCycle) + + assertTrue(solver.searchCycleForVertex(1)) + assertTrue(solver.searchCycleForVertex(2)) + } + + @Test + @DisplayName("two cycles, different answer from undirected case") + override fun twoCycles() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)), + Pair(3, Vertex(4)), + Pair(4, Vertex(5)) + ) + graph.edges = mutableMapOf( + Pair(0, Edge(Pair(0, 1))), + Pair(1, Edge(Pair(1, 2))), + Pair(2, Edge(Pair(0, 2))), + Pair(3, Edge(Pair(0, 3))), + Pair(4, Edge(Pair(4, 3))), + Pair(5, Edge(Pair(4, 0))) + ) + solver = SearchCycleForVertexInDirectedGraphSolver(graph) + + val expected = false + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val firstCycle = listOf(0, 1, 2, 0) + val secondCycle = listOf(0, 3, 4, 0) + val actualCycle = solver.getCycle() + assertNotEquals(firstCycle, actualCycle) + assertNotEquals(secondCycle, actualCycle) + assertEquals(emptyList(), actualCycle) + } + + @Test + @DisplayName("two cycles in directed case, vertex is in the first one") + fun twoCyclesDirected() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)), + Pair(3, Vertex(4)), + Pair(4, Vertex(5)) + ) + graph.edges = mutableMapOf( + Pair(0, Edge(Pair(0, 1))), + Pair(1, Edge(Pair(1, 2))), + Pair(2, Edge(Pair(2, 0))), + Pair(3, Edge(Pair(0, 3))), + Pair(4, Edge(Pair(3, 4))), + Pair(5, Edge(Pair(4, 0))) + ) + solver = SearchCycleForVertexInDirectedGraphSolver(graph) + + val expected = true + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val firstCycle = listOf(0, 1, 2, 0) + val secondCycle = listOf(0, 3, 4, 0) + val actualCycle = solver.getCycle() + assertNotEquals(secondCycle, actualCycle) + assertEquals(firstCycle, actualCycle) + } + + @Test + @DisplayName("previous sample, single answer is in the second one") + fun twoCyclesDirectedAnother() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)), + Pair(3, Vertex(4)), + Pair(4, Vertex(5)) + ) + graph.edges = mutableMapOf( + Pair(0, Edge(Pair(0, 1))), + Pair(1, Edge(Pair(1, 2))), + Pair(2, Edge(Pair(0, 2))), + Pair(3, Edge(Pair(0, 3))), + Pair(4, Edge(Pair(3, 4))), + Pair(5, Edge(Pair(4, 0))) + ) + solver = SearchCycleForVertexInDirectedGraphSolver(graph) + + val expected = true + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val firstCycle = listOf(0, 1, 2, 0) + val secondCycle = listOf(0, 3, 4, 0) + val actualCycle = solver.getCycle() + assertNotEquals(firstCycle, actualCycle) + assertEquals(secondCycle, actualCycle) + + assertFalse(solver.searchCycleForVertex(1)) + assertTrue(solver.searchCycleForVertex(3)) + assertTrue(solver.searchCycleForVertex(4)) + } + + @Test + @DisplayName("cycleOfTwoVertices") + override fun cycleOfTwo() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)) + ) + graph.edges = mutableMapOf( + Pair(0, Edge(Pair(0, 1))), + Pair(1, Edge(Pair(1, 0))) + ) + solver = SearchCycleForVertexInDirectedGraphSolver(graph) + + val expected = true + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val expectedCycle = listOf(0, 1, 0) + val actualCycle = solver.getCycle() + assertEquals(expectedCycle, actualCycle) + + assertTrue(solver.searchCycleForVertex(1)) + } +} \ No newline at end of file diff --git a/src/test/kotlin/algorithmsTests/SearchCycleForVertexInGraphSolverTests.kt b/src/test/kotlin/algorithmsTests/SearchCycleForVertexInGraphSolverTests.kt new file mode 100644 index 0000000..048cb46 --- /dev/null +++ b/src/test/kotlin/algorithmsTests/SearchCycleForVertexInGraphSolverTests.kt @@ -0,0 +1,178 @@ +package algorithmsTests + +import model.algorithms.searchCycle.SearchCycleForVertexInGraphSolver +import model.graphs.edges.Edge +import model.graphs.graphs.Graph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +open class SearchCycleForVertexInGraphSolverTests { + private var graph: Graph = Graph() + protected lateinit var solver: SearchCycleForVertexInGraphSolver + + @Test + @DisplayName("empty graph with no cycle") + fun emptyGraph() { + solver = SearchCycleForVertexInGraphSolver(graph) + + val expected = false + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val expectedCycle = emptyList() + val actualCycle = solver.getCycle() + assertEquals(expectedCycle, actualCycle) + } + + @Test + @DisplayName("isolated vertices with no cycle") + fun isolatedVertices() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)) + ) + solver = SearchCycleForVertexInGraphSolver(graph) + + val expected = false + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val expectedCycle = emptyList() + val actualCycle = solver.getCycle() + assertEquals(expectedCycle, actualCycle) + } + + @Test + @DisplayName("no cycle") + fun noCycle() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)) + ) + graph.edges = mutableMapOf( + Pair(0, Edge(Pair(0, 1))), + Pair(1, Edge(Pair(1, 2))) + ) + solver = SearchCycleForVertexInGraphSolver(graph) + + val expected = false + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + assertTrue(solver.getCycle().isEmpty()) + } + + @Test + @DisplayName("one cycle") + open fun oneCycle() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)) + ) + graph.edges = mutableMapOf( + Pair(0, Edge(Pair(0, 1))), + Pair(1, Edge(Pair(1, 2))), + Pair(2, Edge(Pair(0, 2))) + ) + solver = SearchCycleForVertexInGraphSolver(graph) + + val expected = true + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val expectedCycle = listOf(0, 1, 2, 0) + val actualCycle = solver.getCycle() + assertEquals(expectedCycle, actualCycle) + + assertTrue(solver.searchCycleForVertex(1)) + assertTrue(solver.searchCycleForVertex(2)) + } + + @Test + @DisplayName("two cycles, vertex is in the first one") + open fun twoCycles() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)), + Pair(3, Vertex(4)), + Pair(4, Vertex(5)) + ) + graph.edges = mutableMapOf( + Pair(0, Edge(Pair(0, 1))), + Pair(1, Edge(Pair(1, 2))), + Pair(2, Edge(Pair(0, 2))), + Pair(3, Edge(Pair(0, 3))), + Pair(4, Edge(Pair(4, 3))), + Pair(5, Edge(Pair(4, 0))) + ) + solver = SearchCycleForVertexInGraphSolver(graph) + + val expected = true + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val firstCycle = listOf(0, 1, 2, 0) + val secondCycle = listOf(0, 3, 4, 0) + val actualCycle = solver.getCycle() + assertNotEquals(secondCycle, actualCycle) + assertEquals(firstCycle, actualCycle) + } + + @Test + @DisplayName("two connected components, vertex is not in the second one") + fun twoComponents() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)), + Pair(2, Vertex(3)), + Pair(3, Vertex(4)), + Pair(4, Vertex(5)) + ) + graph.edges = mutableMapOf( + Pair(0, Edge(Pair(0, 1))), + Pair(1, Edge(Pair(3, 2))), + Pair(2, Edge(Pair(4, 3))), + Pair(3, Edge(Pair(2, 4))) + ) + solver = SearchCycleForVertexInGraphSolver(graph) + + val expected = false + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val expectedCycle = listOf(3, 2, 4, 3) + val actualCycle = solver.getCycle() + assertNotEquals(expectedCycle, actualCycle) + assertEquals(emptyList(), actualCycle) + } + + @Test + @DisplayName("cycleOfTwoVertices") + open fun cycleOfTwo() { + graph.vertices = mutableMapOf( + Pair(0, Vertex(1)), + Pair(1, Vertex(2)) + ) + graph.edges = mutableMapOf( + Pair(0, Edge(Pair(0, 1))), + Pair(1, Edge(Pair(1, 0))) + ) + solver = SearchCycleForVertexInGraphSolver(graph) + + val expected = false + val actual = solver.searchCycleForVertex(0) + assertEquals(expected, actual) + + val expectedCycle = emptyList() + val actualCycle = solver.getCycle() + assertEquals(expectedCycle, actualCycle) + } +} \ No newline at end of file diff --git a/src/test/kotlin/algorithmsTests/StronglyConnectedComponentsSelectionSolverTests.kt b/src/test/kotlin/algorithmsTests/StronglyConnectedComponentsSelectionSolverTests.kt new file mode 100644 index 0000000..9225b08 --- /dev/null +++ b/src/test/kotlin/algorithmsTests/StronglyConnectedComponentsSelectionSolverTests.kt @@ -0,0 +1,108 @@ +package algorithmsTests + +import model.algorithms.stronglyConnectedComponentsSelection.StronglyConnectedComponentsSelectionSolver +import model.graphs.edges.Edge +import model.graphs.graphs.DirectedGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +class StronglyConnectedComponentsSelectionSolverTests { + private lateinit var graph: DirectedGraph + private lateinit var solver: StronglyConnectedComponentsSelectionSolver + + @BeforeEach + fun setup() { + graph = DirectedGraph() + solver = StronglyConnectedComponentsSelectionSolver(graph) + } + + @Test + @DisplayName("empty graph components selection") + fun emptyGraphComponentsSelection() { + val expectedComponents: MutableMap = mutableMapOf() + assertEquals(expectedComponents, solver.selectStronglyConnectedComponents()) + } + + @Test + @DisplayName("isolated vertices components selection") + fun isolatedVerticesComponentsSelection() { + graph.vertices = mutableMapOf(Pair(1, Vertex(1)), Pair(2, Vertex(2)), Pair(3, Vertex(3))) + graph.edges = mutableMapOf(Pair(1, Edge(Pair(1, 2))), Pair(2, Edge(Pair(2, 3)))) + val components = solver.selectStronglyConnectedComponents() + assertNotEquals(components[1], components[2]) + assertNotEquals(components[2], components[3]) + assertNotEquals(components[1], components[3]) + } + + @Test + @DisplayName("one component selection") + fun oneComponentSelection() { + graph.vertices = mutableMapOf(Pair(1, Vertex(1)), Pair(2, Vertex(2)), Pair(3, Vertex(3))) + graph.edges = mutableMapOf(Pair(1, Edge(Pair(1, 2))), Pair(2, Edge(Pair(2, 3))), Pair(3, Edge(Pair(3, 1)))) + val expectedComponents = mutableMapOf(Pair(1, 1), Pair(2, 1), Pair(3, 1)) + assertEquals(expectedComponents, solver.selectStronglyConnectedComponents()) + } + + @Test + @DisplayName("two components selection") + fun twoComponentsSelection() { + graph.vertices = mutableMapOf(Pair(1, Vertex(1)), Pair(2, Vertex(2)), Pair(3, Vertex(3)), Pair(4, Vertex(4))) + graph.edges = mutableMapOf( + Pair(1, Edge(Pair(1, 2))), + Pair(2, Edge(Pair(2, 1))), + Pair(3, Edge(Pair(3, 4))), + Pair(4, Edge(Pair(4, 3))), + Pair(5, Edge(Pair(1, 3))) + ) + val components = solver.selectStronglyConnectedComponents() + assertEquals(components[1], components[2]) + assertEquals(components[3], components[4]) + assertNotEquals(components[1], components[3]) + } + + @Test + @DisplayName("two pseudo components with bridge") + fun bridgeBetweenPseudoComponents() { + graph.vertices = mutableMapOf(Pair(1, Vertex(1)), Pair(2, Vertex(2)), Pair(3, Vertex(3)), Pair(4, Vertex(4))) + graph.edges = mutableMapOf( + Pair(1, Edge(Pair(1, 2))), + Pair(2, Edge(Pair(2, 1))), + Pair(3, Edge(Pair(3, 4))), + Pair(4, Edge(Pair(4, 3))), + Pair(5, Edge(Pair(1, 3))), + Pair(6, Edge(Pair(3, 1))) + ) + val expectedComponents = mutableMapOf(Pair(1, 1), Pair(2, 1), Pair(3, 1), Pair(4, 1)) + assertEquals(expectedComponents, solver.selectStronglyConnectedComponents()) + } + + @Test + @DisplayName("three components selection, one vertex is isolated") + fun threeComponentsIsolatedVertex() { + graph.vertices = mutableMapOf( + Pair(1, Vertex(1)), + Pair(2, Vertex(2)), + Pair(3, Vertex(3)), + Pair(4, Vertex(4)), + Pair(5, Vertex(5)) + ) + graph.edges = mutableMapOf( + Pair(1, Edge(Pair(1, 2))), + Pair(2, Edge(Pair(2, 1))), + Pair(3, Edge(Pair(2, 3))), + Pair(4, Edge(Pair(3, 4))), + Pair(5, Edge(Pair(4, 5))), + Pair(6, Edge(Pair(5, 4))) + ) + val components = solver.selectStronglyConnectedComponents() + assertEquals(components[1], components[2]) + assertNotEquals(components[1], components[3]) + assertEquals(components[4], components[5]) + assertNotEquals(components[1], components[4]) + assertNotEquals(components[3], components[4]) + } +} diff --git a/src/test/kotlin/dataTests/AbstractGraphsSerializerTests.kt b/src/test/kotlin/dataTests/AbstractGraphsSerializerTests.kt new file mode 100644 index 0000000..f7d401f --- /dev/null +++ b/src/test/kotlin/dataTests/AbstractGraphsSerializerTests.kt @@ -0,0 +1,253 @@ +package dataTests + +import dataTests.stubs.IntVertexDataSerializer +import dataTests.stubs.StubGraphDeserializer +import dataTests.stubs.StubGraphSerializer +import model.data.GraphRepresentation +import model.graphs.edges.Edge +import model.graphs.edges.WeightedEdge +import model.graphs.graphs.AbstractGraph +import model.graphs.graphs.DirectedGraph +import model.graphs.graphs.Graph +import model.graphs.graphs.WeightedDirectedGraph +import model.graphs.graphs.WeightedGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +open class AbstractGraphsSerializerTests { + lateinit var weightedGraph: WeightedGraph + lateinit var ordinaryGraph: Graph + lateinit var directedGraph: DirectedGraph + lateinit var weightedDirectedGraph: WeightedDirectedGraph + + @BeforeEach + open fun setup() { + weightedGraph = WeightedGraph() + initWeightedGraph(weightedGraph) + ordinaryGraph = Graph() + initOrdinaryGraph(ordinaryGraph) + directedGraph = DirectedGraph() + initDirectedGraph(directedGraph) + weightedDirectedGraph = WeightedDirectedGraph() + initWeightedDirectedGraph(weightedDirectedGraph) + } + + private fun initWeightedDirectedGraph(graph: WeightedDirectedGraph) { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, WeightedEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + graph.changeEdgeWeight(0, 156) + } + private fun initDirectedGraph(graph: DirectedGraph) { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, Edge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + } + private fun initOrdinaryGraph(graph: Graph) { + graph.addVertex(0) + graph.addVertex(1) + graph.addVertex(2) + graph.addVertex(3) + graph.addVertex(4) + + graph.addEdge(0, 1) + graph.addEdge(0, 2) + graph.addEdge(0, 3) + graph.addEdge(1, 4) + graph.addEdge(2, 4) + graph.addEdge(3, 2) + graph.addEdge(3, 4) + } + private fun initWeightedGraph(graph: WeightedGraph) { + graph.addVertex(0) + graph.addVertex(1) + graph.addVertex(2) + graph.addVertex(3) + graph.addVertex(4) + + graph.addEdge(0, 1) + graph.changeEdgeWeight(0, 3) + graph.addEdge(0, 2) + graph.changeEdgeWeight(1, 6) + graph.addEdge(0, 3) + graph.changeEdgeWeight(2, 1) + graph.addEdge(1, 4) + graph.changeEdgeWeight(3, 8) + graph.addEdge(2, 4) + graph.changeEdgeWeight(4, 4) + graph.addEdge(3, 2) + graph.changeEdgeWeight(5, 4) + graph.addEdge(3, 4) + graph.changeEdgeWeight(6, 12) + } + + private fun assertGraphRepresentation(expected: GraphRepresentation, actual: GraphRepresentation) { + assertEquals(expected.name, actual.name) + assertEquals(expected.vertexValueTypeName, actual.vertexValueTypeName) + assertContentEquals(expected.vertexValuesList, actual.vertexValuesList) + assertContentEquals(expected.edges, actual.edges) + assertEquals(expected.isDirected, actual.isDirected) + assertEquals(expected.isWeighted, actual.isWeighted) + assertContentEquals(expected.weightEdgeList, actual.weightEdgeList) + } + + private fun assertGraph(expected: AbstractGraph, actual: AbstractGraph) { + for ((index, edge) in expected.edges) { + val actualKey = actual.edges.keys.toList()[index] + val actualEdge = actual.edges[actualKey] + if (actualEdge == null) throw Error("Edge with index $index not found") + assertEquals(edge.verticesNumbers, actualEdge.verticesNumbers) + if (expected is WeightedGraph) { + assertEquals((edge as WeightedEdge).weight, (actualEdge as WeightedEdge).weight) + } + } + + for ((index, vertex) in expected.vertices) { + val actualKey = actual.vertices.keys.toList()[index] + val actualVertex = actual.vertices[actualKey] + if (actualVertex == null) throw Error("Vertex with index $index not found") + assertEquals(vertex.value, actualVertex.value) + } + + val expectedAdjacencyMap = expected.toAdjacencyMap() + val actualAdjacencyMap = actual.toAdjacencyMap() + + expectedAdjacencyMap.keys.toList() + for (exKey in expectedAdjacencyMap.keys) { + assertTrue(actualAdjacencyMap.containsKey(exKey)) + val actualVal = actualAdjacencyMap[exKey] + assertNotNull(actualVal) + assertContentEquals(expectedAdjacencyMap[exKey]!!.toList(), actualVal.toList()) + } + } + + @Test + @DisplayName("Weighted directed graph deserialization") + fun weightedDirectedGraphDeserialize() { + val graphDeserializer = StubGraphDeserializer() + val representation = graphDeserializer.deserializeGraph("weighteddirected") + + val result = representation.createDirectedWeightedGraphByRepresentation(IntVertexDataSerializer()) + + assertGraph(weightedDirectedGraph, result) + } + + @Test + @DisplayName("Weighted directed graph serialization") + fun weightedDirectedGraphSerialize() { + val graphSerializer = StubGraphSerializer() + graphSerializer.serializeNotOrdinaryGraph("test", weightedDirectedGraph, IntVertexDataSerializer()) + val resultGraphRepresentation = graphSerializer.lastGraphRepresentation + assertNotNull(resultGraphRepresentation) + val expectedGraphRepresentation = GraphRepresentation( + "test", + "int", + listOf("5", "6"), + listOf(Pair(0, 1)), + true, + true, + listOf(156) + ) + assertGraphRepresentation(expectedGraphRepresentation, resultGraphRepresentation) + } + + @Test + @DisplayName("Directed graph serialization") + fun directedGraphSerialize() { + val graphSerializer = StubGraphSerializer() + graphSerializer.serializeNotOrdinaryGraph("test", directedGraph, IntVertexDataSerializer()) + val resultGraphRepresentation = graphSerializer.lastGraphRepresentation + assertNotNull(resultGraphRepresentation) + val expectedGraphRepresentation = GraphRepresentation( + "test", + "int", + listOf("5", "6"), + listOf(Pair(0, 1)), + true, + false, + listOf() + ) + assertGraphRepresentation(expectedGraphRepresentation, resultGraphRepresentation) + } + + @Test + @DisplayName("Directed graph deserialization") + fun directedGraphDeserialize() { + val graphDeserializer = StubGraphDeserializer() + val representation = graphDeserializer.deserializeGraph("directed") + + val result = representation.createDirectedGraphByRepresentation(IntVertexDataSerializer()) + + assertGraph(directedGraph, result) + } + + @Test + @DisplayName("Ordinary graph serialization") + fun ordinaryGraphSerialize() { + val graphSerializer = StubGraphSerializer() + graphSerializer.serializeOrdinaryGraph("test", ordinaryGraph, IntVertexDataSerializer()) + val resultGraphRepresentation = graphSerializer.lastGraphRepresentation + assertNotNull(resultGraphRepresentation) + val expectedGraphRepresentation = GraphRepresentation( + "test", + "int", + listOf("0", "1", "2", "3", "4"), + listOf(Pair(0, 1), Pair(0, 2), Pair(0, 3), Pair(1, 4), Pair(2, 4), Pair(3, 2), Pair(3, 4)), + false, + false, + listOf() + ) + + assertGraphRepresentation(expectedGraphRepresentation, resultGraphRepresentation) + } + + @Test + @DisplayName("Ordinary graph deserialization") + fun ordinaryGraphDeserialize() { + val graphDeserializer = StubGraphDeserializer() + val representation = graphDeserializer.deserializeGraph("ordinary") + + val result = representation.createOrdinaryGraphByRepresentation(IntVertexDataSerializer()) + + assertGraph(ordinaryGraph, result) + } + + @Test + @DisplayName("Weighted graph serialization") + fun weightedGraphSerialize() { + val graphSerializer = StubGraphSerializer() + graphSerializer.serializeNotOrdinaryGraph("test", weightedGraph, IntVertexDataSerializer()) + val resultGraphRepresentation = graphSerializer.lastGraphRepresentation + assertNotNull(resultGraphRepresentation) + val expectedGraphRepresentation = GraphRepresentation( + "test", + "int", + listOf("0", "1", "2", "3", "4"), + listOf(Pair(0, 1), Pair(0, 2), Pair(0, 3), Pair(1, 4), Pair(2, 4), Pair(3, 2), Pair(3, 4)), + false, + true, + listOf(3, 6, 1, 8, 4, 4, 12) + ) + + assertGraphRepresentation(expectedGraphRepresentation, resultGraphRepresentation) + } + + @Test + @DisplayName("Weighted graph deserialization") + fun weightedGraphDeserialize() { + val graphDeserializer = StubGraphDeserializer() + val representation = graphDeserializer.deserializeGraph("weighted") + + val result = representation.createWeightedGraphByRepresentation(IntVertexDataSerializer()) + + assertGraph(weightedGraph, result) + } +} \ No newline at end of file diff --git a/src/test/kotlin/dataTests/stubs/IntVertexDataSerializer.kt b/src/test/kotlin/dataTests/stubs/IntVertexDataSerializer.kt new file mode 100644 index 0000000..449d5e3 --- /dev/null +++ b/src/test/kotlin/dataTests/stubs/IntVertexDataSerializer.kt @@ -0,0 +1,12 @@ +package dataTests.stubs + +import model.data.IVertexDataSerializer +import java.lang.reflect.Type + +class IntVertexDataSerializer : IVertexDataSerializer { + override fun serialize(data: Int): String = data.toString() + + override fun getSerializableType(): Type = Int::class.java + + override fun deserialize(data: String): Int = data.toInt() +} \ No newline at end of file diff --git a/src/test/kotlin/dataTests/stubs/StubGraphDeserializer.kt b/src/test/kotlin/dataTests/stubs/StubGraphDeserializer.kt new file mode 100644 index 0000000..b44984f --- /dev/null +++ b/src/test/kotlin/dataTests/stubs/StubGraphDeserializer.kt @@ -0,0 +1,56 @@ +package dataTests.stubs + +import model.data.AbstractGraphSerializer +import model.data.GraphRepresentation + +class StubGraphDeserializer : AbstractGraphSerializer() { + override fun deserializeGraph(name: String): GraphRepresentation { + if (name == "weighted") return GraphRepresentation( + "weighted", + "int", + listOf("0", "1", "2", "3", "4"), + listOf(Pair(0, 1), Pair(0, 2), Pair(0, 3), Pair(1, 4), Pair(2, 4), Pair(3, 2), Pair(3, 4)), + false, + true, + listOf(3, 6, 1, 8, 4, 4, 12) + ) + if (name == "ordinary") return GraphRepresentation( + "ordinary", + "int", + listOf("0", "1", "2", "3", "4"), + listOf(Pair(0, 1), Pair(0, 2), Pair(0, 3), Pair(1, 4), Pair(2, 4), Pair(3, 2), Pair(3, 4)), + false, + false, + listOf() + ) + if (name == "directed") return GraphRepresentation( + "directed", + "int", + listOf("5", "6"), + listOf(Pair(0, 1)), + true, + false, + listOf() + ) + if (name == "weighteddirected") return GraphRepresentation( + "weighteddirected", + "int", + listOf("5", "6"), + listOf(Pair(0, 1)), + true, + true, + listOf(156) + ) + throw Error("Try deserialize not containable graph") + } + + override fun serializeGraphRepresentation(graph: GraphRepresentation) { + throw NotImplementedError() + } + + override fun getNameForNextGraph(): String { + throw NotImplementedError() + } + + override fun isGraphAlreadyStored(name: String): Boolean = name == "weighteddirected" || name == "weighted" || name == "directed" || name == "ordinary" +} \ No newline at end of file diff --git a/src/test/kotlin/dataTests/stubs/StubGraphSerializer.kt b/src/test/kotlin/dataTests/stubs/StubGraphSerializer.kt new file mode 100644 index 0000000..f5d0e99 --- /dev/null +++ b/src/test/kotlin/dataTests/stubs/StubGraphSerializer.kt @@ -0,0 +1,23 @@ +package dataTests.stubs + +import model.data.AbstractGraphSerializer +import model.data.GraphRepresentation + +class StubGraphSerializer : AbstractGraphSerializer() { + + var lastGraphRepresentation: GraphRepresentation? = null + + override fun deserializeGraph(name: String): GraphRepresentation { + throw NotImplementedError() + } + + override fun serializeGraphRepresentation(graph: GraphRepresentation) { + lastGraphRepresentation = graph + } + + override fun getNameForNextGraph(): String { + throw NotImplementedError() + } + + override fun isGraphAlreadyStored(name: String): Boolean = false +} \ No newline at end of file diff --git a/src/test/kotlin/graphsTests/AbstractGraphTests.kt b/src/test/kotlin/graphsTests/AbstractGraphTests.kt new file mode 100644 index 0000000..7a04b28 --- /dev/null +++ b/src/test/kotlin/graphsTests/AbstractGraphTests.kt @@ -0,0 +1,218 @@ +package graphsTests + +import model.graphs.edges.Edge +import model.graphs.graphs.AbstractGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +abstract class AbstractGraphTests> { + protected lateinit var graph: G + + @BeforeEach + protected abstract fun setup() + + private fun checkEdgesEquals(firstEdge: E?, secondEdge: E?) { + assertEquals(firstEdge?.verticesNumbers, secondEdge?.verticesNumbers) + } + + protected fun checkGraphEdgesEquals(expectedEdges: MutableMap, graphEdges: MutableMap) { + assertEquals(expectedEdges.count(), graphEdges.count()) + for (num in expectedEdges.keys) { + checkEdgesEquals(expectedEdges[num], graphEdges[num]) + } + } + + protected abstract fun createEdge(verticesNumbers: Pair): E + + @Test + @DisplayName("add vertex to empty graph") + fun addVertexEmptyGraph() { + graph.addVertex(5) + val expectedVertices = mutableMapOf(Pair(0, Vertex(5))) + assertEquals(expectedVertices, graph.vertices) + } + + @Test + @DisplayName("add vertex with value which is already in the graph") + fun addVertexExistentValue() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5))) + graph.lastVertexNumber = 1 + graph.addVertex(5) + val expectedVertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(5))) + assertEquals(expectedVertices, graph.vertices) + } + + @Test + @DisplayName("remove existent vertex") + fun removeExistentVertex() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6)), Pair(2, Vertex(7))) + graph.lastVertexNumber = 3 + assertEquals(Vertex(6), graph.removeVertex(1)) + val expectedVertices = mutableMapOf(Pair(0, Vertex(5)), Pair(2, Vertex(7))) + assertEquals(expectedVertices, graph.vertices) + } + + @Test + @DisplayName("remove non-existent vertex") + fun removeNonExistentVertex() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + assertNull(graph.removeVertex(2)) + val expectedVertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + assertEquals(expectedVertices, graph.vertices) + } + + @Test + @DisplayName("get value of existent vertex") + fun getValueExistentVertex() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + assertEquals(5, graph.getVertexValue(0)) + } + + @Test + @DisplayName("get value of non-existent vertex") + fun getValueNonExistentVertex() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + assertNull(graph.getVertexValue(2)) + } + + @Test + @DisplayName("change value of existent vertex") + fun changeValueExistentVertex() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + assertTrue(graph.changeVertexValue(0, 10)) + val expectedVertices = mutableMapOf(Pair(0, Vertex(10)), Pair(1, Vertex(6))) + assertEquals(expectedVertices, graph.vertices) + } + + @Test + @DisplayName("change value of non-existent vertex") + fun changeValueNonExistentVertex() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + assertFalse(graph.changeVertexValue(2, 10)) + val expectedVertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + assertEquals(expectedVertices, graph.vertices) + } + + @Test + @DisplayName("add edge loop") + fun addEdgeLoop() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + assertFalse(graph.addEdge(0, 0)) + val expectedEdges: MutableMap = mutableMapOf() + checkGraphEdgesEquals(expectedEdges, graph.edges) + } + + @Test + @DisplayName("add edge with non-existent first vertex") + fun addEdgeNonExistentFirstVertex() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + assertFalse(graph.addEdge(3, 0)) + val expectedEdges: MutableMap = mutableMapOf() + checkGraphEdgesEquals(expectedEdges, graph.edges) + } + + @Test + @DisplayName("add edge with non-existent second vertex") + fun addEdgeNonExistentSecondVertex() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + assertFalse(graph.addEdge(0, 2)) + val expectedEdges: MutableMap = mutableMapOf() + checkGraphEdgesEquals(expectedEdges, graph.edges) + } + + @Test + @DisplayName("add existent edge") + fun addExistentEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + assertFalse(graph.addEdge(0, 1)) + val expectedEdges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + checkGraphEdgesEquals(expectedEdges, graph.edges) + } + + @Test + @DisplayName("add edge opposite to existent") + protected abstract fun addEdgeOppositeExistent() + + @Test + @DisplayName("add correct edge") + fun addCorrectEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + assertTrue(graph.addEdge(0, 1)) + val expectedEdges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + checkGraphEdgesEquals(expectedEdges, graph.edges) + } + + @Test + @DisplayName("remove existent edge") + fun removeExistentEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + checkEdgesEquals(createEdge(Pair(0, 1)), graph.removeEdge(0)) + val expectedEdges: MutableMap = mutableMapOf() + checkGraphEdgesEquals(expectedEdges, graph.edges) + } + + @Test + @DisplayName("remove non-existent edge") + fun removeNonExistentEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + assertNull(graph.removeEdge(1)) + val expectedEdges: MutableMap = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + checkGraphEdgesEquals(expectedEdges, graph.edges) + } + + @Test + @DisplayName("get vertices numbers of existent edge") + fun getVerticesNumbersExistentEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + val expectedVerticesNumbers = Pair(0, 1) + assertEquals(expectedVerticesNumbers, graph.getEdgeVerticesNumbers(0)) + } + + @Test + @DisplayName("get vertices numbers of non-existent edge") + fun getVerticesNumbersNonExistentEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + assertNull(graph.getEdgeVerticesNumbers(1)) + } + + @Test + @DisplayName("transform graph to its adjacency map") + open fun transformGraphToMap() { + graph.vertices = mutableMapOf(Pair(0, Vertex(1)), Pair(1, Vertex(1)), Pair(2, Vertex(2))) + graph.lastVertexNumber = 3 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1))), Pair(1, createEdge(Pair(1, 2))), Pair(2, createEdge(Pair(0, 2)))) + graph.lastEdgeNumber = 3 + val expectedMap = mapOf(Pair(0, setOf(1, 2)), Pair(1, setOf(0, 2)), Pair(2, setOf(0, 1))) + assertEquals(expectedMap, graph.toAdjacencyMap()) + } +} diff --git a/src/test/kotlin/graphsTests/AbstractWeightedGraphTests.kt b/src/test/kotlin/graphsTests/AbstractWeightedGraphTests.kt new file mode 100644 index 0000000..206f68e --- /dev/null +++ b/src/test/kotlin/graphsTests/AbstractWeightedGraphTests.kt @@ -0,0 +1,86 @@ +package graphsTests + +import model.graphs.edges.WeightedEdge +import model.graphs.graphs.WeightedGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +abstract class AbstractWeightedGraphTests> : AbstractGraphTests() { + @BeforeEach + abstract override fun setup() + + override fun createEdge(verticesNumbers: Pair) = WeightedEdge(verticesNumbers) + + @Test + @DisplayName("add edge opposite to existent") + abstract override fun addEdgeOppositeExistent() + + @Test + @DisplayName("set weight of just added edge") + fun setWeightNewEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.addEdge(0, 1) + assertTrue(graph.changeEdgeWeight(0, 5)) + assertEquals(5, graph.getEdgeWeight(0)) + } + + @Test + @DisplayName("change weight of existent edge") + fun changeWeightExistentEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + graph.edges[0]?.weight = 5 + assertTrue(graph.changeEdgeWeight(0, 10)) + assertEquals(10, graph.getEdgeWeight(0)) + } + + @Test + @DisplayName("change value of non-existent edge") + fun changeWeightNonExistentEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + assertFalse(graph.changeEdgeWeight(1, 10)) + } + + @Test + @DisplayName("get weight of just added edge") + fun getWeightNewEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.addEdge(0, 1) + assertEquals(0, graph.getEdgeWeight(0)) + } + + @Test + @DisplayName("get weight of existent edge") + fun getWeightExistentEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + graph.edges[0]?.weight = 5 + assertEquals(5, graph.getEdgeWeight(0)) + } + + @Test + @DisplayName("get weight of non-existent edge") + fun getWeightNonExistentEdge() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + graph.edges[0]?.weight = 5 + assertNull(graph.getEdgeWeight(1)) + } +} diff --git a/src/test/kotlin/graphsTests/DirectedGraphTests.kt b/src/test/kotlin/graphsTests/DirectedGraphTests.kt new file mode 100644 index 0000000..f81fd49 --- /dev/null +++ b/src/test/kotlin/graphsTests/DirectedGraphTests.kt @@ -0,0 +1,42 @@ +package graphsTests + +import model.graphs.edges.Edge +import model.graphs.graphs.DirectedGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +class DirectedGraphTests : AbstractGraphTests>() { + @BeforeEach + override fun setup() { + graph = DirectedGraph() + } + + override fun createEdge(verticesNumbers: Pair) = Edge(verticesNumbers) + + @Test + @DisplayName("add edge opposite to existent") + override fun addEdgeOppositeExistent() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, Edge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + assertTrue(graph.addEdge(1, 0)) + val expectedEdges = mutableMapOf(Pair(0, Edge(Pair(0, 1))), Pair(1, Edge(Pair(1, 0)))) + checkGraphEdgesEquals(expectedEdges, graph.edges) + } + + @Test + @DisplayName("transform graph to its adjacency map") + override fun transformGraphToMap() { + graph.vertices = mutableMapOf(Pair(0, Vertex(1)), Pair(1, Vertex(1)), Pair(2, Vertex(2))) + graph.lastVertexNumber = 3 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1))), Pair(1, createEdge(Pair(1, 2))), Pair(2, createEdge(Pair(0, 2)))) + graph.lastEdgeNumber = 3 + val expectedMap = mapOf(Pair(0, setOf(1, 2)), Pair(1, setOf(2)), Pair(2, setOf())) + assertEquals(expectedMap, graph.toAdjacencyMap()) + } +} \ No newline at end of file diff --git a/src/test/kotlin/graphsTests/GraphTests.kt b/src/test/kotlin/graphsTests/GraphTests.kt new file mode 100644 index 0000000..11d7b55 --- /dev/null +++ b/src/test/kotlin/graphsTests/GraphTests.kt @@ -0,0 +1,30 @@ +package graphsTests + +import model.graphs.edges.Edge +import model.graphs.graphs.Graph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +class GraphTests : AbstractGraphTests>() { + @BeforeEach + override fun setup() { + graph = Graph() + } + + override fun createEdge(verticesNumbers: Pair) = Edge(verticesNumbers) + + @Test + @DisplayName("add edge opposite to existent") + override fun addEdgeOppositeExistent() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + assertFalse(graph.addEdge(1, 0)) + val expectedEdges = mutableMapOf(Pair(0, Edge(Pair(0, 1)))) + checkGraphEdgesEquals(expectedEdges, graph.edges) + } +} diff --git a/src/test/kotlin/graphsTests/WeightedDirectedGraphTests.kt b/src/test/kotlin/graphsTests/WeightedDirectedGraphTests.kt new file mode 100644 index 0000000..ca1dd15 --- /dev/null +++ b/src/test/kotlin/graphsTests/WeightedDirectedGraphTests.kt @@ -0,0 +1,40 @@ +package graphsTests + +import model.graphs.edges.WeightedEdge +import model.graphs.graphs.WeightedDirectedGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +class WeightedDirectedGraphTests : AbstractWeightedGraphTests>() { + @BeforeEach + override fun setup() { + graph = WeightedDirectedGraph() + } + + @Test + @DisplayName("add edge opposite to existent") + override fun addEdgeOppositeExistent() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, WeightedEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + assertTrue(graph.addEdge(1, 0)) + val expectedEdges = mutableMapOf(Pair(0, WeightedEdge(Pair(0, 1))), Pair(1, WeightedEdge(Pair(1, 0)))) + checkGraphEdgesEquals(expectedEdges, graph.edges) + } + + @Test + @DisplayName("transform graph to its adjacency map") + override fun transformGraphToMap() { + graph.vertices = mutableMapOf(Pair(0, Vertex(1)), Pair(1, Vertex(1)), Pair(2, Vertex(2))) + graph.lastVertexNumber = 3 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1))), Pair(1, createEdge(Pair(1, 2))), Pair(2, createEdge(Pair(0, 2)))) + graph.lastEdgeNumber = 3 + val expectedMap = mapOf(Pair(0, setOf(1, 2)), Pair(1, setOf(2)), Pair(2, setOf())) + assertEquals(expectedMap, graph.toAdjacencyMap()) + } +} diff --git a/src/test/kotlin/graphsTests/WeightedGraphTests.kt b/src/test/kotlin/graphsTests/WeightedGraphTests.kt new file mode 100644 index 0000000..316c10b --- /dev/null +++ b/src/test/kotlin/graphsTests/WeightedGraphTests.kt @@ -0,0 +1,27 @@ +package graphsTests + +import model.graphs.graphs.WeightedGraph +import model.graphs.vertex.Vertex +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test + +class WeightedGraphTests : AbstractWeightedGraphTests>() { + @BeforeEach + override fun setup() { + graph = WeightedGraph() + } + + @Test + @DisplayName("add edge opposite to existent") + override fun addEdgeOppositeExistent() { + graph.vertices = mutableMapOf(Pair(0, Vertex(5)), Pair(1, Vertex(6))) + graph.lastVertexNumber = 2 + graph.edges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + graph.lastEdgeNumber = 1 + assertFalse(graph.addEdge(1, 0)) + val expectedEdges = mutableMapOf(Pair(0, createEdge(Pair(0, 1)))) + checkGraphEdgesEquals(expectedEdges, graph.edges) + } +} diff --git a/src/test/kotlin/integration/ShowBridgeFinderTest.kt b/src/test/kotlin/integration/ShowBridgeFinderTest.kt new file mode 100644 index 0000000..64257f3 --- /dev/null +++ b/src/test/kotlin/integration/ShowBridgeFinderTest.kt @@ -0,0 +1,40 @@ +package integration + +import androidx.compose.ui.graphics.Color +import model.graphs.graphs.Graph +import org.junit.jupiter.api.Test +import viewModel.graphViewModel.CircularPlacementStrategy +import viewModel.screensViewModels.mainScreensViewModels.MainScreenViewModel + +class ShowBridgeFinderTest { + + @Test + fun showBridgeFinderTest() { + val graph = Graph() + graph.addVertex(0) + graph.addVertex(1) + graph.addVertex(2) + graph.addVertex(3) + graph.addVertex(4) + graph.addVertex(5) + graph.addEdge(0, 1) + graph.addEdge(1, 2) + graph.addEdge(2, 0) + graph.addEdge(2, 3) // bridge + graph.addEdge(3, 4) + graph.addEdge(4, 5) + graph.addEdge(5, 3) + val representationStrategy = CircularPlacementStrategy() + val mainScreenViewModel = MainScreenViewModel(graph, representationStrategy) + + mainScreenViewModel.findBridges() + + var hightlightedEdgesCount = 0 + mainScreenViewModel.graphViewModel.edges.forEach { if (it.color == Color.Red) hightlightedEdgesCount++ } + assert(hightlightedEdgesCount == 1) + val bridge = mainScreenViewModel.graphViewModel.edges.first { it.color == Color.Red } + assert(bridge.u.v.value != bridge.v.v.value) + assert(bridge.u.v.value == 2 || bridge.u.v.value == 3) + assert(bridge.v.v.value == 3 || bridge.v.v.value == 2) + } +} \ No newline at end of file