licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
docs
2535
# Contributing to `PhyloDiamond.jl` The following guidelines are designed for contributors to `PhyloDiamond.jl`. ## Reporting Issues For reporting a bug or a failed function or requesting a new feature, you can simply open an issue in the [issue tracker](https://github.com/solislemuslab/PhyloDiamond.jl/issues). If you are reporting a bug, please also include a minimal code example or all relevant information for us to replicate the issue. ## Contributing Code To make contributions to `PhyloDiamond.jl`, you need to set up your [GitHub](https://github.com) account if you do not have and sign in, and request your change(s) or contribution(s) via a pull request against the ``develop`` branch of the [PhyloDiamond.jl repository](https://github.com/solislemuslab/PhyloDiamond.jl). Please use the following steps: 1. Open a new issue for new feature or failed function in the [issue tracker](https://github.com/solislemuslab/PhyloDiamond.jl/issues) 2. Fork the [PhyloDiamond.jl repository](https://github.com/solislemuslab/PhyloDiamond.jl) to your GitHub account 3. Clone your fork locally: ``` $ git clone https://github.com/your-username/PhyloDiamond.jl.git ``` 4. Make your change(s) in the `master` (or `development`) branch of your cloned fork 5. Make sure that all tests (`test/runtests.jl`) are passed without any errors 6. Push your change(s) to your fork in your GitHub account 7. [Submit a pull request](https://github.com/solislemuslab/PhyloDiamond.jl/pulls) describing what problem has been solved and linking to the issue you had opened in step 1 Your contribution will be checked and merged into the original repository. You will be contacted if there is any problem in your contribution Make sure to include the following information in your pull request: * **Code** which you are contributing to this package * **Documentation** of this code if it provides new functionality. This should be a description of new functionality added to the [docs](https://solislemuslab.github.io/PhyloDiamond.jl/dev/). Check out the [docs folder](https://github.com/solislemuslab/PhyloDiamond.jl/tree/main/docs) for instructions on how to update the documentation. - **Tests** of this code to make sure that the previously failed function or the new functionality now works properly --- _These Contributing Guidelines have been adapted from the [Contributing Guidelines](https://github.com/atomneb/AtomNeb-py/blob/master/CONTRIBUTING.md) of [The Turing Way](https://github.com/atomneb/AtomNeb-py)! (License: MIT)_
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
docs
1892
# PhyloDiamond<picture> <img alt="phylodiamond logo" src="docs/src/logo_unrooted_trans.png" align=right></picture> [![Build Status](https://github.com/zwu363/PhyloDiamond.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/zwu363/PhyloDiamond.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/zwu363/PhyloDiamond.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/zwu363/PhyloDiamond.jl) ## Overview `PhyloDiamond.jl` is a [Julia](http://julialang.org/) package for ultrfast learning of 4-node hybridization cycles in phylogenetic networks using algebraic invariants. Input data: - A concordance factor table - A file containing gene trees ## Usage `PhyloDiamond.jl` is a julia package, so the user needs to install julia, and then install the package. To install the package, type inside Julia: ```julia ] add PhyloDiamond ``` ## Help and errors To get help, check the documentation [here](https://solislemuslab.github.io/PhyloDiamond.jl/dev). Please report any bugs and errors by opening an [issue](https://github.com/solislemuslab/PhyloDiamond.jl/issues/new). ## Citation If you use `PhyloDiamond.jl` in your work, we kindly ask that you cite the following paper: ``` @article{wu_solis-lemus_2022, author = {Wu, Z. and Sol'{i}s-Lemus, C.}, year = {2022}, title = {{Ultrafast learning of 4-node hybridization cycles in phylogenetic networks using algebraic invariants}}, url={https://arxiv.org/abs/2211.16647v1} } ``` ## License `PhyloDiamond.jl` is licensed under a [MIT License](https://github.com/solislemuslab/PhyloDiamond.jl/blob/master/LICENSE). ## Contributions Users interested in expanding functionalities in `PhyloDiamond.jl` are welcome to do so. See details on how to contribute in [CONTRIBUTING.md](https://github.com/solislemuslab/PhyloDiamond.jl/blob/master/CONTRIBUTING.md).
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
docs
166
To update the documentation, make changes to the .md files in `src/man` or `src/lib` and push to main. The CI tools will automatically build the necessary html files.
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
docs
557
# PhyloDiamond.jl [PhyloDiamond.jl](https://github.com/solislemuslab/PhyloDiamond.jl) is a [Julia](http://julialang.org/) package to perform PhyloDiamond algorithm to infer 4-node hybridization cycles in phylogenetic networks using algebraic invariants. ## References If you use `PhyloDiamond.jl` in your work, we kindly ask that you cite the following paper: - Wu, Z., Solís-Lemus, C. (2022). Ultrafast learning of 4-node hybridization cycles in phylogenetic networks using algebraic invariants. [arXiv:2211.16647](https://arxiv.org/abs/2211.16647).
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
docs
252
```@meta CurrentModule = PhyloDiamond ``` ```@docs phylo_diamond(cf::DataFrame, m::Int64, output_filename::String="phylo_diamond.txt") ``` ```@docs phylo_diamond(gene_trees_filename::String, m::Int64, output_filename::String="phylo_diamond.txt") ```
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
docs
6537
# Implementing PhyloDiamond Algorithm ## Functions To implement PhyloDiamond Algorithm, users can either input a concordance factor table or directly input a file of gene trees. ### Function taking in a concordance factor table Below takes in three parameters including a concordance factor table: ```julia phylo_diamond(cf::DataFrame, m::Int64, output_filename::String="phylo_diamond.txt") ``` - `cf`: a dataframe containing concordance factor values with taxon names in the first 4 columns and values in the last 3 columns - Each row correspond to a taxon set `s={a,b,c,d}` - There are only three possible quartet splits `q1=ab|cd, q2=ac|bd, q3=ad|bc` - The dataframe should contain 7 columns, ordered as `a, b, c, d, q1, q2, q3` - `m`: the number of optimal phylogenetic networks returned - `output_filename`: a file name for the output file (or "phylo_diamond.txt" by default) ### Function taking in a gene tree file Below takes in three parameters including a gene tree file: ```julia phylo_diamond(gene_trees_filename::String, m::Int64, output_filename::String="phylo_diamond.txt") ``` - `gene_trees_filename`: the file name storing all gene trees - `m`: the number of optimal phylogenetic networks returned - `output_filename`: a file name for the output file (or "phylo_diamond.txt" by default) ## Examples First load the package. ```julia using PhyloDiamond ``` ### Example 1: taking in a concordance factor table If your concordance factor table is in csv file format, you need to read the file in Julia first. If you have not used the CSV.jl package before then you may need to install it first: ```julia using Pkg Pkg.add("CSV") ``` The CSV.jl functions are not loaded automatically and must be imported into the session. ```julia using CSV ``` The concordance factor table can now be read from a CSV file at path `input` using ```julia df = DataFrame(CSV.File(input)) ``` ``` 70×7 DataFrame Row │ tx1 tx2 tx3 tx4 expCF12 expCF13 expCF14 │ String String String String Float64 Float64 Float64 ─────┼───────────────────────────────────────────────────────────────────── 1 │ 7 8 3 4 0.999392 0.000303961 0.000303961 2 │ 7 8 3 1 0.993192 0.00340375 0.00340375 3 │ 7 8 3 2 0.993192 0.00340375 0.00340375 4 │ 7 8 3 5 0.98779 0.00610521 0.00610521 5 │ 7 8 3 6 0.98779 0.00610521 0.00610521 6 │ 7 8 4 1 0.993192 0.00340375 0.00340375 7 │ 7 8 4 2 0.993192 0.00340375 0.00340375 8 │ 7 8 4 5 0.98779 0.00610521 0.00610521 ⋮ │ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ 63 │ 3 1 2 6 0.0999344 0.0999344 0.800131 64 │ 3 1 5 6 0.964386 0.0178072 0.0178072 65 │ 3 2 5 6 0.964386 0.0178072 0.0178072 66 │ 4 1 2 5 0.0999344 0.0999344 0.800131 67 │ 4 1 2 6 0.0999344 0.0999344 0.800131 68 │ 4 1 5 6 0.964386 0.0178072 0.0178072 69 │ 4 2 5 6 0.964386 0.0178072 0.0178072 70 │ 1 2 5 6 0.984151 0.00792452 0.00792452 ``` Then we can implement PhyloDiamond algorithm on this concordance factor table. ```julia phylo_diamond(df, 5) ``` It outputs a dictionary, where is key is the rank and the value is the infered network. The networks are represented in newick format. ``` Dict{Int64, Any} with 5 entries: 5 => "((7:1,8:1):4, (((1:1,2:1):2, ((3:1,4:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" 4 => "((5:1,6:1):4, (((7:1,8:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(3:1,4:1):2):1):1);" 2 => "((7:1,8:1):4, (((5:1,6:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(3:1,4:1):2):1):1);" 3 => "((5:1,6:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(7:1,8:1):2):1):1);" 1 => "((7:1,8:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" ``` Below is what is stored in the output file: ``` Inference of top 5 8-taxon phylogenetic networks with phylogenetic invariants 1. N2222 (2.2216927709301364e-16) [(1,2),(3,4),(5,6),(7,8)] "((7:1,8:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" 2. N2222 (2.2230610911746716e-16) [(1,2),(5,6),(3,4),(7,8)] "((7:1,8:1):4, (((5:1,6:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(3:1,4:1):2):1):1);" 3. N2222 (0.006576057988736475) [(1,2),(3,4),(7,8),(5,6)] "((5:1,6:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(7:1,8:1):2):1):1);" 4. N2222 (0.00657929000066336) [(1,2),(7,8),(3,4),(5,6)] "((5:1,6:1):4, (((7:1,8:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(3:1,4:1):2):1):1);" 5. N2222 (0.0066877783427965855) [(3,4),(1,2),(5,6),(7,8)] "((7:1,8:1):4, (((1:1,2:1):2, ((3:1,4:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" ``` To understand the output file, take the first network as an example. `N2222` is the structure of the network, meaning that there are 2 taxon in clades n0, n1, n2, n3. The value followed is the corresponding score for the infered network, and a small score represents a highly possible network. `[(1,2),(3,4),(5,6),(7,8)]` is the parenthetical format of the network. Then it is the newick format of the network ### Example 2: taking in a gene tree file Here is an example genetree file "gt.txt": ``` ((7:0.722,8:0.722):2.844,(((3:0.878,4:0.878):0.907,(1:0.935,2:0.935):0.849):1.005,(5:1.853,6:1.853):0.937):0.776); ((7:0.649,8:0.649):2.104,((5:1.919,6:1.919):0.374,((3:0.634,4:0.634):1.442,(1:0.660,2:0.660):1.416):0.218):0.460); ((7:0.942,8:0.942):3.188,(6:3.361,(5:2.130,((1:0.816,2:0.816):1.294,(3:1.045,4:1.045):1.065):0.021):1.231):0.769); ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ (((3:0.600,4:0.600):1.746,(1:0.841,2:0.841):1.506):0.654,((7:0.613,8:0.613):2.148,(5:0.762,6:0.762):1.999):0.239); ((7:0.702,8:0.702):2.679,((5:1.454,6:1.454):0.672,(3:1.942,(4:1.707,(1:0.674,2:0.674):1.033):0.234):0.184):1.255); (((3:0.647,4:0.647):1.243,(1:1.407,2:1.407):0.483):0.844,((7:0.581,8:0.581):1.979,(5:1.204,6:1.204):1.357):0.173); ``` ```julia phylo_diamond("gt.txt", 5) ``` ## Error reporting Please report any bugs and errors by opening an [issue](https://github.com/solislemuslab/PhyloDiamond.jl/issues/new).
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
docs
1806
# Installation ## Installation of Julia Julia is a high-level and interactive programming language (like R or Matlab), but it is also high-performance (like C). To install Julia, follow instructions [here](http://julialang.org/downloads/). For a quick & basic tutorial on Julia, see [learn x in y minutes](http://learnxinyminutes.com/docs/julia/). Editors: - [Visual Studio Code](https://code.visualstudio.com) provides an editor and an integrated development environment (IDE) for Julia: highly recommended! - You can also run Julia within a [Jupyter](http://jupyter.org) notebook (formerly IPython notebook). IMPORTANT: Julia code is just-in-time compiled. This means that the first time you run a function, it will be compiled at that moment. So, please be patient! Future calls to the function will be much much faster. Trying out toy examples for the first calls is a good idea. ## Installation of the `PhyloDiamond.jl` package To install the package, type inside Julia: ```julia ] add PhyloDiamond ``` The first step can take a few minutes, be patient. The `PhyloDiamond.jl` package has dependencies like [Distributions](https://juliastats.org/Distributions.jl/stable/starting/) and [DataFrames](http://juliadata.github.io/DataFrames.jl/stable/) (see the `Project.toml` file for the full list), but everything is installed automatically. ## Loading the Package To check that your installation worked, type this in Julia to load the package. This is something to type every time you start a Julia session: ```@example install using PhyloDiamond ``` This step can also take a while, if Julia needs to pre-compile the code (after a package update for instance). Press `?` inside Julia to switch to help mode, followed by the name of a function (or type) to get more details about it.
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
docs
1901
# phylo-invariants Method to estimate phylogenetic networks from invariants - Example code for gene tree simulation - More detailed bash script for gene tree simulation could be found in `./simulation/sim_tree.sh` ```bash ./ms-converter --newick="((7:1,8:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" --run --n 100 --output=sim_trees_2222_100 ./ms-converter --newick="((7:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" --run --n 100 --output=sim_trees_2221_100 ./ms-converter --newick="((7:1,6:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1):2):1):1);" --run --n 100 --output=sim_trees_2212_100 ./ms-converter --newick="((7:1,4:1):4, (((3:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" --run --n 100 --output=sim_trees_2122_100 ./ms-converter --newick="((7:1,2:1):4, (((3:1,4:1):2, ((1:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" --run --n 100 --output=sim_trees_1222_100 ./ms-converter --newick="((6:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1):2):1):1);" --run --n 100 --output=sim_trees_2211_100 ./ms-converter --newick="((4:1,6:1):4, (((3:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1):2):1):1);" --run --n 100 --output=sim_trees_2112_100 ./ms-converter --newick="((6:1):4, (((3:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,4:1):2):1):1);" --run --n 100 --output=sim_trees_2121_100 ./ms-converter --newick="((2:1):4, (((3:1,4:1):2, ((1:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" --run --n 100 --output=sim_trees_1221_100 ./ms-converter --newick="((5:1,6:1):4, (((3:1,4:1):2, ((1:1):1)#H1:1::0.7):1, (#H1:1::0.3,(2:1):2):1):1);" --run --n 100 --output=sim_trees_1212_100 ./ms-converter --newick="((5:1,6:1):4, (((2:1):2, ((1:1):1)#H1:1::0.7):1, (#H1:1::0.3,(3:1,4:1):2):1):1);" --run --n 100 --output=sim_trees_1122_100 ```
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
docs
1284
# Julia - `text_convert.jl` contains the functions to convert between the julia, latex and macaulay formats for the invariants. - `invariants.jl` contains the invariant functions with `a` as input vector (CF values from CF table) - `mapping.jl` contains the functions to map the CF values from a CF table into the `a` vector - `mapping-fn.jl` pseudo code for mapping CF table to values # Macaulay2 - (all): all cf - (sub): independent cf - (incomplete): a subset of cf that gives output - (quadratic): cf containing quadratic terms ## Macaulay2 scripts to obtain the phylogenetic invariants The scripts correspond to networks with 4-cycle hybridizations (4 nodes in the hybridization cycle). `Nijkl` represents the specific network; for example, `N1112` corresponds to the network with 1 taxon from `n_0`, 1 taxon from `n_1`, 1 taxon from `n_2` and 2 taxa from `n_3`. Files with extension `.m2` are the macaulay2 script and the files with `_out.txt` in the file name are the output files. Some scripts do not have output files because they were computationally intensive and have not been run to completion. The command to run the scripts in the terminal is (after having installed [Macaulay2](http://www2.macaulay2.com/Macaulay2/)): ``` cat file.m2 | M2 >& file_out.txt & ```
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
docs
25396
--- title: "Final plots for Wu and Solis-Lemus (2022)" output: html_notebook --- ```{r} library(ggplot2) library(tidyverse) library(patchwork) library(RColorBrewer) ## https://r-graph-gallery.com/38-rcolorbrewers-palettes.html? ``` ```{r} df = read.csv("../../simulation/result/rst_all.csv") ##downloaded from google drive df$nw_type = as.factor(df$nw_type) df$sim_type[df$num_genetree==0 & df$len_seq==0 & df$sd == 0] = "cf" df$sim_type[df$num_genetree==0 & df$len_seq==0 & df$sd != 0] = "cf_noise" df$sim_type[df$num_genetree!=0 & df$len_seq==0] = "gene_tree" df$sim_type[df$num_genetree!=0 & df$len_seq!=0] = "est_gene_tree" df$sim_type = as.factor(df$sim_type) ``` # Figure for invariant score ```{r} ## need to put sim_type in different order: df$sim_type = factor(df$sim_type, levels=c("cf", "cf_noise", "gene_tree", "est_gene_tree")) df2 = df %>% pivot_longer(c("inv_true", "inv_sym"), names_to = "inv_type", values_to = "inv") ## put in right order: df2$inv_type = factor(df2$inv_type) df2$inv_type = factor(df2$inv_type, levels=c("inv_true", "inv_sym")) ``` ## True CF and Noisy CF ```{r} df3 = df2[df2$sim_type %in% c("cf","cf_noise"),] df3$sim_type2 = "cf" df3$sim_type2[df3$sim_type == "cf_noise" & df3$sd == 0.000005] = "cf_noise1" df3$sim_type2[df3$sim_type == "cf_noise" & df3$sd == 0.00005] = "cf_noise2" df3$sim_type2[df3$sim_type == "cf_noise" & df3$sd == 0.0005] = "cf_noise3" df3$sim_type2 = factor(df3$sim_type2) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/invariant-score-true-noisy.pdf", width = 8, height = 4) df3 %>% ggplot(mapping = aes(x = nw_type, y = inv))+ geom_boxplot(aes(col = inv_type)) + facet_wrap(.~sim_type2, #scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("cf" = "True CF", "cf_noise1" = "Noisy CF (sd=5e-6)", "cf_noise2" = "Noisy CF (sd=5e-5)", "cf_noise3" = "Noisy CF (sd=5e-4)")))+ labs(x = "", y = "Invariant Score")+ #scale_colour_manual('', # labels=c('True', 'Symmetric'), # values=c('#43CD80','#3A5FCD'))+ scale_colour_brewer('', labels=c('True', 'Symmetric'), palette="Set1")+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), axis.text.y = element_text(size=12), axis.title.y = element_text(size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), legend.text=element_text(size=12)) dev.off() ``` ## True gene trees ```{r} df3 = df2[df2$sim_type == "gene_tree",] df3$sim_type2 = "gene_tree" df3$sim_type2[df3$num_genetree == 100] = "gene_tree1" df3$sim_type2[df3$num_genetree == 1000] = "gene_tree2" df3$sim_type2[df3$num_genetree == 10000] = "gene_tree3" df3$sim_type2 = factor(df3$sim_type2) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/invariant-score-true-gt.pdf", width = 8, height = 4) df3 %>% ggplot(mapping = aes(x = nw_type, y = inv))+ geom_boxplot(aes(col = inv_type)) + facet_wrap(.~sim_type2, #scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("gene_tree1" = "True g.t. (100)", "gene_tree2" = "True g.t. (1000)", "gene_tree3" = "True g.t. (10000)")))+ labs(x = "", y = "Invariant Score")+ #scale_colour_manual('', # labels=c('True', 'Symmetric'), # values=c('#43CD80','#3A5FCD'))+ scale_colour_brewer('', labels=c('True', 'Symmetric'), palette="Set1")+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), axis.text.y = element_text(size=12), axis.title.y = element_text(size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), legend.text=element_text(size=12)) dev.off() ``` ## Estimated gene trees ```{r} df3 = df2[df2$sim_type == "est_gene_tree",] df3$sim_type2 = "est_gene_tree" #df3$sim_type2[df3$num_genetree == 100 & df3$len_seq == 500] = "est_gene_tree1" df3$sim_type2[df3$num_genetree == 1000 & df3$len_seq == 500] = "est_gene_tree2" df3$sim_type2[df3$num_genetree == 10000 & df3$len_seq == 500] = "est_gene_tree3" #df3$sim_type2[df3$num_genetree == 100 & df3$len_seq == 2000] = "est_gene_tree4" df3$sim_type2[df3$num_genetree == 1000 & df3$len_seq == 2000] = "est_gene_tree5" df3$sim_type2[df3$num_genetree == 10000 & df3$len_seq == 2000] = "est_gene_tree6" df3$sim_type2 = factor(df3$sim_type2) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/invariant-score-est-gt.pdf", width = 8, height = 4) df3 %>% ggplot(mapping = aes(x = nw_type, y = inv))+ geom_boxplot(aes(col = inv_type)) + facet_wrap(.~sim_type2, #scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("est_gene_tree2" = "gt=1000, L=500", "est_gene_tree3" = "gt=10000, L=500", "est_gene_tree5" = "gt=1000, L=2000", "est_gene_tree6" = "gt=10000, L=2000")))+ labs(x = "", y = "Invariant Score")+ #scale_colour_manual('', # labels=c('True', 'Symmetric'), # values=c('#43CD80','#3A5FCD'))+ scale_colour_brewer('', labels=c('True', 'Symmetric'), palette="Set1")+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), axis.text.y = element_text(size=12), axis.title.y = element_text(size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), legend.text=element_text(size=12)) dev.off() ``` # Figure of rank ```{r} df3 = df %>% pivot_longer(c("rank_true", "rank_sym"), names_to = "rank_type", values_to = "rank") ## put in right order: df3$rank_type = factor(df3$rank_type) df3$rank_type = factor(df3$rank_type, levels=c("rank_true", "rank_sym")) ``` ## True and noisy cf ```{r} df4 = df3[df3$sim_type %in% c("cf","cf_noise"),] df4$sim_type2 = "cf" df4$sim_type2[df4$sim_type == "cf_noise" & df4$sd == 0.000005] = "cf_noise1" df4$sim_type2[df4$sim_type == "cf_noise" & df4$sd == 0.00005] = "cf_noise2" df4$sim_type2[df4$sim_type == "cf_noise" & df4$sd == 0.0005] = "cf_noise3" df4$sim_type2 = factor(df4$sim_type2) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/rank-true-noisy-cf.pdf", width = 8, height = 4) df4 %>% ggplot(mapping = aes(x = nw_type, y = rank))+ geom_boxplot(aes(col = rank_type)) + geom_hline(yintercept=5, linetype="dashed", color = "grey") + facet_wrap(.~sim_type2, #scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("cf" = "True CF", "cf_noise1" = "Noisy CF (sd=5e-6)", "cf_noise2" = "Noisy CF (sd=5e-5)", "cf_noise3" = "Noisy CF (sd=5e-4)")))+ labs(x = "", y = "Rank")+ #scale_colour_manual('', # labels=c('True', 'Symmetric'), # values=c('#43CD80','#3A5FCD'))+ scale_colour_brewer('', labels=c('True', 'Symmetric'), palette="Set1")+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), axis.text.y = element_text(size=12), axis.title.y = element_text(size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), legend.text=element_text(size=12)) dev.off() ``` ## True gene trees ```{r} df4 = df3[df3$sim_type == "gene_tree",] df4$sim_type2 = "gene_tree" df4$sim_type2[df4$num_genetree == 100] = "gene_tree1" df4$sim_type2[df4$num_genetree == 1000] = "gene_tree2" df4$sim_type2[df4$num_genetree == 10000] = "gene_tree3" df4$sim_type2 = factor(df4$sim_type2) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/rank-true-gt.pdf", width = 8, height = 4) df4 %>% ggplot(mapping = aes(x = nw_type, y = rank))+ geom_boxplot(aes(col = rank_type)) + geom_hline(yintercept=5, linetype="dashed", color = "grey") + facet_wrap(.~sim_type2, #scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("gene_tree1" = "True g.t. (100)", "gene_tree2" = "True g.t. (1000)", "gene_tree3" = "True g.t. (10000)")))+ labs(x = "", y = "Rank")+ #scale_colour_manual('', # labels=c('True', 'Symmetric'), # values=c('#43CD80','#3A5FCD'))+ scale_colour_brewer('', labels=c('True', 'Symmetric'), palette="Set1")+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), axis.text.y = element_text(size=12), axis.title.y = element_text(size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), legend.text=element_text(size=12)) dev.off() ``` ## Estimated gene trees ```{r} df4 = df3[df3$sim_type == "est_gene_tree",] df4$sim_type2 = "est_gene_tree" df4$sim_type2[df4$num_genetree == 1000 & df4$len_seq == 500] = "est_gene_tree2" df4$sim_type2[df4$num_genetree == 10000 & df4$len_seq == 500] = "est_gene_tree3" df4$sim_type2[df4$num_genetree == 1000 & df4$len_seq == 2000] = "est_gene_tree5" df4$sim_type2[df4$num_genetree == 10000 & df4$len_seq == 2000] = "est_gene_tree6" df4$sim_type2 = factor(df4$sim_type2) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/rank-est-gt.pdf", width = 8, height = 4) df4 %>% ggplot(mapping = aes(x = nw_type, y = rank))+ geom_boxplot(aes(col = rank_type)) + geom_hline(yintercept=5, linetype="dashed", color = "grey") + facet_wrap(.~sim_type2, #scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("est_gene_tree2" = "gt=1000, L=500", "est_gene_tree3" = "gt=10000, L=500", "est_gene_tree5" = "gt=1000, L=2000", "est_gene_tree6" = "gt=10000, L=2000")))+ labs(x = "", y = "Rank")+ #scale_colour_manual('', # labels=c('True', 'Symmetric'), # values=c('#43CD80','#3A5FCD'))+ scale_colour_brewer('', labels=c('True', 'Symmetric'), palette="Set1")+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), axis.text.y = element_text(size=12), axis.title.y = element_text(size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), legend.text=element_text(size=12)) dev.off() ``` # Figure with the top 5 ```{r} df$label[df$rank_sym<=5 & df$rank_true<=5] = "sym_true" df$label[df$rank_true<=5 & df$rank_sym>5] = "true" df$label[df$rank_sym<=5 & df$rank_true>5] = "sym" df$label[df$rank_sym>5 & df$rank_true>5] = "other" ## label is chr, and we need it as factor and in correct order: str(df) df$label = factor(df$label) df$label = factor(df$label, levels = c("sym_true","true","sym","other")) ## need to put sim_type in different order: df$sim_type = factor(df$sim_type, levels=c("cf", "cf_noise", "gene_tree", "est_gene_tree")) ``` ## True and noisy CF ```{r} df2 = df[df$sim_type %in% c("cf","cf_noise"),] df2$sim_type2 = "cf" df2$sim_type2[df2$sim_type == "cf_noise" & df2$sd == 0.000005] = "cf_noise1" df2$sim_type2[df2$sim_type == "cf_noise" & df2$sd == 0.00005] = "cf_noise2" df2$sim_type2[df2$sim_type == "cf_noise" & df2$sd == 0.0005] = "cf_noise3" df2$sim_type2 = factor(df2$sim_type2) #png("1.png", width = 8, height = 6, units = 'in', res = 300) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/top5-true-noisy-cf.pdf", width = 8, height = 4) df2 %>% ggplot(aes(fill=label, x=nw_type)) + #geom_bar()+ geom_bar(aes(y = (..count..)/sum(..count..)))+ facet_wrap(.~sim_type2, scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("cf" = "True CF", "cf_noise1" = "Noisy CF (sd=5e-6)", "cf_noise2" = "Noisy CF (sd=5e-5)", "cf_noise3" = "Noisy CF (sd=5e-4)")))+ labs(x = "", y = "")+ #scale_fill_manual('Types of top 5 networks', # labels=c('Other', 'Symmetrical network', # 'Both symmetrical and true networks', 'True network'), # values=c('#CDC5BF', '#43CD80', '#EE8262', '#3A5FCD'))+ scale_fill_brewer('',labels=c('True and Symmetric', 'True', 'Symmetric','Other'), palette = "PuBuGn", direction=-1)+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), axis.text.y=element_blank(), legend.text=element_text(size=12)) dev.off() ``` ## True gene trees ```{r} df2 = df[df$sim_type == "gene_tree",] df2$sim_type2 = "gene_tree" df2$sim_type2[df2$num_genetree == 100] = "gene_tree1" df2$sim_type2[df2$num_genetree == 1000] = "gene_tree2" df2$sim_type2[df2$num_genetree == 10000] = "gene_tree3" df2$sim_type2 = factor(df2$sim_type2) #png("1.png", width = 8, height = 6, units = 'in', res = 300) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/top5-true-gt.pdf", width = 8, height = 4) df2 %>% ggplot(aes(fill=label, x=nw_type)) + #geom_bar()+ geom_bar(aes(y = (..count..)/sum(..count..)))+ facet_wrap(.~sim_type2, scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("gene_tree1" = "True g.t. (100)", "gene_tree2" = "True g.t. (1000)", "gene_tree3" = "True g.t. (10000)")))+ labs(x = "", y = "")+ #scale_fill_manual('Types of top 5 networks', # labels=c('Other', 'Symmetrical network', # 'Both symmetrical and true networks', 'True network'), # values=c('#CDC5BF', '#43CD80', '#EE8262', '#3A5FCD'))+ scale_fill_brewer('',labels=c('True and Symmetric', 'True', 'Symmetric','Other'), palette = "PuBuGn", direction=-1)+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), axis.text.y=element_blank(), legend.text=element_text(size=12)) dev.off() ``` ## Estimated gene trees ```{r} df2 = df[df$sim_type == "est_gene_tree",] df2$sim_type2 = "est_gene_tree" df2$sim_type2[df2$num_genetree == 1000 & df2$len_seq == 500] = "est_gene_tree2" df2$sim_type2[df2$num_genetree == 10000 & df2$len_seq == 500] = "est_gene_tree3" df2$sim_type2[df2$num_genetree == 1000 & df2$len_seq == 2000] = "est_gene_tree5" df2$sim_type2[df2$num_genetree == 10000 & df2$len_seq == 2000] = "est_gene_tree6" df2$sim_type2 = factor(df2$sim_type2) #png("1.png", width = 8, height = 6, units = 'in', res = 300) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/top5-est-gt.pdf", width = 8, height = 4) df2 %>% ggplot(aes(fill=label, x=nw_type)) + #geom_bar()+ geom_bar(aes(y = (..count..)/sum(..count..)))+ facet_wrap(.~sim_type2, scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("est_gene_tree2" = "gt=1000, L=500", "est_gene_tree3" = "gt=10000, L=500", "est_gene_tree5" = "gt=1000, L=2000", "est_gene_tree6" = "gt=10000, L=2000")))+ labs(x = "", y = "")+ #scale_fill_manual('Types of top 5 networks', # labels=c('Other', 'Symmetrical network', # 'Both symmetrical and true networks', 'True network'), # values=c('#CDC5BF', '#43CD80', '#EE8262', '#3A5FCD'))+ scale_fill_brewer('',labels=c('True and Symmetric', 'True', 'Symmetric','Other'), palette = "PuBuGn", direction=-1)+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), axis.text.y=element_blank(), legend.text=element_text(size=12)) dev.off() ``` # Figure Top 1 ```{r} df$label[df$rank_true==1] = "true" df$label[df$rank_sym==1] = "sym" df$label[df$rank_sym!=1 & df$rank_true!=1] = "other" ## label is chr, and we need it as factor and in correct order: str(df) df$label = factor(df$label) df$label = factor(df$label, levels = c("true","sym","other")) ## need to put sim_type in different order: df$sim_type = factor(df$sim_type, levels=c("cf", "cf_noise", "gene_tree", "est_gene_tree")) ``` ## True and noisy CF ```{r} df2 = df[df$sim_type %in% c("cf","cf_noise"),] df2$sim_type2 = "cf" df2$sim_type2[df2$sim_type == "cf_noise" & df2$sd == 0.000005] = "cf_noise1" df2$sim_type2[df2$sim_type == "cf_noise" & df2$sd == 0.00005] = "cf_noise2" df2$sim_type2[df2$sim_type == "cf_noise" & df2$sd == 0.0005] = "cf_noise3" df2$sim_type2 = factor(df2$sim_type2) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/top1-true-noisy-cf.pdf", width = 8, height = 4) df2 %>% ggplot(aes(fill=label, x=nw_type)) + geom_bar()+ facet_wrap(.~sim_type2, scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("cf" = "True CF", "cf_noise1" = "Noisy CF (sd=5e-6)", "cf_noise2" = "Noisy CF (sd=5e-5)", "cf_noise3" = "Noisy CF (sd=5e-4)")))+ labs(x = "", y = "")+ #scale_fill_manual('', # labels=c('Other', 'Symmetrical network', # 'True network'), # values=c('#CDC5BF', '#43CD80', '#3A5FCD'))+ scale_fill_brewer('',labels=c('True', 'Symmetric','Other'), palette = "PuBuGn", direction=-1)+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), axis.text.y=element_blank(), legend.text=element_text(size=12)) dev.off() ``` ## True gene trees ```{r} df2 = df[df$sim_type == "gene_tree",] df2$sim_type2 = "gene_tree" df2$sim_type2[df2$num_genetree == 100] = "gene_tree1" df2$sim_type2[df2$num_genetree == 1000] = "gene_tree2" df2$sim_type2[df2$num_genetree == 10000] = "gene_tree3" df2$sim_type2 = factor(df2$sim_type2) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/top1-true-gt.pdf", width = 8, height = 4) df2 %>% ggplot(aes(fill=label, x=nw_type)) + geom_bar()+ facet_wrap(.~sim_type2, scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("gene_tree1" = "True g.t. (100)", "gene_tree2" = "True g.t. (1000)", "gene_tree3" = "True g.t. (10000)")))+ labs(x = "", y = "")+ #scale_fill_manual('', # labels=c('Other', 'Symmetrical network', # 'True network'), # values=c('#CDC5BF', '#43CD80', '#3A5FCD'))+ scale_fill_brewer('',labels=c('True', 'Symmetric','Other'), palette = "PuBuGn", direction=-1)+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), axis.text.y=element_blank(), legend.text=element_text(size=12)) dev.off() ``` ## Estimated gene trees ```{r} df2 = df[df$sim_type == "est_gene_tree",] df2$sim_type2 = "est_gene_tree" df2$sim_type2[df2$num_genetree == 1000 & df2$len_seq == 500] = "est_gene_tree2" df2$sim_type2[df2$num_genetree == 10000 & df2$len_seq == 500] = "est_gene_tree3" df2$sim_type2[df2$num_genetree == 1000 & df2$len_seq == 2000] = "est_gene_tree5" df2$sim_type2[df2$num_genetree == 10000 & df2$len_seq == 2000] = "est_gene_tree6" df2$sim_type2 = factor(df2$sim_type2) # Note that I need to copy and paste into the R REPL rather than run through RStudio # for the PDF to be saved: pdf("../../ms/figures/top1-est-gt.pdf", width = 8, height = 4) df2 %>% ggplot(aes(fill=label, x=nw_type)) + geom_bar()+ facet_wrap(.~sim_type2, scales = "free_y", nrow = 1, labeller = labeller(sim_type2 = c("est_gene_tree2" = "gt=1000, L=500", "est_gene_tree3" = "gt=10000, L=500", "est_gene_tree5" = "gt=1000, L=2000", "est_gene_tree6" = "gt=10000, L=2000")))+ labs(x = "", y = "")+ #scale_fill_manual('', # labels=c('Other', 'Symmetrical network', # 'True network'), # values=c('#CDC5BF', '#43CD80', '#3A5FCD'))+ scale_fill_brewer('',labels=c('True', 'Symmetric','Other'), palette = "PuBuGn", direction=-1)+ theme_bw()+ theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, size=12), legend.position = "top", strip.background =element_rect(fill="gray95"), strip.text.x = element_text(size = 12), axis.text.y=element_blank(), legend.text=element_text(size=12)) dev.off() ``` # Old plots; not used in the manuscript anymore ```{r} df$label[df$rank_true==1] = "true" df$label[df$rank_sym==1] = "sym" df$label[df$rank_sym!=1 & df$rank_true!=1] = "other" df %>% ggplot(aes(fill=label, x=nw_type)) + geom_bar()+ facet_wrap(.~sim_type, scales = "free", nrow = 2)+ theme(axis.text.x = element_text(angle = 65, vjust = 0.5)) ``` ```{r} a1 = df %>% ggplot(mapping = aes(x = nw_type, y = rank_true))+ geom_boxplot(aes(col = sim_type))# + #facet_wrap(.~sim_type, scales = "free", nrow = 2) a2 = df %>% ggplot(mapping = aes(x = nw_type, y = rank_sym))+ geom_boxplot(aes(col = sim_type))# + #facet_wrap(.~sim_type, scales = "free", nrow = 2) a1/a2 ``` ```{r} path = "/true_cf" nw = c("1122", "1212", "1221", "1222", "2112", "2121", "2122", "2211", "2212", "2221", "2222") ret = c() nw_rep = c() order = c() for (i in nw){ temp = read.csv(paste("./../../simulation/result", path, "/network", i, ".csv", sep = "")) ret = c(ret, sort(as.numeric(temp[16, -1]))) nw_rep = c(nw_rep, rep(i, ncol(temp)-1)) order = c(order, (1:(ncol(temp)-1)) * 2520 / (ncol(temp)-1)) } df = data.frame(nw = nw_rep, inv = ret, order = order) df$nw = as.factor(df$nw) ggplot(df, aes(x = order, y = inv))+ geom_point(aes(col = nw)) ```
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.2
e04b4f229d811e4d7f44e2607e6ca42da1088c13
code
615
using Documenter, ModernRoboticsBook makedocs( modules = [ModernRoboticsBook], format = Documenter.HTML( analytics = "UA-72743607-4", assets = [], ), pages = [ "Home" => "index.md", "Manual" => Any[ "man/examples.md", ], "Library" => Any[ "Public" => "lib/public.md", ], ], repo = "https://github.com/ferrolho/ModernRoboticsBook.jl/blob/{commit}{path}#L{line}", sitename = "ModernRoboticsBook.jl", authors = "Henrique Ferrolho", ) deploydocs( repo = "github.com/ferrolho/ModernRoboticsBook.jl", )
ModernRoboticsBook
https://github.com/ferrolho/ModernRoboticsBook.jl.git
[ "MIT" ]
0.1.2
e04b4f229d811e4d7f44e2607e6ca42da1088c13
code
36802
module ModernRoboticsBook import LinearAlgebra as LA export NearZero, Normalize, RotInv, VecToso3, so3ToVec, AxisAng3, MatrixExp3, MatrixLog3, RpToTrans, TransToRp, TransInv, VecTose3, se3ToVec, Adjoint, ScrewToAxis, AxisAng6, MatrixExp6, MatrixLog6, ProjectToSO3, ProjectToSE3, DistanceToSO3, DistanceToSE3, TestIfSO3, TestIfSE3, FKinBody, FKinSpace, JacobianBody, JacobianSpace, IKinBody, IKinSpace, ad, InverseDynamics, MassMatrix, VelQuadraticForces, GravityForces, EndEffectorForces, ForwardDynamics, EulerStep, InverseDynamicsTrajectory, ForwardDynamicsTrajectory, CubicTimeScaling, QuinticTimeScaling, JointTrajectory, ScrewTrajectory, CartesianTrajectory, ComputedTorque, SimulateControl # """ # *** BASIC HELPER FUNCTIONS *** # """ """ NearZero(z) Determines whether a scalar is small enough to be treated as zero. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> NearZero(-1e-7) true ``` """ NearZero(z::Number) = abs(z) < 1e-6 """ Normalize(V) Normalizes a vector. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> Normalize([1, 2, 3]) 3-element Vector{Float64}: 0.2672612419124244 0.5345224838248488 0.8017837257372732 ``` """ Normalize(V::Array) = V / LA.norm(V) # """ # *** CHAPTER 3: RIGID-BODY MOTIONS *** # """ """ RotInv(R) Inverts a rotation matrix. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> RotInv([0 0 1; 1 0 0; 0 1 0]) 3×3 adjoint(::Matrix{Int64}) with eltype Int64: 0 1 0 0 0 1 1 0 0 ``` """ RotInv(R::Array) = R' """ VecToso3(ω) Converts a 3-vector to an so(3) representation. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> VecToso3([1 2 3]) 3×3 Matrix{Int64}: 0 -3 2 3 0 -1 -2 1 0 ``` """ function VecToso3(ω::Array) [ 0 -ω[3] ω[2]; ω[3] 0 -ω[1]; -ω[2] ω[1] 0 ] end """ so3ToVec(so3mat) Converts an so(3) representation to a 3-vector. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> so3ToVec([0 -3 2; 3 0 -1; -2 1 0]) 3-element Vector{Int64}: 1 2 3 ``` """ function so3ToVec(so3mat::Array) [so3mat[3, 2], so3mat[1, 3], so3mat[2, 1]] end """ AxisAng3(expc3) Converts a 3-vector of exponential coordinates for rotation into axis-angle form. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> AxisAng3([1, 2, 3]) ([0.2672612419124244, 0.5345224838248488, 0.8017837257372732], 3.7416573867739413) ``` """ AxisAng3(expc3::Array) = Normalize(expc3), LA.norm(expc3) """ MatrixExp3(so3mat) Computes the matrix exponential of a matrix in so(3). # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> MatrixExp3([0 -3 2; 3 0 -1; -2 1 0]) 3×3 Matrix{Float64}: -0.694921 0.713521 0.0892929 -0.192007 -0.303785 0.933192 0.692978 0.63135 0.348107 ``` """ function MatrixExp3(so3mat::Array) omgtheta = so3ToVec(so3mat) if NearZero(LA.norm(omgtheta)) return LA.I else θ = AxisAng3(omgtheta)[2] omgmat = so3mat / θ return LA.I + sin(θ) * omgmat + (1 - cos(θ)) * omgmat * omgmat end end """ MatrixLog3(R) Computes the matrix logarithm of a rotation matrix. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> MatrixLog3([0 0 1; 1 0 0; 0 1 0]) 3×3 Matrix{Float64}: 0.0 -1.2092 1.2092 1.2092 0.0 -1.2092 -1.2092 1.2092 0.0 ``` """ function MatrixLog3(R::Array) acosinput = (LA.tr(R) - 1) / 2 if acosinput >= 1 return zeros(3, 3) elseif acosinput <= -1 if !NearZero(1 + R[3, 3]) omg = (1 / √(2 * (1 + R[3, 3]))) * [R[1, 3], R[2, 3], 1 + R[3, 3]] elseif !NearZero(1 + R[2, 2]) omg = (1 / √(2 * (1 + R[2, 2]))) * [R[1, 2], 1 + R[2, 2], R[3, 2]] else omg = (1 / √(2 * (1 + R[1, 1]))) * [1 + R[1, 1], R[2, 1], R[3, 1]] end return VecToso3(π * omg) else θ = acos(acosinput) return θ / 2 / sin(θ) * (R - R') end end """ RpToTrans(R, p) Converts a rotation matrix and a position vector into homogeneous transformation matrix. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> RpToTrans([1 0 0; 0 0 -1; 0 1 0], [1, 2, 5]) 4×4 Matrix{Int64}: 1 0 0 1 0 0 -1 2 0 1 0 5 0 0 0 1 ``` """ RpToTrans(R::Array, p::Array) = vcat(hcat(R, p), [0 0 0 1]) """ TransToRp(T) Converts a homogeneous transformation matrix into a rotation matrix and position vector. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> TransToRp([1 0 0 0; 0 0 -1 0; 0 1 0 3; 0 0 0 1]) ([1 0 0; 0 0 -1; 0 1 0], [0, 0, 3]) ``` """ TransToRp(T::Array) = T[1:3, 1:3], T[1:3, 4] """ TransInv(T) Inverts a homogeneous transformation matrix. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> TransInv([1 0 0 0; 0 0 -1 0; 0 1 0 3; 0 0 0 1]) 4×4 Matrix{Int64}: 1 0 0 0 0 0 1 -3 0 -1 0 0 0 0 0 1 ``` """ function TransInv(T::Array) R, p = TransToRp(T) vcat(hcat(R', -R' * p), [0 0 0 1]) end """ VecTose3(V) Converts a spatial velocity vector into a 4x4 matrix in se3. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> VecTose3([1 2 3 4 5 6]) 4×4 Matrix{Float64}: 0.0 -3.0 2.0 4.0 3.0 0.0 -1.0 5.0 -2.0 1.0 0.0 6.0 0.0 0.0 0.0 0.0 ``` """ VecTose3(V::Array) = vcat(hcat(VecToso3(V[1:3]), V[4:6]), zeros(1, 4)) """ se3ToVec(se3mat) Converts an se3 matrix into a spatial velocity vector. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> se3ToVec([0 -3 2 4; 3 0 -1 5; -2 1 0 6; 0 0 0 0]) 6-element Vector{Int64}: 1 2 3 4 5 6 ``` """ se3ToVec(se3mat::Array) = vcat([se3mat[3, 2], se3mat[1, 3], se3mat[2, 1]], se3mat[1:3, 4]) """ Adjoint(T) Computes the adjoint representation of a homogeneous transformation matrix. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> Adjoint([1 0 0 0; 0 0 -1 0; 0 1 0 3; 0 0 0 1]) 6×6 Matrix{Float64}: 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 3.0 1.0 0.0 0.0 3.0 0.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 0.0 1.0 0.0 ``` """ function Adjoint(T::Array) R, p = TransToRp(T) vcat(hcat(R, zeros(3, 3)), hcat(VecToso3(p) * R, R)) end """ ScrewToAxis(q, s, h) Takes a parametric description of a screw axis and converts it to a normalized screw axis. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> ScrewToAxis([3; 0; 0], [0; 0; 1], 2) 6-element Vector{Int64}: 0 0 1 0 -3 2 ``` """ ScrewToAxis(q::Array, s::Array, h::Number) = vcat(s, LA.cross(q, s) + h * s) """ AxisAng6(expc6) Converts a 6-vector of exponential coordinates into screw axis-angle form. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> AxisAng6([1, 0, 0, 1, 2, 3]) ([1.0, 0.0, 0.0, 1.0, 2.0, 3.0], 1.0) ``` """ function AxisAng6(expc6::Array) θ = LA.norm(expc6[1:3]) if NearZero(θ) θ = LA.norm(expc6[3:6]) end expc6 / θ, θ end """ MatrixExp6(se3mat) Computes the matrix exponential of an se3 representation of exponential coordinates. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> MatrixExp6([0 0 0 0; 0 0 -1.57079632 2.35619449; 0 1.57079632 0 2.35619449; 0 0 0 0]) 4×4 Matrix{Float64}: 1.0 0.0 0.0 0.0 0.0 6.7949e-9 -1.0 1.01923e-8 0.0 1.0 6.7949e-9 3.0 0.0 0.0 0.0 1.0 ``` """ function MatrixExp6(se3mat::Array) omgtheta = so3ToVec(se3mat[1:3, 1:3]) if NearZero(LA.norm(omgtheta)) return vcat(hcat(LA.I, se3mat[1:3, 4]), [0 0 0 1]) else θ = AxisAng3(omgtheta)[2] omgmat = se3mat[1:3, 1:3] / θ return vcat(hcat(MatrixExp3(se3mat[1:3, 1:3]), (LA.I * θ + (1 - cos(θ)) * omgmat + (θ - sin(θ)) * omgmat * omgmat) * se3mat[1:3, 4] / θ), [0 0 0 1]) end end """ MatrixLog6(T) Computes the matrix logarithm of a homogeneous transformation matrix. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> MatrixLog6([1 0 0 0; 0 0 -1 0; 0 1 0 3; 0 0 0 1]) 4×4 Matrix{Float64}: 0.0 0.0 0.0 0.0 0.0 0.0 -1.5708 2.35619 0.0 1.5708 0.0 2.35619 0.0 0.0 0.0 0.0 ``` """ function MatrixLog6(T::Array) R, p = TransToRp(T) omgmat = MatrixLog3(R) if omgmat == zeros(3, 3) return vcat(hcat(zeros(3, 3), T[1:3, 4]), [0 0 0 0]) else θ = acos((LA.tr(R) - 1) / 2) return vcat(hcat(omgmat, (LA.I - omgmat / 2 + (1 / θ - 1 / tan(θ / 2) / 2) * omgmat * omgmat / θ) * T[1:3, 4]), [0 0 0 0]) end end """ ProjectToSO3(mat) Returns a projection of mat into SO(3). # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> ProjectToSO3([0.675 0.150 0.720; 0.370 0.771 -0.511; -0.630 0.619 0.472]) 3×3 Matrix{Float64}: 0.679011 0.148945 0.718859 0.373207 0.773196 -0.512723 -0.632187 0.616428 0.469421 ``` """ function ProjectToSO3(mat::Array) F = LA.svd(mat) R = F.U * F.Vt if LA.det(R) < 0 # In this case the result may be far from mat. # Hmm, I think this needs to be double-checked... R[:, Int(F.S[3])] = -R[:, Int(F.S[3])] end return R end """ ProjectToSE3(mat) Returns a projection of mat into SE(3). # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> ProjectToSE3([0.675 0.150 0.720 1.2; 0.370 0.771 -0.511 5.4; -0.630 0.619 0.472 3.6; 0.003 0.002 0.010 0.9]) 4×4 Matrix{Float64}: 0.679011 0.148945 0.718859 1.2 0.373207 0.773196 -0.512723 5.4 -0.632187 0.616428 0.469421 3.6 0.0 0.0 0.0 1.0 ``` """ ProjectToSE3(mat::Array) = RpToTrans(ProjectToSO3(mat[1:3, 1:3]), mat[1:3, 4]) """ DistanceToSO3(mat) Returns the Frobenius norm to describe the distance of mat from the SO(3) manifold. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> DistanceToSO3([1.0 0.0 0.0; 0.0 0.1 -0.95; 0.0 1.0 0.1]) 0.08835298523536149 ``` """ DistanceToSO3(mat::Array) = LA.det(mat) > 0 ? LA.norm(mat'mat - LA.I) : 1e+9 """ DistanceToSE3(mat) Returns the Frobenius norm to describe the distance of mat from the SE(3) manifold. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> DistanceToSE3([1.0 0.0 0.0 1.2; 0.0 0.1 -0.95 1.5; 0.0 1.0 0.1 -0.9; 0.0 0.0 0.1 0.98]) 0.13493053768513638 ``` """ function DistanceToSE3(mat::Array) matR = mat[1:3, 1:3] if LA.det(matR) > 0 LA.norm(hcat(vcat(matR'matR, zeros(1, 3)), mat[4, :]) - LA.I) else 1e+9 end end """ TestIfSO3(mat) Returns true if mat is close to or on the manifold SO(3). # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> TestIfSO3([1.0 0.0 0.0; 0.0 0.1 -0.95; 0.0 1.0 0.1]) false ``` """ TestIfSO3(mat::Array) = abs(DistanceToSO3(mat)) < 1e-3 """ TestIfSE3(mat) Returns true if mat is close to or on the manifold SE(3). # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> TestIfSE3([1.0 0.0 0.0 1.2; 0.0 0.1 -0.95 1.5; 0.0 1.0 0.1 -0.9; 0.0 0.0 0.1 0.98]) false ``` """ TestIfSE3(mat::Array) = abs(DistanceToSE3(mat)) < 1e-3 # """ # *** CHAPTER 4: FORWARD KINEMATICS *** # """ """ FKinBody(M, Blist, thetalist) Computes forward kinematics in the body frame for an open chain robot. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> M = [ -1 0 0 0 ; 0 1 0 6 ; 0 0 -1 2 ; 0 0 0 1 ]; julia> Blist = [ 0 0 -1 2 0 0 ; 0 0 0 0 1 0 ; 0 0 1 0 0 0.1 ]'; julia> thetalist = [ π/2, 3, π ]; julia> FKinBody(M, Blist, thetalist) 4×4 Matrix{Float64}: -1.14424e-17 1.0 0.0 -5.0 1.0 1.14424e-17 0.0 4.0 0.0 0.0 -1.0 1.68584 0.0 0.0 0.0 1.0 ``` """ function FKinBody(M::AbstractMatrix, Blist::AbstractMatrix, thetalist::Array) for i = 1:length(thetalist) M *= MatrixExp6(VecTose3(Blist[:, i] * thetalist[i])) end M end """ FKinSpace(M, Slist, thetalist) Computes forward kinematics in the space frame for an open chain robot. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> M = [ -1 0 0 0 ; 0 1 0 6 ; 0 0 -1 2 ; 0 0 0 1 ]; julia> Slist = [ 0 0 1 4 0 0 ; 0 0 0 0 1 0 ; 0 0 -1 -6 0 -0.1 ]'; julia> thetalist = [ π/2, 3, π ]; julia> FKinSpace(M, Slist, thetalist) 4×4 Matrix{Float64}: -1.14424e-17 1.0 0.0 -5.0 1.0 1.14424e-17 0.0 4.0 0.0 0.0 -1.0 1.68584 0.0 0.0 0.0 1.0 ``` """ function FKinSpace(M::AbstractMatrix, Slist::AbstractMatrix, thetalist::Array) for i = length(thetalist):-1:1 M = MatrixExp6(VecTose3(Slist[:, i] * thetalist[i])) * M end M end # """ # *** CHAPTER 5: VELOCITY KINEMATICS AND STATICS *** # """ """ JacobianBody(Blist, thetalist) Computes the body Jacobian for an open chain robot. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> Blist = [0 0 1 0 0.2 0.2; 1 0 0 2 0 3; 0 1 0 0 2 1; 1 0 0 0.2 0.3 0.4]'; julia> thetalist = [0.2, 1.1, 0.1, 1.2]; julia> JacobianBody(Blist, thetalist) 6×4 Matrix{Float64}: -0.0452841 0.995004 0.0 1.0 0.743593 0.0930486 0.362358 0.0 -0.667097 0.0361754 -0.932039 0.0 2.32586 1.66809 0.564108 0.2 -1.44321 2.94561 1.43307 0.3 -2.0664 1.82882 -1.58869 0.4 ``` """ function JacobianBody(Blist::AbstractMatrix, thetalist::Array) T = LA.I Jb = copy(Blist) for i = length(thetalist)-1:-1:1 T *= MatrixExp6(VecTose3(Blist[:, i+1] * -thetalist[i+1])) Jb[:, i] = Adjoint(T) * Blist[:, i] end Jb end """ JacobianSpace(Slist, thetalist) Computes the space Jacobian for an open chain robot. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> Slist = [0 0 1 0 0.2 0.2; 1 0 0 2 0 3; 0 1 0 0 2 1; 1 0 0 0.2 0.3 0.4]'; julia> thetalist = [0.2, 1.1, 0.1, 1.2]; julia> JacobianSpace(Slist, thetalist) 6×4 Matrix{Float64}: 0.0 0.980067 -0.0901156 0.957494 0.0 0.198669 0.444554 0.284876 1.0 0.0 0.891207 -0.0452841 0.0 1.95219 -2.21635 -0.511615 0.2 0.436541 -2.43713 2.77536 0.2 2.96027 3.23573 2.22512 ``` """ function JacobianSpace(Slist::AbstractMatrix, thetalist::Array) T = LA.I Js = copy(Slist) for i = 2:length(thetalist) T *= MatrixExp6(VecTose3(Slist[:, i - 1] * thetalist[i - 1])) Js[:, i] = Adjoint(T) * Slist[:, i] end Js end # """ # *** CHAPTER 6: INVERSE KINEMATICS *** # """ """ IKinBody(Blist, M, T, thetalist0, eomg, ev) Computes inverse kinematics in the body frame for an open chain robot. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> Blist = [ 0 0 -1 2 0 0 ; 0 0 0 0 1 0 ; 0 0 1 0 0 0.1 ]'; julia> M = [ -1 0 0 0 ; 0 1 0 6 ; 0 0 -1 2 ; 0 0 0 1 ]; julia> T = [ 0 1 0 -5 ; 1 0 0 4 ; 0 0 -1 1.6858 ; 0 0 0 1 ]; julia> thetalist0 = [1.5, 2.5, 3]; julia> eomg, ev = 0.01, 0.001; julia> IKinBody(Blist, M, T, thetalist0, eomg, ev) ([1.5707381937148923, 2.999666997382942, 3.141539129217613], true) ``` """ function IKinBody(Blist::AbstractMatrix, M::AbstractMatrix, T::AbstractMatrix, thetalist0::Array, eomg::Number, ev::Number) thetalist = copy(thetalist0) i = 0 maxiterations = 20 Vb = se3ToVec(MatrixLog6(TransInv(FKinBody(M, Blist, thetalist)) * T)) err = LA.norm(Vb[1:3]) > eomg || LA.norm(Vb[4:6]) > ev while err && i < maxiterations thetalist += LA.pinv(JacobianBody(Blist, thetalist)) * Vb i += 1 Vb = se3ToVec(MatrixLog6(TransInv(FKinBody(M, Blist, thetalist)) * T)) err = LA.norm(Vb[1:3]) > eomg || LA.norm(Vb[4:6]) > ev end return thetalist, !err end """ IKinSpace(Slist, M, T, thetalist0, eomg, ev) Computes inverse kinematics in the space frame for an open chain robot. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> Slist = [ 0 0 1 4 0 0 ; 0 0 0 0 1 0 ; 0 0 -1 -6 0 -0.1 ]'; julia> M = [ -1 0 0 0 ; 0 1 0 6 ; 0 0 -1 2 ; 0 0 0 1 ]; julia> T = [ 0 1 0 -5 ; 1 0 0 4 ; 0 0 -1 1.6858 ; 0 0 0 1 ]; julia> thetalist0 = [1.5, 2.5, 3]; julia> eomg, ev = 0.01, 0.001; julia> IKinSpace(Slist, M, T, thetalist0, eomg, ev) ([1.5707378296567203, 2.999663844672524, 3.141534199856583], true) ``` """ function IKinSpace(Slist::AbstractMatrix, M::AbstractMatrix, T::AbstractMatrix, thetalist0::Array, eomg::Number, ev::Number) thetalist = copy(thetalist0) i = 0 maxiterations = 20 Tsb = FKinSpace(M, Slist, thetalist) Vs = Adjoint(Tsb) * se3ToVec(MatrixLog6(TransInv(Tsb) * T)) err = LA.norm(Vs[1:3]) > eomg || LA.norm(Vs[4:6]) > ev while err && i < maxiterations thetalist += LA.pinv(JacobianSpace(Slist, thetalist)) * Vs i += 1 Tsb = FKinSpace(M, Slist, thetalist) Vs = Adjoint(Tsb) * se3ToVec(MatrixLog6(TransInv(Tsb) * T)) err = LA.norm(Vs[1:3]) > eomg || LA.norm(Vs[4:6]) > ev end thetalist, !err end # """ # *** CHAPTER 8: DYNAMICS OF OPEN CHAINS *** # """ """ ad(V) Calculate the 6x6 matrix [adV] of the given 6-vector. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> ad([1, 2, 3, 4, 5, 6]) 6×6 Matrix{Float64}: 0.0 -3.0 2.0 0.0 0.0 0.0 3.0 0.0 -1.0 0.0 0.0 0.0 -2.0 1.0 0.0 0.0 0.0 0.0 0.0 -6.0 5.0 0.0 -3.0 2.0 6.0 0.0 -4.0 3.0 0.0 -1.0 -5.0 4.0 0.0 -2.0 1.0 0.0 ``` """ function ad(V::Array) omgmat = VecToso3(V[1:3]) vcat(hcat(omgmat, zeros(3, 3)), hcat(VecToso3(V[4:6]), omgmat)) end """ InverseDynamics(thetalist, dthetalist, ddthetalist, g, Ftip, Mlist, Glist, Slist) Computes inverse dynamics in the space frame for an open chain robot. """ function InverseDynamics(thetalist::Array, dthetalist::Array, ddthetalist::Array, g::Array, Ftip::Array, Mlist::Array, Glist::Array, Slist::AbstractMatrix) n = length(thetalist) Mi = LA.I Ai = zeros(eltype(thetalist), 6, n) AdTi = Array{Array{eltype(thetalist), 2}}(undef, n + 1) Vi = zeros(eltype(thetalist), 6, n + 1) Vdi = zeros(eltype(thetalist), 6, n + 1) Vdi[:, 1] = vcat(zeros(eltype(thetalist), 3), -g) AdTi[n+1] = Adjoint(TransInv(Mlist[n+1])) Fi = copy(Ftip) taulist = zeros(eltype(thetalist), n) for i = 1:n Mi *= Mlist[i] Ai[:, i] = Adjoint(TransInv(Mi)) * Slist[:, i] AdTi[i] = Adjoint(MatrixExp6(VecTose3(Ai[:, i] * -thetalist[i])) * TransInv(Mlist[i])) Vi[:, i + 1] = AdTi[i] * Vi[:,i] + Ai[:, i] * dthetalist[i] Vdi[:, i + 1] = AdTi[i] * Vdi[:, i] + Ai[:, i] * ddthetalist[i] + ad(Vi[:, i + 1]) * Ai[:, i] * dthetalist[i] end for i = n:-1:1 Fi = AdTi[i + 1]' * Fi + Glist[i] * Vdi[:, i + 1] - ad(Vi[:, i + 1])' * Glist[i] * Vi[:, i + 1] taulist[i] = Fi' * Ai[:, i] end return taulist end """ MassMatrix(thetalist, Mlist, Glist, Slist) Computes the mass matrix of an open chain robot based on the given configuration. """ function MassMatrix(thetalist::Array, Mlist::Array, Glist::Array, Slist::AbstractMatrix) n = length(thetalist) M = zeros(n, n) for i = 1:n ddthetalist = zeros(n) ddthetalist[i] = 1 M[:, i] = InverseDynamics(thetalist, zeros(n), ddthetalist, zeros(3), zeros(6), Mlist, Glist, Slist) end return M end """ VelQuadraticForces(thetalist, dthetalist, Mlist, Glist, Slist) Computes the Coriolis and centripetal terms in the inverse dynamics of an open chain robot. """ function VelQuadraticForces(thetalist::Array, dthetalist::Array, Mlist::Array, Glist::Array, Slist::AbstractMatrix) InverseDynamics(thetalist, dthetalist, zeros(length(thetalist)), zeros(3), zeros(6), Mlist, Glist, Slist) end """ GravityForces(thetalist, g, Mlist, Glist, Slist) Computes the joint forces/torques an open chain robot requires to overcome gravity at its configuration. """ function GravityForces(thetalist::Array, g::Array, Mlist::Array, Glist::Array, Slist::AbstractMatrix) n = length(thetalist) InverseDynamics(thetalist, zeros(n), zeros(n), g, zeros(6), Mlist, Glist, Slist) end """ EndEffectorForces(thetalist, Ftip, Mlist, Glist, Slist) Computes the joint forces/torques an open chain robot requires only to create the end-effector force `Ftip`. # Arguments - `thetalist`: the ``n``-vector of joint variables. - `Ftip`: the spatial force applied by the end-effector expressed in frame `{n+1}`. - `Mlist`: the list of link frames `i` relative to `i-1` at the home position. - `Glist`: the spatial inertia matrices `Gi` of the links. - `Slist`: the screw axes `Si` of the joints in a space frame, in the format of a matrix with axes as the columns. Returns the joint forces and torques required only to create the end-effector force `Ftip`. This function calls InverseDynamics with `g = 0`, `dthetalist = 0`, and `ddthetalist = 0`. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> import LinearAlgebra as LA julia> thetalist = [0.1, 0.1, 0.1] 3-element Vector{Float64}: 0.1 0.1 0.1 julia> Ftip = [1, 1, 1, 1, 1, 1] 6-element Vector{Int64}: 1 1 1 1 1 1 julia> M01 = [1 0 0 0; 0 1 0 0; 0 0 1 0.089159; 0 0 0 1] 4×4 Matrix{Float64}: 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.089159 0.0 0.0 0.0 1.0 julia> M12 = [ 0 0 1 0.28; 0 1 0 0.13585; -1 0 0 0; 0 0 0 1] 4×4 Matrix{Float64}: 0.0 0.0 1.0 0.28 0.0 1.0 0.0 0.13585 -1.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 julia> M23 = [1 0 0 0; 0 1 0 -0.1197; 0 0 1 0.395; 0 0 0 1] 4×4 Matrix{Float64}: 1.0 0.0 0.0 0.0 0.0 1.0 0.0 -0.1197 0.0 0.0 1.0 0.395 0.0 0.0 0.0 1.0 julia> M34 = [1 0 0 0; 0 1 0 0; 0 0 1 0.14225; 0 0 0 1] 4×4 Matrix{Float64}: 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.14225 0.0 0.0 0.0 1.0 julia> Mlist = [M01, M12, M23, M34] 4-element Vector{Matrix{Float64}}: [1.0 0.0 0.0 0.0; 0.0 1.0 0.0 0.0; 0.0 0.0 1.0 0.089159; 0.0 0.0 0.0 1.0] [0.0 0.0 1.0 0.28; 0.0 1.0 0.0 0.13585; -1.0 0.0 0.0 0.0; 0.0 0.0 0.0 1.0] [1.0 0.0 0.0 0.0; 0.0 1.0 0.0 -0.1197; 0.0 0.0 1.0 0.395; 0.0 0.0 0.0 1.0] [1.0 0.0 0.0 0.0; 0.0 1.0 0.0 0.0; 0.0 0.0 1.0 0.14225; 0.0 0.0 0.0 1.0] julia> G1 = LA.Diagonal([0.010267, 0.010267, 0.00666, 3.7, 3.7, 3.7]) 6×6 LinearAlgebra.Diagonal{Float64, Vector{Float64}}: 0.010267 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.010267 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.00666 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 3.7 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 3.7 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 3.7 julia> G2 = LA.Diagonal([0.22689, 0.22689, 0.0151074, 8.393, 8.393, 8.393]) 6×6 LinearAlgebra.Diagonal{Float64, Vector{Float64}}: 0.22689 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.22689 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.0151074 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 8.393 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 8.393 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 8.393 julia> G3 = LA.Diagonal([0.0494433, 0.0494433, 0.004095, 2.275, 2.275, 2.275]) 6×6 LinearAlgebra.Diagonal{Float64, Vector{Float64}}: 0.0494433 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.0494433 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.004095 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 2.275 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 2.275 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 2.275 julia> Glist = [G1, G2, G3] 3-element Vector{LinearAlgebra.Diagonal{Float64, Vector{Float64}}}: [0.010267 0.0 … 0.0 0.0; 0.0 0.010267 … 0.0 0.0; … ; 0.0 0.0 … 3.7 0.0; 0.0 0.0 … 0.0 3.7] [0.22689 0.0 … 0.0 0.0; 0.0 0.22689 … 0.0 0.0; … ; 0.0 0.0 … 8.393 0.0; 0.0 0.0 … 0.0 8.393] [0.0494433 0.0 … 0.0 0.0; 0.0 0.0494433 … 0.0 0.0; … ; 0.0 0.0 … 2.275 0.0; 0.0 0.0 … 0.0 2.275] julia> Slist = [ 1 0 1 0 1 0; 0 1 0 -0.089 0 0; 0 1 0 -0.089 0 0.425]' 6×3 adjoint(::Matrix{Float64}) with eltype Float64: 1.0 0.0 0.0 0.0 1.0 1.0 1.0 0.0 0.0 0.0 -0.089 -0.089 1.0 0.0 0.0 0.0 0.0 0.425 julia> EndEffectorForces(thetalist, Ftip, Mlist, Glist, Slist) 3-element Vector{Float64}: 1.4095460782639782 1.857714972318063 1.392409 ``` """ function EndEffectorForces(thetalist::Array, Ftip::Array, Mlist::Array, Glist::Array, Slist::AbstractMatrix) n = length(thetalist) InverseDynamics(thetalist, zeros(n), zeros(n), zeros(3), Ftip, Mlist, Glist, Slist) end """ ForwardDynamics(thetalist, dthetalist, taulist, g, Ftip, Mlist, Glist, Slist) Computes forward dynamics in the space frame for an open chain robot. """ function ForwardDynamics(thetalist::Array, dthetalist::Array, taulist::Array, g::Array, Ftip::Array, Mlist::Array, Glist::Array, Slist::AbstractMatrix) LA.inv(MassMatrix(thetalist, Mlist, Glist, Slist)) * (taulist - VelQuadraticForces(thetalist, dthetalist, Mlist, Glist, Slist) - GravityForces(thetalist, g, Mlist, Glist, Slist) - EndEffectorForces(thetalist, Ftip, Mlist, Glist, Slist)) end """ EulerStep(thetalist, dthetalist, ddthetalist, dt) Compute the joint angles and velocities at the next timestep using first order Euler integration. # Arguments - `thetalist`: the ``n``-vector of joint variables. - `dthetalist`: the ``n``-vector of joint rates. - `ddthetalist`: the ``n``-vector of joint accelerations. - `dt`: the timestep delta t. # Return - `thetalistNext`: the vector of joint variables after `dt` from first order Euler integration. - `dthetalistNext`: the vector of joint rates after `dt` from first order Euler integration. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> EulerStep([0.1, 0.1, 0.1], [0.1, 0.2, 0.3], [2, 1.5, 1], 0.1) ([0.11000000000000001, 0.12000000000000001, 0.13], [0.30000000000000004, 0.35000000000000003, 0.4]) ``` """ function EulerStep(thetalist::Array, dthetalist::Array, ddthetalist::Array, dt::Number) thetalist + dt * dthetalist, dthetalist + dt * ddthetalist end """ InverseDynamicsTrajectory(thetamat, dthetamat, ddthetamat, g, Ftipmat, Mlist, Glist, Slist) Calculates the joint forces/torques required to move the serial chain along the given trajectory using inverse dynamics. """ function InverseDynamicsTrajectory(thetamat::Array, dthetamat::Array, ddthetamat::Array, g::Array, Ftipmat::Array, Mlist::Array, Glist::Array, Slist::AbstractMatrix) thetamat = thetamat' dthetamat = dthetamat' ddthetamat = ddthetamat' Ftipmat = Ftipmat' taumat = copy(thetamat) for i = 1:size(thetamat, 2) taumat[:, i] = InverseDynamics(thetamat[:, i], dthetamat[:, i], ddthetamat[:, i], g, Ftipmat[:, i], Mlist, Glist, Slist) end taumat' end """ ForwardDynamicsTrajectory(thetalist, dthetalist, taumat, g, Ftipmat, Mlist, Glist, Slist, dt, intRes) Simulates the motion of a serial chain given an open-loop history of joint forces/torques. """ function ForwardDynamicsTrajectory(thetalist::Array, dthetalist::Array, taumat::AbstractMatrix, g::Array, Ftipmat::Array, Mlist::Array, Glist::Array, Slist::AbstractMatrix, dt::Number, intRes::Number) taumat = taumat' Ftipmat = Ftipmat' thetamat = copy(taumat) thetamat[:, 1] = thetalist dthetamat = copy(taumat) dthetamat[:, 1] = dthetalist for i = 1:size(taumat, 2)-1 for j = 1:intRes ddthetalist = ForwardDynamics(thetalist, dthetalist, taumat[:, i], g, Ftipmat[:, i], Mlist, Glist, Slist) thetalist, dthetalist = EulerStep(thetalist, dthetalist, ddthetalist, 1.0 * dt / intRes) end thetamat[:, i + 1] = thetalist dthetamat[:, i + 1] = dthetalist end thetamat = thetamat' dthetamat = dthetamat' return thetamat, dthetamat end # """ # *** CHAPTER 9: TRAJECTORY GENERATION *** # """ """ CubicTimeScaling(Tf, t) Computes s(t) for a cubic time scaling. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> CubicTimeScaling(2, 0.6) 0.21600000000000003 ``` """ CubicTimeScaling(Tf::Number, t::Number) = 3(t / Tf)^2 - 2(t / Tf)^3 """ QuinticTimeScaling(Tf, t) Computes s(t) for a quintic time scaling. # Examples ```jldoctest; setup = :(using ModernRoboticsBook) julia> QuinticTimeScaling(2, 0.6) 0.16308 ``` """ QuinticTimeScaling(Tf::Number, t::Number) = 10(t / Tf)^3 - 15(t / Tf)^4 + 6(t / Tf)^5 """ JointTrajectory(thetastart, thetaend, Tf, N, method) Computes a straight-line trajectory in joint space. """ function JointTrajectory(thetastart::Array, thetaend::Array, Tf::Number, N::Integer, method::Integer) timegap = Tf / (N - 1) traj = zeros(length(thetastart), N) for i = 1:N if method == 3 s = CubicTimeScaling(Tf, timegap * (i - 1)) else s = QuinticTimeScaling(Tf, timegap * (i - 1)) end traj[:, i] = s * thetaend + (1 - s) * thetastart end traj' end """ ScrewTrajectory(Xstart, Xend, Tf, N, method) Computes a trajectory as a list of N SE(3) matrices corresponding to the screw motion about a space screw axis. """ function ScrewTrajectory(Xstart::Array, Xend::Array, Tf::Number, N::Integer, method::Integer) timegap = Tf / (N - 1) traj = Array{Array{Float64, 2}}(undef, N) for i = 1:N if method == 3 s = CubicTimeScaling(Tf, timegap * (i - 1)) else s = QuinticTimeScaling(Tf, timegap * (i - 1)) end traj[i] = Xstart * MatrixExp6(MatrixLog6(TransInv(Xstart) * Xend) * s) end return traj end """ CartesianTrajectory(Xstart, Xend, Tf, N, method) Computes a trajectory as a list of N SE(3) matrices corresponding to the origin of the end-effector frame following a straight line. """ function CartesianTrajectory(Xstart::Array, Xend::Array, Tf::Number, N::Integer, method::Integer) timegap = Tf / (N - 1) traj = Array{Array{Float64, 2}}(undef, N) Rstart, pstart = TransToRp(Xstart) Rend, pend = TransToRp(Xend) for i = 1:N if method == 3 s = CubicTimeScaling(Tf, timegap * (i - 1)) else s = QuinticTimeScaling(Tf, timegap * (i - 1)) end traj[i] = vcat(hcat(Rstart * MatrixExp3(MatrixLog3(Rstart' * Rend) * s), s * pend + (1 - s) * pstart), [0 0 0 1]) end return traj end # """ # *** CHAPTER 11: ROBOT CONTROL *** # """ """ ComputedTorque(thetalist, dthetalist, eint, g, Mlist, Glist, Slist, thetalistd, dthetalistd, ddthetalistd, Kp, Ki, Kd) Computes the joint control torques at a particular time instant. """ function ComputedTorque(thetalist::Array, dthetalist::Array, eint::Array, g::Array, Mlist::Array, Glist::Array, Slist::AbstractMatrix, thetalistd::Array, dthetalistd::Array, ddthetalistd::Array, Kp::Number, Ki::Number, Kd::Number) e = thetalistd - thetalist MassMatrix(thetalist, Mlist, Glist, Slist) * (Kp * e + Ki * (eint + e) + Kd * (dthetalistd - dthetalist)) + InverseDynamics(thetalist, dthetalist, ddthetalistd, g, zeros(6), Mlist, Glist, Slist) end """ SimulateControl(thetalist, dthetalist, g, Ftipmat, Mlist, Glist, Slist, thetamatd, dthetamatd, ddthetamatd, gtilde, Mtildelist, Gtildelist, Kp, Ki, Kd, dt, intRes) Simulates the computed torque controller over a given desired trajectory. """ function SimulateControl(thetalist::Array, dthetalist::Array, g::Array, Ftipmat::Array, Mlist::Array, Glist::Array, Slist::AbstractMatrix, thetamatd::Array, dthetamatd::Array, ddthetamatd::Array, gtilde::Array, Mtildelist::Array, Gtildelist::Array, Kp::Number, Ki::Number, Kd::Number, dt::Number, intRes::Number) Ftipmat = Ftipmat' thetamatd = thetamatd' dthetamatd = dthetamatd' ddthetamatd = ddthetamatd' m, n = size(thetamatd) thetacurrent = copy(thetalist) dthetacurrent = copy(dthetalist) eint = reshape(zeros(m, 1), (m,)) taumat = zeros(size(thetamatd)) thetamat = zeros(size(thetamatd)) for i = 1:n taulist = ComputedTorque(thetacurrent, dthetacurrent, eint, gtilde, Mtildelist, Gtildelist, Slist, thetamatd[:, i], dthetamatd[:, i], ddthetamatd[:, i], Kp, Ki, Kd) for j = 1:intRes ddthetalist = ForwardDynamics(thetacurrent, dthetacurrent, taulist, g, Ftipmat[:, i], Mlist, Glist, Slist) thetacurrent, dthetacurrent = EulerStep(thetacurrent, dthetacurrent, ddthetalist, dt / intRes) end taumat[:, i] = taulist thetamat[:, i] = thetacurrent eint += dt * (thetamatd[:, i] - thetacurrent) end taumat', thetamat' end end # module
ModernRoboticsBook
https://github.com/ferrolho/ModernRoboticsBook.jl.git
[ "MIT" ]
0.1.2
e04b4f229d811e4d7f44e2607e6ca42da1088c13
code
26345
using Aqua using ModernRoboticsBook using Test import LinearAlgebra as LA Aqua.test_all(ModernRoboticsBook) @testset "ModernRoboticsBook.jl" begin @testset "basic helper functions" begin @test NearZero(-1e-7) @test Normalize([1, 2, 3]) == [0.2672612419124244, 0.5345224838248488, 0.8017837257372732] end @testset "chapter 3: rigid-body motions" begin @test RotInv([0 0 1; 1 0 0; 0 1 0]) == [0 1 0; 0 0 1; 1 0 0] @test VecToso3([1, 2, 3]) == [0 -3 2; 3 0 -1; -2 1 0] @test so3ToVec([0 -3 2; 3 0 -1; -2 1 0]) == [1, 2, 3] @test AxisAng3([1, 2, 3]) == ([0.2672612419124244, 0.5345224838248488, 0.8017837257372732], 3.7416573867739413) @test isapprox(MatrixExp3([ 0 -3 2; 3 0 -1; -2 1 0]), [-0.694921 0.713521 0.0892929 -0.192007 -0.303785 0.933192 0.692978 0.63135 0.348107 ]; rtol=1e-6) @test MatrixExp3(zeros(3, 3)) == [1 0 0; 0 1 0; 0 0 1] @test isapprox(MatrixLog3([0 0 1; 1 0 0; 0 1 0]), [ 0.0 -1.2092 1.2092 1.2092 0.0 -1.2092 -1.2092 1.2092 0.0 ]; rtol=1e-6) @test MatrixLog3(zeros(3, 3)) == zeros(3, 3) @test MatrixLog3([-3 0 0; 0 1 0; 0 0 1]) == [0 -π 0; π 0 0; 0 0 0] @test MatrixLog3([-2 0 0; 0 1 0; 0 0 -1]) == [0 0 π; 0 0 0; -π 0 0] @test MatrixLog3([1 0 0; 0 -1 0; 0 0 -1]) == [0 0 0; 0 0 -π; 0 π 0] @test RpToTrans([1 0 0; 0 0 -1; 0 1 0], [1, 2, 5]) == [1 0 0 1 0 0 -1 2 0 1 0 5 0 0 0 1] @test TransToRp([1 0 0 0; 0 0 -1 0; 0 1 0 3; 0 0 0 1]) == ([1 0 0; 0 0 -1; 0 1 0], [0, 0, 3]) @test TransInv([1 0 0 0; 0 0 -1 0; 0 1 0 3; 0 0 0 1]) == [1 0 0 0 0 0 1 -3 0 -1 0 0 0 0 0 1] @test VecTose3([1, 2, 3, 4, 5, 6]) == [ 0 -3 2 4 3 0 -1 5 -2 1 0 6 0 0 0 0] @test se3ToVec([ 0 -3 2 4; 3 0 -1 5; -2 1 0 6; 0 0 0 0]) == [1, 2, 3, 4, 5, 6] @test Adjoint([1 0 0 0; 0 0 -1 0; 0 1 0 3; 0 0 0 1]) == [1 0 0 0 0 0 0 0 -1 0 0 0 0 1 0 0 0 0 0 0 3 1 0 0 3 0 0 0 0 -1 0 0 0 0 1 0] @test ScrewToAxis([3; 0; 0], [0; 0; 1], 2) == [0, 0, 1, 0, -3, 2] @test AxisAng6([1, 0, 0, 1, 2, 3]) == ([1, 0, 0, 1, 2, 3], 1) @test AxisAng6([0, 0, 0, 0, 0, 4]) == ([0, 0, 0, 0, 0, 1], 4) @test MatrixExp6([0 0 0 0 ; 0 0 -π/2 3π/4; 0 π/2 0 3π/4; 0 0 0 0 ]) ≈ [1 0 0 0; 0 0 -1 0; 0 1 0 3; 0 0 0 1] @test MatrixLog6([1 0 0 0; 0 0 -1 0; 0 1 0 3; 0 0 0 1]) ≈ [0 0 0 0 ; 0 0 -π/2 3π/4; 0 π/2 0 3π/4; 0 0 0 0 ] @test MatrixLog6(Array(LA.Diagonal(ones(4)))) == zeros(4, 4) @test isapprox(ProjectToSO3([ 0.675 0.150 0.720; 0.370 0.771 -0.511; -0.630 0.619 0.472]), [ 0.679011 0.148945 0.718859 0.373207 0.773196 -0.512723 -0.632187 0.616428 0.469421]; rtol=1e-6) @test ProjectToSO3([-1 0 0; 0 -1 0; 0 0 -1]) == [1 0 0; 0 -1 0; 0 0 -1] @test isapprox(ProjectToSE3([ 0.675 0.150 0.720 1.2; 0.370 0.771 -0.511 5.4; -0.630 0.619 0.472 3.6; 0.003 0.002 0.010 0.9]), [ 0.679011 0.148945 0.718859 1.2 0.373207 0.773196 -0.512723 5.4 -0.632187 0.616428 0.469421 3.6 0.0 0.0 0.0 1.0]; rtol=1e-6) @test DistanceToSO3([1.0 0.0 0.0 ; 0.0 0.1 -0.95; 0.0 1.0 0.1 ]) == 0.08835298523536149 @test DistanceToSE3([1.0 0.0 0.0 1.2 ; 0.0 0.1 -0.95 1.5 ; 0.0 1.0 0.1 -0.9 ; 0.0 0.0 0.1 0.98]) == 0.13493053768513638 @test DistanceToSE3(Array(reshape(1:9, (3, 3)))) >= 1e+9 @test !TestIfSO3([1.0 0.0 0.0 ; 0.0 0.1 -0.95; 0.0 1.0 0.1 ]) @test !TestIfSE3([1.0 0.0 0.0 1.2 ; 0.0 0.1 -0.95 1.5 ; 0.0 1.0 0.1 -0.9 ; 0.0 0.0 0.1 0.98]) end @testset "chapter 4: forward kinematics" begin M = [-1 0 0 0 ; 0 1 0 6 ; 0 0 -1 2 ; 0 0 0 1 ] Blist = [ 0 0 -1 2 0 0 ; 0 0 0 0 1 0 ; 0 0 1 0 0 0.1 ]' Slist = [ 0 0 1 4 0 0 ; 0 0 0 0 1 0 ; 0 0 -1 -6 0 -0.1 ]' thetalist = [ π/2, 3, π ] @test isapprox(FKinBody(M, Blist, thetalist), [-1.14424e-17 1.0 0.0 -5.0 ; 1.0 1.14424e-17 0.0 4.0 ; 0.0 0.0 -1.0 1.68584 ; 0.0 0.0 0.0 1.0 ]; rtol=1e-6) @test isapprox(FKinSpace(M, Slist, thetalist), [-1.14424e-17 1.0 0.0 -5.0 ; 1.0 1.14424e-17 0.0 4.0 ; 0.0 0.0 -1.0 1.68584 ; 0.0 0.0 0.0 1.0 ]; rtol=1e-6) end @testset "chapter 5: velocity kinematics and statics" begin Blist = [0 0 1 0 0.2 0.2; 1 0 0 2 0 3; 0 1 0 0 2 1; 1 0 0 0.2 0.3 0.4]' Slist = [0 0 1 0 0.2 0.2; 1 0 0 2 0 3; 0 1 0 0 2 1; 1 0 0 0.2 0.3 0.4]' thetalist = [0.2, 1.1, 0.1, 1.2] @test isapprox(JacobianBody(Blist, thetalist), [ -0.0452841 0.995004 0.0 1.0 ; 0.743593 0.0930486 0.362358 0.0 ; -0.667097 0.0361754 -0.932039 0.0 ; 2.32586 1.66809 0.564108 0.2 ; -1.44321 2.94561 1.43307 0.3 ; -2.0664 1.82882 -1.58869 0.4 ]; rtol=1e-5) @test isapprox(JacobianSpace(Slist, thetalist), [0.0 0.980067 -0.0901156 0.957494 ; 0.0 0.198669 0.444554 0.284876 ; 1.0 0.0 0.891207 -0.0452841; 0.0 1.95219 -2.21635 -0.511615 ; 0.2 0.436541 -2.43713 2.77536 ; 0.2 2.96027 3.23573 2.22512 ]; rtol=1e-5) end @testset "chapter 6: inverse kinematics" begin Blist = [ 0 0 -1 2 0 0 ; 0 0 0 0 1 0 ; 0 0 1 0 0 0.1 ]' Slist = [ 0 0 1 4 0 0 ; 0 0 0 0 1 0 ; 0 0 -1 -6 0 -0.1 ]' M = [ -1 0 0 0 ; 0 1 0 6 ; 0 0 -1 2 ; 0 0 0 1 ] T = [ 0 1 0 -5 ; 1 0 0 4 ; 0 0 -1 1.6858 ; 0 0 0 1 ] thetalist0 = [1.5, 2.5, 3] eomg, ev = 0.01, 0.001 thetalist, success = IKinBody(Blist, M, T, thetalist0, eomg, ev) @test isapprox(thetalist, [1.57074, 2.99967, 3.14154]; rtol=1e-5) @test success thetalist, success = IKinSpace(Slist, M, T, thetalist0, eomg, ev) @test isapprox(thetalist, [1.57074, 2.99966, 3.14153]; rtol=1e-5) @test success end @testset "chapter 8: dynamics of open chains" begin @test ad([1, 2, 3, 4, 5, 6]) == [ 0.0 -3.0 2.0 0.0 0.0 0.0 3.0 0.0 -1.0 0.0 0.0 0.0 -2.0 1.0 0.0 0.0 0.0 0.0 0.0 -6.0 5.0 0.0 -3.0 2.0 6.0 0.0 -4.0 3.0 0.0 -1.0 -5.0 4.0 0.0 -2.0 1.0 0.0 ] thetalist = [0.1, 0.1, 0.1] dthetalist = [0.1, 0.2, 0.3] ddthetalist = [2, 1.5, 1] g = [0, 0, -9.8] Ftip = [1, 1, 1, 1, 1, 1] M01 = [1 0 0 0 ; 0 1 0 0 ; 0 0 1 0.089159 ; 0 0 0 1 ] M12 = [0 0 1 0.28 ; 0 1 0 0.13585 ; -1 0 0 0 ; 0 0 0 1 ] M23 = [1 0 0 0 ; 0 1 0 -0.1197 ; 0 0 1 0.395 ; 0 0 0 1 ] M34 = [1 0 0 0 ; 0 1 0 0 ; 0 0 1 0.14225 ; 0 0 0 1 ] G1 = LA.Diagonal([0.010267, 0.010267, 0.00666, 3.7, 3.7, 3.7]) G2 = LA.Diagonal([0.22689, 0.22689, 0.0151074, 8.393, 8.393, 8.393]) G3 = LA.Diagonal([0.0494433, 0.0494433, 0.004095, 2.275, 2.275, 2.275]) Glist = [G1, G2, G3] Mlist = [M01, M12, M23, M34] Slist = [ 1 0 1 0 1 0 ; 0 1 0 -0.089 0 0 ; 0 1 0 -0.089 0 0.425 ]' taulist_actual = InverseDynamics(thetalist, dthetalist, ddthetalist, g, Ftip, Mlist, Glist, Slist) @test taulist_actual ≈ [74.69616155287451, -33.06766015851458, -3.230573137901424] @test isapprox(MassMatrix(thetalist, Mlist, Glist, Slist), [ 22.5433 -0.307147 -0.00718426; -0.307147 1.96851 0.432157 ; -0.00718426 0.432157 0.191631 ]; rtol=1e-5) @test VelQuadraticForces(thetalist, dthetalist, Mlist, Glist, Slist) ≈ [ 0.26453118054501235 ; -0.0550515682891655 ; -0.006891320068248911] @test GravityForces(thetalist, g, Mlist, Glist, Slist) ≈ [ 28.40331261821983 ; -37.64094817177068 ; -5.4415891999683605] @test EndEffectorForces(thetalist, Ftip, Mlist, Glist, Slist) ≈ [ 1.4095460782639782; 1.8577149723180628; 1.392409 ] taulist = [0.5, 0.6, 0.7] @test ForwardDynamics(thetalist, dthetalist, taulist, g, Ftip, Mlist, Glist, Slist) ≈ [ -0.9739290670855626; 25.584667840340558 ; -32.91499212478149 ] @test hcat(EulerStep([0.1, 0.1, 0.1], [0.1, 0.2, 0.3], [2, 1.5, 1], 0.1)...) ≈ hcat([0.11, 0.12, 0.13], [0.3, 0.35, 0.4]) @testset "inverse dynamics trajectory" begin thetastart = [0, 0, 0] thetaend = [π/2, π/2, π/2] Tf = 3 N = 10 method = 5 traj = JointTrajectory(thetastart, thetaend, Tf, N, method) thetamat = copy(traj) dthetamat = zeros(N, 3) ddthetamat = zeros(N, 3) dt = Tf / (N - 1) for i = 1:size(traj, 1) - 1 dthetamat[i + 1, :] = (thetamat[i + 1, :] - thetamat[i, :]) / dt ddthetamat[i + 1, :] = (dthetamat[i + 1, :] - dthetamat[i, :]) / dt end Ftipmat = ones(N, 6) taumat_actual = InverseDynamicsTrajectory(thetamat, dthetamat, ddthetamat, g, Ftipmat, Mlist, Glist, Slist) taumat_expected = [ 1.32297079e+01 -3.62621080e+01 -4.18134100e+00 ; 1.96974217e+01 -3.59188701e+01 -4.07919728e+00 ; 5.11979532e+01 -3.44705050e+01 -3.59488765e+00 ; 9.41368122e+01 -3.14099606e+01 -2.41622731e+00 ; 1.25417579e+02 -2.45283212e+01 5.76295281e-02 ; 1.24948454e+02 -1.85038921e+01 1.94898550e+00 ; 1.01525941e+02 -1.88375820e+01 2.07369432e+00 ; 7.68134579e+01 -2.23610568e+01 1.96172027e+00 ; 6.44365965e+01 -2.46704062e+01 2.07890001e+00 ; 6.72354909e+01 -2.47008371e+01 2.19474783e+00 ] @test taumat_actual ≈ taumat_expected end @testset "forward dynamics trajectory" begin taumat = [ 3.63 -6.58 -5.57 ; 3.74 -5.55 -5.5 ; 4.31 -0.68 -5.19 ; 5.18 5.63 -4.31 ; 5.85 8.17 -2.59 ; 5.78 2.79 -1.7 ; 4.99 -5.3 -1.19 ; 4.08 -9.41 0.07 ; 3.56 -10.1 0.97 ; 3.49 -9.41 1.23 ] Ftipmat = ones(size(taumat, 1), 6) dt = 0.1 intRes = 8 thetamat_expected = [ 0.1 0.1 0.1 ; 0.10643138 0.2625997 -0.22664947 ; 0.10197954 0.71581297 -1.22521632 ; 0.0801044 1.33930884 -2.28074132 ; 0.0282165 2.11957376 -3.07544297 ; -0.07123855 2.87726666 -3.83289684 ; -0.20136466 3.397858 -4.83821609 ; -0.32380092 3.73338535 -5.98695747 ; -0.41523262 3.85883317 -7.01130559 ; -0.4638099 3.63178793 -7.63190052 ] dthetamat_expected = [ 0.1 0.2 0.3 ; 0.01212502 3.42975773 -7.74792602 ; -0.13052771 5.55997471 -11.22722784 ; -0.35521041 7.11775879 -9.18173035 ; -0.77358795 8.17307573 -7.05744594 ; -1.2350231 6.35907497 -8.99784746 ; -1.31426299 4.07685875 -11.18480509 ; -1.06794821 2.49227786 -11.69748583 ; -0.70264871 -0.55925705 -8.16067131 ; -0.1455669 -4.57149985 -3.43135114 ] thetamat_actual, dthetamat_actual = ForwardDynamicsTrajectory(thetalist, dthetalist, taumat, g, Ftipmat, Mlist, Glist, Slist, dt, intRes) @test thetamat_actual ≈ thetamat_expected @test dthetamat_actual ≈ dthetamat_expected end end @testset "chapter 9: trajectory generation" begin @test CubicTimeScaling(2, 0.6) ≈ 0.216 @test QuinticTimeScaling(2, 0.6) ≈ 0.16308 @testset "joint trajectory" begin thetastart = [1, 0, 0, 1, 1, 0.2, 0,1] thetaend = [1.2, 0.5, 0.6, 1.1, 2, 2, 0.9, 1] Tf = 4 N = 6 method = 3 expected = [ 1 0 0 1 1 0.2 0 1 ; 1.0208 0.052 0.0624 1.0104 1.104 0.3872 0.0936 1 ; 1.0704 0.176 0.2112 1.0352 1.352 0.8336 0.3168 1 ; 1.1296 0.324 0.3888 1.0648 1.648 1.3664 0.5832 1 ; 1.1792 0.448 0.5376 1.0896 1.896 1.8128 0.8064 1 ; 1.2 0.5 0.6 1.1 2 2 0.9 1 ] @test JointTrajectory(thetastart, thetaend, Tf, N, method) ≈ expected end @testset "screw trajectory" begin Xstart = [1 0 0 1 ; 0 1 0 0 ; 0 0 1 1 ; 0 0 0 1 ] Xend = [0 0 1 0.1 ; 1 0 0 0 ; 0 1 0 4.1 ; 0 0 0 1 ] Tf = 5 N = 4 method = 3 expected = [[ 1 0 0 1 ; 0 1 0 0 ; 0 0 1 1 ; 0 0 0 1 ], [ 0.904 -0.25 0.346 0.441 ; 0.346 0.904 -0.25 0.529 ; -0.25 0.346 0.904 1.601 ; 0 0 0 1 ], [ 0.346 -0.25 0.904 -0.117 ; 0.904 0.346 -0.25 0.473 ; -0.25 0.904 0.346 3.274 ; 0 0 0 1 ], [ 0 0 1 0.1 ; 1 0 0 0 ; 0 1 0 4.1 ; 0 0 0 1 ]] actual = ScrewTrajectory(Xstart, Xend, Tf, N, method) @test isapprox(actual, expected; rtol=1e-3) end @testset "cartesian trajectory" begin Xstart = [ 1 0 0 1 ; 0 1 0 0 ; 0 0 1 1 ; 0 0 0 1 ] Xend = [ 0 0 1 0.1 ; 1 0 0 0 ; 0 1 0 4.1 ; 0 0 0 1 ] Tf = 5 N = 4 method = 5 expected = [[ 1 0 0 1 ; 0 1 0 0 ; 0 0 1 1 ; 0 0 0 1 ], [ 0.937 -0.214 0.277 0.811 ; 0.277 0.937 -0.214 0 ; -0.214 0.277 0.937 1.651 ; 0 0 0 1 ], [ 0.277 -0.214 0.937 0.289 ; 0.937 0.277 -0.214 0 ; -0.214 0.937 0.277 3.449 ; 0 0 0 1 ], [ 0 0 1 0.1 ; 1 0 0 0 ; 0 1 0 4.1 ; 0 0 0 1 ]] actual = CartesianTrajectory(Xstart, Xend, Tf, N, method) @test isapprox(actual, expected; rtol=1e-3) end end @testset "chapter 11: robot control" begin thetalist = [0.1, 0.1, 0.1] dthetalist = [0.1, 0.2, 0.3] # Initialise robot description (Example with 3 links) g = [0, 0, -9.8] M01 = [1 0 0 0 ; 0 1 0 0 ; 0 0 1 0.089159 ; 0 0 0 1 ] M12 = [0 0 1 0.28 ; 0 1 0 0.13585 ; -1 0 0 0 ; 0 0 0 1 ] M23 = [1 0 0 0 ; 0 1 0 -0.1197 ; 0 0 1 0.395 ; 0 0 0 1 ] M34 = [1 0 0 0 ; 0 1 0 0 ; 0 0 1 0.14225 ; 0 0 0 1 ] G1 = LA.Diagonal([0.010267, 0.010267, 0.00666, 3.7, 3.7, 3.7]) G2 = LA.Diagonal([0.22689, 0.22689, 0.0151074, 8.393, 8.393, 8.393]) G3 = LA.Diagonal([0.0494433, 0.0494433, 0.004095, 2.275, 2.275, 2.275]) Mlist = [M01, M12, M23, M34] Glist = [G1, G2, G3] Slist = [ 1 0 1 0 1 0 ; 0 1 0 -0.089 0 0 ; 0 1 0 -0.089 0 0.425 ]' # Create a trajectory to follow thetaend = [π / 2, π, 1.5 * π] Tf = 1 dt = 0.05 N = Int(Tf / dt) method = 5 traj = JointTrajectory(thetalist, thetaend, Tf, N, method) thetamatd = copy(traj) dthetamatd = zeros(N, 3) ddthetamatd = zeros(N, 3) dt = Tf / (N - 1) for i = 1:size(traj, 1) - 1 dthetamatd[i + 1, :] = (thetamatd[i + 1, :] - thetamatd[i, :]) / dt ddthetamatd[i + 1, :] = (dthetamatd[i + 1, :] - dthetamatd[i, :]) / dt end # Possibly wrong robot description (Example with 3 links) gtilde = [0.8, 0.2, -8.8] Mhat01 = [1 0 0 0; 0 1 0 0; 0 0 1 0.1; 0 0 0 1] Mhat12 = [0 0 1 0.3; 0 1 0 0.2; -1 0 0 0; 0 0 0 1] Mhat23 = [1 0 0 0; 0 1 0 -0.2; 0 0 1 0.4; 0 0 0 1] Mhat34 = [1 0 0 0; 0 1 0 0; 0 0 1 0.2; 0 0 0 1] Ghat1 = LA.Diagonal([0.1, 0.1, 0.1, 4, 4, 4]) Ghat2 = LA.Diagonal([0.3, 0.3, 0.1, 9, 9, 9]) Ghat3 = LA.Diagonal([0.1, 0.1, 0.1, 3, 3, 3]) Gtildelist = [Ghat1, Ghat2, Ghat3] Mtildelist = [Mhat01, Mhat12, Mhat23, Mhat34] # Other required arguments Ftipmat = ones(size(traj, 1), 6) Kp = 20 Ki = 10 Kd = 18 intRes = 8 taumat_expected = [ -14.2640765 -54.06797429 -11.265448 ; 71.7014572 -17.58330542 3.86417108 ; 208.80692807 6.94442209 8.4352746 ; 269.9223766 14.44412677 11.24081382 ; 316.48343344 6.4020598 10.60970699 ; 327.82241593 -3.98984379 14.31752441 ; 248.33306921 -16.39336633 21.61795095 ; 93.7564835 -28.5575642 28.0092122 ; 13.12918592 -44.38407547 19.04258057 ; 56.35246455 -8.56189073 1.69770764 ; 32.68030349 39.77791901 -5.94800597 ; -49.85502041 37.95496258 -15.10367806 ; -104.48630504 24.8129766 -16.25667052 ; -123.14920836 -3.62727714 -14.4680164 ; -84.15220471 -25.40152665 -12.85439272 ; -50.09890916 -33.73575763 -12.38441089 ; -30.41466046 -34.03362524 -11.30974711 ; -13.90701987 -26.40700004 -9.50026445 ; 7.93416317 -12.95474009 -6.58132646 ; 44.38627151 4.53534718 -2.32611269 ] thetamat_expected = [ 0.1028237 0.10738308 0.07715206 ; 0.10475535 0.11170712 0.05271794 ; 0.11930448 0.13796752 0.12315113 ; 0.1582068 0.21615938 0.27654789 ; 0.22464764 0.35314707 0.51117109 ; 0.31872944 0.54551689 0.81897456 ; 0.4377715 0.78011155 1.21554584 ; 0.57501633 1.03974866 1.71548388 ; 0.72137128 1.30551854 2.2916328 ; 0.87221934 1.56564069 2.84693996 ; 1.0257972 1.841874 3.32092634 ; 1.17352729 2.14460368 3.72255083 ; 1.30459739 2.44287634 4.03953656 ; 1.41155584 2.71108778 4.28079221 ; 1.49166143 2.92224332 4.45724092 ; 1.54707169 3.06503575 4.57357234 ; 1.579692 3.14295613 4.62867261 ; 1.59184568 3.1665363 4.62924012 ; 1.58827951 3.15316968 4.59115503 ; 1.57746305 3.12631855 4.54394792 ] taumat_actual, thetamat_actual = SimulateControl(thetalist, dthetalist, g, Ftipmat, Mlist, Glist, Slist, thetamatd, dthetamatd, ddthetamatd, gtilde, Mtildelist, Gtildelist, Kp, Ki, Kd, dt, intRes) @test taumat_actual ≈ taumat_expected @test thetamat_actual ≈ thetamat_expected end end
ModernRoboticsBook
https://github.com/ferrolho/ModernRoboticsBook.jl.git
[ "MIT" ]
0.1.2
e04b4f229d811e4d7f44e2607e6ca42da1088c13
docs
1877
# ModernRoboticsBook.jl [![Stable][docs-stable-img]][docs-stable-url] [![Dev][docs-dev-img]][docs-dev-url] [![Build Status][travis-img]][travis-url] [![Build Status][appveyor-img]][appveyor-url] [![Codecov][codecov-img]][codecov-url] [![Coveralls][coveralls-img]][coveralls-url] [![Aqua QA][aqua-img]][aqua-url] Some examples can be found on the [Examples](https://ferrolho.github.io/ModernRoboticsBook.jl/dev/man/examples/) page. See the [Index](https://ferrolho.github.io/ModernRoboticsBook.jl/dev/#main-index-1) for the complete list of documented functions and types. ## Installation The latest release of **ModernRoboticsBook** can be installed from the Julia REPL prompt with ```julia julia> import Pkg; Pkg.add("ModernRoboticsBook") ``` [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: https://ferrolho.github.io/ModernRoboticsBook.jl/stable [docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg [docs-dev-url]: https://ferrolho.github.io/ModernRoboticsBook.jl/dev [travis-img]: https://app.travis-ci.com/ferrolho/ModernRoboticsBook.jl.svg?branch=master [travis-url]: https://app.travis-ci.com/ferrolho/ModernRoboticsBook.jl [appveyor-img]: https://ci.appveyor.com/api/projects/status/github/ferrolho/ModernRoboticsBook.jl?svg=true [appveyor-url]: https://ci.appveyor.com/project/ferrolho/ModernRoboticsBook-jl [codecov-img]: https://codecov.io/gh/ferrolho/ModernRoboticsBook.jl/branch/master/graph/badge.svg [codecov-url]: https://codecov.io/gh/ferrolho/ModernRoboticsBook.jl [coveralls-img]: https://coveralls.io/repos/github/ferrolho/ModernRoboticsBook.jl/badge.svg?branch=master [coveralls-url]: https://coveralls.io/github/ferrolho/ModernRoboticsBook.jl?branch=master [aqua-img]: https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg [aqua-url]: https://github.com/JuliaTesting/Aqua.jl
ModernRoboticsBook
https://github.com/ferrolho/ModernRoboticsBook.jl.git
[ "MIT" ]
0.1.2
e04b4f229d811e4d7f44e2607e6ca42da1088c13
docs
552
# ModernRoboticsBook.jl Some examples can be found on the [Examples](@ref) page. See the [Index](@ref main-index) for the complete list of documented functions and types. ## Installation The latest release of **ModernRoboticsBook** can be installed from the Julia REPL prompt with ```julia julia> Pkg.add("ModernRoboticsBook") ``` ## Manual Outline ```@contents Pages = [ "man/examples.md", ] Depth = 1 ``` ## Library Outline ```@contents Pages = ["lib/public.md"] ``` ### [Index](@id main-index) ```@index Pages = ["lib/public.md"] ```
ModernRoboticsBook
https://github.com/ferrolho/ModernRoboticsBook.jl.git
[ "MIT" ]
0.1.2
e04b4f229d811e4d7f44e2607e6ca42da1088c13
docs
256
# Public Documentation Documentation for `ModernRoboticsBook.jl`'s public interface. ## Contents ```@contents Pages = ["public.md"] ``` ## Index ```@index Pages = ["public.md"] ``` ## Public Interface ```@autodocs Modules = [ModernRoboticsBook] ```
ModernRoboticsBook
https://github.com/ferrolho/ModernRoboticsBook.jl.git
[ "MIT" ]
0.1.2
e04b4f229d811e4d7f44e2607e6ca42da1088c13
docs
5553
# Examples Here are some examples for Forward and Inverse Dynamics Trajectories, and Control Simulation. ## Contents ```@contents Pages = ["examples.md"] ``` ## Inverse Dynamics Trajectory ```julia using ModernRoboticsBook import LinearAlgebra const linalg = LinearAlgebra; ``` Create a trajectory to follow using functions from Chapter 9: ```julia thetastart = [0, 0, 0] thetaend = [π / 2, π / 2, π / 2] Tf = 3 N = 1000 method = 5 traj = JointTrajectory(thetastart, thetaend, Tf, N, method) thetamat = copy(traj) dthetamat = zeros(1000, 3) ddthetamat = zeros(1000, 3) dt = Tf / (N - 1.0) for i = 1:size(traj, 1) - 1 dthetamat[i + 1, :] = (thetamat[i + 1, :] - thetamat[i, :]) / dt ddthetamat[i + 1, :] = (dthetamat[i + 1, :] - dthetamat[i, :]) / dt end ``` Initialize robot description (example with 3 links): ```julia g = [0, 0, -9.8] Ftipmat = ones(N, 6) M01 = [ 1 0 0 0 ; 0 1 0 0 ; 0 0 1 0.089159 ; 0 0 0 1 ] M12 = [ 0 0 1 0.28 ; 0 1 0 0.13585 ; -1 0 0 0 ; 0 0 0 1 ] M23 = [ 1 0 0 0 ; 0 1 0 -0.1197 ; 0 0 1 0.395 ; 0 0 0 1 ] M34 = [ 1 0 0 0 ; 0 1 0 0 ; 0 0 1 0.14225 ; 0 0 0 1 ] Mlist = [M01, M12, M23, M34] G1 = linalg.Diagonal([0.010267, 0.010267, 0.00666, 3.7, 3.7, 3.7]) G2 = linalg.Diagonal([0.22689, 0.22689, 0.0151074, 8.393, 8.393, 8.393]) G3 = linalg.Diagonal([0.0494433, 0.0494433, 0.004095, 2.275, 2.275, 2.275]) Glist = [G1, G2, G3] Slist = [ 1 0 1 0 1 0 ; 0 1 0 -0.089 0 0 ; 0 1 0 -0.089 0 0.425 ]' taumat = InverseDynamicsTrajectory(thetamat, dthetamat, ddthetamat, g, Ftipmat, Mlist, Glist, Slist) ``` Plot the joint forces/torques: ```julia using Plots gr() timestamp = range(1, Tf, length=N) plot(timestamp, taumat[:, 1], linewidth=2, label="Tau 1") plot!(timestamp, taumat[:, 2], linewidth=2, label="Tau 2") plot!(timestamp, taumat[:, 3], linewidth=2, label="Tau 3") xlabel!("Time") ylabel!("Torque") title!("Plot of Torque Trajectories") ``` ![inverse_dynamics_trajectory](../assets/examples/inverse_dynamics_trajectory.svg) ## Forward Dynamics Trajectory ```julia dt = 0.1 intRes = 8 thetalist = [0.1, 0.1, 0.1] dthetalist = [0.1, 0.2, 0.3] taumat = [[3.63, -6.58, -5.57], [3.74, -5.55, -5.5], [4.31, -0.68, -5.19], [5.18, 5.63, -4.31], [5.85, 8.17, -2.59], [5.78, 2.79, -1.7], [4.99, -5.3, -1.19], [4.08, -9.41, 0.07], [3.56, -10.1, 0.97], [3.49, -9.41, 1.23]] taumat = cat(taumat..., dims=2)' thetamat, dthetamat = ForwardDynamicsTrajectory(thetalist, dthetalist, taumat, g, Ftipmat, Mlist, Glist, Slist, dt, intRes) ``` Plot the joint angle/velocities: ```julia theta1 = thetamat[:, 1] theta2 = thetamat[:, 2] theta3 = thetamat[:, 3] dtheta1 = dthetamat[:, 1] dtheta2 = dthetamat[:, 2] dtheta3 = dthetamat[:, 3] N = size(taumat, 1) Tf = size(taumat, 1) * dt timestamp = range(0, Tf, length=N) plot(timestamp, theta1, linewidth=2, label="Theta1") plot!(timestamp, theta2, linewidth=2, label="Theta2") plot!(timestamp, theta3, linewidth=2, label="Theta3") plot!(timestamp, dtheta1, linewidth=2, label="DTheta1") plot!(timestamp, dtheta2, linewidth=2, label="DTheta2") plot!(timestamp, dtheta3, linewidth=2, label="DTheta3") xlabel!("Time") ylabel!("Joint Angles/Velocities") title!("Plot of Joint Angles and Joint Velocities") ``` ![forward_dynamics_trajectory](../assets/examples/forward_dynamics_trajectory.svg) ## Simulate Control Create a trajectory to follow: ```julia thetaend = [π / 2, π, 1.5 * π] Tf = 1 dt = 0.01 N = round(Int, Tf / dt) method = 5 traj = JointTrajectory(thetalist, thetaend, Tf, N, method) thetamatd = copy(traj) dthetamatd = zeros(N, 3) ddthetamatd = zeros(N, 3) dt = Tf / (N - 1) for i = 1:size(traj, 1)-1 dthetamatd[i + 1, :] = (thetamatd[i + 1, :] - thetamatd[i, :]) / dt ddthetamatd[i + 1, :] = (dthetamatd[i + 1, :] - dthetamatd[i, :]) / dt end ``` Create a (possibly) wrong robot description: ```julia gtilde = [0.8, 0.2, -8.8] Mhat01 = [1 0 0 0 ; 0 1 0 0 ; 0 0 1 0.1 ; 0 0 0 1 ] Mhat12 = [ 0 0 1 0.3 ; 0 1 0 0.2 ; -1 0 0 0 ; 0 0 0 1 ] Mhat23 = [1 0 0 0 ; 0 1 0 -0.2 ; 0 0 1 0.4 ; 0 0 0 1 ] Mhat34 = [1 0 0 0 ; 0 1 0 0 ; 0 0 1 0.2 ; 0 0 0 1 ] Mtildelist = [Mhat01, Mhat12, Mhat23, Mhat34] Ghat1 = linalg.Diagonal([0.1, 0.1, 0.1, 4, 4, 4]) Ghat2 = linalg.Diagonal([0.3, 0.3, 0.1, 9, 9, 9]) Ghat3 = linalg.Diagonal([0.1, 0.1, 0.1, 3, 3, 3]) Gtildelist = [Ghat1, Ghat2, Ghat3] Ftipmat = ones(size(traj, 1), 6) Kp = 20 Ki = 10 Kd = 18 intRes = 8 taumat, thetamat = SimulateControl(thetalist, dthetalist, g, Ftipmat, Mlist, Glist, Slist, thetamatd, dthetamatd, ddthetamatd, gtilde, Mtildelist, Gtildelist, Kp, Ki, Kd, dt, intRes) ``` Finally, plot the results: ```julia N, links = size(thetamat) Tf = N * dt timestamp = range(0, Tf, length=N) plot() for i = 1:links plot!(timestamp, thetamat[:, i], lw=2, linestyle=:dash, label="ActualTheta $i") plot!(timestamp, thetamatd[:, i], lw=2, linestyle=:dot, label="DesiredTheta $i") end xlabel!("Time") ylabel!("Joint Angles") title!("Plot of Actual and Desired Joint Angles") ``` ![simulated_control](../assets/examples/simulated_control.svg)
ModernRoboticsBook
https://github.com/ferrolho/ModernRoboticsBook.jl.git
[ "MIT" ]
0.1.7
76e8797d9bb184f55b1a24f92056fb78b1839bf2
code
9002
#= License Copyright 2019, 2020 (c) Yossi Bokor Katharine Turner 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. =# __precompile__() module PersistentHomologyTransfer #### Requirements #### using CSV using Hungarian using DataFrames using LinearAlgebra using SparseArrays using Eirene #### Exports #### export PHT, Recenter, Direction_Filtration, Evaluate_Barcode, Total_Rank_Exact, Total_Rank_Grid, Total_Rank_Auto, Average_Rank_Grid, Create_Heat_Map, Set_Mean_Zero, Weighted_Inner_Product, Weighted_Inner_Product_Matrix, Principal_Component_Scores, Average_Discretised_Rank, unittest #### First some functions to recenter the curves #### function Find_Center(points) n_p = size(points,1) c_x = Float64(0) c_y = Float64(0) for i in 1:n_p c_x += points[i,1] c_y += points[i,2] end return Float64(c_x/n_p), Float64(c_y/n_p) end function Recenter(points) points = convert(Array{Float64}, points) center = Find_Center(points) for i in 1:size(points)[1] points[i,1] = points[i,1] - center[1] points[i,2] = points[i,2] - center[2] end return points end function Evaluate_Rank(barcode, point) n = size(barcode)[1] count = 0 if point[2] < point[1] #return 0 else for i in 1:n if barcode[i,1] <= point[1] if barcode[i,2] >= point[2] count +=1 end end end return count end end function Total_Rank_Exact(barcode) @assert size(barcode,2) == 2 rks = [] n = size(barcode,1) b = copy(barcode) reshape(b, 2,n) for i in 1:n for j in 1:n if barcode[i,1] < barcode[j,1] if barcode[i,2] < barcode[j,2] b = vcat(b, [barcode[j,1] barcode[i,2]]) m += 1 end end end end for i in 1:n append!(rks, Evaluate_Rank(barcode, b[i,:])) end return b, rks end function Total_Rank_Grid(barcode, x_g, y_g) #the grid should be an array, with 0s in all entries below the second diagonal. @assert size(x_g) == size(y_g) #I should maybe change this as you don't REALLY need to use the same size grid..... n_g = size(x_g,1) rks = zeros(n_g,n_g) n_p = size(barcode,1) for i in 1:n_p point = barcode[i,:] x_i = findfirst(>=(point[1]), x_g) y_i = findfirst(<=(point[2]), y_g) for j in x_i:n_g-y_i+1 for k in j:n_g-y_i+1 rks[n_g-k+1,j] += 1 end end end return rks end function Average_Rank_Grid(list_of_barcodes, x_g, y_g) rks = zeros(length(x_g),length(y_g)) n_b = length(list_of_barcodes) for i in 1:n_b rk_i = Total_Rank_Grid(list_of_barcodes[i], x_g,y_g) rks = rks .+ rk_i end rks = rks/n_b return rks end function Average_Rank_Point(list_of_barcodes, x,y) rk = 0 n_b = length(list_of_barcodes) if y >= x for i in 1:n_b rk += Evaluate_Rank(list_of_barcodes[i], [x,y]) end return rk/n_b else return 0 end end function Create_Heat_Map(barcode, x_g, y_g) f(x,y) = begin if x > y return 0 else return Evaluate_Rank(barcode,[x,y]) end end #Z = map(f, X, Y) p1 = contour(x_g, y_g, f, fill=true) return p1 end # Let us do PCA for the rank functions using Kate and Vanessa's paper. # So, I first need to calculate the pointwise norm function Set_Mean_Zero(discretised_ranks) n_r = length(discretised_ranks) println(n_r) grid_size = size(discretised_ranks[1]) for i in 1:n_r @assert size(discretised_ranks[i]) == grid_size end mu = zeros(grid_size) for i in 1:n_r mu = mu .+ discretised_ranks[i] end mu = mu./n_r normalised = [] for i in 1:n_r append!(normalised, [discretised_ranks[i] .- mu]) end return normalised end function Weighted_Inner_Product(disc_rank_1, disc_rank_2, weights) wip = sum((disc_rank_1.*disc_rank_2).*weights) return wip end function Weighted_Inner_Product_Matrix(discretised_ranks, weights) n_r = length(discretised_ranks) D = Array{Float64}(undef, n_r, n_r) for i in 1:n_r for j in i:n_r wip = Weighted_Inner_Product(discretised_ranks[i], discretised_ranks[j], weights) D[i,j] = wip D[j,i] = wip end end return D end function Principal_Component_Scores(inner_prod_matrix, dimension) F = LinearAlgebra.eigen(inner_prod_matrix, permute = false, scale=false) # this sorts the eigenvectors in ascending order n_r = size(inner_prod_matrix,1) lambda = Array{Float64}(undef, 1,dimension) w = Array{Float64}(undef, size(F.vectors)[1],dimension) n_v = length(F.values) for i in 1:dimension lambda[i] = F.values[n_v-i+1] w[:,i] = F.vectors[:,n_v-i+1] end s = Array{Float64}(undef, n_r,dimension) for i in 1:size(inner_prod_matrix,1) for j in 1:dimension den = sqrt(sum([w[k,j]*sum(w[l,j]*inner_prod_matrix[k,l] for l in 1:n_r) for k in 1:n_r])) numerator = sum(w[:,j].*inner_prod_matrix[:,i]) s[i,j] = numerator/den end end return s end function Average_Discretised_Rank(list_of_disc_ranks) average = Array{Float64}(undef, size(list_of_disc_ranks[1])) n_r = length(list_of_disc_ranks) for i in n_r average = average .+ list_of_disc_ranks[i] end return average/n_r end function Direction_Filtration(ordered_points, direction; out = "barcode") number_of_points = length(ordered_points[:,1]) #number of points heights = zeros(number_of_points) #empty array to be changed to heights for filtration fv = zeros(2*number_of_points) #blank fv Eirene for i in 1:number_of_points heights[i]= ordered_points[i,1]*direction[1] + ordered_points[i,2]*direction[2] #calculate heights in specificed direction end for i in 1:number_of_points fv[i]= heights[i] # for a point the filtration step is the height end for i in 1:(number_of_points-1) fv[(i+number_of_points)]=maximum([heights[i], heights[i+1]]) # for an edge between two adjacent points it enters when the 2nd of the two points does end fv[2*number_of_points] = maximum([heights[1] , heights[number_of_points]]) #last one is a special snowflake dv = [] # template dv for Eirene for i in 1:number_of_points append!(dv,0) # every point is 0 dimensional end for i in (1+number_of_points):(2*number_of_points) append!(dv,1) # edges are 1 dimensional end D = zeros((2*number_of_points, 2*number_of_points)) for i in 1:number_of_points D[i,(i+number_of_points)]=1 # create boundary matrix and put in entries end for i in 2:(number_of_points) D[i, (i+number_of_points-1)]=1 # put in entries for boundary matrix end D[1, (2*number_of_points)]=1 ev = [number_of_points, number_of_points] # template ev for Eirene S = sparse(D) # converting as required for Eirene rv = S.rowval # converting as required for Eirene cp = S.colptr # converting as required for Eirene C = Eirene.eirene(rv=rv,cp=cp,ev=ev,fv=fv) # put it all into Eirene if out == "barcode" return barcode(C, dim=0) else return C end end #### Wrapper for the PHT function #### function PHT(curve_points, directions) ##accepts an ARRAY of points if typeof(directions) == Int64 println("auto generating directions") dirs = Array{Float64}(undef, directions,2) for n in 1:directions dirs[n,1] = cos(n*pi/(directions/2)) dirs[n,2] = sin(n*pi/(directions/2)) end println("Directions are:") println(dirs) else println("using directions provided") dirs = copy(directions) end pht = [] for i in 1:size(dirs,1) pd = Direction_Filtration(curve_points, dirs[i,:]) pht = vcat(pht, [pd]) end return pht end #### Wrapper for PCA #### function PCA(ranks, dimension, weights) normalised = Set_Mean_Zero(ranks) D = Weighted_InnerProd_Matrix(normalised, weights) return Principal_Component_Scores(D, dimension) end #### Unittests #### function test_1() return PHT([0,0,0],0) end function test_2() pht = PHT([1 1; 5 5], 1) if pht == [0.9999999999999998 4.999999999999999] return [] else println("Error: test_2, pht = ") return pht end end function unittest() x = Array{Any}(undef, 2) x[1] = test_1() x[2] = test_2() for p = 1:length(x) if !isempty(x[p]) println(p) return x end end return [] end end# module
PersistentHomologyTransfer
https://github.com/yossibokor/PersistentHomologyTransfer.jl.git
[ "MIT" ]
0.1.7
76e8797d9bb184f55b1a24f92056fb78b1839bf2
code
89
using PersistentHomologyTransfer using JLDEirene using Base.Test @test unittest() == []
PersistentHomologyTransfer
https://github.com/yossibokor/PersistentHomologyTransfer.jl.git
[ "MIT" ]
0.1.7
76e8797d9bb184f55b1a24f92056fb78b1839bf2
docs
4430
# PersistentHomologyTransfer.jl Persistent Homology Transform is produced and maintained by \ Yossi Bokor and Katharine Turner \ <[email protected]> and <[email protected]> This package provides an implementation of the Persistent Homology Transform, as defined in [Persistent Homology Transform for Modeling Shapes and Surfaces](https://arxiv.org/abs/1310.1030). It also does Rank Functions of Persistence Diagrams, and implements [Principal Component Analysis of Rank functions](https://www.sciencedirect.com/science/article/pii/S0167278916000476). ## Installation Currently, the best way to install PersistentHomologyTransfer is to run the following in `Julia`: ```julia using Pkg Pkg.add("PersistentHomologyTransfer") ``` ## Functionality - PersistentHomologyTransfer computes the Persistent Homology Transform of simple, closed curves in $\mathbb{R}^2$. - Rank functions of persistence diagrams. - Principal Component Analysis of Rank Functions. ### Persistent Homology Transform Given an $m \times 2$ matrix of ordered points sampled from a simple, closed curve $C \subset \mathbb{R}^2$ (in either a clockwise or anti-clockwise direction), calculate the Persistent Homology Transform for a set of directions. You can either specify the directions explicity as a $n \times 2$ array (`directions::Array{Float64}(n,2)`), or specify an integer (`directions::Int64`) and then the directions used will be generated by ```julia angles = [n*pi/(directions/2) for n in 1:directions] directions = [[cos(x), sin(x)] for x in angles] ``` To perform the Persistent Homology Transfer for the directions, run ```julia PHT(points, directions) ``` This outputs an array of [Eirene](https://github.com/Eetion/Eirene.jl) Persistence Diagrams, one for each direction. ### Rank Functions Given an [Eirene](https://github.com/Eetion/Eirene.jl) Persistence Diagram $D$, PersistentHomologyTransfer can calculate the Rank Function $r_D$ either exactly, or given a grid of points, calculate a discretised version. Recall that $D$ is an $n \times 2$ array of points, and hence the function `Total_Rank_Exact` accepts an $n \times 2$ array of points, and returns a list of points critical points of the Rank function and the value at each of these points. Running ```julia rk = Total_Rank_Exact(barcode) ``` we obtain the critical points via ```julia rk[1] ``` which returns an array of points in $\mathbb{R}^2$, and the values through ```julia rk[2] ``` wich returns an array of integers. To obtain a discrete approximation of a Rank Function over a persistence diagram $D$, use `Total_Rank_Grid`, which acceps as input an [Eirene](https://github.com/Eetion/Eirene.jl) Persistence Diagram $D$, an increasing `StepRange` for $x$-coordinates `x_g`, and a decreasing `StepRange` for $y$-coordinates `y_g`. The `StepRanges` are obtained by running ```julia x_g = lb:delta:ub x_g = ub:-delta:lb ``` with `lb` being the lower bound so that $(lb, lb)$ is the lower left corner of the grid, and `ub` being the upper bound so that $(ub,ub)$ is the top right corner of the grid, and $delta$ is the step size. Finally, the rank is obtained by ```julia rk = Total_Rank_Grid(D, x_g, y_g) ``` which returns an array or values. ### PCA of Rank Functions Given a set of rank functions, we can perform principal component analysis on them. The easiest way to do this is to use the wrapper function `PCA` which has inputs an array of rank functions evaluated at the same points (best to use `Total_Rank_Grid` to obtain them), an dimension $d$ and an array of weights `weights`, where the weights correspond to the grid points used in `Total_Rank_Grid`. To perform Principal Component Analysis and obtain the scores run ```julia scores = PCA(ranks, d, weights) ``` which returns the scores in $d$-dimensions. ## Examples ### Persistent Homology Transfer We will go through an example using a random [shape](https://github.com/yossibokor/PersistentHomologyTransfer.jl/Example/Example1.png) and 20 directions. You can download the CSV file from [here](https://github.com/yossibokor/PersistentHomologyTransfer.jl/Example/Example1.csv) To begin, load the CSV file into an array in Julia ```julia Boundary = CSV.read("<path/to/file>") Persistence_Diagrams = PHT(Boundary, 20) ``` You can then access the persistence diagram corresponding to the $i^{th}$ direction as ```julia Persistence_Diagrams[i] ``` <!---### Rank Functions -->
PersistentHomologyTransfer
https://github.com/yossibokor/PersistentHomologyTransfer.jl.git
[ "MIT" ]
1.4.0
e8f41ed9a2cabf6699d9906c195bab1f773d4ca7
code
3854
__precompile__() module TikzGraphs export plot, Layouts import Graphs: DiGraph, Graph, vertices, edges, src, dst preamble = read(joinpath(dirname(@__FILE__), "..", "src", "preamble.tex"), String) const AbstractGraph = Union{Graph, DiGraph} using TikzPictures module Layouts export Layered, Spring, SpringElectrical, SimpleNecklace abstract type Layout end struct Layered <: Layout sib_dist lev_dist Layered(;sib_dist=-1,lev_dist=-1) = new(sib_dist,lev_dist) end struct Spring <: Layout randomSeed dist Spring(;randomSeed=42,dist=-1) = new(randomSeed,dist) end struct SpringElectrical <: Layout randomSeed charge dist SpringElectrical(;randomSeed=42,charge=1.,dist=-1) = new(randomSeed,charge,dist) end struct SimpleNecklace <: Layout end end using .Layouts plot(g, layout::Layouts.Layout, labels::Vector{T}=map(string, vertices(g)); args...) where {T<:AbstractString} = plot(g; layout=layout, labels=labels, args...) plot(g, labels::Vector{T}; args...) where {T<:AbstractString} = plot(g; layout=Layered(), labels=labels, args...) function edgeHelper(o::IOBuffer, a, b, edge_labels, edge_styles, edge_style) print(o, " [$(edge_style),") if haskey(edge_labels, (a,b)) print(o, "edge label={$(edge_labels[(a,b)])},") end if haskey(edge_styles, (a,b)) print(o, "$(edge_styles[(a,b)]),") end print(o, "] ") end function nodeHelper(o::IOBuffer, v, labels, node_styles, node_style) print(o, "$v/\"$(labels[v])\" [$(node_style)") if haskey(node_styles, v) print(o, ",$(node_styles[v])") end println(o, "],") end # helper function for edge type edge_str(g::DiGraph) = "->" edge_str(g::Graph) = "--" function plot(g::AbstractGraph; layout::Layouts.Layout = Layered(), labels::Vector{T}=map(string, vertices(g)), edge_labels::Dict = Dict(), node_styles::Dict = Dict(), node_style="", edge_styles::Dict = Dict(), edge_style="", options="", graph_options="", prepend_preamble::String="") where T<:AbstractString o = IOBuffer() println(o, "\\graph [$(layoutname(layout)), $(options_str(layout)), $graph_options] {") for v in vertices(g) nodeHelper(o, v, labels, node_styles, node_style) end println(o, ";") for e in edges(g) a = src(e) b = dst(e) print(o, "$a $(edge_str(g))") edgeHelper(o, a, b, edge_labels, edge_styles, edge_style) println(o, "$b;") end println(o, "};") mypreamble = prepend_preamble * preamble * "\n\\usegdlibrary{$(libraryname(layout))}" TikzPicture(String(take!(o)), preamble=mypreamble, options=options) end for (_layout, _libraryname, _layoutname) in [ (:Layered, "layered", "layered layout"), (:Spring, "force", "spring layout"), (:SpringElectrical, "force", "spring electrical layout"), (:SimpleNecklace, "circular", "simple necklace layout") ] @eval libraryname(p::$(_layout)) = $_libraryname @eval layoutname(p::$(_layout)) = $_layoutname end options_str(p::Layouts.Layout) = "" function options_str(p::Layouts.Layered) sib_str = "" lev_str = "" if p.sib_dist > 0 sib_str="sibling distance=$(p.sib_dist)mm," end if p.lev_dist > 0 lev_str = "level distance=$(p.lev_dist)mm," end return sib_str*lev_str end function options_str(p::Spring) if p.dist == -1 return "random seed = $(p.randomSeed)," else return "random seed = $(p.randomSeed), node distance=$(p.dist)," end end function options_str(p::SpringElectrical) if p.dist == -1 return "random seed = $(p.randomSeed), electric charge=$(p.charge)," else return "random seed = $(p.randomSeed), electric charge=$(p.charge), node distance=$(p.dist)," end end end # module
TikzGraphs
https://github.com/JuliaTeX/TikzGraphs.jl.git
[ "MIT" ]
1.4.0
e8f41ed9a2cabf6699d9906c195bab1f773d4ca7
code
149
using TikzGraphs using Test @assert success(`lualatex -v`) using NBInclude @nbinclude joinpath(dirname(@__FILE__), "..", "doc", "TikzGraphs.ipynb")
TikzGraphs
https://github.com/JuliaTeX/TikzGraphs.jl.git
[ "MIT" ]
1.4.0
e8f41ed9a2cabf6699d9906c195bab1f773d4ca7
docs
478
# TikzGraphs [![Build Status](https://github.com/JuliaTeX/TikzGraphs.jl/workflows/CI/badge.svg)](https://github.com/JuliaTeX/TikzGraphs.jl/actions) [![codecov](https://codecov.io/gh/JuliaTeX/TikzGraphs.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/JuliaTeX/TikzGraphs.jl) This library generates graph layouts using the TikZ graph layout package. Read the [documentation](http://nbviewer.ipython.org/github/JuliaTeX/TikzGraphs.jl/blob/master/doc/TikzGraphs.ipynb).
TikzGraphs
https://github.com/JuliaTeX/TikzGraphs.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
2198
using Documenter using GeometricProblems using DocumenterCitations # if the docs are generated with github actions, then this changes the path; see: https://github.com/JuliaDocs/Documenter.jl/issues/921 const buildpath = haskey(ENV, "CI") ? ".." : "" const bib = CitationBibliography(joinpath(@__DIR__, "src", "GeometricProblems.bib")) makedocs(; plugins = [bib], sitename = "GeometricProblems.jl", format = Documenter.HTML(; prettyurls = get(ENV, "CI", nothing) == "true", assets = [ "assets/extra_styles.css", ], ), pages = ["Home" => "index.md", "Diagnostics" => "diagnostics.md", "ABC Flow" => "abc_flow.md", "Coupled Harmonic Oscillator" => "coupled_harmonic_oscillator.md", "Double Pendulum" => "double_pendulum.md", "Harmonic Oscillator" => "harmonic_oscillator.md", "Hénon-Heiles System" => "henon_heiles.md", "Kepler Problem" => "kepler_problem.md", "Linear Wave Equation" => "linear_wave.md", "Lorenz Attractor" => "lorenz_attractor.md", "Lotka-Volterra 2d" => "lotka_volterra_2d.md", "Lotka-Volterra 3d" => "lotka_volterra_3d.md", "Lotka-Volterra 4d" => "lotka_volterra_4d.md", "Massless Charged Particle" => "massless_charged_particle.md", "Mathematical Pendulum" => "pendulum.md", "Nonlinear Oscillators" => "nonlinear_oscillators.md", "Point Vortices" => "point_vortices.md", "Inner Solar System" => "inner_solar_system.md", "Outer Solar System" => "outer_solar_system.md", "Rigid body" => "rigid_body.md", "Toda Lattice" => "toda_lattice.md", "Initial conditions" => ["bump" => "initial_condition.md",] ] ) deploydocs( repo = "github.com/JuliaGNI/GeometricProblems.jl", devurl = "latest", devbranch = "main", )
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
1310
""" GeometricProblems.jl is a collection of ODEs and DAEs with interesting geometric structures. """ module GeometricProblems include("bump_initial_condition.jl") include("diagnostics.jl") include("plot_recipes.jl") include("abc_flow.jl") include("double_pendulum.jl") include("duffing_oscillator.jl") include("harmonic_oscillator.jl") include("kubo_oscillator.jl") include("lennard_jones_oscillator.jl") include("linear_wave.jl") include("lorenz_attractor.jl") include("lotka_volterra_2d.jl") include("lotka_volterra_2d_gauge.jl") include("lotka_volterra_2d_singular.jl") include("lotka_volterra_2d_symmetric.jl") include("lotka_volterra_2d_plots.jl") include("lotka_volterra_3d.jl") include("lotka_volterra_3d_plots.jl") include("lotka_volterra_4d.jl") include("lotka_volterra_4d_lagrangian.jl") include("lotka_volterra_4d_plots.jl") include("massless_charged_particle.jl") include("massless_charged_particle_plots.jl") include("coupled_harmonic_oscillator.jl") include("mathews_lakshmanan_oscillator.jl") include("morse_oscillator.jl") include("pendulum.jl") include("point_vortices.jl") include("point_vortices_linear.jl") include("rigid_body.jl") include("toda_lattice.jl") end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
1171
@doc raw""" # ABC Flow ```math \begin{aligned} \dot{x} = A\sin(z) + C\cos(y) \\ \dot{y} = B\sin(x) + A\cos(z) \\ \dot{z} = C\sin(y) + B\cos(x) \end{aligned} ``` """ module ABCFlow using GeometricEquations using GeometricSolutions using Parameters export odeproblem, odeensemble const tspan = (0.0, 100.0) const tstep = 0.1 const default_parameters = ( A = 0.5, B = 1., C = 1. ) const q₀ = [0.0, 0., 0.] const q₁ = [0.5, 0., 0.] const q₂ = [0.6, 0., 0.] function abc_flow_v(v, t, q, params) @unpack A, B, C = params v[1] = A * sin(q[3]) + C * cos(q[2]) v[2] = B * sin(q[1]) + A * cos(q[3]) v[3] = C * sin(q[2]) + B * cos(q[1]) nothing end function odeproblem(q₀ = q₀; tspan = tspan, tstep = tstep, parameters = default_parameters) ODEProblem(abc_flow_v, tspan, tstep, q₀; parameters = parameters) end function odeensemble(samples = [q₀, q₁, q₂]; parameters = default_parameters, tspan = tspan, tstep = tstep) ODEEnsemble(abc_flow_v, tspan, tstep, samples; parameters = parameters) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
1938
""" Third-degree spline that is used as a basis to construct the initial conditions. """ function h(x::T) where T <: Real if 0 ≤ x ≤ 1 1 - 3 * x ^ 2 / 2 + 3 * x ^ 3 / 4 elseif 1 < x ≤ 2 (2 - x) ^ 3 / 4 else zero(T) end end function ∂h(x::T) where T <: Real if 0 ≤ x ≤ 1 -3x + 9 * x ^ 2 / 4 elseif 1 < x ≤ 2 - 3 * (2 - x) ^ 2 / 4 else zero(T) end end function s(ξ::Real, μ::Real) 20μ * abs(ξ + μ / 2) end function ∂s(ξ::T, μ::T) where T <: Real ξ + μ / 2 ≥ 0 ? 20μ : -20μ end function s(ξ::AbstractVector{T}, μ::T) where T <: Real s_closure(ξ_scalar) = s(ξ_scalar, μ) s_closure.(ξ) end function ∂s(ξ::AbstractVector{T}, μ::T) where T <: Real ∂s_closure(ξ_scalar) = s(ξ_scalar, μ) ∂s_closure.(ξ) end u₀(ξ::Real, μ::Real) = h(s(ξ, μ)) function u₀(ξ::AbstractVector{T}, μ::T) where T <: Real h.(s(ξ, μ)) end function ∂u₀(ξ::T, μ::T) where T <: Real ∂h(s(ξ, μ)) * ∂s(ξ, μ) end function ∂u₀(ξ::AbstractVector{T}, μ::T) where T <: Real ∂u₀_closure(ξ_scalar) = ∂u₀(ξ_scalar, μ) ∂u₀_closure.(ξ) end function compute_domain(N::Integer, T=Float64) Δx = 1. / (N - 1) T(-0.5) : Δx : T(0.5) end function compute_p₀(ξ::T, μ::T) where T <: Real - μ * ∂u₀(ξ, μ) end function compute_p₀(Ω::AbstractVector{T}, μ::T) where T p₀_closure(ξ::T) = compute_p₀(ξ, μ) p₀_closure.(Ω) end @doc raw""" Produces initial conditions for the bump function. Here the ``p``-part is initialized with zeros. """ function compute_initial_condition(μ::T, N::Integer) where T Ω = compute_domain(N, T) (q =u₀(Ω, μ), p = zero(Ω)) end @doc raw""" Produces initial condition for the bump function. Here the ``p``-part is initialized as ``-\mu\partial_\xi u_0(\xi, \mu)``. """ function compute_initial_condition2(μ::T, N::Integer) where T Ω = compute_domain(N, T) (q =u₀(Ω, μ), p = compute_p₀(Ω, μ)) end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
3628
@doc raw""" CoupledHarmonicOscillator The `CoupledHarmonicOscillator` module provides functions `hodeproblem` and `lodeproblem` each returning a Hamiltonian or Lagrangian problem, respectively, to be solved in the GeometricIntegrators.jl ecosystem. The actual code is generated with EulerLagrange.jl. The coupled harmonic oscillator is a collection of two point masses that are connected to a fixed wall with spring constants ``k_1`` and ``k_2`` and are furthermore coupled nonlinearly resulting in the Hamiltonian: ```math H(q_1, q_2, p_1, p_2) = \frac{q_1^2}{2m_1} + \frac{q_2^2}{2m_2} + k_1\frac{q_1^2}{2} + k_2\frac{q_2^2}{2} + k\sigma(q_1)\frac{(q_2 - q_1)^2}{2}, ``` where ``\sigma(x) = 1 / (1 + e^{-x})`` is the sigmoid activation function. System parameters: * `k₁`: spring constant of mass 1 * `k₂`: spring constant of mass 2 * `m₁`: mass 1 * `m₂`: mass 2 * `k`: coupling strength between the two masses. """ module CoupledHarmonicOscillator using EulerLagrange using LinearAlgebra using Parameters using GeometricEquations: HODEEnsemble export hamiltonian, lagrangian export hodeproblem, lodeproblem export hodeensemble const tspan = (0.0, 100.0) const tstep = 0.4 const default_parameters = ( m₁ = 2., m₂ = 1., k₁ = 1.5, k₂ = 0.3, k = 1.0 ) const q₀ = [1., 0.] const p₀ = [2., 0.] function σ(x::T) where {T<:Real} T(1) / (T(1) + exp(-x)) end function hamiltonian(t, q, p, parameters) @unpack k₁, k₂, m₁, m₂, k = parameters p[1] ^ 2 / (2 * m₁) + p[2] ^ 2 / (2 * m₂) + k₁ * q[1] ^ 2 / 2 + k₂ * q[2] ^ 2 / 2 + k * σ(q[1]) * (q[2] - q[1]) ^2 / 2 end function lagrangian(t, q, q̇, parameters) @unpack k₁, k₂, m₁, m₂, k = parameters q̇[1] ^ 2 / (2 * m₁) + q̇[2] ^ 2 / (2 * m₂) - k₁ * q[1] ^ 2 / 2 - k₂ * q[2] ^ 2 / 2 - k * σ(q[1]) * (q[2] - q[1]) ^2 / 2 end """ Hamiltonian problem for coupled oscillator Constructor with default arguments: ``` hodeproblem( q₀ = $(q₀), p₀ = $(p₀); tspan = $(tspan), tstep = $(tstep), parameters = $(default_parameters) ) ``` """ function hodeproblem(q₀ = q₀, p₀ = p₀; tspan = tspan, tstep = tstep, parameters = default_parameters) t, q, p = hamiltonian_variables(2) sparams = symbolize(parameters) ham_sys = HamiltonianSystem(hamiltonian(t, q, p, sparams), t, q, p, sparams) HODEProblem(ham_sys, tspan, tstep, q₀, p₀; parameters = parameters) end function v̄(v, t, q, p, parameters) v[1] = p[1] / parameters.m₁ v[2] = p[2] / parameters.m₂ nothing end """ Lagrangian problem for the coupled oscillator Constructor with default arguments: ``` lodeproblem( q₀ = $(q₀), p₀ = $(p₀); tspan = $(tspan), tstep = $(tstep), parameters = $(default_parameters) ) ``` """ function lodeproblem(q₀ = q₀, p₀ = p₀; tspan = tspan, tstep = tstep, parameters = default_parameters) t, x, v = lagrangian_variables(2) sparams = symbolize(parameters) lag_sys = LagrangianSystem(lagrangian(t, x, v, sparams), t, x, v, sparams) LODEProblem(lag_sys, tspan, tstep, q₀, p₀; v̄ = v̄, parameters = parameters) end function hodeensemble(q₀ = q₀, p₀ = p₀; tspan = tspan, tstep = tstep, parameters = default_parameters) eq = hodeproblem().equation HODEEnsemble(eq.v, eq.f, eq.hamiltonian, tspan, tstep, q₀, p₀; parameters = parameters) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
7204
module Diagnostics using GeometricSolutions export compute_one_form, compute_invariant, compute_invariant_error, compute_momentum_error, compute_error_drift """ Takes a ScalarDataSeries holding an invariant and computes the relative error `(inv(t)-inv(0))/inv(0)`. Returns a ScalarDataSeries similar to the argument holding the time series of the relativ errors. """ function compute_relative_error(invds::ScalarDataSeries{T}) where {T} errds = similar(invds) for i in eachindex(errds, invds) errds[i] = (invds[i] - invds[0]) / invds[0] end return errds end """ Compute the one-form (symplectic potential) for the solution of a Lagrangian system. Arguments: `(t::TimeSeries, q::DataSeries, one_form::Base.Callable)` The `one_form` function needs to take three arguments `(t,q,k)` where `k` is the index of the one-form component. Returns a DataSeries similar to `q` holding the time series of the one-form. """ function compute_one_form(t::TimeSeries, q::DataSeries, one_form::Base.Callable) ϑ = similar(q) try for i in axes(p,2) for k in axes(p,1) ϑ[k,i] = one_form(t[i], q[:,i], k) end end catch ex if isa(ex, DomainError) @warn("DOMAIN ERROR: One-form diagnostics crashed.") else throw(ex) end end return ϑ end """ Compute an invariant for the solution of an ODE or DAE system. Arguments: `(t::TimeSeries, q::DataSeries{T}, invariant::Base.Callable)` The `invariant` functions needs to take two arguments `(t,q)` and return the corresponding value of the invariant. Returns a ScalarDataSeries holding the time series of the invariant. """ function compute_invariant(t::TimeSeries, q::DataSeries{T}, invariant::Base.Callable) where {T} invds = DataSeries(T, ntime(q)) try for i in eachindex(invds) invds[i] = invariant(t[i], q[i]) end catch ex if isa(ex, DomainError) @warn("DOMAIN ERROR: Invariant diagnostics crashed.") else throw(ex) end end return invds end """ Compute an invariant for the solution of a partitioned ODE or DAE system. Arguments: `(t::TimeSeries, q::DataSeries{T}, p::DataSeries{T}, invariant::Base.Callable)` The `invariant` functions needs to take three arguments `(t,q,p)` and return the corresponding value of the invariant. Returns a ScalarDataSeries holding the time series of the invariant. """ function compute_invariant(t::TimeSeries, q::DataSeries{T}, p::DataSeries{T}, invariant::Base.Callable) where {T} invds = DataSeries(T, ntime(q)) try for i in eachindex(invds) invds[i] = invariant(t[i], q[i], p[i]) end catch ex if isa(ex, DomainError) @warn("DOMAIN ERROR: Invariant diagnostics crashed.") else throw(ex) end end return invds end """ Compute the relative error of an invariant for the solution of an ODE or DAE system. Arguments: `(t::TimeSeries, q::DataSeries{T}, invariant::Base.Callable)` The `invariant` functions needs to take two arguments `(t,q)` and return the corresponding value of the invariant. Returns a tuple of two 1d DataSeries holding the time series of the invariant and the relativ error, respectively. """ function compute_invariant_error(t::TimeSeries, q::DataSeries, invariant::Base.Callable) invds = compute_invariant(t, q, invariant) errds = compute_relative_error(invds) (invds, errds) end """ Compute the relative error of an invariant for the solution of a partitioned ODE or DAE system. Arguments: `(t::TimeSeries, q::DataSeries{T}, p::DataSeries{T}, invariant::Base.Callable)` The `invariant` functions needs to take three arguments `(t,q,p)` and return the corresponding value of the invariant. Returns a tuple of two ScalarDataSeries holding the time series of the invariant and the relativ error, respectively. """ function compute_invariant_error(t::TimeSeries, q::DataSeries{T}, p::DataSeries{T}, invariant::Base.Callable) where {T} invds = compute_invariant(t, q, p, invariant) errds = compute_relative_error(invds) (invds, errds) end """ Computes the difference of the momentum and the one-form of an implicit ODE or DAE system. Arguments: `(t::TimeSeries, q::DataSeries{T}, p::DataSeries{T}, one_form::Function)` The `one_form` function needs to take three arguments `(t,q,k)` where `k` is the index of the one-form component. Returns a DataSeries similar to `p` holding the time series of the difference between the momentum and the one-form. """ function compute_momentum_error(t::TimeSeries, q::DataSeries{T}, p::DataSeries{T}, one_form::Function) where {T} e = similar(p) for n in axes(p,1) for k in eachindex(p[n]) e[n][k] = p[n][k] - one_form(t[n], q[n], k) end end return e end """ Computes the difference of the momentum and the one-form of an implicit ODE or DAE system. Arguments: `(p::DataSeries{DT}, ϑ::DataSeries{DT})` Returns a DataSeries similar to `p` holding the time series of the difference between `p` and `ϑ`. """ function compute_momentum_error(p::DataSeries{DT}, ϑ::DataSeries{DT}) where {DT} @assert axes(p) == axes(ϑ) e = similar(p) parent(e) .= parent(p) .- parent(ϑ) return e end """ Computes the drift in an invariant error. Arguments: `(t::TimeSeries, invariant_error::DataSeries{T,1}, interval_length=100)` The time series of the solution is split into intervals of `interval_length` time steps. In each interval, the maximum of the absolute value of the invariant error is determined. Returns a tuple of a TimeSeries that holds the centers of all intervals and a ScalarDataSeries that holds the maxima. This is useful to detect drifts in invariants that are not preserved exactly but whose error is oscillating such as the energy error of Hamiltonian systems with symplectic integrators. """ function compute_error_drift(t::TimeSeries, invariant_error::ScalarDataSeries{T}, interval_length=100) where {T} @assert ntime(t) == ntime(invariant_error) @assert mod(t.n, interval_length) == 0 nint = div(ntime(invariant_error), interval_length) Tdrift = TimeSeries(nint, (t[end] - t[begin]) / nint) Idrift = DataSeries(T, nint) Tdrift[0] = t[0] for i in 1:nint i1 = interval_length*(i-1)+1 i2 = interval_length*i Idrift[i] = maximum(abs.(invariant_error[i1:i2])) Tdrift[i] = div(t[i1] + t[i2], 2) end (Tdrift, Idrift) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
4343
@doc raw""" DoublePendulum The `DoublePendulum` module provides functions `hodeproblem` and `lodeproblem` each returning a Hamiltonian or Lagrangian problem, respectively, to be solved in the GeometricIntegrators.jl ecosystem. The actual code is generated with EulerLagrange.jl. The double pendulum consists of two pendula, one attached to the origin at ``(x,y) = (0,0)``, and the second attached to the first. Each pendulum consists of a point mass ``m_i`` attached to a massless rod of length ``l_i`` with ``i \in (1,2)``. The dynamics of the system is described in terms of the angles ``\theta_i`` between the rods ``l_i`` and the vertical axis ``y``. All motion is assumed to be frictionless. System parameters: * `l₁`: length of rod 1 * `l₂`: length of rod 2 * `m₁`: mass of pendulum 1 * `m₂`: mass of pendulum 2 * `g`: gravitational constant """ module DoublePendulum using EulerLagrange using LinearAlgebra using Parameters export hamiltonian, lagrangian export hodeproblem, lodeproblem ϑ₁(t, q, q̇, params) = (params.m₁ + params.m₂) * params.l₁^2 * q̇[1] + params.m₂ * params.l₁ * params.l₂ * q̇[2] * cos(q[1] - q[2]) ϑ₂(t, q, q̇, params) = params.m₂ * params.l₂^2 * q̇[2] + params.m₂ * params.l₁ * params.l₂ * q̇[1] * cos(q[1] - q[2]) ϑ(t, q, q̇, params) = [ϑ₁(t, q, q̇, params), ϑ₂(t, q, q̇, params)] function θ̇₁(t, q, p, params) @unpack l₁, l₂, m₁, m₂, g = params ( l₂ * p[1] - l₁ * p[2] * cos(q[1] - q[2]) ) / ( l₁^2 * l₂ * ( m₁ + m₂ * sin(q[1] - q[2])^2 ) ) end function θ̇₂(t, q, p, params) @unpack l₁, l₂, m₁, m₂, g = params ( (m₁ + m₂) * l₁ * p[2] - m₂ * l₂ * p[1] * cos(q[1] - q[2]) ) / ( m₂ * l₁ * l₂^2 * ( m₁ + m₂ * sin(q[1] - q[2])^2 ) ) end θ̇(t, q, p, params) = [θ̇₁(t, q, p, params), θ̇₂(t, q, p, params)] function θ̇(v, t, q, p, params) v[1] = θ̇₁(t, q, p, params) v[2] = θ̇₂(t, q, p, params) nothing end const tstep = 0.01 const tspan = (0.0, 10.0) const default_parameters = ( l₁ = 2.0, l₂ = 3.0, m₁ = 1.0, m₂ = 2.0, g = 9.80665, ) const θ₀ = [π/4, π/2] const ω₀ = [0.0, π/8] const p₀ = ϑ(tspan[begin], θ₀, ω₀, default_parameters) function hamiltonian(t, q, p, params) @unpack l₁, l₂, m₁, m₂, g = params nom = (m₁ + m₂) * l₁^2 * p[2]^2 / 2+ m₂ * l₂^2 * p[1]^2 / 2 - m₂ * l₁ * l₂ * p[1] * p[2] * cos(q[1] - q[2]) den = m₂ * l₁^2 * l₂^2 * ( m₁ + m₂ * sin(q[1] - q[2])^2 ) nom/den - g * (m₁ + m₂) * l₁ * cos(q[1]) - g * m₂ * l₂ * cos(q[2]) end function lagrangian(t, q, q̇, params) @unpack l₁, l₂, m₁, m₂, g = params (m₁ + m₂) * l₁^2 * q̇[1]^2 / 2 + m₂ * l₂^2 * q̇[2]^2 / 2 + m₂ * l₁ * l₂ * q̇[1] * q̇[2] * cos(q[1] - q[2]) + (m₁ + m₂) * l₁ * g * cos(q[1]) + m₂ * l₂ * g * cos(q[2]) end """ Hamiltonian problem for the double pendulum Constructor with default arguments: ``` hodeproblem( q₀ = [π/4, π/2], p₀ = $(p₀); tspan = $(tspan), tstep = $(tstep), params = $(default_parameters) ) ``` """ function hodeproblem(q₀ = θ₀, p₀ = p₀; tspan = tspan, tstep = tstep, parameters = default_parameters) t, q, p = hamiltonian_variables(2) sparams = symbolize(parameters) ham_sys = HamiltonianSystem(hamiltonian(t, q, p, sparams), t, q, p, sparams) HODEProblem(ham_sys, tspan, tstep, q₀, p₀; parameters = parameters) end """ Lagrangian problem for the double pendulum Constructor with default arguments: ``` lodeproblem( q₀ = [π/4, π/2], p₀ = $(p₀); tspan = $(tspan), tstep = $(tstep), params = $(default_parameters) ) ``` """ function lodeproblem(q₀ = θ₀, p₀ = p₀; tspan = tspan, tstep = tstep, parameters = default_parameters) t, x, v = lagrangian_variables(2) sparams = symbolize(parameters) lag_sys = LagrangianSystem(lagrangian(t, x, v, sparams), t, x, v, sparams) LODEProblem(lag_sys, tspan, tstep, q₀, p₀; v̄ = θ̇, parameters = parameters) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
72
@doc raw""" """ module DuffingOscillator export hamiltonian end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
14869
@doc raw""" # Harmonic Oscillator """ module HarmonicOscillator using GeometricEquations using GeometricSolutions using Parameters export odeproblem, podeproblem, hodeproblem, iodeproblem, lodeproblem, sodeproblem, daeproblem, pdaeproblem, hdaeproblem, idaeproblem, ldaeproblem, degenerate_iodeproblem, degenerate_lodeproblem export odeensemble, podeensemble, hodeensemble export hamiltonian, lagrangian export compute_energy_error, exact_solution const t₀ = 0.0 const Δt = 0.1 const nt = 10 const tspan = (t₀, Δt*nt) const k = 0.5 const ω = √k const default_parameters = (k=k, ω=ω) ϑ₁(t,q) = q[2] ϑ₂(t,q) = zero(eltype(q)) function ϑ(q) p = zero(q) p[1] = ϑ₁(0,q) p[2] = ϑ₂(0,q) return p end function ω!(ω, t, q, params) ω[1,1] = 0 ω[1,2] = -1 ω[2,1] = +1 ω[2,2] = 0 nothing end function hamiltonian(t, q, params) @unpack k = params q[2]^2 / 2 + k * q[1]^2 / 2 end function hamiltonian(t, q, p, params) @unpack k = params p[1]^2 / 2 + k * q[1]^2 / 2 end function lagrangian(t, q, v, params) @unpack k = params v[1]^2 / 2 - k * q[1]^2 / 2 end function degenerate_lagrangian(t, q, v, params) ϑ₁(t,q) * v[1] + ϑ₂(t,q) * v[2] - hamiltonian(t, q, params) end A(q, p, params) = q * sqrt(1 + p^2 / q^2 / params.k) ϕ(q, p, params) = atan(p / q / params.ω) exact_solution_q(t, q₀, p₀, t₀, params) = A(q₀, p₀, params) * cos(params.ω * (t-t₀) - ϕ(q₀, p₀, params)) exact_solution_p(t, q₀, p₀, t₀, params) = - params.ω * A(q₀, p₀, params) * sin(params.ω * (t-t₀) - ϕ(q₀, p₀, params)) exact_solution_q(t, q₀::AbstractVector, p₀::AbstractVector, t₀, params) = exact_solution_q(t, q₀[1], p₀[1], t₀, params) exact_solution_p(t, q₀::AbstractVector, p₀::AbstractVector, t₀, params) = exact_solution_p(t, q₀[1], p₀[1], t₀, params) exact_solution_q(t, x₀::AbstractVector, t₀, params) = exact_solution_q(t, x₀[1], x₀[2], t₀, params) exact_solution_p(t, x₀::AbstractVector, t₀, params) = exact_solution_p(t, x₀[1], x₀[2], t₀, params) exact_solution(t, x₀::AbstractVector, t₀, params) = [exact_solution_q(t, x₀, t₀, params), exact_solution_p(t, x₀, t₀, params)] const q₀ = [0.5] const p₀ = [0.0] const x₀ = vcat(q₀, p₀) const xmin = [-2., -2.] const xmax = [+2., +2.] const nsamples = [10, 10] const reference_solution_q = exact_solution_q(Δt * nt, q₀[1], p₀[1], t₀, default_parameters) const reference_solution_p = exact_solution_p(Δt * nt, q₀[1], p₀[1], t₀, default_parameters) const reference_solution = [reference_solution_q, reference_solution_p] function _ode_samples(qmin, qmax, nsamples) qs = [range(qmin[i], qmax[i]; length = nsamples[i]) for i in eachindex(qmin, qmax, nsamples)] samples = vec(collect.(collect(Base.Iterators.product(qs...)))) (q = samples,) end function _pode_samples(qmin, qmax, pmin, pmax, qsamples, psamples) qs = [range(qmin[i], qmax[i]; length = qsamples[i]) for i in eachindex(qmin, qmax, qsamples)] ps = [range(pmin[i], pmax[i]; length = psamples[i]) for i in eachindex(pmin, pmax, psamples)] qsamples = vec(collect.(collect(Base.Iterators.product(qs...)))) psamples = vec(collect.(collect(Base.Iterators.product(ps...)))) samples = vec(collect(Base.Iterators.product(qsamples, psamples))) (q = qsamples, p = psamples) end function oscillator_ode_v(v, t, x, params) @unpack k = params v[1] = x[2] v[2] = -k * x[1] nothing end function odeproblem(x₀ = x₀; parameters = default_parameters, tspan = tspan, tstep = Δt) @assert length(x₀) == 2 ODEProblem(oscillator_ode_v, tspan, tstep, x₀; invariants = (h=hamiltonian,), parameters = parameters) end function odeensemble(qmin = xmin, qmax = xmax, nsamples = nsamples; parameters = default_parameters, tspan = tspan, tstep = Δt) samples = _ode_samples(qmin, qmax, nsamples) ODEEnsemble(oscillator_ode_v, tspan, tstep, samples...; invariants = (h=hamiltonian,), parameters = parameters) end function exact_solution!(sol::GeometricSolution, prob::ODEProblem) for n in eachtimestep(sol) sol.q[n] .= exact_solution(sol.t[n], sol.q[0], sol.t[0], parameters(prob)) end return sol end function exact_solution(prob::ODEProblem) exact_solution!(GeometricSolution(prob), prob) end function oscillator_pode_v(v, t, q, p, params) v[1] = p[1] nothing end function oscillator_pode_f(f, t, q, p, params) @unpack k = params f[1] = -k * q[1] nothing end function podeproblem(q₀ = q₀, p₀ = p₀; parameters = default_parameters, tspan = tspan, tstep = Δt) @assert length(q₀) == length(p₀) == 1 PODEProblem(oscillator_pode_v, oscillator_pode_f, tspan, tstep, q₀, p₀; invariants = (h=hamiltonian,), parameters = parameters) end function hodeproblem(q₀ = q₀, p₀ = p₀; parameters = default_parameters, tspan = tspan, tstep = Δt) @assert length(q₀) == length(p₀) == 1 HODEProblem(oscillator_pode_v, oscillator_pode_f, hamiltonian, tspan, tstep, q₀, p₀; parameters = parameters) end function podeensemble(qmin = [xmin[1]], qmax = [xmax[1]], pmin = [xmin[2]], pmax = [xmax[2]], qsamples = [nsamples[1]], psamples = [nsamples[2]]; parameters = default_parameters, tspan = tspan, tstep = Δt) samples = _pode_samples(qmin, qmax, pmin, pmax, qsamples, psamples) PODEEnsemble(oscillator_pode_v, oscillator_pode_f, tspan, tstep, samples...; invariants = (h=hamiltonian,), parameters = parameters) end function hodeensemble(qmin = [xmin[1]], qmax = [xmax[1]], pmin = [xmin[2]], pmax = [xmax[2]], qsamples = [nsamples[1]], psamples = [nsamples[2]]; parameters = default_parameters, tspan = tspan, tstep = Δt) samples = _pode_samples(qmin, qmax, pmin, pmax, qsamples, psamples) HODEEnsemble(oscillator_pode_v, oscillator_pode_f, hamiltonian, tspan, tstep, samples...; parameters = parameters) end function exact_solution!(sol::GeometricSolution, prob::Union{PODEProblem,HODEProblem}) for n in eachtimestep(sol) sol.q[n] = [exact_solution_q(sol.t[n], sol.q[0], sol.p[0], sol.t[0], parameters(prob))] sol.p[n] = [exact_solution_p(sol.t[n], sol.q[0], sol.p[0], sol.t[0], parameters(prob))] end return sol end function exact_solution(prob::Union{PODEProblem,HODEProblem}) exact_solution!(GeometricSolution(prob), prob) end function oscillator_sode_v_1(v, t, q, params) v[1] = q[2] v[2] = 0 nothing end function oscillator_sode_v_2(v, t, q, params) @unpack k = params v[1] = 0 v[2] = -k * q[1] nothing end function oscillator_sode_q_1(q₁, t₁, q₀, t₀, params) q₁[1] = q₀[1] + (t₁ - t₀) * q₀[2] q₁[2] = q₀[2] nothing end function oscillator_sode_q_2(q₁, t₁, q₀, t₀, params) @unpack k = params q₁[1] = q₀[1] q₁[2] = q₀[2] - (t₁ - t₀) * k * q₀[1] nothing end function sodeproblem(x₀ = x₀; parameters = default_parameters, tspan = tspan, tstep = Δt) SODEProblem((oscillator_sode_v_1, oscillator_sode_v_2), (oscillator_sode_q_1, oscillator_sode_q_2), tspan, tstep, x₀; v̄ = oscillator_ode_v, parameters = parameters) end function oscillator_iode_ϑ(p, t, q, v, params) p[1] = v[1] nothing end function oscillator_iode_f(f, t, q, v, params) @unpack k = params f[1] = -k * q[1] nothing end function oscillator_iode_g(g, t, q, v, λ, params) g[1] = λ[1] nothing end function oscillator_iode_v(v, t, q, p, params) v[1] = p[1] nothing end function iodeproblem(q₀=q₀, p₀=p₀; parameters = default_parameters, tspan = tspan, tstep = Δt) @assert length(q₀) == length(p₀) == 1 IODEProblem(oscillator_iode_ϑ, oscillator_iode_f, oscillator_iode_g, tspan, tstep, q₀, p₀; invariants = (h=hamiltonian,), parameters = parameters, v̄ = oscillator_iode_v) end function lodeproblem(q₀=q₀, p₀=p₀; parameters = default_parameters, tspan = tspan, tstep = Δt) @assert length(q₀) == length(p₀) == 1 LODEProblem(oscillator_iode_ϑ, oscillator_iode_f, oscillator_iode_g, ω!, lagrangian, tspan, tstep, q₀, p₀; invariants = (h=hamiltonian,), parameters = parameters, v̄ = oscillator_iode_v) end function degenerate_oscillator_iode_ϑ(p, t, q, v, params) p[1] = q[2] p[2] = 0 nothing end function degenerate_oscillator_iode_f(f, t, q, v, params) @unpack k = params f[1] = -k * q[1] f[2] = v[1] - q[2] nothing end function degenerate_oscillator_iode_g(g, t, q, v, λ, params) g[1] = 0 g[2] = λ[1] nothing end function degenerate_oscillator_iode_v(v, t, q, p, params) @unpack k = params v[1] = q[2] v[2] = -k * q[1] nothing end function degenerate_iodeproblem(q₀ = x₀, p₀ = ϑ(q₀); parameters = default_parameters, tspan = tspan, tstep = Δt) @assert length(q₀) == length(p₀) == 2 IODEProblem(degenerate_oscillator_iode_ϑ, degenerate_oscillator_iode_f, degenerate_oscillator_iode_g, tspan, tstep, q₀, p₀; invariants = (h=hamiltonian,), parameters = parameters, v̄ = degenerate_oscillator_iode_v) end function degenerate_lodeproblem(q₀ = x₀, p₀ = ϑ(q₀); parameters = default_parameters, tspan = tspan, tstep = Δt) @assert length(q₀) == length(p₀) == 2 LODEProblem(degenerate_oscillator_iode_ϑ, degenerate_oscillator_iode_f, degenerate_oscillator_iode_g, ω!, lagrangian, tspan, tstep, q₀, p₀; invariants = (h=hamiltonian,), parameters = parameters, v̄ = degenerate_oscillator_iode_v) end function oscillator_dae_u(u, t, x, λ, params) @unpack k = params u[1] = k * x[1] * λ[1] u[2] = x[2] * λ[1] end function oscillator_dae_ϕ(ϕ, t, x, params) ϕ[1] = hamiltonian(t, x, params) - hamiltonian(t₀, x₀, params) end function daeproblem(x₀=x₀, λ₀=[zero(eltype(x₀))]; parameters = default_parameters, tspan = tspan, tstep = Δt) DAEProblem(oscillator_ode_v, oscillator_dae_u, oscillator_dae_ϕ, tspan, tstep, x₀, λ₀; v̄ = oscillator_ode_v, invariants = (h=hamiltonian,), parameters = parameters) end function oscillator_pdae_v(v, t, q, p, params) @unpack k = params v[1] = p[1] nothing end function oscillator_pdae_f(f, t, q, p, params) @unpack k = params f[1] = -k * q[1] nothing end function oscillator_pdae_u(u, t, q, p, λ, params) @unpack k = params u[1] = k * q[1] * λ[1] nothing end function oscillator_pdae_g(g, t, q, p, λ, params) g[1] = p[1] * λ[1] nothing end function oscillator_pdae_ū(u, t, q, p, λ, params) @unpack k = params u[1] = k * q[1] * λ[1] nothing end function oscillator_pdae_ḡ(g, t, q, p, λ, params) g[1] = p[1] * λ[1] nothing end function oscillator_pdae_ϕ(ϕ, t, q, p, params) ϕ[1] = hamitlonian(t, q, p, params) nothing end function oscillator_pdae_ψ(ψ, t, q, p, q̇, ṗ, params) @unpack k = params ψ[1] = p[1] * ṗ[1] + k * q[1] * q̇[1] nothing end function pdaeproblem(q₀ = q₀, p₀ = p₀, λ₀ = zero(q₀); parameters = default_parameters, tspan = tspan, tstep = Δt) @assert length(q₀) == length(p₀) == 1 PDAEProblem(oscillator_pdae_v, oscillator_pdae_f, oscillator_pdae_u, oscillator_pdae_g, oscillator_pdae_ϕ, tspan, tstep, q₀, p₀, λ₀; invariants=(h=hamiltonian,), parameters = parameters) end function hdaeproblem(q₀ = q₀, p₀ = p₀, λ₀ = zero(q₀); parameters = default_parameters, tspan = tspan, tstep = Δt) @assert length(q₀) == length(p₀) == 1 HDAEProblem(oscillator_pdae_v, oscillator_pdae_f, oscillator_pdae_u, oscillator_pdae_g, oscillator_pdae_ϕ, oscillator_pdae_ū, oscillator_pdae_ḡ, oscillator_pdae_ψ, hamiltonian, tspan, tstep, q₀, p₀, λ₀; parameters = parameters) end oscillator_idae_u(u, t, q, v, p, λ, params) = oscillator_pdae_u(u, t, q, p, λ, params) oscillator_idae_g(g, t, q, v, p, λ, params) = oscillator_pdae_g(g, t, q, p, λ, params) oscillator_idae_ū(u, t, q, v, p, λ, params) = oscillator_pdae_ū(u, t, q, p, λ, params) oscillator_idae_ḡ(g, t, q, v, p, λ, params) = oscillator_pdae_ḡ(g, t, q, p, λ, params) oscillator_idae_ϕ(ϕ, t, q, v, p, params) = oscillator_pdae_ϕ(ϕ, t, q, p, params) oscillator_idae_ψ(ψ, t, q, v, p, q̇, ṗ, params) = oscillator_pdae_ψ(ψ, t, q, p, q̇, ṗ, params) function idaeproblem(q₀ = q₀, p₀ = p₀, λ₀ = zero(q₀); parameters = default_parameters, tspan = tspan, tstep = Δt) @assert length(q₀) == length(p₀) == length(λ₀) == 1 IDAEProblem(oscillator_iode_ϑ, oscillator_iode_f, oscillator_idae_u, oscillator_idae_g, oscillator_idae_ϕ, tspan, tstep, q₀, p₀, λ₀; v̄ = oscillator_iode_v, invariants = (h=hamiltonian,), parameters = parameters) end function ldaeproblem(q₀ = q₀, p₀ = p₀, λ₀ = zero(q₀); parameters = default_parameters, tspan = tspan, tstep = Δt) @assert length(q₀) == length(p₀) == length(λ₀) == 1 LDAEProblem(oscillator_iode_ϑ, oscillator_iode_f, oscillator_idae_u, oscillator_idae_g, oscillator_idae_ϕ, ω!, lagrangian, tspan, tstep, q₀, p₀, λ₀; v̄ = oscillator_iode_v, invariants = (h=hamiltonian,), parameters = parameters) end function exact_solution(probs::Union{ODEEnsemble,PODEEnsemble,HODEEnsemble}) sols = EnsembleSolution(probs) for (sol, prob) in zip(sols, probs) exact_solution!(sol, prob) end return sols end function compute_energy_error(t, q::DataSeries{T}, params) where {T} h = DataSeries(T, q.nt) e = DataSeries(T, q.nt) for i in axes(q,2) h[i] = hamiltonian(t[i], q[:,i], params) e[i] = (h[i] - h[0]) / h[0] end (h, e) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
6559
module KuboOscillator using GeometricEquations using Parameters export kubo_oscillator_sde_1, kubo_oscillator_psde_1, kubo_oscillator_spsde_1 export kubo_oscillator_sde_2, kubo_oscillator_psde_2, kubo_oscillator_spsde_2 export kubo_oscillator_sde_3, kubo_oscillator_psde_3, kubo_oscillator_spsde_3 export kubo_oscillator_ode q_init_A=[0.5, 0.0] q_init_B=[[ 0.5, 0.0], [ 0.0, 0.5], [-0.5, 0.0]] const noise_intensity = 0.1 const Δt = 0.01 const nt = 10 const tspan = (0.0, Δt*nt) const default_parameters = (ν = noise_intensity,) function kubo_oscillator_sde_v(v, t, q, params) v[1]= q[2] v[2]= -q[1] end function kubo_oscillator_sde_B(B::AbstractVector, t, q, params) @unpack ν = params B[1] = +ν * q[2] B[2] = -ν * q[1] end function kubo_oscillator_sde_B(B::AbstractMatrix, t, q, params) @unpack ν = params for j in axes(B, 2) B[1,j] = +ν * q[2] B[2,j] = -ν * q[1] end end function kubo_oscillator_sde_1(q₀=q_init_A; tspan = tspan, tstep = Δt, parameters = default_parameters) # q_init_A - interpreted as one random initial conditions with one sample path # 1-dimensional noise SDEProblem(1, 1, kubo_oscillator_sde_v, kubo_oscillator_sde_B, tspan, tstep, q₀; parameters = parameters) end function kubo_oscillator_sde_2(q₀=q_init_A; tspan = tspan, tstep = Δt, parameters = default_parameters) # q_init_A - single deterministic initial condition # Generating 3 sample paths # 1-dimensional noise SDEProblem(1, 3, kubo_oscillator_sde_v, kubo_oscillator_sde_B, tspan, tstep, q₀; parameters = parameters) end function kubo_oscillator_sde_3(q₀=q_init_B; tspan = tspan, tstep = Δt, parameters = default_parameters) # q_init_B - interpreted as three random initial conditions # The 3 columns correspond to 3 sample paths # 1-dimensional noise SDEProblem(1, 1, kubo_oscillator_sde_v, kubo_oscillator_sde_B, tspan, tstep, q₀; parameters = parameters) end # ODE function kubo_oscillator_ode(q₀=q_init_A; tspan = tspan, tstep = Δt, parameters = default_parameters) ODEProblem(kubo_oscillator_sde_v, tspan, tstep, q₀; parameters = parameters) end # PSDE q_init_C=[0.5] p_init_C=[0.0] q_init_D=[[0.5], [0.0], [-0.5]] p_init_D=[[0.0], [0.5], [ 0.0]] function kubo_oscillator_psde_v(v, t, q, p, params) v[1] = p[1] end function kubo_oscillator_psde_f(f, t, q, p, params) f[1] = -q[1] end function kubo_oscillator_psde_B(B, t, q, p, params) @unpack ν = params B[1,1] = +ν * p[1] end function kubo_oscillator_psde_G(G, t, q, p, params) @unpack ν = params G[1,1] = -ν * q[1] end function kubo_oscillator_psde_1(q₀=q_init_C, p₀=p_init_C; tspan = tspan, tstep = Δt, parameters = default_parameters) # q_init_C - interpreted as a single random initial condition with one sample path # 1-dimensional noise PSDEProblem(1, 1, kubo_oscillator_psde_v, kubo_oscillator_psde_f, kubo_oscillator_psde_B, kubo_oscillator_psde_G, tspan, tstep, q₀, p₀; parameters = parameters) end function kubo_oscillator_psde_2(q₀=q_init_C, p₀=p_init_C; tspan = tspan, tstep = Δt, parameters = default_parameters) # q_init_C - single deterministic initial condition # Generating 3 sample paths # 1-dimensional noise PSDEProblem(1, 3, kubo_oscillator_psde_v, kubo_oscillator_psde_f, kubo_oscillator_psde_B, kubo_oscillator_psde_G, tspan, tstep, q₀, p₀; parameters = parameters) end function kubo_oscillator_psde_3(q₀=q_init_D, p₀=p_init_D; tspan = tspan, tstep = Δt, parameters = default_parameters) # q_init_D - interpreted as a single random initial condition # The 3 columns correspond to 3 sample paths # 1-dimensional noise PSDEProblem(1, 1, kubo_oscillator_psde_v, kubo_oscillator_psde_f, kubo_oscillator_psde_B, kubo_oscillator_psde_G, tspan, tstep, q₀, p₀; parameters = parameters) end # SPSDE function kubo_oscillator_spsde_v(v, t, q, p, params) v[1] = p[1] end function kubo_oscillator_spsde_f1(f, t, q, p, params) f[1] = -q[1] end function kubo_oscillator_spsde_f2(f, t, q, p, params) f[1] = 0 end function kubo_oscillator_spsde_B(B, t, q, p, params) @unpack ν = params B[1,1] = +ν * p[1] end function kubo_oscillator_spsde_G1(G, t, q, p, params) @unpack ν = params G[1,1] = -ν * q[1] end function kubo_oscillator_spsde_G2(G, t, q, p, params) G[1,1] = 0 end function kubo_oscillator_spsde_1(q₀ = q_init_C, p₀ = p_init_C; tspan = tspan, tstep = Δt, parameters = default_parameters) # q_init_C - interpreted as a single random initial condition with one sample path # 1-dimensional noise SPSDEProblem(1, 1, kubo_oscillator_spsde_v, kubo_oscillator_spsde_f1, kubo_oscillator_spsde_f2, kubo_oscillator_spsde_B, kubo_oscillator_spsde_G1, kubo_oscillator_spsde_G2, tspan, tstep, q₀, p₀; parameters = parameters) end function kubo_oscillator_spsde_2(q₀ = q_init_C, p₀ = p_init_C; tspan = tspan, tstep = Δt, parameters = default_parameters) # q_init_C - single deterministic initial condition # Generating 3 sample paths # 1-dimensional noise SPSDEProblem(1, 3, kubo_oscillator_spsde_v, kubo_oscillator_spsde_f1, kubo_oscillator_spsde_f2, kubo_oscillator_spsde_B, kubo_oscillator_spsde_G1, kubo_oscillator_spsde_G2, tspan, tstep, q₀, p₀; parameters = parameters) end function kubo_oscillator_spsde_3(q₀ = q_init_D, p₀ = p_init_D; tspan = tspan, tstep = Δt, parameters = default_parameters) # q_init_D - interpreted as a single random initial condition # The 3 columns correspond to 3 sample paths # 1-dimensional noise SPSDEProblem(1, 1, kubo_oscillator_spsde_v, kubo_oscillator_spsde_f1, kubo_oscillator_spsde_f2, kubo_oscillator_spsde_B, kubo_oscillator_spsde_G1, kubo_oscillator_spsde_G2, tspan, tstep, q₀, p₀; parameters = parameters) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
77
@doc raw""" """ module LennardJonesOscillator export hamiltonian end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
2333
@doc raw""" The discretized version of the 1d linear wave equation. It is a prime example of a non-trivial completely integrable system. The only system parameters are the *number of points* ``N`` for which the system is discretized and ``\mu``. """ module LinearWave using EulerLagrange using LinearAlgebra using Parameters export hamiltonian, lagrangian export hodeproblem, lodeproblem include("bump_initial_condition.jl") const μ̃ = .6 const Ñ = 256 const default_parameters = (μ = μ̃, N = Ñ) function hamiltonian(t, q, p, parameters) @unpack N, μ = parameters Δx = one(μ) / (Ñ + 1) Δx² = Δx ^ 2 μ² = μ ^ 2 sum(p[n] ^ 2 / 2 for n in 1 : (Ñ + 2)) + sum(μ² / 4Δx² * ((q[i] - q[i - 1]) ^ 2 + (q[i + 1] - q[i]) ^ 2) for i in 2 : (Ñ + 1)) end function lagrangian(t, q, q̇, parameters) @unpack N, μ = parameters Δx = one(μ) / (Ñ + 1) Δx² = Δx ^ 2 μ² = μ ^ 2 sum(q̇[n] ^ 2 / 2 for n in 1 : (Ñ + 2)) - sum(μ² / 4Δx² * ((q[i] - q[i - 1]) ^ 2 + (q[i + 1] - q[i]) ^ 2) for i in 2 : (Ñ + 1)) end _tstep(tspan::Tuple, n_time_steps::Integer) = (tspan[2] - tspan[1]) / (n_time_steps-1) const tspan = (0, 1) const n_time_steps = 200 const tstep = _tstep(tspan, n_time_steps) const q₀ = compute_initial_condition2(μ̃, Ñ + 2).q const p₀ = compute_initial_condition2(μ̃, Ñ + 2).p """ Hamiltonian problem for the linear wave equation. """ function hodeproblem(q₀ = q₀, p₀ = p₀; tspan = tspan, tstep = tstep, parameters = default_parameters) t, q, p = hamiltonian_variables(Ñ + 2) sparams = symbolize(parameters) ham_sys = HamiltonianSystem(hamiltonian(t, q, p, sparams), t, q, p, sparams) HODEProblem(ham_sys, tspan, tstep, q₀, p₀; parameters = parameters) end """ Lagrangian problem for the linear wave equation. """ function lodeproblem(q₀ = q₀, p₀ = p₀; tspan = tspan, tstep = tstep, parameters = default_parameters) t, x, v = lagrangian_variables(Ñ + 2) sparams = symbolize(parameters) lag_sys = LagrangianSystem(lagrangian(t, x, v, sparams), t, x, v, sparams) lodeproblem(lag_sys, tspan, tstep, q₀, p₀; parameters = parameters) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
807
@doc raw""" # Lorenz Attractor """ module LorenzAttractor using GeometricEquations export lorenz_attractor_ode, plot_lorenz_attractor const Δt = 0.01 const nt = 1000 const tspan = (0.0, Δt*nt) const q₀ = [1., 1., 1.] const default_parameters = (σ = 10., ρ = 28., β = 8/3) const reference_solution = [-4.902687541134471, -3.743872921802973, 24.690858102790042] function lorenz_attractor_v(v, t, x, params) σ, ρ, β = params v[1] = σ * (x[2] - x[1]) v[2] = x[1] * (ρ - x[3]) - x[2] v[3] = x[1] * x[2] - β * x[3] nothing end function lorenz_attractor_ode(q₀=q₀; tspan = tspan, tstep = Δt, parameters = default_parameters) ODEProblem(lorenz_attractor_v, tspan, tstep, q₀; parameters = parameters) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
3192
@doc raw""" # Lotka-Volterra model in 2D ```math \begin{aligned} L (q, \dot{q}) &= \bigg( q_2 + \frac{\log q_2}{q_1} \bigg) \, \dot{q_1} + q_1 \, \dot{q_2} - H(q) , \\ H(q) &= a_1 \, q_1 + a_2 \, q_2 + b_1 \, \log q_1 + b_2 \, \log q_2 \end{aligned} ``` """ module LotkaVolterra2d export iodeproblem_dg_gauge ϑ₁(t, q) = q[2] + log(q[2]) / q[1] ϑ₂(t, q) = q[1] dϑ₁dx₁(t, q) = - log(q[2]) / q[1]^2 dϑ₁dx₂(t, q) = 1 + 1 / (q[1] * q[2]) dϑ₂dx₁(t, q) = one(eltype(q)) dϑ₂dx₂(t, q) = zero(eltype(q)) include("lotka_volterra_2d_common.jl") include("lotka_volterra_2d_equations.jl") function d²ϑ₁d₁d₁(t, q) + 2 * log(q[2]) / q[1]^3 end function d²ϑ₁d₁d₂(t, q) - 1 / (q[1]^2 * q[2]) end function d²ϑ₁d₂d₁(t, q) - 1 / (q[1]^2 * q[2]) end function d²ϑ₁d₂d₂(t, q) - 1 / (q[1] * q[2]^2) end function d²ϑ₂d₁d₁(t, q) zero(eltype(q)) end function d²ϑ₂d₁d₂(t, q) zero(eltype(q)) end function d²ϑ₂d₂d₁(t, q) zero(eltype(q)) end function d²ϑ₂d₂d₂(t, q) zero(eltype(q)) end function g̅₁(t, q, v) d²ϑ₁d₁d₁(t,q) * q[1] * v[1] + d²ϑ₁d₂d₁(t,q) * q[1] * v[2] + d²ϑ₂d₁d₁(t,q) * q[2] * v[1] + d²ϑ₂d₂d₁(t,q) * q[2] * v[2] end function g̅₂(t, q, v) d²ϑ₁d₁d₂(t,q) * q[1] * v[1] + d²ϑ₁d₂d₂(t,q) * q[1] * v[2] + d²ϑ₂d₁d₂(t,q) * q[2] * v[1] + d²ϑ₂d₂d₂(t,q) * q[2] * v[2] end function lotka_volterra_2d_ϑ_κ(Θ, t, q, v, params, κ) Θ[1] = (1-κ) * ϑ₁(t,q) - κ * f₁(t,q,q) Θ[2] = (1-κ) * ϑ₂(t,q) - κ * f₂(t,q,q) nothing end function lotka_volterra_2d_f_κ(f::AbstractVector, t::Real, q::AbstractVector, v::AbstractVector, params, κ::Real) f[1] = (1-κ) * f₁(t,q,v) - κ * (g₁(t,q,v) + g̅₁(t,q,v)) - dHd₁(t, q, params) f[2] = (1-κ) * f₂(t,q,v) - κ * (g₂(t,q,v) + g̅₂(t,q,v)) - dHd₂(t, q, params) nothing end function lotka_volterra_2d_g_κ(g::AbstractVector, t::Real, q::AbstractVector, v::AbstractVector, params, κ::Real) g[1] = (1-κ) * f₁(t,q,v) - κ * (g₁(t,q,v) + g̅₁(t,q,v)) g[2] = (1-κ) * f₂(t,q,v) - κ * (g₂(t,q,v) + g̅₂(t,q,v)) nothing end # function lotka_volterra_2d_g(κ::Real, t::Real, q::AbstractVector, v::AbstractVector, g::AbstractVector) # g[1] = (1-κ) * g₁(t,q,v) - κ * g̅₁(t,q,v) - κ * f₁(t,q,v) # g[2] = (1-κ) * g₂(t,q,v) - κ * g̅₂(t,q,v) - κ * f₂(t,q,v) # nothing # end function iodeproblem_dg_gauge(q₀=q₀, p₀=ϑ(t₀, q₀); tspan=tspan, tstep=Δt, parameters=default_parameters, κ=0) lotka_volterra_2d_ϑ = (p, t, q, v, params) -> lotka_volterra_2d_ϑ_κ(p, t, q, v, params, κ) lotka_volterra_2d_f = (f, t, q, v, params) -> lotka_volterra_2d_f_κ(f, t, q, v, params, κ) lotka_volterra_2d_g = (g, t, q, λ, params) -> lotka_volterra_2d_g_κ(g, t, q, λ, params, κ) IODEProblem(lotka_volterra_2d_ϑ, lotka_volterra_2d_f, lotka_volterra_2d_g, tspan, tstep, q₀, p₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_2d_v) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
5260
using Parameters export ϑ, ω, hamiltonian function ϑ(Θ::AbstractVector, t::Number, q::AbstractVector) Θ[1] = ϑ₁(t,q) Θ[2] = ϑ₂(t,q) nothing end function ϑ(t::Number, q::AbstractVector) [ϑ₁(t,q), ϑ₂(t,q)] end function ϑ(t::Number, q::AbstractVector, k::Int) if k == 1 ϑ₁(t, q) elseif k == 2 ϑ₂(t, q) else throw(BoundsError(ϑ,k)) end end ϑ(t::Number, q::AbstractVector, params::NamedTuple, k::Int) = ϑ(t,q,k) function lotka_volterra_2d_pᵢ(qᵢ, tᵢ=0) pᵢ = zero(qᵢ) if ndims(qᵢ) == 1 ϑ(pᵢ, tᵢ, qᵢ) else for i in axes(qᵢ,2) ϑ((@view pᵢ[:,i]), tᵢ, (@view qᵢ[:,i])) end end pᵢ end function ω(Ω, t, q) Ω[1,1] = 0 Ω[1,2] = dϑ₁dx₂(t,q) - dϑ₂dx₁(t,q) Ω[2,1] = dϑ₂dx₁(t,q) - dϑ₁dx₂(t,q) Ω[2,2] = 0 nothing end function hamiltonian(t, q, params) @unpack a₁, a₂, b₁, b₂ = params a₁*q[1] + a₂*q[2] + b₁*log(q[1]) + b₂*log(q[2]) end hamiltonian_iode(t, q, params) = hamiltonian(t, q, params) # This is a workaround. It should be removed asap. hamiltonian_iode(t, q, v, params) = hamiltonian(t, q, params) hamiltonian_pode(t, q, p, params) = hamiltonian(t, q, params) function lagrangian(t, q, v, params) ϑ₁(t,q) * v[1] + ϑ₂(t,q) * v[2] - hamiltonian(t, q, params) end function dHd₁(t, q, params) @unpack a₁, b₁ = params a₁ + b₁ / q[1] end function dHd₂(t, q, params) @unpack a₂, b₂ = params a₂ + b₂ / q[2] end function v₁(t, q, params) @unpack a₁, a₂, b₁, b₂ = params + q[1] * (a₂*q[2] + b₂) end function v₂(t, q, params) @unpack a₁, a₂, b₁, b₂ = params - q[2] * (a₁*q[1] + b₁) end f₁(t, q, v) = dϑ₁dx₁(t,q) * v[1] + dϑ₂dx₁(t,q) * v[2] f₂(t, q, v) = dϑ₁dx₂(t,q) * v[1] + dϑ₂dx₂(t,q) * v[2] g₁(t, q, v) = dϑ₁dx₁(t,q) * v[1] + dϑ₁dx₂(t,q) * v[2] g₂(t, q, v) = dϑ₂dx₁(t,q) * v[1] + dϑ₂dx₂(t,q) * v[2] lotka_volterra_2d_ϑ(Θ, t, q, params) = ϑ(Θ, t, q) lotka_volterra_2d_ϑ(Θ, t, q, v, params) = ϑ(Θ, t, q) lotka_volterra_2d_ω(Ω, t, q, params) = ω(Ω, t, q) lotka_volterra_2d_ω(Ω, t, q, v, params) = ω(Ω, t, q) function lotka_volterra_2d_dH(dH, t, q, params) dH[1] = dHd₁(t, q, params) dH[2] = dHd₂(t, q, params) nothing end function lotka_volterra_2d_v(v, t, q, params) v[1] = v₁(t, q, params) v[2] = v₂(t, q, params) nothing end function lotka_volterra_2d_v(v, t, q, p, params) lotka_volterra_2d_v(v, t, q, params) end function lotka_volterra_2d_v_ham(v, t, q, p, params) v .= 0 nothing end function lotka_volterra_2d_v_dae(v, t, q, params) v[1] = v[3] v[2] = v[4] v[3] = 0 v[4] = 0 nothing end function lotka_volterra_2d_f(f::AbstractVector, t::Real, q::AbstractVector, v::AbstractVector, params) f[1] = f₁(t,q,v) - dHd₁(t, q, params) f[2] = f₂(t,q,v) - dHd₂(t, q, params) nothing end function lotka_volterra_2d_f_ham(f::AbstractVector, t::Real, q::AbstractVector, params) f[1] = - dHd₁(t, q, params) f[2] = - dHd₂(t, q, params) nothing end function lotka_volterra_2d_f_ham(f::AbstractVector, t::Real, q::AbstractVector, v::AbstractVector, params) lotka_volterra_2d_f_ham(f, t, q, params) end function lotka_volterra_2d_g(g::AbstractVector, t::Real, q::AbstractVector, v::AbstractVector, params) g[1] = f₁(t,q,v) g[2] = f₂(t,q,v) nothing end lotka_volterra_2d_g(g, t, q, p, λ, params) = lotka_volterra_2d_g(g, t, q, λ, params) lotka_volterra_2d_g(g, t, q, v, p, λ, params) = lotka_volterra_2d_g(g, t, q, p, λ, params) function lotka_volterra_2d_ḡ(g::AbstractVector, t::Real, q::AbstractVector, v::AbstractVector, params) g[1] = g₁(t,q,v) g[2] = g₂(t,q,v) nothing end lotka_volterra_2d_ḡ(g, t, q, p, λ, params) = lotka_volterra_2d_ḡ(g, t, q, λ, params) lotka_volterra_2d_ḡ(g, t, q, v, p, λ, params) = lotka_volterra_2d_ḡ(g, t, q, p, λ, params) function lotka_volterra_2d_u_dae(u, t, q, λ, params) u[1] = 0 u[2] = 0 u[3] = λ[1] u[4] = λ[2] nothing end function lotka_volterra_2d_u(u, t, q, λ, params) u .= λ nothing end lotka_volterra_2d_u(u, t, q, p, λ, params) = lotka_volterra_2d_u(u, t, q, λ, params) lotka_volterra_2d_u(u, t, q, v, p, λ, params) = lotka_volterra_2d_u(u, t, q, p, λ, params) function lotka_volterra_2d_ū(u, t, q, λ, params) u .= λ nothing end lotka_volterra_2d_ū(u, t, q, p, λ, params) = lotka_volterra_2d_ū(u, t, q, λ, params) lotka_volterra_2d_ū(u, t, q, v, p, λ, params) = lotka_volterra_2d_ū(u, t, q, p, λ, params) function lotka_volterra_2d_ϕ_dae(ϕ, t, q, params) ϕ[1] = q[3] - v₁(t,q,params) ϕ[2] = q[4] - v₂(t,q,params) nothing end function lotka_volterra_2d_ϕ(ϕ, t, q, p, params) ϕ[1] = p[1] - ϑ₁(t,q) ϕ[2] = p[2] - ϑ₂(t,q) nothing end lotka_volterra_2d_ϕ(ϕ, t, q, v, p, params) = lotka_volterra_2d_ϕ(ϕ, t, q, p, params) function lotka_volterra_2d_ψ(ψ, t, q, p, q̇, ṗ, params) ψ[1] = ṗ[1] - g₁(t,q,q̇) ψ[2] = ṗ[2] - g₂(t,q,q̇) nothing end lotka_volterra_2d_ψ(ψ, t, q, v, p, q̇, ṗ, params) = lotka_volterra_2d_ψ(ψ, t, q, p, q̇, ṗ, params) function lotka_volterra_2d_ψ_lode(ψ, t, q, v, p, q̇, ṗ, params) ψ[1] = f₁(t,q,v) - g₁(t,q,v) - dHd₁(t, q, params) ψ[2] = f₂(t,q,v) - g₂(t,q,v) - dHd₂(t, q, params) nothing end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
7446
using GeometricEquations using Requires import ..Diagnostics: compute_invariant_error export odeproblem, daeproblem, podeproblem, pdaeproblem, iodeproblem, idaeproblem, lodeproblem, ldaeproblem, hodeproblem, hdaeproblem, iodeproblem_dg, ldaeproblem_slrk, idaeproblem_spark export ode_poincare_invariant_1st, iode_poincare_invariant_1st export compute_energy_error const Δt = 0.01 const nt = 1000 const tspan = (0.0, Δt*nt) const default_parameters = (a₁=-1.0, a₂=-1.0, b₁=1.0, b₂=2.0) const reference_solution = [2.576489958858641, 1.5388112243762107] const t₀ = tspan[begin] const q₀ = [2.0, 1.0] const v₀ = [v₁(0, q₀, default_parameters), v₂(0, q₀, default_parameters)] function f_loop(s) rx = 0.2 ry = 0.3 x0 = 1.0 y0 = 1.0 xs = x0 + rx*cos(2π*s) ys = y0 + ry*sin(2π*s) qs = [xs, ys] return qs end function f_loop(i, n) f_loop(i/n) end function initial_conditions_loop(n) q₀ = zeros(2, n) for i in axes(q₀,2) q₀[:,i] .= f_loop(i, n) end return q₀ end compute_energy_error(t,q,params) = compute_invariant_error(t,q, (t,q) -> hamiltonian(t,q,params)) "Creates an ODE object for the Lotka-Volterra 2D model." function odeproblem(q₀=q₀; tspan=tspan, tstep=Δt, parameters=default_parameters) ODEProblem(lotka_volterra_2d_v, tspan, tstep, q₀; parameters=parameters, invariants=(h=hamiltonian,)) end "Creates a Hamiltonian ODE object for the Lotka-Volterra 2D model." function hodeproblem(q₀=q₀, p₀=ϑ(t₀, q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) HODEProblem(lotka_volterra_2d_v, lotka_volterra_2d_f, hamiltonian_pode, tspan, tstep, q₀, p₀; parameters=parameters) end "Creates an implicit ODE object for the Lotka-Volterra 2D model." function iodeproblem(q₀=q₀, p₀=ϑ(t₀, q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) IODEProblem(lotka_volterra_2d_ϑ, lotka_volterra_2d_f, lotka_volterra_2d_g, tspan, tstep, q₀, p₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_2d_v) end "Creates a partitioned ODE object for the Lotka-Volterra 2D model." function podeproblem(q₀=q₀, p₀=ϑ(t₀, q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) PODEProblem(lotka_volterra_2d_v, lotka_volterra_2d_f, tspan, tstep, q₀, p₀; parameters=parameters, invariants=(h=hamiltonian_pode,)) end "Creates a variational ODE object for the Lotka-Volterra 2D model." function lodeproblem(q₀=q₀, p₀=ϑ(t₀, q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) LODEProblem(lotka_volterra_2d_ϑ, lotka_volterra_2d_f, lotka_volterra_2d_g, lagrangian, lotka_volterra_2d_ω, tspan, tstep, q₀, p₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_2d_v) end "Creates a DAE object for the Lotka-Volterra 2D model." function daeproblem(q₀=vcat(q₀,v₀), λ₀=zero(q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) DAEProblem(lotka_volterra_2d_v_dae, lotka_volterra_2d_u_dae, lotka_volterra_2d_ϕ_dae, tspan, tstep, q₀, λ₀; parameters=parameters, invariants=(h=hamiltonian,)) end "Creates a Hamiltonian DAE object for the Lotka-Volterra 2D model." function hdaeproblem(q₀=q₀, p₀=ϑ(t₀, q₀), λ₀=zero(q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) HDAEProblem(lotka_volterra_2d_v, lotka_volterra_2d_f, lotka_volterra_2d_u, lotka_volterra_2d_g, lotka_volterra_2d_ϕ, lotka_volterra_2d_ū, lotka_volterra_2d_ḡ, lotka_volterra_2d_ψ, hamiltonian_pode, tspan, tstep, q₀, p₀, λ₀; parameters=parameters) end "Creates an implicit DAE object for the Lotka-Volterra 2D model." function idaeproblem(q₀=q₀, p₀=ϑ(t₀, q₀), λ₀=zero(q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) IDAEProblem(lotka_volterra_2d_ϑ, lotka_volterra_2d_f, lotka_volterra_2d_u, lotka_volterra_2d_g, lotka_volterra_2d_ϕ, tspan, tstep, q₀, p₀, λ₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_2d_v) end "Creates an implicit DAE object for the Lotka-Volterra 2D model." function idaeproblem_spark(q₀=q₀, p₀=ϑ(t₀, q₀), λ₀=zero(q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) IDAEProblem(lotka_volterra_2d_ϑ, lotka_volterra_2d_f_ham, lotka_volterra_2d_u, lotka_volterra_2d_g, lotka_volterra_2d_ϕ, tspan, tstep, q₀, p₀, λ₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_2d_v, f̄=lotka_volterra_2d_f) end "Creates a partitioned DAE object for the Lotka-Volterra 2D model." function pdaeproblem(q₀=q₀, p₀=ϑ(t₀, q₀), λ₀=zero(q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) PDAEProblem(lotka_volterra_2d_v_ham, lotka_volterra_2d_f_ham, lotka_volterra_2d_u, lotka_volterra_2d_g, lotka_volterra_2d_ϕ, tspan, tstep, q₀, p₀, λ₀; parameters=parameters, invariants=(h=hamiltonian_pode,), v̄=lotka_volterra_2d_v, f̄=lotka_volterra_2d_f) end "Creates a variational DAE object for the Lotka-Volterra 2D model." function ldaeproblem(q₀=q₀, p₀=ϑ(t₀, q₀), λ₀=zero(q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) LDAEProblem(lotka_volterra_2d_ϑ, lotka_volterra_2d_f_ham, lotka_volterra_2d_u, lotka_volterra_2d_g, lotka_volterra_2d_ϕ, lotka_volterra_2d_ū, lotka_volterra_2d_ḡ, lotka_volterra_2d_ψ_lode, lagrangian, lotka_volterra_2d_ω, tspan, tstep, q₀, p₀, λ₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_2d_v, f̄=lotka_volterra_2d_f) end "Creates a variational DAE object for the Lotka-Volterra 2D model for use with SLRK integrators." function ldaeproblem_slrk(q₀=q₀, p₀=ϑ(t₀, q₀), λ₀=zero(q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) LDAEProblem(lotka_volterra_2d_ϑ, lotka_volterra_2d_f, lotka_volterra_2d_u, lotka_volterra_2d_g, lotka_volterra_2d_ϕ, lotka_volterra_2d_ū, lotka_volterra_2d_ḡ, lotka_volterra_2d_ψ, lagrangian, lotka_volterra_2d_ω, tspan, tstep, q₀, p₀, λ₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_2d_v, f̄=lotka_volterra_2d_f) end "Creates an implicit ODE object for the Lotka-Volterra 2D model for use with DG integrators." function iodeproblem_dg(q₀=q₀, p₀=ϑ(t₀, q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) IODEProblem(lotka_volterra_2d_ϑ, lotka_volterra_2d_f, lotka_volterra_2d_g, tspan, tstep, q₀, p₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_2d_v) end function ode_loop(n) lotka_volterra_2d_ode(initial_conditions_loop(n)) end function iode_loop(n) lotka_volterra_2d_iode(initial_conditions_loop(n)) end function __init__() @require PoincareInvariants = "26663084-47d3-540f-bd97-40ca743aafa4" begin function ode_poincare_invariant_1st(tstep, nloop, ntime, nsave, DT=Float64) PoincareInvariant1st(lotka_volterra_2d_ode, f_loop, ϑ, tstep, 2, nloop, ntime, nsave, DT) end function iode_poincare_invariant_1st(tstep, nloop, ntime, nsave, DT=Float64) PoincareInvariant1st(lotka_volterra_2d_iode, f_loop, ϑ, tstep, 2, nloop, ntime, nsave, DT) end end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
992
@doc raw""" # Lotka-Volterra model in 2D with symmetric Lagrangian with gauge term ```math \begin{aligned} L (q, \dot{q}) &= \bigg( q_2 + \frac{1}{2} \frac{\log q_2}{q_1} \bigg) \, \dot{q_1} + \bigg( q_1 - \frac{1}{2} \frac{\log q_1}{q_2} \bigg) \, \dot{q_2} - H(q) , \\ H(q) &= a_1 \, q_1 + a_2 \, q_2 + b_1 \, \log q_1 + b_2 \, \log q_2 \end{aligned} ``` This Lagrangian is equivalent to the Lagrangian of the symmetric Lotka-Volterra model. It differs only by a gauge transformation with the term ``d(q_1 q_2)/dt``. It leads to the same Euler-Lagrange equations but to a different variational integrator. """ module LotkaVolterra2dGauge ϑ₁(t, q) = + log(q[2]) / q[1] / 2 ϑ₂(t, q) = - log(q[1]) / q[2] / 2 dϑ₁dx₁(t, q) = - log(q[2]) / q[1]^2 / 2 dϑ₁dx₂(t, q) = + 1 / (q[1] * q[2]) / 2 dϑ₂dx₁(t, q) = - 1 / (q[2] * q[1]) / 2 dϑ₂dx₂(t, q) = + log(q[1]) / q[2]^2 / 2 include("lotka_volterra_2d_common.jl") include("lotka_volterra_2d_equations.jl") end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
6527
module LotkaVolterra2dPlots using GeometricEquations using GeometricSolutions using GeometricProblems.Diagnostics using LaTeXStrings using Measures: mm using RecipesBase """ Plots the solution of a 2D Lotka-Volterra model together with the energy error. Arguments: * `sol <: GeometricSolution` * `equ <: GeometricProblem` Keyword aguments: * `nplot=1`: plot every `nplot`th time step * `xlims=:auto`: xlims for solution plot * `ylims=:auto`: ylims for solution plot * `latex=true`: use LaTeX guides """ @userplot Plot_Lotka_Volterra_2d @recipe function f(p::Plot_Lotka_Volterra_2d; nplot=1, nt=:auto, xlims=:auto, ylims=:auto, latex=true) if length(p.args) != 2 || !(typeof(p.args[1]) <: GeometricSolution) || !(typeof(p.args[2]) <: GeometricProblem) error("Lotka-Volterra plot should be given two arguments: a solution and an equation. Got: $(typeof(p.args))") end sol = p.args[1] equ = p.args[2] params = equ.parameters if nt == :auto nt = ntime(sol) end if nt > ntime(sol) nt = ntime(sol) end H, ΔH = compute_invariant_error(sol.t, sol.q, (t,q) -> invariants(equ)[:h](t,q,params)) size := (1000,400) layout := (1,2) legend := :none right_margin := 10mm bottom_margin := 10mm guidefontsize := 18 tickfontsize := 12 @series begin subplot := 1 left_margin := 10mm if ntime(sol) ≤ 200 markersize := 5 else markersize := 1 markercolor := 1 linecolor := 1 markerstrokewidth := 1 markerstrokecolor := 1 end # seriestype := :scatter if latex xguide := L"x_1" yguide := L"x_2" else xguide := "x₁" yguide := "x₂" end xlims := xlims ylims := ylims aspect_ratio := 1 sol.q[0:nplot:nt, 1], sol.q[0:nplot:nt, 2] end @series begin subplot := 2 if latex xguide := L"t" yguide := L"[H(t) - H(0)] / H(0)" else xguide := "t" yguide := "[H(t) - H(0)] / H(0)" end xlims := (sol.t[0], Inf) ylims := :auto yformatter := :scientific right_margin := 10mm sol.t[0:nplot:nt], ΔH[0:nplot:nt] end end """ Plots the solution of a 2D Lotka-Volterra model. Arguments: * `sol <: GeometricSolution` * `equ <: GeometricProblem` Keyword aguments: * `nplot=1`: plot every `nplot`th time step * `xlims=:auto`: xlims for solution plot * `ylims=:auto`: ylims for solution plot * `latex=true`: use LaTeX guides """ @userplot Plot_Lotka_Volterra_2d_Solution @recipe function f(p::Plot_Lotka_Volterra_2d_Solution; nplot=1, nt=:auto, xlims=:auto, ylims=:auto, latex=true) if length(p.args) != 2 || !(typeof(p.args[1]) <: GeometricSolution) || !(typeof(p.args[2]) <: GeometricProblem) error("Lotka-Volterra solution plot should be given two arguments: a solution and an equation. Got: $(typeof(p.args))") end sol = p.args[1] equ = p.args[2] params = equ.parameters if nt == :auto nt = ntime(sol) end if nt > ntime(sol) nt = ntime(sol) end if ntime(sol) ≤ 200 markersize := 5 else markersize := 1 markercolor := 1 linecolor := 1 markerstrokewidth := 1 markerstrokecolor := 1 end legend := :none size := (400,400) # solution @series begin # seriestype := :scatter if latex xguide := L"x_1" yguide := L"x_2" else xguide := "x₁" yguide := "x₂" end xlims := xlims ylims := ylims aspect_ratio := 1 guidefontsize := 18 tickfontsize := 12 sol.q[0:nplot:nt, 1], sol.q[0:nplot:nt, 2] end end """ Plots time traces of the solution of a 2D Lotka-Volterra model and its energy error. Arguments: * `sol <: GeometricSolution` * `equ <: GeometricProblem` Keyword aguments: * `nplot=1`: plot every `nplot`th time step * `latex=true`: use LaTeX guides """ @userplot Plot_Lotka_Volterra_2d_Traces @recipe function f(p::Plot_Lotka_Volterra_2d_Traces; nplot=1, nt=:auto, latex=true) if length(p.args) != 2 || !(typeof(p.args[1]) <: GeometricSolution) || !(typeof(p.args[2]) <: GeometricProblem) error("Lotka-Volterra traces plot should be given two arguments: a solution and an equation. Got: $(typeof(p.args))") end sol = p.args[1] equ = p.args[2] params = equ.parameters if nt == :auto nt = ntime(sol) end if nt > ntime(sol) nt = ntime(sol) end H, ΔH = compute_invariant_error(sol.t, sol.q, (t,q) -> invariants(equ)[:h](t,q,params)) size := (800,600) legend := :none guidefontsize := 18 tickfontsize := 12 # traces layout := (3,1) if latex ylabels = (L"x_1", L"x_2") else ylabels = ("x₁", "x₂") end for i in 1:2 @series begin subplot := i yguide := ylabels[i] xlims := (sol.t[0], Inf) xaxis := false right_margin := 10mm sol.t[0:nplot:nt], sol.q[0:nplot:nt, i] end end @series begin subplot := 3 if latex xguide := L"t" yguide := L"[H(t) - H(0)] / H(0)" else xguide := "t" yguide := "[H(t) - H(0)] / H(0)" end xlims := (sol.t[0], Inf) yformatter := :scientific guidefontsize := 18 tickfontsize := 12 right_margin := 10mm sol.t[0:nplot:nt], ΔH[0:nplot:nt] end end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
1094
@doc raw""" # Lotka-Volterra model in 2D with "singular" Lagrangian ```math \begin{aligned} L (q, \dot{q}) &= \frac{\log q_2}{q_1} \, \dot{q_1} - H(q) , \\ H(q) &= a_1 \, q_1 + a_2 \, q_2 + b_1 \, \log q_1 + b_2 \, \log q_2 \end{aligned} ``` This Lagrangian is equivalent to the Lagrangian of the symmetric Lotka-Volterra model. It differs only by a gauge transformation with the term ``- 1/2 \, d(\log(q_1) \log(q_2))/dt``. It leads to the same Euler-Lagrange equations but to a different variational integrator. """ module LotkaVolterra2dSingular ϑ₁(t, q) = + log(q[2]) / q[1] ϑ₂(t, q) = zero(eltype(q)) dϑ₁dx₁(t, q) = - log(q[2]) / q[1]^2 dϑ₁dx₂(t, q) = + 1 / (q[1] * q[2]) dϑ₂dx₁(t, q) = zero(eltype(q)) dϑ₂dx₂(t, q) = zero(eltype(q)) # ϑ₁(t, q) = zero(eltype(q)) # ϑ₂(t, q) = - log(q[1]) / q[2] # dϑ₁dx₁(t, q) = zero(eltype(q)) # dϑ₁dx₂(t, q) = zero(eltype(q)) # dϑ₂dx₁(t, q) = - 1 / (q[2] * q[1]) # dϑ₂dx₂(t, q) = + log(q[1]) / q[2]^2 include("lotka_volterra_2d_common.jl") include("lotka_volterra_2d_equations.jl") end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
924
@doc raw""" # Lotka-Volterra model in 2D with symmetric Lagrangian ```math \begin{aligned} L (q, \dot{q}) &= \frac{1}{2} \frac{\log q_2}{q_1} \, \dot{q_1} - \frac{1}{2} \frac{\log q_1}{q_2} \, \dot{q_2} - H(q) , \\ H(q) &= a_1 \, q_1 + a_2 \, q_2 + b_1 \, \log q_1 + b_2 \, \log q_2 \end{aligned} ``` This Lagrangian is a slight generalization of Equation (5) in José Fernández-Núñez, Lagrangian Structure of the Two-Dimensional Lotka-Volterra System, International Journal of Theoretical Physics, Vol. 37, No. 9, pp. 2457-2462, 1998. """ module LotkaVolterra2dSymmetric ϑ₁(t, q) = + log(q[2]) / q[1] / 2 ϑ₂(t, q) = - log(q[1]) / q[2] / 2 dϑ₁dx₁(t, q) = - log(q[2]) / q[1]^2 / 2 dϑ₁dx₂(t, q) = + 1 / (q[1] * q[2]) / 2 dϑ₂dx₁(t, q) = - 1 / (q[2] * q[1]) / 2 dϑ₂dx₂(t, q) = + log(q[1]) / q[2]^2 / 2 include("lotka_volterra_2d_common.jl") include("lotka_volterra_2d_equations.jl") end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
3716
@doc raw""" # Lotka-Volterra Model in 3D The Lotka–Volterra model in 3D is an example of a Hamiltonian system with degenerate Poisson structure. The equations read ```math \begin{aligned} \dot{q}_{1} &= q_{1} ( - a_{2} q_{2} + a_{3} q_{3} - b_{2} + b_{3} ) , \\ \dot{q}_{2} &= q_{2} ( \hphantom{-} a_{1} q_{1} - a_{3} q_{3} + b_{1} - b_{3} ) , \\ \dot{q}_{3} &= q_{3} ( - a_{1} q_{1} + a_{2} q_{2} - b_{1} + b_{2} ) , \\ \end{aligned} ``` which can be written in Poisson-form as ```math \dot{q} = P(q) \nabla H(q) , ``` with Poisson matrix ```math P(q) = \begin{pmatrix} 0 & - q_{1} q_{2} & \hphantom{-} q_{1} q_{3} \\ \hphantom{-} q_{1} q_{2} & 0 & - q_{2} q_{3} \\ - q_{1} q_{3} & \hphantom{-} q_{2} q_{3} & 0 \\ \end{pmatrix} , ``` and Hamiltonian ```math H(q) = a_{1} q_{1} + a_{2} q_{2} + a_{3} q_{3} + b_{1} \ln q_{1} + b_{2} \ln q_{2} + b_{3} \ln q_{3} . ``` References: * A. M. Perelomov. Selected topics on classical integrable systems, Troisième cycle de la physique, expanded version of lectures delivered in May 1995. * Yuri B. Suris. Integrable discretizations for lattice systems: local equations of motion and their Hamiltonian properties, Rev. Math. Phys. 11, pp. 727–822, 1999. """ module LotkaVolterra3d using GeometricBase using GeometricEquations using GeometricSolutions using Parameters export odeproblem export hamiltonian, casimir export compute_energy_error, compute_casimir_error const Δt = 0.01 const nt = 1000 const tspan = (0.0, Δt*nt) const default_parameters = (A1 = 1.0, A2 = 1.0, A3 = 1.0, B1 = 0.0, B2 = 1.0, B3 = 1.0) const reference_solution = [0.39947308320241187, 1.9479527336244262, 2.570183075433086] function v₁(t, q, params) @unpack A1, A2, A3, B1, B2, B3 = params q[1] * ( - A2 * q[2] + A3 * q[3] + B2 - B3) end function v₂(t, q, params) @unpack A1, A2, A3, B1, B2, B3 = params q[2] * ( + A1 * q[1] - A3 * q[3] - B1 + B3) end function v₃(t, q, params) @unpack A1, A2, A3, B1, B2, B3 = params q[3] * ( - A1 * q[1] + A2 * q[2] + B1 - B2) end const X₀ = 1.0 const Y₀ = 1.0 const Z₀ = 2.0 const q₀ = [X₀, Y₀, Z₀] const v₀ = [v₁(0, q₀, default_parameters), v₂(0, q₀, default_parameters), v₃(0, q₀, default_parameters)] function hamiltonian(t, q, params) @unpack A1, A2, A3, B1, B2, B3 = params A1*q[1] + A2*q[2] + A3*q[3] - B1*log(q[1]) - B2*log(q[2]) - B3*log(q[3]) end hamiltonian_iode(v, t, q, params) = hamiltonian(t, q, params) function casimir(t, q, params) log(q[1]) + log(q[2]) + log(q[3]) end function lotka_volterra_3d_v(v, t, q, params) v[1] = v₁(t, q, params) v[2] = v₂(t, q, params) v[3] = v₃(t, q, params) nothing end function odeproblem(q₀=q₀; tspan=tspan, tstep=Δt, parameters=default_parameters) ODEProblem(lotka_volterra_3d_v, tspan, tstep, q₀; parameters=parameters, invariants=(h=hamiltonian,)) end function compute_energy_error(t::TimeSeries, q::DataSeries{T}, params) where {T} h = DataSeries(T, ntime(q)) e = DataSeries(T, ntime(q)) for i in axes(q,1) h[i] = hamiltonian(t[i], q[i], params) e[i] = (h[i] - h[0]) / h[0] end (h, e) end function compute_casimir_error(t::TimeSeries, q::DataSeries{T}, params) where {T} c = DataSeries(T, ntime(q)) e = DataSeries(T, ntime(q)) for i in axes(q,1) c[i] = casimir(t[i], q[i], params) e[i] = (c[i] - c[0]) / c[0] end (c, e) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
1819
module LotkaVolterra3dPlots using LaTeXStrings using Measures: mm using RecipesBase import GeometricProblems.Diagnostics: compute_invariant_error, compute_momentum_error # export compute_energy_error, compute_momentum_error compute_energy_error(t,q,params) = compute_invariant_error(t,q, (t,q) -> hamiltonian(t,q,params)) # compute_momentum_error(t,q,p) = compute_momentum_error(t,q,p,ϑ) @userplot PlotLotkaVolterra3d @recipe function f(p::PlotLotkaVolterra3d; latex=true) # if length(p.args) != 2 || !(typeof(p.args[1][1]) <: Solution) || !(typeof(p.args[2]) <: NamedTuple) # error("Lotka-Volterra plots should be given a solution. Got: $(typeof(p.args))") # end sol = p.args[1] params = p.args[2] H, ΔH = compute_energy_error(sol.t, sol.q, params); size := (800,1200) legend := :none guidefontsize := 12 tickfontsize := 8 left_margin := 12mm right_margin := 8mm # traces layout := (4,1) if latex ylabels = (L"x_1", L"x_2", L"x_3") else ylabels = ("x₁", "x₂", "x₃") end for i in 1:3 @series begin subplot := i yguide := ylabels[i] xlims := (sol.t[0], Inf) xaxis := false sol.t, sol.q[i,:] end end @series begin subplot := 4 if latex xguide := L"t" yguide := L"[H(t) - H(0)] / H(0)" else xguide := "t" yguide := "[H(t) - H(0)] / H(0)" end xlims := (sol.t[0], Inf) yformatter := :scientific sol.t, ΔH end end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
14694
@doc raw""" """ module LotkaVolterra4d using GeometricEquations using Parameters export hamiltonian, ϑ, ϑ₁, ϑ₂, ω export odeproblem, podeproblem, pdaeproblem, iodeproblem, idaeproblem, lodeproblem, ldaeproblem, iodeproblem_dg const Δt = 0.01 const nt = 1000 const tspan = (0.0, Δt*nt) const q₀ = [2.0, 1.0, 1.0, 1.0] const default_parameters = (a₁=1.0, a₂=1.0, a₃=1.0, a₄=1.0, b₁=-1.0, b₂=-2.0, b₃=-1.0, b₄=-1.0) const reference_solution = [0.5988695239096916, 2.068567531039674, 0.2804351458645534, 1.258449091830993] # const q₀ = [2.0, 1.0, 2.0, 1.0] # const p = (a₁=1.0, a₂=1.0, a₃=1.0, a₄=1.0, b₁=-1.0, b₂=-2.0, b₃=-1.0, b₄=-2.0) # const q₀ = [2.0, 1.0, 2.0, 1.0] # const p = (a₁=1.0, a₂=1.0, a₃=1.0, a₄=1.0, b₁=-1.0, b₂=-4.0, b₃=-2.0, b₄=-3.0) ϑ₁(t, q) = 0.5 * ( + log(q[2]) - log(q[3]) + log(q[4]) ) / q[1] ϑ₂(t, q) = 0.5 * ( - log(q[1]) + log(q[3]) - log(q[4]) ) / q[2] ϑ₃(t, q) = 0.5 * ( + log(q[1]) - log(q[2]) + log(q[4]) ) / q[3] ϑ₄(t, q) = 0.5 * ( - log(q[1]) + log(q[2]) - log(q[3]) ) / q[4] # ϑ₁(t, q) = ( log(q[2]) + log(q[4]) ) / q[1] # ϑ₂(t, q) = ( log(q[3]) ) / q[2] # ϑ₃(t, q) = ( log(q[1]) + log(q[4]) ) / q[3] # ϑ₄(t, q) = ( log(q[2]) ) / q[4] # ϑ₁(t, q) = ( + log(q[2]) - log(q[3]) + log(q[4]) ) / q[1] / 2 + q[2] + q[3] + q[4] # ϑ₂(t, q) = ( - log(q[1]) + log(q[3]) - log(q[4]) ) / q[2] / 2 + q[1] + q[3] + q[4] # ϑ₃(t, q) = ( + log(q[1]) - log(q[2]) + log(q[4]) ) / q[3] / 2 + q[1] + q[2] + q[4] # ϑ₄(t, q) = ( - log(q[1]) + log(q[2]) - log(q[3]) ) / q[4] / 2 + q[1] + q[2] + q[3] # ϑ₁(t, q) = ( + log(q[2]) - log(q[3]) + log(q[4]) ) / q[1] # ϑ₂(t, q) = ( + log(q[3]) - log(q[4]) ) / q[2] # ϑ₃(t, q) = log(q[4]) / q[3] # ϑ₄(t, q) = zero(eltype(q)) function v₁(t, q, params) @unpack a₁, a₂, a₃, a₄, b₁, b₂, b₃, b₄ = params q[1] * (+ a₂*q[2] + a₃*q[3] + a₄*q[4] + b₂ + b₃ + b₄) end function v₂(t, q, params) @unpack a₁, a₂, a₃, a₄, b₁, b₂, b₃, b₄ = params q[2] * (- a₁*q[1] + a₃*q[3] + a₄*q[4] - b₁ + b₃ + b₄) end function v₃(t, q, params) @unpack a₁, a₂, a₃, a₄, b₁, b₂, b₃, b₄ = params q[3] * (- a₁*q[1] - a₂*q[2] + a₄*q[4] - b₁ - b₂ + b₄) end function v₄(t, q, params) @unpack a₁, a₂, a₃, a₄, b₁, b₂, b₃, b₄ = params q[4] * (- a₁*q[1] - a₂*q[2] - a₃*q[3] - b₁ - b₂ - b₃) end dϑ₁dx₁(t, q) = ( - log(q[2]) + log(q[3]) - log(q[4]) ) / q[1]^2 / 2 dϑ₁dx₂(t, q) = + 1 / (q[1] * q[2]) / 2 dϑ₁dx₃(t, q) = - 1 / (q[1] * q[3]) / 2 dϑ₁dx₄(t, q) = + 1 / (q[1] * q[4]) / 2 dϑ₂dx₁(t, q) = - 1 / (q[2] * q[1]) / 2 dϑ₂dx₂(t, q) = ( + log(q[1]) - log(q[3]) + log(q[4]) ) / q[2]^2 / 2 dϑ₂dx₃(t, q) = + 1 / (q[2] * q[3]) / 2 dϑ₂dx₄(t, q) = - 1 / (q[2] * q[4]) / 2 dϑ₃dx₁(t, q) = + 1 / (q[3] * q[1]) / 2 dϑ₃dx₂(t, q) = - 1 / (q[3] * q[2]) / 2 dϑ₃dx₃(t, q) = ( - log(q[1]) + log(q[2]) - log(q[4]) ) / q[3]^2 / 2 dϑ₃dx₄(t, q) = + 1 / (q[3] * q[4]) / 2 dϑ₄dx₁(t, q) = - 1 / (q[4] * q[1]) / 2 dϑ₄dx₂(t, q) = + 1 / (q[4] * q[2]) / 2 dϑ₄dx₃(t, q) = - 1 / (q[4] * q[3]) / 2 dϑ₄dx₄(t, q) = ( + log(q[1]) - log(q[2]) + log(q[3]) ) / q[4]^2 / 2 # dϑ₁dx₁(t, q) = - ( log(q[2]) + log(q[4]) ) / q[1]^2 # dϑ₁dx₂(t, q) = 1 / (q[1] * q[2]) # dϑ₁dx₃(t, q) = zero(eltype(q)) # dϑ₁dx₄(t, q) = 1 / (q[1] * q[4]) # dϑ₂dx₁(t, q) = zero(eltype(q)) # dϑ₂dx₂(t, q) = - ( log(q[3]) ) / q[2]^2 # dϑ₂dx₃(t, q) = 1 / (q[2] * q[3]) # dϑ₂dx₄(t, q) = zero(eltype(q)) # dϑ₃dx₁(t, q) = + 1 / (q[3] * q[1]) # dϑ₃dx₂(t, q) = zero(eltype(q)) # dϑ₃dx₃(t, q) = - ( log(q[1]) + log(q[4]) ) / q[3]^2 # dϑ₃dx₄(t, q) = + 1 / (q[3] * q[4]) # dϑ₄dx₁(t, q) = zero(eltype(q)) # dϑ₄dx₂(t, q) = 1 / (q[4] * q[2]) # dϑ₄dx₃(t, q) = zero(eltype(q)) # dϑ₄dx₄(t, q) = - ( log(q[2]) ) / q[4]^2 # dϑ₁dx₁(t, q) = ( - log(q[2]) + log(q[3]) - log(q[4]) ) / q[1]^2 / 2 # dϑ₁dx₂(t, q) = 1 + 1 / (q[1] * q[2]) / 2 # dϑ₁dx₃(t, q) = 1 - 1 / (q[1] * q[3]) / 2 # dϑ₁dx₄(t, q) = 1 + 1 / (q[1] * q[4]) / 2 # dϑ₂dx₁(t, q) = 1 - 1 / (q[2] * q[1]) / 2 # dϑ₂dx₂(t, q) = ( + log(q[1]) - log(q[3]) + log(q[4]) ) / q[2]^2 / 2 # dϑ₂dx₃(t, q) = 1 + 1 / (q[2] * q[3]) / 2 # dϑ₂dx₄(t, q) = 1 - 1 / (q[2] * q[4]) / 2 # dϑ₃dx₁(t, q) = 1 + 1 / (q[3] * q[1]) / 2 # dϑ₃dx₂(t, q) = 1 - 1 / (q[3] * q[2]) / 2 # dϑ₃dx₃(t, q) = ( - log(q[1]) + log(q[2]) - log(q[4]) ) / q[3]^2 / 2 # dϑ₃dx₄(t, q) = 1 + 1 / (q[3] * q[4]) / 2 # dϑ₄dx₁(t, q) = 1 - 1 / (q[4] * q[1]) / 2 # dϑ₄dx₂(t, q) = 1 + 1 / (q[4] * q[2]) / 2 # dϑ₄dx₃(t, q) = 1 - 1 / (q[4] * q[3]) / 2 # dϑ₄dx₄(t, q) = ( + log(q[1]) - log(q[2]) + log(q[3]) ) / q[4]^2 / 2 # dϑ₁dx₁(t, q) = ( - log(q[2]) + log(q[3]) - log(q[4]) ) / q[1]^2 # dϑ₁dx₂(t, q) = + 1 / (q[1] * q[2]) # dϑ₁dx₃(t, q) = - 1 / (q[1] * q[3]) # dϑ₁dx₄(t, q) = + 1 / (q[1] * q[4]) # dϑ₂dx₁(t, q) = zero(eltype(q)) # dϑ₂dx₂(t, q) = ( - log(q[3]) + log(q[4]) ) / q[2]^2 # dϑ₂dx₃(t, q) = + 1 / (q[2] * q[3]) # dϑ₂dx₄(t, q) = - 1 / (q[2] * q[4]) # dϑ₃dx₁(t, q) = zero(eltype(q)) # dϑ₃dx₂(t, q) = zero(eltype(q)) # dϑ₃dx₃(t, q) = ( - log(q[4]) ) / q[3]^2 # dϑ₃dx₄(t, q) = + 1 / (q[3] * q[4]) # dϑ₄dx₁(t, q) = zero(eltype(q)) # dϑ₄dx₂(t, q) = zero(eltype(q)) # dϑ₄dx₃(t, q) = zero(eltype(q)) # dϑ₄dx₄(t, q) = zero(eltype(q)) function ϑ(Θ::AbstractVector, t::Number, q::AbstractVector) Θ[1] = ϑ₁(t,q) Θ[2] = ϑ₂(t,q) Θ[3] = ϑ₃(t,q) Θ[4] = ϑ₄(t,q) nothing end function ϑ(t::Number, q::AbstractVector) Θ = zero(q) ϑ(Θ, t, q) return Θ end function ϑ(t::Number, q::AbstractVector, k::Int) if k == 1 ϑ₁(t, q) elseif k == 2 ϑ₂(t, q) elseif k == 3 ϑ₃(t, q) elseif k == 4 ϑ₄(t, q) else throw(BoundsError(ϑ,k)) end end function ω(Ω, t, q) Ω[1,1] = 0 Ω[1,2] = dϑ₁dx₂(t,q) - dϑ₂dx₁(t,q) Ω[1,3] = dϑ₁dx₃(t,q) - dϑ₃dx₁(t,q) Ω[1,4] = dϑ₁dx₄(t,q) - dϑ₄dx₁(t,q) Ω[2,1] = dϑ₂dx₁(t,q) - dϑ₁dx₂(t,q) Ω[2,2] = 0 Ω[2,3] = dϑ₂dx₃(t,q) - dϑ₃dx₂(t,q) Ω[2,4] = dϑ₂dx₄(t,q) - dϑ₄dx₂(t,q) Ω[3,1] = dϑ₃dx₁(t,q) - dϑ₁dx₃(t,q) Ω[3,2] = dϑ₃dx₂(t,q) - dϑ₂dx₃(t,q) Ω[3,3] = 0 Ω[3,4] = dϑ₃dx₄(t,q) - dϑ₄dx₃(t,q) Ω[4,1] = dϑ₄dx₁(t,q) - dϑ₁dx₄(t,q) Ω[4,2] = dϑ₄dx₂(t,q) - dϑ₂dx₄(t,q) Ω[4,3] = dϑ₄dx₃(t,q) - dϑ₃dx₄(t,q) Ω[4,4] = 0 nothing end f₁(t, q, v) = dϑ₁dx₁(t,q) * v[1] + dϑ₂dx₁(t,q) * v[2] + dϑ₃dx₁(t,q) * v[3] + dϑ₄dx₁(t,q) * v[4] f₂(t, q, v) = dϑ₁dx₂(t,q) * v[1] + dϑ₂dx₂(t,q) * v[2] + dϑ₃dx₂(t,q) * v[3] + dϑ₄dx₂(t,q) * v[4] f₃(t, q, v) = dϑ₁dx₃(t,q) * v[1] + dϑ₂dx₃(t,q) * v[2] + dϑ₃dx₃(t,q) * v[3] + dϑ₄dx₃(t,q) * v[4] f₄(t, q, v) = dϑ₁dx₄(t,q) * v[1] + dϑ₂dx₄(t,q) * v[2] + dϑ₃dx₄(t,q) * v[3] + dϑ₄dx₄(t,q) * v[4] g₁(t, q, v) = dϑ₁dx₁(t,q) * v[1] + dϑ₁dx₂(t,q) * v[2] + dϑ₁dx₃(t,q) * v[3] + dϑ₁dx₄(t,q) * v[4] g₂(t, q, v) = dϑ₂dx₁(t,q) * v[1] + dϑ₂dx₂(t,q) * v[2] + dϑ₂dx₃(t,q) * v[3] + dϑ₂dx₄(t,q) * v[4] g₃(t, q, v) = dϑ₃dx₁(t,q) * v[1] + dϑ₃dx₂(t,q) * v[2] + dϑ₃dx₃(t,q) * v[3] + dϑ₃dx₄(t,q) * v[4] g₄(t, q, v) = dϑ₄dx₁(t,q) * v[1] + dϑ₄dx₂(t,q) * v[2] + dϑ₄dx₃(t,q) * v[3] + dϑ₄dx₄(t,q) * v[4] function hamiltonian(t, q, params) @unpack a₁, a₂, a₃, a₄, b₁, b₂, b₃, b₄ = params a = [a₁, a₂, a₃, a₄] b = [b₁, b₂, b₃, b₄] sum(a .* q) + sum(b .* log.(q)) end hamiltonian_iode(t, q, v, params) = hamiltonian(t, q, params) hamiltonian_pode(t, q, p, params) = hamiltonian(t, q, params) function dHd₁(t, q, params) @unpack a₁, b₁ = params a₁ + b₁ / q[1] end function dHd₂(t, q, params) @unpack a₂, b₂ = params a₂ + b₂ / q[2] end function dHd₃(t, q, params) @unpack a₃, b₃ = params a₃ + b₃ / q[3] end function dHd₄(t, q, params) @unpack a₄, b₄ = params a₄ + b₄ / q[4] end function lotka_volterra_4d_dH(dH, t, q, params) dH[1] = dHd₁(t, q, params) dH[2] = dHd₂(t, q, params) dH[3] = dHd₃(t, q, params) dH[4] = dHd₄(t, q, params) nothing end lotka_volterra_4d_ϑ(Θ, t, q, params) = ϑ(Θ, t, q) lotka_volterra_4d_ϑ(Θ, t, q, v, params) = ϑ(Θ, t, q) lotka_volterra_4d_ω(Ω, t, q, params) = ω(Ω, t, q) function lotka_volterra_4d_v(v, t, q, params) v[1] = v₁(t, q, params) v[2] = v₂(t, q, params) v[3] = v₃(t, q, params) v[4] = v₄(t, q, params) nothing end function lotka_volterra_4d_v(v, t, q, p, params) lotka_volterra_4d_v(v, t, q, params) end function lotka_volterra_4d_v_ham(v, t, q, p, params) v .= 0 nothing end function lotka_volterra_4d_f(f::AbstractVector, t::Real, q::AbstractVector, v::AbstractVector, params) f[1] = f₁(t,q,v) - dHd₁(t, q, params) f[2] = f₂(t,q,v) - dHd₂(t, q, params) f[3] = f₃(t,q,v) - dHd₃(t, q, params) f[4] = f₄(t,q,v) - dHd₄(t, q, params) nothing end function lotka_volterra_4d_f_ham(f::AbstractVector, t::Real, q::AbstractVector, v::AbstractVector, params) f[1] = - dHd₁(t, q, params) f[2] = - dHd₂(t, q, params) f[3] = - dHd₃(t, q, params) f[4] = - dHd₄(t, q, params) end function lotka_volterra_4d_g(g::AbstractVector, t::Real, q::AbstractVector, v::AbstractVector, params) g[1] = f₁(t,q,v) g[2] = f₂(t,q,v) g[3] = f₃(t,q,v) g[4] = f₄(t,q,v) nothing end lotka_volterra_4d_g(g, t, q, p, λ, params) = lotka_volterra_4d_g(g, t, q, λ, params) lotka_volterra_4d_g(g, t, q, v, p, λ, params) = lotka_volterra_4d_g(g, t, q, p, λ, params) function lotka_volterra_4d_g̅(g::AbstractVector, t::Real, q::AbstractVector, v::AbstractVector, params) g[1] = g₁(t,q,v) g[2] = g₂(t,q,v) g[3] = g₃(t,q,v) g[4] = g₄(t,q,v) nothing end function lotka_volterra_4d_g̅(g::AbstractVector, t::Real, q::AbstractVector, p::AbstractVector, v::AbstractVector, params) lotka_volterra_4d_g̅(t, q, v, g, params) end function lotka_volterra_4d_u(u, t, q, λ, params) u .= λ nothing end lotka_volterra_4d_u(u, t, q, p, λ, params) = lotka_volterra_4d_u(u, t, q, λ, params) lotka_volterra_4d_u(u, t, q, v, p, λ, params) = lotka_volterra_4d_u(u, t, q, p, λ, params) function lotka_volterra_4d_ϕ(ϕ, t, q, p, params) ϕ[1] = p[1] - ϑ₁(t,q) ϕ[2] = p[2] - ϑ₂(t,q) ϕ[3] = p[3] - ϑ₃(t,q) ϕ[4] = p[4] - ϑ₄(t,q) nothing end lotka_volterra_4d_ϕ(ϕ, t, q, v, p, params) = lotka_volterra_4d_ϕ(ϕ, t, q, p, params) function lotka_volterra_4d_ψ(ψ, t, q, p, q̇, ṗ, params) ψ[1] = f[1] - g₁(t,q,q̇) ψ[2] = f[2] - g₂(t,q,q̇) ψ[3] = f[3] - g₃(t,q,q̇) ψ[4] = f[4] - g₄(t,q,q̇) nothing end lotka_volterra_4d_ψ(ψ, t, q, v, p, q̇, ṗ, params) = lotka_volterra_4d_ψ(ψ, t, q, p, q̇, ṗ, params) function odeproblem(q₀=q₀; tspan=tspan, tstep=Δt, parameters=default_parameters) ODEProblem(lotka_volterra_4d_v, tspan, tstep, q₀; parameters=parameters, invariants=(h=hamiltonian,)) end function podeproblem(q₀=q₀, p₀=nothing; tspan=tspan, tstep=Δt, parameters=default_parameters) p₀ === nothing ? p₀ = ϑ(tspan[begin], q₀) : nothing PODEProblem(lotka_volterra_4d_v, lotka_volterra_4d_f, tspan, tstep, q₀, p₀; parameters=parameters, invariants=(h=hamiltonian_pode,)) end function iodeproblem(q₀=q₀, p₀=nothing; tspan=tspan, tstep=Δt, parameters=default_parameters) p₀ === nothing ? p₀ = ϑ(tspan[begin], q₀) : nothing IODEProblem(lotka_volterra_4d_ϑ, lotka_volterra_4d_f, lotka_volterra_4d_g, tspan, tstep, q₀, p₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_4d_v) end function lodeproblem(q₀=q₀, p₀=nothing; tspan=tspan, tstep=Δt, parameters=default_parameters) p₀ === nothing ? p₀ = ϑ(tspan[begin], q₀) : nothing LODEProblem(lotka_volterra_4d_ϑ, lotka_volterra_4d_f, lotka_volterra_4d_g, tspan, tstep, q₀, p₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_4d_v, Ω=lotka_volterra_4d_ω, ∇H=lotka_volterra_4d_dH) end function idaeproblem(q₀=q₀, p₀=nothing, λ₀=zero(q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) p₀ === nothing ? p₀ = ϑ(tspan[begin], q₀) : nothing IDAEProblem(lotka_volterra_4d_ϑ, lotka_volterra_4d_f, lotka_volterra_4d_u, lotka_volterra_4d_g, lotka_volterra_4d_ϕ, tspan, tstep, q₀, p₀, λ₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_4d_v) end function pdaeproblem(q₀=q₀, p₀=nothing, λ₀=zero(q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) p₀ === nothing ? p₀ = ϑ(tspan[begin], q₀) : nothing PDAEProblem(lotka_volterra_4d_v_ham, lotka_volterra_4d_f_ham, lotka_volterra_4d_u, lotka_volterra_4d_g, lotka_volterra_4d_ϕ, tspan, tstep, q₀, p₀, λ₀; v̄=lotka_volterra_4d_v, f̄=lotka_volterra_4d_f, parameters=parameters, invariants=(h=hamiltonian_pode,)) end function ldaeproblem(q₀=q₀, p₀=nothing, λ₀=zero(q₀); tspan=tspan, tstep=Δt, parameters=default_parameters) p₀ === nothing ? p₀ = ϑ(tspan[begin], q₀) : nothing LDAEProblem(lotka_volterra_4d_ϑ, lotka_volterra_4d_f_ham, lotka_volterra_4d_g, lotka_volterra_4d_g̅, lotka_volterra_4d_ϕ, lotka_volterra_4d_ψ, tspan, tstep, q₀, p₀, λ₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_4d_v, f̄=lotka_volterra_4d_f,) end function iodeproblem_dg(q₀=q₀, p₀=nothing; tspan=tspan, tstep=Δt, parameters=default_parameters) p₀ === nothing ? p₀ = ϑ(tspan[begin], q₀) : nothing IODEProblem(lotka_volterra_4d_ϑ, lotka_volterra_4d_f, lotka_volterra_4d_g, tspan, tstep, q₀, p₀; parameters=parameters, invariants=(h=hamiltonian_iode,), v̄=lotka_volterra_4d_v) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
9284
@doc raw""" Implements equations for Lagrangian Lotka-Volterra models in 4d of the form ```math L(q, \dot{q}) = \frac{1}{2} (\log q)^T A \frac{\dot{q}}{q} + q^T B \dot{q} - H (q) , ``` with hamiltonian ```math H(q) = a_1 q^1 + a_2 q^2 + a_3 q^3 + a_4 q^4 + b_1 \log q^1 + b_2 \log q^2 + b_3 \log q^3 + b_4 \log q^4 + b_5 \log q^5 . ``` """ module LotkaVolterra4dLagrangian using GeometricEquations using GeometricSolutions using Parameters using RuntimeGeneratedFunctions using Symbolics using Symbolics: Sym RuntimeGeneratedFunctions.init(@__MODULE__) # export hamiltonian, ϑ, ϑ₁, ϑ₂, ω export lotka_volterra_4d_ode, lotka_volterra_4d_iode, lotka_volterra_4d_idae, lotka_volterra_4d_lode # lotka_volterra_4d_ldae, # lotka_volterra_4d_dg # include("lotka_volterra_4d_plots.jl") const Δt = 0.01 const nt = 1000 const tspan = (0.0, Δt*nt) const q₀ = [2.0, 1.0, 1.0, 1.0] const default_parameters = (a₁=1.0, a₂=1.0, a₃=1.0, a₄=1.0, b₁=-1.0, b₂=-2.0, b₃=-1.0, b₄=-1.0) const reference_solution = [0.5988695239096916, 2.068567531039674, 0.2804351458645534, 1.258449091830993] const A_antisym = 1//2 .* [ 0 -1 +1 -1 +1 0 -1 +1 -1 +1 0 -1 +1 -1 +1 0] const A_positive = [ 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0] const A_upper = [ 0 -1 +1 -1 0 0 -1 +1 0 0 0 -1 0 0 0 0] const A_lower = [ 0 0 0 0 +1 0 0 0 -1 +1 0 0 +1 -1 +1 0] const A_quasicanonical_antisym = 1//2 .* [ 0 -1 +1 -1 +1 0 -1 0 -1 +1 0 -1 +1 0 +1 0] const A_quasicanonical_reduced = 1//2 .* [ 0 0 +1 0 +2 0 -2 0 -1 0 0 0 +2 0 +2 0] const B = [ 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0] const A_default = A_antisym const B_default = zero(B) _parameter(name::Symbol) = Num(Sym{Real}(name)) function get_parameters(p) return (a = [p.a₁, p.a₂, p.a₃, p.a₄], b = [p.b₁, p.b₂, p.b₃, p.b₄]) end H(x, a, b) = a' * x + b' * log.(x) K(x, v, A, B) = log.(x)' * A * (v ./ x) + x' * B * v L(x, v, A, B, a, b) = K(x, v, A, B) - H(x, a, b) function substitute_ẋ_with_v!(eqs, ẋ, v) for i in eachindex(eqs) eqs[i] = substitute(eqs[i], [ẋᵢ=>vᵢ for (ẋᵢ,vᵢ) in zip(ẋ,v)]) end return eqs end function substitute_variables!(eqs, x, v, X, V) for i in eachindex(eqs) eqs[i] = substitute(eqs[i], [z=>Z for (z,Z) in zip([x..., v...], [X..., V...])]) end return eqs end function get_functions(A,B,a,b) t = _parameter(:t) params = _parameter(:params) @variables x₁(t), x₂(t), x₃(t), x₄(t) @variables v₁(t), v₂(t), v₃(t), v₄(t) @variables X[1:4] @variables V[1:4] @variables P[1:4] @variables F[1:4] x = [x₁, x₂, x₃, x₄] v = [v₁, v₂, v₃, v₄] Dt = Differential(t) Dx = Differential.(x) Dv = Differential.(v) # DX = Differential.(X) # DV = Differential.(V) let L = simplify(L(x, v, A, B, a, b)), K = simplify(K(x, v, A, B)), H = simplify(H(x, a, b)) # let L = (L(x, v, A, B, a, b)), K = (K(x, v, A, B)), H = (H(x, a, b)) EL = [expand_derivatives(Dx[i](L) - Dt(Dv[i](L))) for i in eachindex(Dx,Dv)] ∇H = [expand_derivatives(dx(H)) for dx in Dx] f = [expand_derivatives(dx(L)) for dx in Dx] f̄ = [expand_derivatives(dx(K)) for dx in Dx] g = [expand_derivatives(Dt(dv(L))) for dv in Dv] ϑ = [expand_derivatives(dv(L)) for dv in Dv] ω = [expand_derivatives(simplify(Dx[i](ϑ[j]) - Dx[j](ϑ[i]))) for i in eachindex(Dx,ϑ), j in eachindex(Dx,ϑ)] Σ = simplify.(inv(ω)) ẋ = simplify.(Σ * ∇H) for eq in (EL, ∇H, f, f̄, g, ϑ, ω, Σ, ẋ) substitute_ẋ_with_v!(eq, Dt.(x), v) substitute_variables!(eq, x, v, X, V) end H = substitute(H, [z=>Z for (z,Z) in zip([x..., v...], [X..., V...])]) L = substitute(L, [z=>Z for (z,Z) in zip([x..., v...], [X..., V...])]) ϕ = [P[i] - ϑ[i] for i in eachindex(P,ϑ)] ψ = [F[i] - g[i] for i in eachindex(F,g)] code_EL = build_function(EL, t, X, V, params)[2] code_f = build_function(f, t, X, V, params)[2] code_f̄ = build_function(f̄, t, X, V, params)[2] code_g = build_function(g, t, X, V, params)[2] code_∇H = build_function(∇H, t, X, params)[2] code_p = build_function(ϑ, t, X, V, params)[1] code_ϑ = build_function(ϑ, t, X, V, params)[2] code_ω = build_function(ω, t, X, V, params)[2] code_P = build_function(Σ, t, X, params)[2] code_ẋ = build_function(ẋ, t, X, params)[2] code_ϕ = build_function(ϕ, t, X, V, P, params)[2] code_ψ = build_function(ψ, t, X, V, P, F, params)[2] code_H = build_function(H, t, X, params) code_L = build_function(L, t, X, V, params) return ( EL = @RuntimeGeneratedFunction(code_EL), ∇H = @RuntimeGeneratedFunction(code_∇H), f = @RuntimeGeneratedFunction(code_f), f̄ = @RuntimeGeneratedFunction(code_f̄), g = @RuntimeGeneratedFunction(code_g), p = @RuntimeGeneratedFunction(code_p), ϑ = @RuntimeGeneratedFunction(code_ϑ), ω = @RuntimeGeneratedFunction(code_ω), P = @RuntimeGeneratedFunction(code_P), ẋ = @RuntimeGeneratedFunction(code_ẋ), ϕ = @RuntimeGeneratedFunction(code_ϕ), ψ = @RuntimeGeneratedFunction(code_ψ), H = @RuntimeGeneratedFunction(code_H), L = @RuntimeGeneratedFunction(code_L), ) end end function odeproblem(q₀=q₀, A=A_default, B=B_default; tspan=tspan, tstep=Δt, parameters=default_parameters) a, b = get_parameters(parameters) funcs = get_functions(A,B,a,b) GeometricEquations.ODEProblem(funcs[:ẋ], tspan, tstep, q₀; parameters=parameters, invariants = (h = funcs[:H],)) end function iodeproblem(q₀=q₀, A=A_default, B=B_default; tspan=tspan, tstep=Δt, parameters=default_parameters) a, b = get_parameters(parameters) funcs = get_functions(A,B,a,b) IODEProblem(funcs[:ϑ], funcs[:f], (f̄,t,x,v,λ,params) -> funcs[:f̄](f̄,t,x,λ,params), tspan, tstep, q₀, funcs[:p](0, q₀, zero(q₀), ()); v̄ = (v,t,x,p,params) -> funcs[:ẋ](v,t,x,params), parameters=parameters, invariants = (h = (t,x,v,params) -> funcs[:H](t,x,params),)) end function lodeproblem(q₀=q₀, A=A_default, B=B_default; tspan=tspan, tstep=Δt, parameters=default_parameters) a, b = get_parameters(parameters) funcs = get_functions(A,B,a,b) LODEProblem(funcs[:ϑ], funcs[:f], (f̄,t,x,v,λ,params) -> funcs[:f̄](f̄,t,x,λ,params), funcs[:L], funcs[:ω], tspan, tstep, q₀, funcs[:p](0, q₀, zero(q₀), ()); v̄ = (v,t,x,p,params) -> funcs[:ẋ](v,t,x,params), f̄ = funcs[:f], parameters=parameters, invariants = (h = (t,x,v,params) -> funcs[:H](t,x,params),)) end function idaeproblem(q₀=q₀, A=A_default, B=B_default; tspan=tspan, tstep=Δt, parameters=default_parameters) a, b = get_parameters(parameters) funcs = get_functions(A,B,a,b) IDAEProblem(funcs[:ϑ], funcs[:f], (u,t,x,p,v,λ,params) -> u .= λ, (f̄,t,x,p,v,λ,params) -> funcs[:f̄](f̄,t,x,λ,params), funcs[:ϕ], tspan, tstep, q₀, funcs[:p](0, q₀, zero(q₀), ()), zero(q₀); v̄ = (v,t,x,p,params) -> funcs[:ẋ](v,t,x,params), parameters=parameters, invariants = (h = (t,x,v,params) -> funcs[:H](t,x,params),)) end # function ldaeproblem(q₀=q₀, p₀=ϑ(0, q₀), λ₀=zero(q₀), params=p) # LDAE(lotka_volterra_4d_ϑ, lotka_volterra_4d_f_ham, # lotka_volterra_4d_g, lotka_volterra_4d_g̅, # lotka_volterra_4d_ϕ, lotka_volterra_4d_ψ, # q₀, p₀, λ₀; parameters=params, h=hamiltonian, v=lotka_volterra_4d_v) # end # function iodeproblem_dg(q₀=q₀, p₀=ϑ(0, q₀), params=p) # IODE(lotka_volterra_4d_ϑ, lotka_volterra_4d_f, # lotka_volterra_4d_g, q₀, p₀; # parameters=params, h=hamiltonian, v=lotka_volterra_4d_v) # end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
1774
module LotkaVolterra4dPlots using LaTeXStrings using Measures: mm using RecipesBase import GeometricProblems.Diagnostics: compute_invariant_error, compute_momentum_error compute_energy_error(t,q,params) = compute_invariant_error(t,q, (t,q) -> hamiltonian(t,q,params)) # compute_momentum_error(t,q,p) = compute_momentum_error(t,q,p,ϑ) @userplot PlotLotkaVolterra4d @recipe function f(p::PlotLotkaVolterra4d; latex=true) # if length(p.args) != 2 || !(typeof(p.args[1][1]) <: Solution) || !(typeof(p.args[2]) <: NamedTuple) # error("Lotka-Volterra plots should be given a solution. Got: $(typeof(p.args))") # end sol = p.args[1] params = p.args[2] H, ΔH = compute_energy_error(sol.t, sol.q, params); size := (800,1200) legend := :none guidefontsize := 12 tickfontsize := 8 left_margin := 12mm right_margin := 8mm # traces layout := (5,1) if latex ylabels = (L"x_1", L"x_2", L"x_3", L"x_4") else ylabels = ("x₁", "x₂", "x₃", "x₄") end for i in 1:4 @series begin subplot := i yguide := ylabels[i] xlims := (sol.t[0], Inf) xaxis := false sol.t, sol.q[i,:] end end @series begin subplot := 5 if latex xguide := L"t" yguide := L"[H(t) - H(0)] / H(0)" else xguide := "t" yguide := "[H(t) - H(0)] / H(0)" end xlims := (sol.t[0], Inf) yformatter := :scientific sol.t, ΔH end end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
7501
@doc raw""" # Massless charged particle in 2D The Lagrangian is given by ```math L(x, \dot{x}) = A(x) \cdot \dot{x} - \phi (x) , ``` with magnetic vector potential ```math A(x) = \frac{A_0}{2} \big( 1 + x_1^2 + x_2^2 \big) \begin{pmatrix} - x_2 \\ + x_1 \\ \end{pmatrix} , ``` electrostatic potential ```math \phi(x) = E_0 \, \big( \cos (x_1) + \sin(x_2) \big) , ``` and magnetic and electric fields ```math \begin{aligned} B(x) &= \nabla \times A(x) = A_0 \, (1 + 2 x_1^2 + 2 x_2^2) , \\ E(x) &= - \nabla \phi(x) = E_0 \, \big( \sin x_1, \, - \cos x_2 \big)^T . \end{aligned} ``` The Hamiltonian form of the equations of motion reads ```math \dot{x} = \frac{1}{B(x)} \begin{pmatrix} \hphantom{-} 0 & + 1 \\ - 1 & \hphantom{+} 0 \\ \end{pmatrix} \nabla \phi (x) . ``` """ module MasslessChargedParticle using GeometricEquations using ..Diagnostics import ..Diagnostics: compute_invariant_error, compute_momentum_error export ϑ, A, B, ϕ, E, hamiltonian export odeproblem, iodeproblem, idaeproblem, idaeproblem_spark export compute_energy_error, compute_momentum_error # default simulation parameters const Δt = 0.2 const nt = 5000 const tspan = (0.0, Δt*nt) # default initial conditions and parameters q₀ = [1.0, 1.0] default_parameters = (A₀ = 1.0, E₀ = 1.0) # components of the vector potential A₁(q, params) = - params[:A₀] * q[2] * (1 + q[1]^2 + q[2]^2) / 2 A₂(q, params) = + params[:A₀] * q[1] * (1 + q[1]^2 + q[2]^2) / 2 A(q, params) = [A₁(q, params), A₂(q, params)] # z-componend of the magnetic field B(q, params) = params[:A₀] * (1 + 2 * q[1]^2 + 2 * q[2]^2) # electrostatic potential ϕ(q, params) = params[:E₀] * (cos(q[1]) + sin(q[2])) # ϕ(q, params) = E₀ * (q[1]^2 + q[2]^2) # components of the electric field E₁(q, params) = + params[:E₀] * sin(q[1]) E₂(q, params) = - params[:E₀] * cos(q[2]) # E₁(q, params) = + params[:E₀] * q[1] # E₂(q, params) = + params[:E₀] * q[2] E(q, params) = [E₁(q, params), E₂(q, params)] # components of the velocity v₁(t, q, params) = - E₂(q, params) / B(q, params) v₂(t, q, params) = + E₁(q, params) / B(q, params) # components of the one-form (symplectic potential) ϑ₁(t, q, params) = A₁(q, params) ϑ₂(t, q, params) = A₂(q, params) ϑ(t, q, params) = [ϑ₁(t, q, params), ϑ₂(t, q, params)] function ϑ(t::Number, q::AbstractVector, params::NamedTuple, k::Int) if k == 1 ϑ₁(t, q, params) elseif k == 2 ϑ₂(t, q, params) else throw(BoundsError(ϑ,k)) end end # derivatives of the one-form components dϑ₁dx₁(t, q, params) = - params[:A₀] * q[1] * q[2] dϑ₁dx₂(t, q, params) = - params[:A₀] * (1 + q[1]^2 + 3 * q[2]^2) / 2 dϑ₂dx₁(t, q, params) = + params[:A₀] * (1 + 3 * q[1]^2 + q[2]^2) / 2 dϑ₂dx₂(t, q, params) = + params[:A₀] * q[1] * q[2] # components of the force f₁(v, t, q, params) = dϑ₁dx₁(t, q, params) * v[1] + dϑ₂dx₁(t, q, params) * v[2] f₂(v, t, q, params) = dϑ₁dx₂(t, q, params) * v[1] + dϑ₂dx₂(t, q, params) * v[2] g₁(v, t, q, params) = dϑ₁dx₁(t, q, params) * v[1] + dϑ₁dx₂(t, q, params) * v[2] g₂(v, t, q, params) = dϑ₂dx₁(t, q, params) * v[1] + dϑ₂dx₂(t, q, params) * v[2] # Hamiltonian (total energy) hamiltonian(t, q, params) = ϕ(q, params) # components of the gradient of the Hamiltonian dHd₁(t, q, params) = - E₁(q, params) dHd₂(t, q, params) = - E₂(q, params) function massless_charged_particle_dH(dH, t, q, params) dH[1] = dHd₁(t, q, params) dH[2] = dHd₂(t, q, params) nothing end function massless_charged_particle_v(v, t, q, params) v[1] = v₁(t, q, params) v[2] = v₂(t, q, params) nothing end function massless_charged_particle_v(v, t, q, p, params) massless_charged_particle_v(v, t, q, params) end function massless_charged_particle_ϑ(Θ, t, q, params) Θ[1] = ϑ₁(t, q, params) Θ[2] = ϑ₂(t, q, params) nothing end massless_charged_particle_ϑ(Θ, t, q, v, params) = massless_charged_particle_ϑ(Θ, t, q, params) function massless_charged_particle_f(f, t, q, v, params) f[1] = f₁(v, t, q, params) - dHd₁(t, q, params) f[2] = f₂(v, t, q, params) - dHd₂(t, q, params) nothing end function massless_charged_particle_f̄(f, t, q, v, params) f[1] = - dHd₁(t, q, params) f[2] = - dHd₂(t, q, params) nothing end function massless_charged_particle_g(g, t, q, v, params) g[1] = f₁(v, t, q, params) g[2] = f₂(v, t, q, params) nothing end massless_charged_particle_g(g, t, q, p, v, params) = massless_charged_particle_g(g, t, q, v, params) function massless_charged_particle_u(u, t, q, v, params) u .= v nothing end massless_charged_particle_u(u, t, q, p, v, params) = massless_charged_particle_u(u, t, q, v, params) function massless_charged_particle_ϕ(ϕ, t, q, p, params) ϕ[1] = p[1] - ϑ₁(t,q,params) ϕ[2] = p[2] - ϑ₂(t,q,params) nothing end function massless_charged_particle_ψ(ψ, t, q, p, v, f, params) ψ[1] = f[1] - g₁(t,q,v,params) ψ[2] = f[2] - g₂(t,q,v,params) nothing end "Creates an ODE object for the massless charged particle in 2D." function odeproblem(q₀=q₀; tspan=tspan, tstep=Δt, params=default_parameters) ODEProblem(massless_charged_particle_v, tspan, tstep, q₀; invariants=(h=hamiltonian,), parameters=params) end "Creates an implicit ODE object for the massless charged particle in 2D." function iodeproblem(q₀=q₀; tspan=tspan, tstep=Δt, params=default_parameters) IODEProblem(massless_charged_particle_ϑ, massless_charged_particle_f, massless_charged_particle_g, tspan, tstep, q₀, ϑ(0., q₀, params); v̄=massless_charged_particle_v, f̄=massless_charged_particle_f, invariants=(h=hamiltonian,), parameters=params) end "Creates an implicit DAE object for the massless charged particle in 2D." function idaeproblem(q₀=q₀; tspan=tspan, tstep=Δt, params=default_parameters) IDAEProblem(massless_charged_particle_ϑ, massless_charged_particle_f, massless_charged_particle_u, massless_charged_particle_g, massless_charged_particle_ϕ, tspan, tstep, q₀, ϑ(0., q₀, params), zero(q₀); v̄=massless_charged_particle_v, f̄=massless_charged_particle_f, invariants=(h=hamiltonian,), parameters=params) end "Creates an implicit DAE object for the massless charged particle in 2D." function idaeproblem_spark(q₀=q₀; tspan=tspan, tstep=Δt, params=default_parameters) IDAEProblem(massless_charged_particle_ϑ, massless_charged_particle_f̄, massless_charged_particle_u, massless_charged_particle_g, massless_charged_particle_ϕ, tspan, tstep, q₀, ϑ(0., q₀, params), zero(q₀); v̄=massless_charged_particle_v, f̄=massless_charged_particle_f, invariants=(h=hamiltonian,), parameters=params) end compute_energy_error(t,q,params) = compute_invariant_error(t,q, (t,q) -> hamiltonian(t,q,params)) compute_momentum_error(t,q,p,params::NamedTuple) = compute_momentum_error(t, q, p, (t,q,k) -> ϑ(t,q,params,k)) end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
12588
module MasslessChargedParticlePlots using GeometricEquations using GeometricSolutions using GeometricProblems.Diagnostics using LaTeXStrings using Measures: mm using RecipesBase """ Plots the solution of a massless charged particle together with the energy error. Arguments: * `sol <: GeometricSolution` * `equ <: GeometricProblem` Keyword aguments: * `nplot=1`: plot every `nplot`th time step * `xlims=:auto`: xlims for solution plot * `ylims=:auto`: ylims for solution plot """ @userplot Plot_Massless_Charged_Particle @recipe function f(p::Plot_Massless_Charged_Particle; nplot=1, nt=:auto, xlims=:auto, ylims=:auto, elims=:auto, latex=true) if length(p.args) != 2 || !(typeof(p.args[1]) <: GeometricSolution) || !(typeof(p.args[2]) <: GeometricProblem) error("Massless charged particle plots should be given two arguments: a solution and a parameter tuple. Got: $(typeof(p.args))") end sol = p.args[1] equ = p.args[2] params = equ.parameters if nt == :auto nt = ntime(sol) end if nt > ntime(sol) nt = ntime(sol) end H, ΔH = compute_invariant_error(sol.t, sol.q, (t,q) -> invariants(equ)[:h](t,q,params)) size := (800,300) layout := (1,2) legend := :none right_margin := 10mm bottom_margin := 10mm guidefontsize := 14 tickfontsize := 10 @series begin subplot := 1 if ntime(sol) ≤ 200 markersize := 5 else markersize := .5 markercolor := 1 linecolor := 1 markerstrokewidth := .5 markerstrokecolor := 1 end if nplot > 1 seriestype := :scatter end if latex xguide := L"x_1" yguide := L"x_2" else # if backend() == Plots.PlotlyJSBackend() xguide := "x₁" yguide := "x₂" end xlims := xlims ylims := ylims aspect_ratio := 1 sol.q[0:nplot:end, 1], sol.q[0:nplot:end, 2] end @series begin subplot := 2 if latex xguide := L"t" yguide := L"[H(t) - H(0)] / H(0)" else xguide := "t" yguide := "[H(t) - H(0)] / H(0)" end xlims := (sol.t[0], Inf) ylims := elims yformatter := :scientific sol.t[0:nplot:nt], ΔH[0:nplot:nt] end end """ Plots the solution of a massless charged particle. Arguments: * `sol <: GeometricSolution` * `equ <: GeometricProblem` Keyword aguments: * `nplot=1`: plot every `nplot`th time step * `xlims=:auto`: xlims for solution plot * `ylims=:auto`: ylims for solution plot """ @userplot Plot_Massless_Charged_Particle_Solution @recipe function f(p::Plot_Massless_Charged_Particle_Solution; nplot=1, nt=:auto, xlims=:auto, ylims=:auto, latex=true) if length(p.args) != 2 || !(typeof(p.args[1]) <: GeometricSolution) || !(typeof(p.args[2]) <: GeometricProblem) error("Massless charged particle plots should be given two arguments: a solution and a parameter tuple. Got: $(typeof(p.args))") end sol = p.args[1] equ = p.args[2] params = equ.parameters if nt == :auto nt = ntime(sol) end if nt > ntime(sol) nt = ntime(sol) end if ntime(sol) ≤ 200 markersize := 5 else markersize := .5 markercolor := 1 linecolor := 1 markerstrokewidth := .5 markerstrokecolor := 1 end if nplot > 1 seriestype := :scatter end legend := :none size := (400,400) # if backend() == Plots.PlotlyJSBackend() || backend() == Plots.GRBackend() guidefontsize := 18 tickfontsize := 12 # else # guidefontsize := 14 # tickfontsize := 10 # end # solution @series begin if latex xguide := L"x_1" yguide := L"x_2" else # if backend() == Plots.PlotlyJSBackend() xguide := "x₁" yguide := "x₂" end xlims := xlims ylims := ylims aspect_ratio := 1 sol.q[0:nplot:nt, 1], sol.q[0:nplot:nt, 2] end end """ Plots time traces of the energy error of a massless charged particle. Arguments: * `sol <: GeometricSolution` * `equ <: GeometricProblem` Keyword aguments: * `nplot=1`: plot every `nplot`th time step """ @userplot Plot_Massless_Charged_Particle_Energy_Error @recipe function f(p::Plot_Massless_Charged_Particle_Energy_Error; nplot=1, nt=:auto, latex=true) if length(p.args) != 2 || !(typeof(p.args[1]) <: GeometricSolution) || !(typeof(p.args[2]) <: GeometricProblem) error("Massless charged particle plots should be given two arguments: a solution and a parameter tuple. Got: $(typeof(p.args))") end sol = p.args[1] equ = p.args[2] params = equ.parameters if nt == :auto nt = ntime(sol) end if nt > ntime(sol) nt = ntime(sol) end H, ΔH = compute_invariant_error(sol.t, sol.q, (t,q) -> invariants(equ)[:h](t,q,params)) size := (800,200) legend := :none right_margin := 10mm # if backend() == Plots.GRBackend() left_margin := 10mm bottom_margin := 10mm # end guidefontsize := 12 tickfontsize := 10 @series begin if latex xguide := L"t" yguide := L"[H(t) - H(0)] / H(0)" # if backend() == Plots.PlotlyJSBackend() else xguide := "t" yguide := "[H(t) - H(0)] / H(0)" end xlims := (sol.t[0], Inf) yformatter := :scientific sol.t[0:nplot:nt], ΔH[0:nplot:nt] end end """ Plots time traces of the momentum error of a massless charged particle. Arguments: * `sol <: GeometricSolution` * `equ <: GeometricProblem` Keyword aguments: * `nplot=1`: plot every `nplot`th time step * `k=0`: index of momentum component (0 plots all components) """ @userplot Plot_Massless_Charged_Particle_Momentum_Error @recipe function f(p::Plot_Massless_Charged_Particle_Momentum_Error; k=0, nplot=1, nt=:auto, latex=true) if length(p.args) != 2 || !(typeof(p.args[1]) <: GeometricSolution) || !(typeof(p.args[2]) <: GeometricProblem) error("Massless charged particle plots should be given two arguments: a solution and a parameter tuple. Got: $(typeof(p.args))") end sol = p.args[1] equ = p.args[2] params = equ.parameters if nt == :auto nt = ntime(sol) end if nt > ntime(sol) nt = ntime(sol) end Δp = compute_momentum_error(sol.t, sol.q, sol.p, params) ntrace = (k == 0 ? Δp.nd : 1 ) trange = (k == 0 ? (1:Δp.nd) : (k:k)) size := (800,200*ntrace) legend := :none layout := (ntrace,1) right_margin := 10mm if ntrace == 1 #&& backend() == Plots.GRBackend() left_margin := 10mm end guidefontsize := 12 tickfontsize := 10 for i in trange @series begin if k == 0 subplot := i end if i == Δp.nd || k ≠ 0 if latex xguide := L"t" # if backend() == Plots.PlotlyJSBackend() else xguide := "t" end else xaxis := false bottom_margin := 10mm end # if i < Δp.nd && k == 0 # if backend() == Plots.PGFPlotsXBackend() # bottom_margin := -6mm # elseif backend() == Plots.GRBackend() # bottom_margin := -3mm # end # end # if i > 1 && k == 0 # if backend() == Plots.PGFPlotsXBackend() # top_margin := -6mm # elseif backend() == Plots.GRBackend() # top_margin := -3mm # end # end if latex yguide := latexstring("p_$i (t) - \\vartheta_$i (t)") # if backend() == Plots.PlotlyJSBackend() else yguide := "p" * subscript(i) * "(t) - ϑ" * subscript(i) * "(t)" end xlims := (sol.t[0], Inf) yformatter := :scientific sol.t[0:nplot:nt], Δp[0:nplot:nt, i] end end end """ Plots time traces of the solution of a massless charged particle trajectory and its energy error. Arguments: * `sol <: GeometricSolution` * `equ <: GeometricProblem` Keyword aguments: * `nplot=1`: plot every `nplot`th time step """ @userplot Plot_Massless_Charged_Particle_Traces @recipe function f(p::Plot_Massless_Charged_Particle_Traces; nplot=1, nt=:auto, xlims=:auto, ylims=:auto, elims=:auto, latex=true) if length(p.args) != 2 || !(typeof(p.args[1]) <: GeometricSolution) || !(typeof(p.args[2]) <: GeometricProblem) error("Massless charged particle plots should be given two arguments: a solution and a parameter tuple. Got: $(typeof(p.args))") end sol = p.args[1] equ = p.args[2] params = equ.parameters if nt == :auto nt = ntime(sol) end if nt > ntime(sol) nt = ntime(sol) end H, ΔH = compute_invariant_error(sol.t, sol.q, (t,q) -> invariants(equ)[:h](t,q,params)) size := (800,600) legend := :none right_margin := 10mm # traces layout := (3,1) # if backend() == Plots.PlotlyJSBackend() || backend() == Plots.GRBackend() guidefontsize := 14 tickfontsize := 10 # else # guidefontsize := 12 # tickfontsize := 10 # end if latex ylabels = (L"x_1", L"x_2") # if backend() == Plots.PlotlyJSBackend() else ylabels = ("x₁", "x₂") end lims = (xlims, ylims, elims) for i in 1:2 @series begin subplot := i yguide := ylabels[i] xlims := (sol.t[0], Inf) ylims := lims[i] xaxis := false # if i == 1 && backend() == Plots.PGFPlotsXBackend() # bottom_margin := -4mm # elseif i == 1 && backend() == Plots.GRBackend() # bottom_margin := -2mm # end # if i == 2 && backend() == Plots.PGFPlotsXBackend() # top_margin := -2mm # bottom_margin := -2mm # elseif i == 2 && backend() == Plots.GRBackend() # top_margin := -1mm # bottom_margin := -1mm # end sol.t[0:nplot:nt], sol.q[0:nplot:nt, i] end end @series begin subplot := 3 # if backend() == Plots.PGFPlotsXBackend() # top_margin := -4mm # elseif backend() == Plots.GRBackend() # top_margin := -2mm # end if latex xguide := L"t" yguide := L"[H(t) - H(0)] / H(0)" # if backend() == Plots.PlotlyJSBackend() else xguide := "t" yguide := "[H(t) - H(0)] / H(0)" end xlims := (sol.t[0], Inf) ylims := elims yformatter := :scientific sol.t[0:nplot:nt], ΔH[0:nplot:nt] end end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
82
@doc raw""" """ module MathewsLakshmananOscillator export hamiltonian end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
70
@doc raw""" """ module MorseOscillator export hamiltonian end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
2641
@doc raw""" # Mathematical Pendulum """ module Pendulum using GeometricEquations export odeproblem, podeproblem, iodeproblem, idaeproblem function pendulum_ode_v(v, t, q, params) v[1] = q[2] v[2] = sin(q[1]) nothing end function odeproblem(q₀=[acos(0.4), 0.0]) ODE(pendulum_ode_v, q₀) end function pendulum_pode_v(v, t, q, p, params) v[1] = p[1] nothing end function pendulum_pode_f(f, t, q, p, params) f[1] = sin(q[1]) nothing end function podeproblem(q₀=[acos(0.4)], p₀=[0.0]) PODE(pendulum_pode_v, pendulum_pode_f, q₀, p₀) end function pendulum_iode_α(p, t, q, v, params) p[1] = q[2] p[2] = 0 nothing end function pendulum_iode_f(f, t, q, v, params) f[1] = sin(q[1]) f[2] = v[1] - q[2] nothing end function pendulum_iode_g(g, t, q, λ, params) g[1] = 0 g[2] = λ[1] nothing end function pendulum_iode_v(v, t, q, p, params) v[1] = q[2] v[2] = sin(q[1]) nothing end function iodeproblem(q₀=[acos(0.4), 0.0], p₀=[0.0, 0.0]) IODE(pendulum_iode_α, pendulum_iode_f, pendulum_iode_g, q₀, p₀; v̄=pendulum_iode_v) end # function pendulum_pdae_v(t, q, p, v) # v[1] = 0 # nothing # end # # function pendulum_pdae_f(t, q, p, f) # f[1] = sin(q[1]) # nothing # end # # function pendulum_pdae_u(t, q, p, λ, u) # u[1] = λ[1] # nothing # end # # function pendulum_pdae_g(t, q, p, λ, g) # g[1] = 0 # nothing # end # # # TODO # function pendulum_pdae_ϕ(t, q, p, ϕ) # ϕ[1] = p[1] - q[2] # nothing # end # # # TODO # function pendulum_pdae(q₀=[acos(0.4)], p₀=[0.0], λ₀=[0.0, 0.0]) # PDAE(pendulum_pdae_v, pendulum_pdae_f, pendulum_pdae_u, pendulum_pdae_g, pendulum_pdae_ϕ, q₀, p₀, λ₀) # end function pendulum_idae_u(u, t, q, p, λ, params) u[1] = λ[1] u[2] = λ[2] nothing end function pendulum_idae_g(g, t, q, p, λ, params) g[1] = 0 g[2] = λ[1] nothing end function pendulum_idae_ϕ(ϕ, t, q, p, params) ϕ[1] = p[1] - q[2] ϕ[2] = p[2] nothing end function idaeproblem(q₀=[acos(0.4), 0.0], p₀=[0.0, 0.0], λ₀=[0.0, 0.0]) IDAE(pendulum_iode_f, pendulum_iode_α, pendulum_idae_u, pendulum_idae_g, pendulum_idae_ϕ, q₀, p₀, λ₀; v̄=pendulum_iode_v) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
7743
module PlotRecipes using LaTeXStrings using Measures: mm using RecipesBase using GeometricSolutions using GeometricProblems.Diagnostics subscript(i::Integer) = i<0 ? error("$i is negative") : join('₀'+d for d in reverse(digits(i))) @userplot PlotEnergyError @recipe function f(p::PlotEnergyError; energy=nothing, nplot=1, nt=:auto, latex=true) if length(p.args) == 1 && typeof(p.args[1]) <: Solution sol = p.args[1] t = sol.t if typeof(sol) <: Union{SolutionPODE, SolutionPDAE} H, ΔH = compute_invariant_error(sol.t, sol.q, sol.p, energy) else H, ΔH = compute_invariant_error(sol.t, sol.q, energy) end elseif length(p.args) == 2 && typeof(p.args[1]) <: TimeSeries && typeof(p.args[2]) <: DataSeries t = p.args[1] ΔH = p.args[2] @assert length(t) == length(ΔH) else error("Energy error plot should be given a solution or a timeseries and a data series. Got: $(typeof(p.args))") end if nt == :auto nt = ntime(t) end if nt > ntime(t) nt = ntime(t) end legend := :none size := (800,400) @series begin if latex xguide := L"t" yguide := L"[H(t) - H(0)] / H(0)" else xguide := "t" yguide := "[H(t) - H(0)] / H(0)" end xlims := (t[0], Inf) yformatter := :scientific guidefontsize := 18 tickfontsize := 12 right_margin := 10mm t[0:nplot:nt], ΔH[0:nplot:nt] end end @userplot PlotEnergyDrift @recipe function f(p::PlotEnergyDrift; nt=:auto, latex=true) if length(p.args) == 2 && typeof(p.args[1]) <: TimeSeries && typeof(p.args[2]) <: DataSeries t = p.args[1] d = p.args[2] @assert length(t) == length(d) else error("Energy drift plot should be given a timeseries and a dataseries. Got: $(typeof(p.args))") end if nt == :auto nt = ntime(t) end if nt > ntime(t) nt = ntime(t) end legend := :none size := (800,400) @series begin seriestype := :scatter if latex xguide := L"t" yguide := L"\Delta H" else xguide := "t" yguide := "ΔH" end xlims := (t[0], Inf) yformatter := :scientific guidefontsize := 18 tickfontsize := 12 right_margin := 10mm t[1:nt], d[1:nt] end end @userplot PlotConstraintError @recipe function f(p::PlotConstraintError; nplot=1, nt=:auto, k=0, latex=true, plot_title=nothing) if length(p.args) == 1 && typeof(p.args[1]) <: Solution sol = p.args[1] t = sol.t Δp = compute_momentum_error(sol.t, sol.q, sol.p) # TODO: fix elseif length(p.args) == 2 && typeof(p.args[1]) <: TimeSeries && typeof(p.args[2]) <: DataSeries t = p.args[1] Δp = p.args[2] @assert ntime(t) == ntime(Δp) else error("Constraint error plots should be given a solution or a timeseries and a dataseries. Got: $(typeof(p.args))") end if nt == :auto nt = ntime(t) end if nt > ntime(t) nt = ntime(t) end nd = length(Δp[begin]) ntrace = (k == 0 ? nd : 1 ) trange = (k == 0 ? (1:nd) : (k:k)) size := (800,200*ntrace) legend := :none layout := (ntrace,1) for i in trange @series begin if k == 0 subplot := i end if plot_title !== nothing if i == trange[begin] title := plot_title else title := " " end end if i == nd || k ≠ 0 if latex xguide := L"t" else xguide := "t" end else xaxis := false end if latex yguide := latexstring("p_$i (t) - \\vartheta_$i (t)") else yguide := "p" * subscript(i) * "(t) - ϑ" * subscript(i) * "(t)" end xlims := (t[0], Inf) yformatter := :scientific guidefontsize := 18 tickfontsize := 12 right_margin := 24mm right_margin := 12mm t[0:nplot:nt], Δp[i,0:nplot:nt] end end end @userplot PlotLagrangeMultiplier @recipe function f(p::PlotLagrangeMultiplier; nplot=1, nt=:auto, k=0, latex=true, plot_title=nothing) if length(p.args) == 1 && typeof(p.args[1]) <: Solution sol = p.args[1] t = sol.t λ = sol.λ elseif length(p.args) == 2 && typeof(p.args[1]) <: TimeSeries && typeof(p.args[2]) <: DataSeries t = p.args[1] λ = p.args[2] @assert ntime(t) == ntime(λ) else error("Lagrange multiplier plots should be given a solution or a timeseries and a data series. Got: $(typeof(p.args))") end if nt == :auto nt = ntime(t) end if nt > ntime(t) nt = ntime(t) end nd = length(λ[begin]) ntrace = (k == 0 ? nd : 1 ) trange = (k == 0 ? (1:nd) : (k:k)) size := (800,200*ntrace) legend := :none layout := (ntrace,1) right_margin := 10mm if ntrace == 1 && backend() == Plots.GRBackend() left_margin := 10mm end guidefontsize := 12 tickfontsize := 10 for i in trange @series begin if k == 0 subplot := i end if plot_title !== nothing if i == trange[begin] title := plot_title else title := " " end end if i == nd || k ≠ 0 if latex xguide := L"t" else xguide := "t" end bottom_margin := 10mm else xaxis := false end # if i < λ.nd && k == 0 # if backend() == Plots.PGFPlotsXBackend() # bottom_margin := -6mm # elseif backend() == Plots.GRBackend() # bottom_margin := -3mm # end # end # if i > 1 && k == 0 # if backend() == Plots.PGFPlotsXBackend() # top_margin := -6mm # elseif backend() == Plots.GRBackend() # top_margin := -3mm # end # end if latex yguide := latexstring("\\lambda_$i (t)") else yguide := "λ" * subscript(i) * "(t)" end xlims := (t[0], Inf) t[0:nplot:nt], λ[i,0:nplot:nt] end end end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
8266
@doc raw""" # Planar Point Vortices """ module PointVortices using GeometricEquations using GeometricSolutions export odeproblem, iodeproblem, idaeproblem, iodeproblem_dg, lodeproblem_formal_lagrangian, hamiltonian, angular_momentum, ϑ1, ϑ2, ϑ3, ϑ4 export compute_energy_error, compute_angular_momentum_error const Δt = 0.01 const nt = 1000 const tspan = (0.0, Δt*nt) const reference_solution = [0.18722529318641928, 0.38967432450068706, 0.38125332930294187, 0.4258020604293123] const γ₁ = +0.5 const γ₂ = +0.5 const X0 = +0.5 const Y0 = +0.1 const X1 = +0.5 const Y1 = -0.1 S(x::T, y::T) where {T} = 1 + x^2 + y^2 S2(x::T, y::T) where {T} = 1 + 2x^2 + 2y^2 dSdx(x::T, y::T) where {T} = 2x dSdy(x::T, y::T) where {T} = 2y function hamiltonian(t, q, params) γ₁ * γ₂ * S(q[1],q[2]) * S(q[3],q[4]) * log( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / (2π) end ϑ1(q) = - γ₁ * q[2] * S(q[1], q[2]) / 2 ϑ2(q) = + γ₁ * q[1] * S(q[1], q[2]) / 2 ϑ3(q) = - γ₂ * q[4] * S(q[3], q[4]) / 2 ϑ4(q) = + γ₂ * q[3] * S(q[3], q[4]) / 2 ϑ(q) = [ϑ1(q), ϑ2(q), ϑ3(q), ϑ4(q)] function angular_momentum(t, q, params) q[1] * ϑ2(q) - q[2] * ϑ1(q) + q[3] * ϑ4(q) - q[4] * ϑ3(q) end const q₀ = [X0, Y0, X1, Y1] const p₀ = ϑ(q₀) dϑ1d1(t, q) = - γ₁ * q[2] * dSdx(q[1], q[2]) / 2 dϑ1d2(t, q) = - γ₁ * q[2] * dSdy(q[1], q[2]) / 2 - γ₁ * S(q[1], q[2]) / 2 dϑ1d3(t, q) = zero(eltype(q)) dϑ1d4(t, q) = zero(eltype(q)) dϑ2d1(t, q) = + γ₁ * q[1] * dSdx(q[1], q[2]) / 2 + γ₁ * S(q[1], q[2]) / 2 dϑ2d2(t, q) = + γ₁ * q[1] * dSdy(q[1], q[2]) / 2 dϑ2d3(t, q) = zero(eltype(q)) dϑ2d4(t, q) = zero(eltype(q)) dϑ3d1(t, q) = zero(eltype(q)) dϑ3d2(t, q) = zero(eltype(q)) dϑ3d3(t, q) = - γ₂ * q[4] * dSdx(q[3], q[4]) / 2 dϑ3d4(t, q) = - γ₂ * q[4] * dSdy(q[3], q[4]) / 2 - γ₂ * S(q[3], q[4]) / 2 dϑ4d1(t, q) = zero(eltype(q)) dϑ4d2(t, q) = zero(eltype(q)) dϑ4d3(t, q) = + γ₂ * q[3] * dSdx(q[3], q[4]) / 2 + γ₂ * S(q[3], q[4]) / 2 dϑ4d4(t, q) = + γ₂ * q[3] * dSdy(q[3], q[4]) / 2 function ϑ(p, t, q, params) p[1] = ϑ1(q) p[2] = ϑ2(q) p[3] = ϑ3(q) p[4] = ϑ4(q) end function ω(Ω, t, q, params) Ω[1,1] = 0 Ω[1,2] = dϑ1d2(t,q) - dϑ2d1(t,q) Ω[1,3] = dϑ1d3(t,q) - dϑ3d1(t,q) Ω[1,4] = dϑ1d4(t,q) - dϑ4d1(t,q) Ω[2,1] = dϑ2d1(t,q) - dϑ1d2(t,q) Ω[2,2] = 0 Ω[2,3] = dϑ2d3(t,q) - dϑ3d2(t,q) Ω[2,4] = dϑ2d4(t,q) - dϑ4d2(t,q) Ω[3,1] = dϑ3d1(t,q) - dϑ1d3(t,q) Ω[3,2] = dϑ3d2(t,q) - dϑ2d3(t,q) Ω[3,3] = 0 Ω[3,4] = dϑ3d4(t,q) - dϑ4d3(t,q) Ω[4,1] = dϑ4d1(t,q) - dϑ1d4(t,q) Ω[4,2] = dϑ4d2(t,q) - dϑ2d4(t,q) Ω[4,3] = dϑ4d3(t,q) - dϑ3d4(t,q) Ω[4,4] = 0 nothing end function f1(t, q, v) γ₁ * ( dSdx(q[1],q[2]) * (q[1] * v[2] - q[2] * v[1]) + v[2] * S(q[1], q[2]) ) / 2 end function f2(t, q, v) γ₁ * ( dSdy(q[1],q[2]) * (q[1] * v[2] - q[2] * v[1]) - v[1] * S(q[1], q[2]) ) / 2 end function f3(t, q, v) γ₂ * ( dSdx(q[3],q[4]) * (q[3] * v[4] - q[4] * v[3]) + v[4] * S(q[3], q[4]) ) / 2 end function f4(t, q, v) γ₂ * ( dSdy(q[3],q[4]) * (q[3] * v[4] - q[4] * v[3]) - v[3] * S(q[3], q[4]) ) / 2 end function dHd1(t, q) + γ₁ * γ₂ * dSdx(q[1],q[2]) * S(q[3],q[4]) * log( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / (2π) + γ₁ * γ₂ * S(q[1],q[2]) * S(q[3],q[4]) * (q[1] - q[3]) / ( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / π end function dHd2(t, q) + γ₁ * γ₂ * dSdy(q[1],q[2]) * S(q[3],q[4]) * log( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / (2π) + γ₁ * γ₂ * S(q[1],q[2]) * S(q[3],q[4]) * (q[2] - q[4]) / ( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / π end function dHd3(t, q) + γ₁ * γ₂ * dSdx(q[3],q[4]) * S(q[1],q[2]) * log( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / (2π) - γ₁ * γ₂ * S(q[1],q[2]) * S(q[3],q[4]) * (q[1] - q[3]) / ( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / π end function dHd4(t, q) + γ₁ * γ₂ * dSdy(q[3],q[4]) * S(q[1],q[2]) * log( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / (2π) - γ₁ * γ₂ * S(q[1],q[2]) * S(q[3],q[4]) * (q[2] - q[4]) / ( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / π end function dH(dH, t, q, params) dH[1] = dHd1(t, q) dH[2] = dHd2(t, q) dH[3] = dHd3(t, q) dH[4] = dHd4(t, q) nothing end function point_vortices_v(v, t, q, params) denominator1 = 1 / (γ₁ * S2(q[1], q[2])) denominator2 = 1 / (γ₂ * S2(q[3], q[4])) v[1] = - dHd2(t,q) * denominator1 v[2] = + dHd1(t,q) * denominator1 v[3] = - dHd4(t,q) * denominator2 v[4] = + dHd3(t,q) * denominator2 nothing end function point_vortices_v(v, t, q, p, params) point_vortices_v(v, t, q, params) end function point_vortices_ϑ(p, t, q, params) p[1] = ϑ1(q) p[2] = ϑ2(q) p[3] = ϑ3(q) p[4] = ϑ4(q) nothing end function point_vortices_ϑ(p, t, q, v, params) point_vortices_ϑ(p, t, q, params) end function point_vortices_f(f, t, q, v, params) f[1] = f1(t,q,v) - dHd1(t,q) f[2] = f2(t,q,v) - dHd2(t,q) f[3] = f3(t,q,v) - dHd3(t,q) f[4] = f4(t,q,v) - dHd4(t,q) nothing end point_vortices_f(f, t, q, v, p, params) = point_vortices_f(f, t, q, v, params) function point_vortices_g(g, t, q, λ, params) g[1] = f1(t,q,λ) g[2] = f2(t,q,λ) g[3] = f3(t,q,λ) g[4] = f4(t,q,λ) nothing end point_vortices_g(g, t, q, p, λ, params) = point_vortices_g(g, t, q, λ, params) point_vortices_g(g, t, q, v, p, λ, params) = point_vortices_g(g, t, q, p, λ, params) function point_vortices_u(u, t, q, v, params) u[1] = v[1] u[2] = v[2] u[3] = v[3] u[4] = v[4] nothing end point_vortices_u(u, t, q, p, λ, params) = point_vortices_u(u, t, q, λ, params) point_vortices_u(u, t, q, v, p, λ, params) = point_vortices_u(u, t, q, p, λ, params) function point_vortices_ϕ(ϕ, t, q, p, params) ϕ[1] = p[1] - ϑ1(q) ϕ[2] = p[2] - ϑ2(q) ϕ[3] = p[3] - ϑ3(q) ϕ[4] = p[4] - ϑ4(q) nothing end point_vortices_ϕ(ϕ, t, q, v, p, params) = point_vortices_ϕ(ϕ, t, q, p, params) function odeproblem(q₀=q₀; tspan = tspan, tstep = Δt) ODEProblem(point_vortices_v, tspan, tstep, q₀) end function iodeproblem(q₀=q₀, p₀=ϑ(q₀); tspan = tspan, tstep = Δt) IODEProblem(point_vortices_ϑ, point_vortices_f, point_vortices_g, tspan, tstep, q₀, p₀; v̄=point_vortices_v) end function idaeproblem(q₀=q₀, p₀=ϑ(q₀), λ₀=zero(q₀); tspan = tspan, tstep = Δt) IDAEProblem(point_vortices_ϑ, point_vortices_f, point_vortices_u, point_vortices_g, point_vortices_ϕ, tspan, tstep, q₀, p₀, λ₀; v̄=point_vortices_v) end function idoeproblem_dg(q₀=q₀; tspan = tspan, tstep = Δt) IODEProblem(point_vortices_ϑ, point_vortices_f, point_vortices_g, tspan, tstep, q₀, q₀; v=point_vortices_v) end function lodeproblem_formal_lagrangian(q₀=q₀, p₀=ϑ(q₀); tspan = tspan, tstep = Δt) LODEProblem(ϑ, point_vortices_f, point_vortices_g, tspan, tstep, q₀, p₀; v̄=point_vortices_v, Ω=ω, ∇H=dH) end function compute_energy_error(t, q::DataSeries{T}, params) where {T} h = DataSeries(T, q.nt) e = DataSeries(T, q.nt) for i in axes(q,2) h[i] = hamiltonian(t[i], q[:,i], params) e[i] = (h[i] - h[0]) / h[0] end (h, e) end function compute_angular_momentum_error(t, q::DataSeries{T}, params) where {T} m = DataSeries(T, q.nt) e = DataSeries(T, q.nt) for i in axes(q,2) m[i] = angular_momentum(t[i], q[:,i], params) e[i] = (m[i] - m[0]) / m[0] end (m, e) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
6257
@doc raw""" # Planar Point Vortices with linear one-form """ module PointVorticesLinear using GeometricEquations export odeproblem, iodeproblem, iodeproblem_dg, lodeproblem_formal_lagrangian, hamiltonian, angular_momentum, ϑ1, ϑ2, ϑ3, ϑ4, compute_energy, compute_energy_error, compute_angular_momentum_error, compute_momentum_error, compute_one_form const Δt = 0.01 const nt = 1000 const tspan = (0.0, Δt*nt) const γ₁ = 4.0 const γ₂ = 2.0 const d = 1.0 const q₀ = [γ₂*d/(γ₁+γ₂), 0.0, -γ₁*d/(γ₁+γ₂), 0.0] function hamiltonian(t,q) γ₁ * γ₂ * log( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / (4π) end ϑ1(q) = - γ₁ * q[2] / 2 ϑ2(q) = + γ₁ * q[1] / 2 ϑ3(q) = - γ₂ * q[4] / 2 ϑ4(q) = + γ₂ * q[3] / 2 ϑ(q) = [ϑ1(q), ϑ2(q), ϑ3(q), ϑ4(q)] function angular_momentum(t,q) # γ₁ * (q[1]^2 + q[2]^2) * S(q[1],q[2]) + # γ₂ * (q[3]^2 + q[4]^2) * S(q[3],q[4]) q[1] * ϑ2(q) - q[2] * ϑ1(q) + q[3] * ϑ4(q) - q[4] * ϑ3(q) end dϑ1d1(t, q) = zero(eltype(q)) dϑ1d2(t, q) = - γ₁ / 2 dϑ1d3(t, q) = zero(eltype(q)) dϑ1d4(t, q) = zero(eltype(q)) dϑ2d1(t, q) = + γ₁ / 2 dϑ2d2(t, q) = zero(eltype(q)) dϑ2d3(t, q) = zero(eltype(q)) dϑ2d4(t, q) = zero(eltype(q)) dϑ3d1(t, q) = zero(eltype(q)) dϑ3d2(t, q) = zero(eltype(q)) dϑ3d3(t, q) = zero(eltype(q)) dϑ3d4(t, q) = - γ₂ / 2 dϑ4d1(t, q) = zero(eltype(q)) dϑ4d2(t, q) = zero(eltype(q)) dϑ4d3(t, q) = + γ₂ / 2 dϑ4d4(t, q) = zero(eltype(q)) function ϑ(p, t, q) p[1] = ϑ1(q) p[2] = ϑ2(q) p[3] = ϑ3(q) p[4] = ϑ4(q) end function ω(Ω, t, q) Ω[1,1] = 0 Ω[1,2] = dϑ1d2(t,q) - dϑ2d1(t,q) Ω[1,3] = dϑ1d3(t,q) - dϑ3d1(t,q) Ω[1,4] = dϑ1d4(t,q) - dϑ4d1(t,q) Ω[2,1] = dϑ2d1(t,q) - dϑ1d2(t,q) Ω[2,2] = 0 Ω[2,3] = dϑ2d3(t,q) - dϑ3d2(t,q) Ω[2,4] = dϑ2d4(t,q) - dϑ4d2(t,q) Ω[3,1] = dϑ3d1(t,q) - dϑ1d3(t,q) Ω[3,2] = dϑ3d2(t,q) - dϑ2d3(t,q) Ω[3,3] = 0 Ω[3,4] = dϑ3d4(t,q) - dϑ4d3(t,q) Ω[4,1] = dϑ4d1(t,q) - dϑ1d4(t,q) Ω[4,2] = dϑ4d2(t,q) - dϑ2d4(t,q) Ω[4,3] = dϑ4d3(t,q) - dϑ3d4(t,q) Ω[4,4] = 0 nothing end f1(t, q, v) = + γ₁ * v[2] / 2 f2(t, q, v) = - γ₁ * v[1] / 2 f3(t, q, v) = + γ₂ * v[4] / 2 f4(t, q, v) = - γ₂ * v[3] / 2 dHd1(t, q) = + γ₁ * γ₂ * (q[1] - q[3]) / ( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / (2π) dHd2(t, q) = + γ₁ * γ₂ * (q[2] - q[4]) / ( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / (2π) dHd3(t, q) = - γ₁ * γ₂ * (q[1] - q[3]) / ( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / (2π) dHd4(t, q) = - γ₁ * γ₂ * (q[2] - q[4]) / ( (q[1] - q[3])^2 + (q[2] - q[4])^2 ) / (2π) function dH(dH, t, q, params) dH[1] = dHd1(t, q) dH[2] = dHd2(t, q) dH[3] = dHd3(t, q) dH[4] = dHd4(t, q) nothing end function point_vortices_v(v, t, q, params) v[1] = - dHd2(t,q) / γ₁ v[2] = + dHd1(t,q) / γ₁ v[3] = - dHd4(t,q) / γ₂ v[4] = + dHd3(t,q) / γ₂ nothing end function odeproblem(q₀=q₀; tspan = tspan, tstep = Δt) ODEProblem(point_vortices_v, tspan, tstep, q₀) end function point_vortices_ϑ(p, t, q, v, params) p[1] = ϑ1(q) p[2] = ϑ2(q) p[3] = ϑ3(q) p[4] = ϑ4(q) nothing end function point_vortices_f(f, t, q, v, params) f[1] = f1(t,q,v) - dHd1(t,q) f[2] = f2(t,q,v) - dHd2(t,q) f[3] = f3(t,q,v) - dHd3(t,q) f[4] = f4(t,q,v) - dHd4(t,q) nothing end function point_vortices_g(g, t, q, λ, params) g[1] = f1(t,q,λ) g[2] = f2(t,q,λ) g[3] = f3(t,q,λ) g[4] = f4(t,q,λ) nothing end point_vortices_g(g, t, q, p, λ, params) = point_vortices_g(g, t, q, λ, params) point_vortices_g(g, t, q, v, p, λ, params) = point_vortices_g(g, t, q, p, λ, params) function point_vortices_v(v, t, q, p, params) point_vortices_v(v, t, q, params) end function iodeproblem(q₀=q₀, p₀=ϑ(q₀); tspan = tspan, tstep = Δt) IODEProblem(point_vortices_ϑ, point_vortices_f, point_vortices_g, tspan, tstep, q₀, p₀; v̄=point_vortices_v) end function iodeproblem_dg(q₀=q₀; tspan = tspan, tstep = Δt) IODEProblem(point_vortices_ϑ, point_vortices_f, point_vortices_g, tspan, tstep, q₀, q₀; v=point_vortices_v) end function lodeproblem_formal_lagrangian(q₀=q₀, p₀=ϑ(q₀); tspan = tspan, tstep = Δt) LODEProblem(ϑ, point_vortices_f, point_vortices_g, tspan, tstep, q₀, p₀; v̄=point_vortices_v, Ω=ω, ∇H=dH) end function compute_energy(t, q) h = zeros(q.nt+1) for i in 1:(q.nt+1) h[i] = hamiltonian(t.t[i], q.d[:,i]) end return h end function compute_energy_error(t, q) h = zeros(q.nt+1) for i in 1:(q.nt+1) h[i] = hamiltonian(t.t[i], q.d[:,i]) end h_error = (h .- h[1]) / h[1] end function compute_angular_momentum_error(t, q) P = zeros(q.nt+1) for i in 1:(q.nt+1) P[i] = angular_momentum(t.t[i], q.d[:,i]) end P_error = (P .- P[1]) / P[1] end function compute_momentum_error(t, q, p) p1_error = zeros(q.nt+1) p2_error = zeros(q.nt+1) p3_error = zeros(q.nt+1) p4_error = zeros(q.nt+1) for i in 1:(q.nt+1) p1_error[i] = p.d[1,i] - ϑ1(q.d[:,i]) p2_error[i] = p.d[2,i] - ϑ2(q.d[:,i]) p3_error[i] = p.d[3,i] - ϑ3(q.d[:,i]) p4_error[i] = p.d[4,i] - ϑ4(q.d[:,i]) end (p1_error, p2_error, p3_error, p4_error) end function compute_one_form(t, q) p1 = zeros(q.nt+1) p2 = zeros(q.nt+1) p3 = zeros(q.nt+1) p4 = zeros(q.nt+1) for i in 1:(q.nt+1) p1[i] = ϑ1(q.d[:,i]) p2[i] = ϑ2(q.d[:,i]) p3[i] = ϑ3(q.d[:,i]) p4[i] = ϑ4(q.d[:,i]) end (p1, p2, p3, p4) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
1486
@doc raw""" # Rigid body ```math \begin{aligned} \dot{x} = Ayz \\ \dot{y} = Bxz \\ \dot{z} = Cxy \end{aligned}, ``` where ``A = (I_2 - I_3)/(I_2I_3)``, ``B = (I_3 - I_1)/(I_3I_1)`` and ``C = (I_1 - I_2)/(I_1I_2)``; ``I_{\cdot}`` are the *principal components of inertia*. The initial condition and the default parameters are taken from [bajars2023locally](@cite). """ module RigidBody using GeometricEquations using GeometricSolutions using Parameters export odeproblem, odeensemble const tspan = (0.0, 100.0) const tstep = 0.1 const default_parameters = ( I₁ = 2., I₂ = 1., I₃ = 2. / 3. ) const q₀ = [cos(1.1), 0., sin(1.1)] const q₁ = [cos(2.1), 0., sin(2.1)] const q₂ = [cos(2.2), 0., sin(2.2)] function rigid_body_v(v, t, q, params) @unpack I₁, I₂, I₃ = params A = (I₂ - I₃) / (I₂ * I₃) B = (I₃ - I₁) / (I₃ * I₁) C = (I₁ - I₂) / (I₁ * I₂) v[1] = A * q[2] * q[3] v[2] = B * q[1] * q[3] v[3] = C * q[1] * q[2] nothing end function odeproblem(q₀ = q₀; tspan = tspan, tstep = tstep, parameters = default_parameters) ODEProblem(rigid_body_v, tspan, tstep, q₀; parameters = parameters) end function odeensemble(samples = [q₀, q₁, q₂]; parameters = default_parameters, tspan = tspan, tstep = tstep) ODEEnsemble(rigid_body_v, tspan, tstep, samples; parameters = parameters) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
2392
@doc raw""" The Toda lattice is a model for a one-dimensional crystal named after its discoverer Morikazu Toda [toda1967vibration](@cite). It is a prime example of a non-trivial completely integrable system. The only system parameters are the *number of points* ``N`` in the periodic lattice and ``\alpha`` which adjusts the strength of the interactions in the lattice. """ module TodaLattice using EulerLagrange using LinearAlgebra using Parameters using GeometricEquations: HODEEnsemble export hamiltonian, lagrangian export hodeproblem, lodeproblem export hodeensemble include("bump_initial_condition.jl") const α̃ = .64 const Ñ = 200 const default_parameters = ( α = α̃, N = Ñ ) function hamiltonian(t, q, p, params) @unpack N, α = params sum(p[n] ^ 2 / 2 + α * exp(q[n] - q[n % Ñ + 1]) for n in 1:Ñ) end function lagrangian(t, q, q̇, params) @unpack N, α = params sum(q̇[n] ^ 2 / 2 - α * exp(q[n] - q[n % Ñ + 1]) for n in 1:Ñ) end const tstep = .1 const tspan = (0.0, 120.0) # parameter for the initial conditions const μ = .3 const q₀ = compute_initial_condition(μ, Ñ).q const p₀ = compute_initial_condition(μ, Ñ).p """ Hamiltonian problem for the Toda lattice. """ function hodeproblem(q₀ = q₀, p₀ = p₀; tspan = tspan, tstep = tstep, parameters = default_parameters) t, q, p = hamiltonian_variables(Ñ) sparams = symbolize(parameters) ham_sys = HamiltonianSystem(hamiltonian(t, q, p, sparams), t, q, p, sparams) HODEProblem(ham_sys, tspan, tstep, q₀, p₀; parameters = parameters) end """ Lagrangian problem for the Toda lattice. """ function lodeproblem(q₀ = q₀, p₀ = p₀; tspan = tspan, tstep = tstep, parameters = default_parameters) t, x, v = lagrangian_variables(Ñ) sparams = symbolize(parameters) lag_sys = LagrangianSystem(lagrangian(t, x, v, sparams), t, x, v, sparams) lodeproblem(lag_sys, tspan, tstep, q₀, p₀; parameters = parameters) end function hodeensemble(q₀ = q₀, p₀ = p₀; tspan = tspan, tstep = tstep, parameters = default_parameters) eq = hodeproblem().equation HODEEnsemble(eq.v, eq.f, eq.hamiltonian, tspan, tstep, q₀, p₀; parameters = parameters) end end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
383
using Test using GeometricIntegrators using GeometricProblems.ABCFlow using GeometricSolutions @testset "$(rpad("ABC Flow",80))" begin @test_nowarn odeproblem() @test_nowarn odeensemble() ode = odeproblem([0.5, 0., 0.]) ref_sol = integrate(ode, Gauss(8)) ode_sol = integrate(ode, Gauss(2)) @test relative_maximum_error(ode_sol.q, ref_sol.q) < 1E-5 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
971
import GeometricProblems.LinearWave as lw using GeometricProblems: h, s, u₀, ∂h, ∂s, ∂u₀ using ForwardDiff using Test const test_point₁ = 0.5 const test_point₂ = 1.5 const test_point₃ = 2.5 const μ = lw.default_parameters.μ function test_h_derivative(test_point) h_autodiff = ForwardDiff.derivative(h, test_point) @test h_autodiff ≈ ∂h(test_point) end function test_s_derivative(test_point) s_closure(ξ) = s(ξ, μ) s_autodiff = ForwardDiff.derivative(s_closure, test_point) @test s_autodiff ≈ ∂s(test_point, μ) end function test_u₀_derivative(test_point) u₀_closure(ξ) = u₀(ξ, μ) u₀_autodiff = ForwardDiff.derivative(u₀_closure, test_point) @test u₀_autodiff ≈ ∂u₀(test_point, μ) end function test_all_derivatives(test_point) test_h_derivative(test_point) test_s_derivative(test_point) test_u₀_derivative(test_point) end test_all_derivatives(test_point₁) test_all_derivatives(test_point₂) test_all_derivatives(test_point₃)
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
484
using Test using GeometricIntegrators using GeometricProblems.DoublePendulum using GeometricSolutions @testset "$(rpad("Double Pendulum",80))" begin @test_nowarn hodeproblem() @test_nowarn lodeproblem() hode = hodeproblem() lode = lodeproblem() hode_sol = integrate(hode, Gauss(2)) lode_sol = integrate(lode, Gauss(2)) @test relative_maximum_error(hode_sol.q, lode_sol.q) < 1E-13 @test relative_maximum_error(hode_sol.p, lode_sol.p) < 1E-11 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
1592
using Test using GeometricIntegrators using GeometricProblems.HarmonicOscillator using GeometricProblems.HarmonicOscillator: reference_solution, reference_solution_q, reference_solution_p using GeometricSolutions @testset "$(rpad("Harmonic Oscillator",80))" begin @test_nowarn odeproblem() @test_nowarn hodeproblem() @test_nowarn iodeproblem() @test_nowarn lodeproblem() @test_nowarn podeproblem() @test_nowarn sodeproblem() @test_nowarn degenerate_iodeproblem() @test_nowarn degenerate_lodeproblem() @test_nowarn daeproblem() @test_nowarn hdaeproblem() @test_nowarn idaeproblem() @test_nowarn ldaeproblem() @test_nowarn pdaeproblem() @test_nowarn odeensemble() @test_nowarn podeensemble() @test_nowarn hodeensemble() ode = odeproblem() iode = degenerate_iodeproblem() pode = podeproblem() hode = hodeproblem() ref = exact_solution(ode) sol = integrate(ode, Gauss(2)) @test relative_maximum_error(sol.q, ref.q) < 1E-4 sol = integrate(iode, MidpointProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 1E-4 sol = integrate(iode, SymmetricProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 1E-4 sol = exact_solution(ode) @test sol.q[end] == reference_solution sol = exact_solution(pode) @test sol.q[end] == [reference_solution_q] @test sol.p[end] == [reference_solution_p] sol = exact_solution(hode) @test sol.q[end] == [reference_solution_q] @test sol.p[end] == [reference_solution_p] end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
2093
using GeometricIntegrators using GeometricProblems.KuboOscillator using Test @testset "$(rpad("Kubo Oscillator",80))" begin sde = kubo_oscillator_sde_1() psde = kubo_oscillator_psde_1() spsde = kubo_oscillator_spsde_1() sde_equs = functions(sde) @test_nowarn sde_equs[:v](zero(sde.ics.q), tbegin(sde), sde.ics.q) @test_nowarn sde_equs[:B](zeros(eltype(sde.ics.q), tbegin(sde), sde.ics.q, sde.d, sde.m)) @test_nowarn sde_equs[:B](zeros(eltype(sde.ics.q), tbegin(sde), sde.ics.q, sde.d, sde.m), 1) psde_equs = functions(psde) @test_nowarn psde_equs[:v](zero(psde.ics.q), tbegin(psde), psde.ics.q, psde.ics.p) @test_nowarn psde_equs[:f](zero(psde.ics.p), tbegin(psde), psde.ics.q, psde.ics.p) @test_nowarn psde_equs[:B](zero(psde.ics.q), tbegin(psde), psde.ics.q, psde.ics.p) @test_nowarn psde_equs[:G](zero(psde.ics.p), tbegin(psde), psde.ics.q, psde.ics.p) @test_nowarn psde_equs[:B](zeros(eltype(psde.ics.q), tbegin(psde), psde.ics.q, psde.ics.p, psde.d, psde.m)) @test_nowarn psde_equs[:G](zeros(eltype(psde.ics.p), tbegin(psde), psde.ics.q, psde.ics.p, psde.d, psde.m)) spsde_equs = functions(spsde) @test_nowarn spsde_equs[:v ](zero(spsde.ics.q), tbegin(spsde), spsde.ics.q, spsde.ics.p) @test_nowarn spsde_equs[:f1](zero(spsde.ics.p), tbegin(spsde), spsde.ics.q, spsde.ics.p) @test_nowarn spsde_equs[:f2](zero(spsde.ics.p), tbegin(spsde), spsde.ics.q, spsde.ics.p) @test_nowarn spsde_equs[:B ](zero(spsde.ics.q), tbegin(spsde), spsde.ics.q, spsde.ics.p) @test_nowarn spsde_equs[:G1](zero(spsde.ics.p), tbegin(spsde), spsde.ics.q, spsde.ics.p) @test_nowarn spsde_equs[:G2](zero(spsde.ics.p), tbegin(spsde), spsde.ics.q, spsde.ics.p) @test_nowarn spsde_equs[:B ](zeros(eltype(spsde.ics.q), tbegin(spsde), spsde.ics.q, spsde.ics.p, spsde.d, spsde.m)) @test_nowarn spsde_equs[:G1](zeros(eltype(spsde.ics.p), tbegin(spsde), spsde.ics.q, spsde.ics.p, spsde.d, spsde.m)) @test_nowarn spsde_equs[:G2](zeros(eltype(spsde.ics.p), tbegin(spsde), spsde.ics.q, spsde.ics.p, spsde.d, spsde.m)) end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
468
using Test using GeometricIntegrators using GeometricProblems.LorenzAttractor using GeometricProblems.LorenzAttractor: reference_solution using GeometricSolutions @testset "$(rpad("Lorenz Attractor",80))" begin ode = lorenz_attractor_ode() sol = integrate(ode, Gauss(1)) @test relative_maximum_error(sol.q[end], reference_solution) < 4E-2 sol = integrate(ode, Gauss(2)) @test relative_maximum_error(sol.q[end], reference_solution) < 2E-5 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
999
using Test using GeometricIntegrators using GeometricIntegrators.SPARK using GeometricProblems.LotkaVolterra2dGauge using GeometricSolutions @testset "$(rpad("Lotka-Volterra 2D with symmetric Lagrangian with gauge terms",80))" begin ode = odeproblem() iode = iodeproblem() idae = idaeproblem() ref = integrate(ode, Gauss(8)) sol = integrate(ode, Gauss(2)) @test relative_maximum_error(sol.q, ref.q) < 4E-4 sol = integrate(iode, MidpointProjection(VPRKGauss(2))) # println(relative_maximum_error(sol.q, ref.q)) @test relative_maximum_error(sol.q, ref.q) < 2E-3 sol = integrate(iode, SymmetricProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 5E-4 sol = integrate(idae, TableauVSPARKGLRKpMidpoint(2)) # println(relative_maximum_error(sol.q, ref.q)) @test relative_maximum_error(sol.q, ref.q) < 2E-3 sol = integrate(idae, TableauVSPARKGLRKpSymmetric(2)) @test relative_maximum_error(sol.q, ref.q) < 5E-4 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
880
using Test using GeometricIntegrators using GeometricIntegrators.SPARK using GeometricProblems.LotkaVolterra2dSingular using GeometricSolutions @testset "$(rpad("Lotka-Volterra 2D with singular Lagrangian",80))" begin ode = odeproblem() iode = iodeproblem() idae = idaeproblem() ref = integrate(ode, Gauss(8)) sol = integrate(ode, Gauss(2)) @test relative_maximum_error(sol.q, ref.q) < 5E-4 sol = integrate(iode, MidpointProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 5E-4 sol = integrate(iode, SymmetricProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 5E-4 sol = integrate(idae, TableauVSPARKGLRKpMidpoint(2)) @test relative_maximum_error(sol.q, ref.q) < 5E-4 sol = integrate(idae, TableauVSPARKGLRKpSymmetric(2)) @test relative_maximum_error(sol.q, ref.q) < 5E-4 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
986
using Test using GeometricIntegrators using GeometricIntegrators.SPARK using GeometricProblems.LotkaVolterra2dSymmetric using GeometricSolutions @testset "$(rpad("Lotka-Volterra 2D with symmetric Lagrangian",80))" begin ode = odeproblem() iode = iodeproblem() idae = idaeproblem() ref = integrate(ode, Gauss(8)) sol = integrate(ode, Gauss(2)) @test relative_maximum_error(sol.q, ref.q) < 4E-4 sol = integrate(iode, MidpointProjection(VPRKGauss(2))) # println(relative_maximum_error(sol.q, ref.q)) @test relative_maximum_error(sol.q, ref.q) < 2E-3 sol = integrate(iode, SymmetricProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 5E-4 sol = integrate(idae, TableauVSPARKGLRKpMidpoint(2)) # println(relative_maximum_error(sol.q, ref.q)) @test relative_maximum_error(sol.q, ref.q) < 2E-3 sol = integrate(idae, TableauVSPARKGLRKpSymmetric(2)) @test relative_maximum_error(sol.q, ref.q) < 5E-4 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
1023
using Test using GeometricIntegrators using GeometricIntegrators.SPARK using GeometricProblems.LotkaVolterra2d using GeometricSolutions @testset "$(rpad("Lotka-Volterra 2d",80))" begin ode = odeproblem() hode = hodeproblem() iode = iodeproblem() pode = podeproblem() lode = lodeproblem() dae = daeproblem() hdae = hdaeproblem() idae = idaeproblem() pdae = pdaeproblem() ldae = ldaeproblem() ref = integrate(ode, Gauss(8)) sol = integrate(ode, Gauss(2)) @test relative_maximum_error(sol.q, ref.q) < 5E-4 sol = integrate(iode, MidpointProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 5E-4 sol = integrate(iode, SymmetricProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 5E-4 sol = integrate(idae, TableauVSPARKGLRKpMidpoint(2)) @test relative_maximum_error(sol.q, ref.q) < 5E-4 sol = integrate(idae, TableauVSPARKGLRKpSymmetric(2)) @test relative_maximum_error(sol.q, ref.q) < 5E-4 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
757
using Test using GeometricIntegrators using GeometricProblems.LotkaVolterra3d using GeometricSolutions @testset "$(rpad("Lotka-Volterra 3D",80))" begin ode = odeproblem() ref = integrate(ode, Gauss(8)) sol = integrate(ode, Gauss(1)) H, ΔH = compute_energy_error(sol.t, sol.q, parameters(ode)) C, ΔC = compute_casimir_error(sol.t, sol.q, parameters(ode)) @test relative_maximum_error(sol.q, ref.q) < 5E-4 @test ΔH[end] < 4E-6 @test ΔC[end] < 8E-6 sol = integrate(ode, Gauss(2)) H, ΔH = compute_energy_error(sol.t, sol.q, parameters(ode)) C, ΔC = compute_casimir_error(sol.t, sol.q, parameters(ode)) @test relative_maximum_error(sol.q, ref.q) < 2E-9 @test ΔH[end] < 5E-11 @test ΔC[end] < 2E-11 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
5639
using Test using GeometricEquations using GeometricIntegrators using GeometricIntegrators.SPARK using GeometricSolutions import GeometricProblems.LotkaVolterra4d import GeometricProblems.LotkaVolterra4dLagrangian import GeometricProblems.LotkaVolterra4dLagrangian: reference_solution @testset "$(rpad("Lotka-Volterra 4D (Lagrangian)",80))" begin lag_ode = LotkaVolterra4dLagrangian.odeproblem() lag_iode = LotkaVolterra4dLagrangian.iodeproblem() lag_idae = LotkaVolterra4dLagrangian.idaeproblem() ref_ode = LotkaVolterra4d.odeproblem() ref_iode = LotkaVolterra4d.iodeproblem() ref_idae = LotkaVolterra4d.idaeproblem() ref = integrate(ref_ode, Gauss(8)) @assert tbegin(lag_ode) == tbegin(ref_ode) @assert tbegin(lag_iode) == tbegin(ref_iode) @assert tbegin(lag_idae) == tbegin(ref_idae) @assert lag_ode.ics == ref_ode.ics @assert lag_iode.ics == ref_iode.ics @assert lag_idae.ics == ref_idae.ics lag_equs = functions(lag_ode) lag_invs = invariants(lag_ode) ref_equs = functions(ref_ode) ref_invs = invariants(ref_ode) v1 = zero(lag_ode.ics.q) v2 = zero(ref_ode.ics.q) lag_equs[:v](v1, tbegin(lag_ode), lag_ode.ics.q, parameters(lag_ode)) ref_equs[:v](v2, tbegin(ref_ode), ref_ode.ics.q, parameters(ref_ode)) @test v1 ≈ v2 atol=eps() h1 = lag_invs[:h](tbegin(lag_ode), lag_ode.ics.q, parameters(lag_ode)) h2 = ref_invs[:h](tbegin(ref_ode), ref_ode.ics.q, parameters(ref_ode)) @test h1 ≈ h2 atol=eps() sol = integrate(lag_ode, Gauss(2)) @test relative_maximum_error(sol.q, ref.q) < 8E-4 ref_sol = integrate(ref_ode, Gauss(2)) @test relative_maximum_error(sol.q, ref_sol.q) < 2E-14 lag_equs = functions(lag_iode) lag_invs = invariants(lag_iode) lag_igs = initialguess(lag_iode) ref_equs = functions(ref_iode) ref_invs = invariants(ref_iode) @test lag_iode.ics.q == ref_iode.ics.q @test lag_iode.ics.p == ref_iode.ics.p @test parameters(lag_iode) == parameters(ref_iode) ϑ1 = zero(lag_iode.ics.q) ϑ2 = zero(ref_iode.ics.q) lag_equs[:ϑ](ϑ1, tbegin(lag_iode), lag_iode.ics.q, v1, parameters(lag_iode)) ref_equs[:ϑ](ϑ2, tbegin(ref_iode), ref_iode.ics.q, v2, parameters(ref_iode)) @test ϑ1 ≈ ϑ2 atol=eps() f1 = zero(lag_iode.ics.q) f2 = zero(ref_iode.ics.q) lag_equs[:f](f1, tbegin(lag_iode), lag_iode.ics.q, v1, parameters(lag_iode)) ref_equs[:f](f2, tbegin(ref_iode), ref_iode.ics.q, v2, parameters(ref_iode)) @test f1 ≈ f2 atol=eps() g1 = zero(lag_iode.ics.q) g2 = zero(ref_iode.ics.q) λ1 = zero(v1) λ2 = zero(v2) lag_equs[:g](g1, tbegin(lag_iode), lag_iode.ics.q, v1, λ1, parameters(lag_iode)) ref_equs[:g](g2, tbegin(ref_iode), ref_iode.ics.q, v2, λ2, parameters(ref_iode)) @test g1 ≈ g2 atol=eps() v1 = zero(lag_iode.ics.q) v2 = zero(ref_iode.ics.q) lag_igs[:v](v1, tbegin(lag_iode), lag_iode.ics.q, zero(f1), parameters(lag_iode)) lag_igs[:v](v2, tbegin(ref_iode), ref_iode.ics.q, zero(f2), parameters(ref_iode)) @test v1 ≈ v2 atol=eps() f1 = zero(lag_iode.ics.q) f2 = zero(ref_iode.ics.q) lag_igs[:f](f1, tbegin(lag_iode), lag_iode.ics.q, v1, parameters(lag_iode)) lag_igs[:f](f2, tbegin(ref_iode), ref_iode.ics.q, v2, parameters(ref_iode)) @test f1 ≈ f2 atol=eps() h1 = lag_invs[:h](tbegin(lag_iode), lag_iode.ics.q, zero(lag_iode.ics.q), parameters(lag_iode)) h2 = ref_invs[:h](tbegin(ref_iode), ref_iode.ics.q, zero(ref_iode.ics.q), parameters(ref_iode)) @test h1 ≈ h2 atol=eps() sol = integrate(lag_iode, MidpointProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 2E-3 ref_sol = integrate(ref_iode, MidpointProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref_sol.q) < 8E-14 sol = integrate(lag_iode, SymmetricProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 8E-4 ref_sol = integrate(ref_iode, SymmetricProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref_sol.q) < 4E-14 lag_equs = functions(lag_idae) lag_invs = invariants(lag_idae) lag_igs = initialguess(lag_idae) ref_equs = functions(ref_idae) ref_invs = invariants(ref_idae) @test lag_idae.ics.q == ref_idae.ics.q @test lag_idae.ics.p == ref_idae.ics.p @test parameters(lag_idae) == parameters(ref_idae) v1 = zero(lag_idae.ics.q) v2 = zero(ref_idae.ics.q) lag_igs[:v](v1, tbegin(lag_idae), lag_idae.ics.q, zero(f1), parameters(lag_idae)) lag_igs[:v](v2, tbegin(ref_idae), ref_idae.ics.q, zero(f2), parameters(ref_idae)) @test v1 ≈ v2 atol=eps() f1 = zero(lag_idae.ics.q) f2 = zero(ref_idae.ics.q) lag_igs[:f](f1, tbegin(lag_idae), lag_idae.ics.q, v1, parameters(lag_idae)) lag_igs[:f](f2, tbegin(ref_idae), ref_idae.ics.q, v2, parameters(ref_idae)) @test f1 ≈ f2 atol=eps() h1 = lag_invs[:h](tbegin(lag_idae), lag_idae.ics.q, zero(lag_idae.ics.q), parameters(lag_idae)) h2 = ref_invs[:h](tbegin(ref_idae), ref_idae.ics.q, zero(ref_idae.ics.q), parameters(ref_idae)) @test h1 ≈ h2 atol=eps() sol = integrate(lag_idae, TableauVSPARKGLRKpMidpoint(2)) @test relative_maximum_error(sol.q, ref.q) < 2E-3 ref_sol = integrate(ref_idae, TableauVSPARKGLRKpMidpoint(2)) @test relative_maximum_error(sol.q, ref_sol.q) < 4E-14 sol = integrate(lag_idae, TableauVSPARKGLRKpSymmetric(2)) @test relative_maximum_error(sol.q, ref.q) < 8E-4 ref_sol = integrate(ref_idae, TableauVSPARKGLRKpSymmetric(2)) @test relative_maximum_error(sol.q, ref_sol.q) < 8E-14 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
847
using Test using GeometricIntegrators using GeometricIntegrators.SPARK using GeometricProblems.LotkaVolterra4d using GeometricSolutions @testset "$(rpad("Lotka-Volterra 4D",80))" begin ode = odeproblem() iode = iodeproblem() idae = idaeproblem() ref = integrate(ode, Gauss(8)) sol = integrate(ode, Gauss(2)) @test relative_maximum_error(sol.q, ref.q) < 8E-4 sol = integrate(iode, MidpointProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 2E-3 sol = integrate(iode, SymmetricProjection(VPRKGauss(2))) @test relative_maximum_error(sol.q, ref.q) < 8E-4 sol = integrate(idae, TableauVSPARKGLRKpMidpoint(2)) @test relative_maximum_error(sol.q, ref.q) < 2E-3 sol = integrate(idae, TableauVSPARKGLRKpSymmetric(2)) @test relative_maximum_error(sol.q, ref.q) < 8E-4 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
434
using Test using GeometricIntegrators using GeometricProblems.PointVorticesLinear using GeometricSolutions @testset "$(rpad("Point Vortices (linear)",80))" begin ode = odeproblem() iode = iodeproblem() ref = integrate(ode, Gauss(8)) sol = integrate(ode, Gauss(2)) @test relative_maximum_error(sol.q, ref.q) < 1E-9 sol = integrate(iode, Gauss(2)) @test relative_maximum_error(sol.q, ref.q) < 1E-9 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
590
using Test using GeometricIntegrators using GeometricIntegrators.SPARK using GeometricProblems.PointVortices using GeometricSolutions @testset "$(rpad("Point Vortices",80))" begin ode = odeproblem() iode = iodeproblem() idae = idaeproblem() ref = integrate(ode, Gauss(8)) sol = integrate(ode, Gauss(2)) @test relative_maximum_error(sol.q, ref.q) < 1E-5 sol = integrate(iode, Gauss(2)) @test relative_maximum_error(sol.q, ref.q) < 2E-5 sol = integrate(idae, TableauVSPARKGLRKpSymmetric(2)) @test relative_maximum_error(sol.q, ref.q) < 1E-5 end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
99
using GeometricProblems.RigidBody using Test @test_nowarn odeproblem() @test_nowarn odeensemble()
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
2499
using SafeTestsets @safetestset "Bump initial condition: test derivative. " begin include("bump_initial_condition_test_derivatives.jl") end @safetestset "ABC Flow " begin include("abc_flow_tests.jl") end @safetestset "Double Pendulum " begin include("double_pendulum_tests.jl") end @safetestset "Harmonic Oscillator " begin include("harmonic_oscillator_tests.jl") end # @safetestset "Kubo Oscillator " begin include("kubo_oscillator_tests.jl") end @safetestset "Lorenz Attractor " begin include("lorenz_attractor_tests.jl") end @safetestset "Lotka-Volterra 2D " begin include("lotka_volterra_2d_tests.jl") end @safetestset "Lotka-Volterra 2D with singular Lagrangian " begin include("lotka_volterra_2d_singular_tests.jl") end @safetestset "Lotka-Volterra 2D with symmetric Lagrangian " begin include("lotka_volterra_2d_symmetric_tests.jl") end @safetestset "Lotka-Volterra 2D with symmetric Lagrangian with gauge terms " begin include("lotka_volterra_2d_gauge_tests.jl") end @safetestset "Lotka-Volterra 3D " begin include("lotka_volterra_3d_tests.jl") end @safetestset "Lotka-Volterra 4D " begin include("lotka_volterra_4d_tests.jl") end @safetestset "Lotka-Volterra 4D (Lagrangian) " begin include("lotka_volterra_4d_lagrangian_tests.jl") end @safetestset "Point Vortices " begin include("point_vortices_tests.jl") end @safetestset "Point Vortices (linear) " begin include("point_vortices_linear_tests.jl") end @safetestset "Rigid Body " begin include("rigid_body_test.jl") end @safetestset "HODEEnsemble " begin include("test_hodeensembles.jl") end
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
code
1431
using GeometricIntegrators: ImplicitMidpoint, integrate import GeometricProblems.CoupledHarmonicOscillator as cho import GeometricProblems.TodaLattice as tl using Test function test_multiple_initial_conditions(cho::Module) q₀_vec = [cho.q₀ .+ α for α in 0. : .4 : .4] p₀_vec = [cho.p₀ .+ α for α in 0. : .4 : .4] # ensemble problem epr = cho.hodeensemble(q₀_vec, p₀_vec) # ensemble solution esol = integrate(epr, ImplicitMidpoint()) sol = integrate(cho.hodeproblem(), ImplicitMidpoint()) @test esol.s[1].q.d.parent ≈ sol.q.d.parent @test esol.s[2].q.d.parent ≉ sol.q.d.parent end function test_multiple_parameters(cho::Module) params_vec = Vector{NamedTuple}() for i in 0:1 param_vals = () for key in keys(cho.default_parameters) param_vals = (param_vals..., cho.default_parameters[key] .+ 1. * i) end params_vec = push!(params_vec, NamedTuple{keys(cho.default_parameters)}(param_vals)) end # ensemble problem epr = cho.hodeensemble(; parameters = params_vec) # ensemble solution esol = integrate(epr, ImplicitMidpoint()) sol = integrate(cho.hodeproblem(), ImplicitMidpoint()) @test esol.s[1].q.d.parent ≈ sol.q.d.parent @test esol.s[2].q.d.parent ≉ sol.q.d.parent end test_multiple_initial_conditions(cho) test_multiple_initial_conditions(tl) test_multiple_parameters(cho) test_multiple_parameters(tl)
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
776
# Authors GeometricProblems' development is coordinated by a group of *principal developers*, who are also its main contributors and who can be contacted in case of questions about GeometricProblems. In addition, there are *contributors* who have provided substantial additions or modifications. Together, these two groups form "The GeometricProblems Authors" as mentioned in the [LICENSE](LICENSE.md) file. ## Principal Developers * [Michael Kraus](https://www.michael-kraus.org/), Max Planck Institute for Plasma Physics, Garching, Germany * Benedikt Brantner, Max Planck Institute for Plasma Physics, Garching, Germany ## Contributors The following people contributed to GeometricProblems and are listed in alphabetical order: * Benedikt Brantner * Michael Kraus
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
2508
# GeometricProblems.jl *Collection of example problems with interesting geometric structure for [GeometricIntegrators.jl](https://github.com/JuliaGNI/GeometricIntegrators.jl).* [![Stable Docs](https://img.shields.io/badge/docs-stable-blue.svg)](https://juliagni.github.io/GeometricProblems.jl/stable) [![Latest Docs](https://img.shields.io/badge/docs-latest-blue.svg)](https://juliagni.github.io/GeometricProblems.jl/latest) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE.md) [![Build Status](https://github.com/JuliaGNI/GeometricProblems.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/JuliaGNI/GeometricProblems.jl/actions/workflows/CI.yml?query=branch%3Amain) [![codecov](https://codecov.io/gh/JuliaGNI/GeometricProblems.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/JuliaGNI/GeometricProblems.jl) [![DOI](https://zenodo.org/badge/doi/10.5281/zenodo.3740036.svg)](https://doi.org/10.5281/zenodo.3740036) #### Example Problems - [x] ABC Flow, - [x] Exponential Growth, - [ ] Fermi-Pasta-Ulam Problem, - [ ] Hénon-Heiles System, - [ ] Kepler Problem, - [x] Lorenz Attractor in 3D, - [x] Lotka-Volterra in 2D, - [x] Lotka-Volterra in 3D, - [x] Lotka-Volterra in 4D, - [x] Massless Charged Particle, - [x] Harmonic Oscillator, - [x] Coupled Harmonic Oscillator, - [ ] Nonlinear Oscillators, - [ ] Duffing Oscillator, - [ ] Lennard-Jones Oscillator, - [ ] Mathews-Lakshmanan Oscillator, - [ ] Morse Oscillator, - [x] Pendulum, - [x] Mathematical Pendulum, - [x] Double Pendulum, - [x] Planar Point Vortices, - [ ] Rigid Body, - [ ] Chaplygin Sleigh, - [ ] Inner Solar System, - [ ] Outer Solar System, - [ ] Heavy Top, - [x] Toda lattice. See [ChargedParticleDynamics.jl](https://github.com/JuliaPlasma/ChargedParticleDynamics.jl) for - Charged Particle Motion in various electromagnetic Fields, - Pauli Particle Dynamics in various electromagnetic Fields, - Guiding Center Dynamics in various magnetic fields, - Gyrokinetic Dynamics in various magnetic fields. See [GeometricExamples.jl](https://github.com/JuliaGNI/GeometricExamples.jl) for example scripts that run these problems with the integrators implemented in [GeometricIntegrators.jl](https://github.com/JuliaGNI/GeometricIntegrators.jl). ## Development We are using git hooks, e.g., to enforce that all tests pass before pushing. In order to activate these hooks, the following command must be executed once: ``` git config core.hooksPath .githooks ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
693
# ABC Flow The ABC flow (see [hairer2006geometric](@cite)) is described by a divergence-free differential equation whose flow strongly depends on the initial condition. ```@example using GeometricIntegrators: integrate, ImplicitMidpoint using GeometricProblems.ABCFlow using Plots ensemble_solution = integrate(odeensemble(), ImplicitMidpoint()) p = plot() for solution in ensemble_solution plot!(p, solution.q[:, 1], solution.q[:, 2], solution.q[:, 3]) end p ``` ## Library functions ```@docs GeometricProblems.ABCFlow ``` ```@autodocs Modules = [GeometricProblems.ABCFlow] Order = [:constant, :type, :macro, :function] ``` ```@bibliography Pages = [] hairer2006geometric ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
1911
# Coupled Harmonic Oscillator This system describes two harmonic oscillators that are coupled nonlinearly. ```@example HTML("""<object type="image/svg+xml" class="display-light-only" data=$(joinpath(Main.buildpath, "images/coupled_harmonic_oscillator.png"))></object>""") # hide ``` ```@example HTML("""<object type="image/svg+xml" class="display-dark-only" data=$(joinpath(Main.buildpath, "images/coupled_harmonic_oscillator_dark.png"))></object>""") # hide ``` The following shows the ``q_1`` component of the system for different values of ``k``: ```@eval using GeometricIntegrators: integrate, ImplicitMidpoint using GeometricProblems.CoupledHarmonicOscillator: hodeensemble, default_parameters using Plots const m₁ = default_parameters.m₁ const m₂ = default_parameters.m₂ const k₁ = default_parameters.k₁ const k₂ = default_parameters.k₂ const k = [0.0, 0.5, 0.75, 1.0, 2.0, 3.0, 4.0] params_collection = [(m₁ = m₁, m₂ = m₂, k₁ = k₁, k₂ = k₂, k = k_val) for k_val in k] # ensemble problem ep = hodeensemble(; parameters = params_collection) ensemble_solution = integrate(ep, ImplicitMidpoint()) t = ensemble_solution.t q₁ = zeros(1, length(t), length(k)) for index in axes(k, 1) q₁[1, :, index] = ensemble_solution.s[index].q[:, 1] end n_param_sets = length(params_collection) #hide labels = reshape(["k = "*string(parameters.k) for parameters in params_collection], 1, n_param_sets) q₁ = q₁[1, :, :] const one_plot = false const psize = (900, 600) plot_q₁ = one_plot ? plot(0.0:0.4:100.0, q₁, size=psize) : plot(0.0:0.4:100.0, q₁, layout=(n_param_sets, 1), size=psize, label=labels, legend=:topright) png(plot_q₁, "q_component") nothing ``` ![](q_component.png) ## Library functions ```@docs GeometricProblems.CoupledHarmonicOscillator ``` ```@autodocs Modules = [GeometricProblems.CoupledHarmonicOscillator] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
123
# Diagnostics ```@autodocs Modules = [GeometricProblems.Diagnostics] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
2949
# Double Pendulum The double pendulum consists of two pendula, one attached to the origin at ``(x,y) = (0,0)``, and the second attached to the first. Each pendulum consists of a point mass ``m_i`` attached to a massless rod of length ``l_i`` with ``i \in (1,2)``. All motion is assumed to be frictionless. ```@example HTML("""<object type="image/svg+xml" class="display-light-only" data=$(joinpath(Main.buildpath, "images/double-pendulum.png"))></object>""") # hide ``` ```@example HTML("""<object type="image/svg+xml" class="display-dark-only" data=$(joinpath(Main.buildpath, "images/double-pendulum_dark.png"))></object>""") # hide ``` The dynamics of the system is most naturally described in terms of the angles ``\theta_i`` between the rods ``l_i`` and the vertical axis ``y``. In terms of these angles, the cartesian coordinates are given by ```math \begin{align*} x_1 &= l_1 \sin\theta_1 , \\ x_2 &= l_1 \sin\theta_1 + l_2 \sin\theta_2 , \\ y_1 &= - l_1 \cos\theta_1 , \\ y_2 &= -l_1 \cos\theta_1 - l_2 \cos\theta_2 . \end{align*} ``` In terms of the generalized coordinates ``\theta_i``, the Lagrangian reads ```math \begin{align*} L (\theta_1, \theta_2, \dot{\theta}_1, \dot{\theta}_2) = \frac{1}{2} (m_1 + m_2) l_1^2 \dot{\theta}_1^2 &+ \frac{1}{2} m_2 l_2^2 \dot{\theta}_2^2 + m_2 l_1 l_2 \dot{\theta}_1 \dot{\theta}_2 \cos(\theta_1 - \theta_2) \\ &+ g (m_1 + m_2) l_1 \cos\theta_1 + g m_2 l_2 \cos\theta_2 . \end{align*} ``` The canonical conjugate momenta ``p_i`` are obtained from the Lagrangian as ```math \begin{align*} p_1 &= \frac{\partial L}{\partial \dot{\theta}_1} = (m_1 + m_2) l_1^2 \dot{\theta}_1 + m_2 l_1 l_2 \dot{\theta}_2 \cos(\theta_1 - \theta_2), \\ p_2 &= \frac{\partial L}{\partial \dot{\theta}_2} = m_2 l_2^2 \dot{\theta}_2 + m_2 l_1 l_2 \dot{\theta}_1 \cos(\theta_1 - \theta_2) . \end{align*} ``` After solving these relations for the generalized velocities ``\dot{\theta}_i``, ```math \begin{align*} \dot{\theta}_1 &= \frac{l_2 p_{\theta_1} - l_1 p_{\theta_2} \cos(\theta_1 - \theta_2)}{l_1^2 l_2 \left[ m_1 + m_2 \sin^2(\theta_1 - \theta_2) \right] } \\ \dot{\theta}_2 &= \frac{(m_1 + m_2) l_1 p_{\theta_2} - m_2 l_2 p_{\theta_1} \cos(\theta_1 - \theta_2)}{m_2 l_1 l_2^2 \left[ m_1 + m_2 \sin^2 (\theta_1 - \theta_2) \right] } , \end{align*} ``` the Hamiltonian can be obtained via the Legendre transform, ```math H = \sum_{i=1}^2 \dot{\theta}_i p_i - L , ``` as ```math \begin{align*} H &= \frac{m_2 l_2^2 p^2_{\theta_1} + (m_1 + m_2) l_1^2 p^2_{\theta_2} - 2 m_2 l_1 l_2 p_{\theta_1} p_{\theta_2} \cos(\theta_1 - \theta_2)}{2 m_2 l_1^2 l_2^2 \left[ m_1 + m_2 \sin^2(\theta_1 - \theta_2) \right] } \\ & \qquad\qquad \vphantom{\frac{l}{l}} - g (m_1 + m_2) l_1 \cos\theta_1 - g m_2 l_2 \cos\theta_2 . \end{align*} ``` ## Library functions ```@docs GeometricProblems.DoublePendulum ``` ```@autodocs Modules = [GeometricProblems.DoublePendulum] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
137
# Harmonic Oscillator ```@autodocs Modules = [GeometricProblems.HarmonicOscillator] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
4010
# GeometricProblems.jl *GeometricProblems.jl is a collection of ODEs and DAEs with interesting geometric structures together with useful diagnostics and plotting tools.* [![PkgEval Status](https://juliaci.github.io/NanosoldierReports/pkgeval_badges/G/GeometricProblems.svg)](https://juliaci.github.io/NanosoldierReports/pkgeval_badges/G/GeometricProblems.html) ![CI](https://github.com/JuliaGNI/GeometricProblems.jl/workflows/CI/badge.svg) [![Build Status](https://travis-ci.org/JuliaGNI/GeometricProblems.jl.svg?branch=main)](https://travis-ci.org/JuliaGNI/GeometricProblems.jl) [![Coverage Status](https://coveralls.io/repos/github/JuliaGNI/GeometricProblems.jl/badge.svg)](https://coveralls.io/github/JuliaGNI/GeometricProblems.jl) [![codecov](https://codecov.io/gh/JuliaGNI/GeometricProblems.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/JuliaGNI/GeometricProblems.jl) [![DOI](https://zenodo.org/badge/doi/10.5281/zenodo.3740036.svg)](https://doi.org/10.5281/zenodo.3740036) Typical structures are * Variational structure, i.e., the equations can defined in terms of a Lagrangian function and be obtained from an action principle; * Hamiltonian structure, i.e., the equations can be defined in terms of a Hamiltonian function together with a symplectic or Poisson matrix; * Invariants, i.e., the equations have symmetries and associated conservation laws; * Volume preservation, i.e., the flow of the equations is divergence-free. ## Contents ```@contents Pages = [ "diagnostics.md", "abc_flow.md", "coupled_harmonic_oscillator.md", "henon_heiles.md", "kepler_problem.md", "lorenz_attractor.md", "lotka_volterra_2d.md", "lotka_volterra_3d.md", "lotka_volterra_4d.md", "massless_charged_particle.md", "harmonic_oscillator.md", "nonlinear_oscillators.md", "pendulum.md", "double_pendulum.md", "point_vortices.md", "inner_solar_system.md", "outer_solar_system.md", "rigid_body.md", "toda_lattice.md" ] Depth = 1 ``` ## References If you use the figures or implementations provided here, please consider citing GeometricIntegrators.jl as ``` @misc{Kraus:2020:GeometricIntegratorsRepo, title={GeometricIntegrators.jl: Geometric Numerical Integration in Julia}, author={Kraus, Michael}, year={2020}, howpublished={\url{https://github.com/JuliaGNI/GeometricIntegrators.jl}}, doi={10.5281/zenodo.3648325} } ``` as well as this repository as ``` @misc{Kraus:2020:GeometricProblemsRepo, title={GeometricProblems.jl: Collection of Differential Equations with Geometric Structure.}, author={Kraus, Michael}, year={2020}, howpublished={\url{https://github.com/JuliaGNI/GeometricProblems.jl}}, doi={10.5281/zenodo.4285904} } ``` ## Figure License > Copyright (c) Michael Kraus <[email protected]> > > All figures are licensed under the Creative Commons [CC BY-NC-SA 4.0 License](https://creativecommons.org/licenses/by-nc-sa/4.0/). ## Software License > Copyright (c) Michael Kraus <[email protected]> > > 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.
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
2212
# Bump as Initial Condition In here we describe the initial condition used for the [discretized linear wave](linear_wave.md) and the [Toda lattice](toda_lattice.md). The initial conditions are based on the following third-degree spline (also used in [buchfink2023symplectic](@cite)): ```math h(s) = \begin{cases} 1 - \frac{3}{2}s^2 + \frac{3}{4}s^3 & \text{if } 0 \leq s \leq 1 \\ \frac{1}{4}(2 - s)^3 & \text{if } 1 < s \leq 2 \\ 0 & \text{else.} \end{cases} ``` Plotted on the relevant domain it takes the following shape: ```@example HTML("""<object type="image/svg+xml" class="display-light-only" data=$(joinpath(Main.buildpath, "images/third_degree_spline.png"))></object>""") # hide ``` ```@example HTML("""<object type="image/svg+xml" class="display-dark-only" data=$(joinpath(Main.buildpath, "images/third_degree_spline_dark.png"))></object>""") # hide ``` Taking the above function ``h(s)`` as a starting point, the initial conditions for the linear wave equations are modelled with ```math q_0(\omega;\mu) = h(s(\omega, \mu)). ``` Further for ``s(\cdot, \cdot)`` we pick: ```math s(\omega, \mu) = 20 \mu \left|\omega + \frac{\mu}{2}\right| ``` And we end up with the following choice of parametrized initial conditions: ```math q_0(\mu)(\omega). ``` Three initial conditions and their time evolutions are shown in the figure below. As was required, we can see that the peak gets sharper and moves to the left as we increase the parameter ``\mu``; the curves also get a good coverage of the domain ``\Omega``. ```@example # Plot our initial conditions for different values of μ here! using GeometricProblems: compute_initial_condition, compute_domain using Plots # hide using LaTeXStrings # hide μ_vals = [0.416, 0.508, 0.600] Ñ = 128 Ω = compute_domain(Ñ) ics = [compute_initial_condition(μ, Ñ) for μ in μ_vals] p = plot(Ω, ics[1].q, label = L"\mu"*"="*string(μ_vals[1]), xlabel = L"\Omega", ylabel = L"q_0") plot!(p, Ω, ics[2].q, label = L"\mu"*"="*string(μ_vals[2])) plot!(p, Ω, ics[3].q, label = L"\mu"*"="*string(μ_vals[3])) png(p, "ics_plot") nothing ``` ![Plot of initial conditions for various values of mu.](ics_plot.png)
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
2301
# The Discretized Linear Wave The linear wave equation in one dimension has the following Hamiltonian (see e.g. [buchfink2023symplectic](@cite)): ```math \mathcal{H}_\mathrm{cont}(q, p; \mu) := \frac{1}{2}\int_\Omega \mu^2(\partial_\xi q(t, \xi; \mu))^2 + p(t, \xi; \mu)^2 d\xi, ``` where the domain is ``\Omega = (-1/2, 1/2)``. We then divide the domain into ``\tilde{N}`` equidistantly spaces points[^1] ``\xi_i = i\Delta_\xi - 1/2`` for ``i = 1, \ldots, \tilde{N}`` and ``\Delta_xi := 1/(\tilde{N} + 1)``. [^1]: In total the system is therefore described by ``N = \tilde{N} + 2`` coordinates, since we also have to consider the boundary. The resulting Hamiltonian then is: ```math \mathcal{H}_h(z) = \sum_{i = 1}^{\tilde{N}}\frac{\Delta{}x}{2}\left[ p_i^2 + \mu^2 \frac{(q_i - q_{i - 1})^2 + (q_{i+1} - q_i)^2}{2\Delta{}x} \right]. ``` The discretized linear wave equation example of an *completely-integrable system*, i.e. a Hamiltonian system evolving in ``\mathbb{R}^{2n}`` that has ``n`` Poisson-commuting invariants of motion (see [arnold1978mathematical](@cite)). For evaluating the system we specify the following initial[^2] and boundary conditions: ```math \begin{aligned} q_0(\omega;\mu) := & q(0, \omega; \mu) \\ p(0, \omega; \mu) = \partial_tq(0,\xi;\mu) = & -\mu\partial_\omega{}q_0(\xi;\mu) \\ q(t,\omega;\mu) = & 0, \text{ for } \omega\in\partial\Omega. \end{aligned} ``` [^2]: The precise shape of ``q_0(\cdot;\cdot)`` is described in [the chapter on initial conditions](initial_condition.md). By default `GeometricProblems` uses the following parameters: ```@example linear_wave using GeometricIntegrators, Plots # hide import GeometricProblems.LinearWave as lw lw.default_parameters ``` And if we integrate we get: ```@example linear_wave problem = lw.hodeproblem() sol = integrate(problem, ImplicitMidpoint()) # plot 6 time steps time_steps = 0 : (length(sol.t) - 1) ÷ 5 : (length(sol.t) - 1) p = plot() for time_step in time_steps plot!(p, lw.compute_domain(lw.Ñ + 2), sol.q[time_step, :], label = "t = "*string(round(sol.t[time_step]; digits = 2))) end p ``` As we can see the thin pulse travels in one direction. ## Library functions ```@docs GeometricProblems.LinearWave ``` ```@bibliography Pages = [] buchfink2023symplectic ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
137
# Lorenz Attractor in 3d ```@autodocs Modules = [GeometricProblems.LorenzAttractor] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
1650
# Lotka-Volterra 2d Lotka–Volterra models are used in mathematical biology for modelling population dynamics of animal species, as well as many other fields where predator-prey and similar models appear. The dynamics of the growth of two interacting species can be modelled by the following noncanonical Hamiltonian system ```math \dot{q} = \begin{pmatrix} \hphantom{-} 0 & + q_1 q_2 \\ - q_1 q_2 & \hphantom{+} 0 \\ \end{pmatrix} \nabla H (q) , \quad H (q) = a_1 \, q_1 + a_2 \, q_2 + b_1 \, \log q_1 + b_2 \, \log q_2 . ``` ```@eval using Plots using GeometricIntegrators using GeometricProblems.LotkaVolterra2d using GeometricProblems.LotkaVolterra2dPlots ode = odeproblem() sol = integrate(ode, Gauss(1)) plot_lotka_volterra_2d(sol, ode) savefig("lotka_volterra_2d.svg") nothing ``` ![](lotka_volterra_2d.svg) ## Sub-models The Euler-Lagrange equations of the Lotka-Volterra model can be obtained from different Lagrangians, which are connected by gauge transformations. Although they all lead to the same equations of motion, they lead to different variational integrators. Therefore different models based on different Lagrangians are implemented. ```@docs GeometricProblems.LotkaVolterra2d ``` ```@docs GeometricProblems.LotkaVolterra2dSymmetric ``` ```@docs GeometricProblems.LotkaVolterra2dSingular ``` ```@docs GeometricProblems.LotkaVolterra2dGauge ``` ## User Functions ```@autodocs Modules = [GeometricProblems.LotkaVolterra2d] Order = [:constant, :type, :macro, :function] ``` ## Plotting Functions ```@autodocs Modules = [GeometricProblems.LotkaVolterra2dPlots] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
180
# Lotka-Volterra 3d ```@docs GeometricProblems.LotkaVolterra3d ``` ```@autodocs Modules = [GeometricProblems.LotkaVolterra3d] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
133
# Lotka-Volterra 4d ```@autodocs Modules = [GeometricProblems.LotkaVolterra4d] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
539
# Massless Charged Particle ```@docs GeometricProblems.MasslessChargedParticle ``` ```@eval using Plots using GeometricIntegrators using GeometricProblems.MasslessChargedParticle using GeometricProblems.MasslessChargedParticlePlots ode = odeproblem() sol = integrate(ode, Gauss(1)) plot_massless_charged_particle(sol, ode) savefig("massless_charged_particle.svg") nothing ``` ![](massless_charged_particle.svg) ```@autodocs Modules = [GeometricProblems.MasslessChargedParticle] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
814
# Nonlinear Oscillators ## Duffing Oscillator ```@docs GeometricProblems.DuffingOscillator ``` ```@autodocs Modules = [GeometricProblems.DuffingOscillator] Order = [:constant, :type, :macro, :function] ``` ## Lennard-Jones Oscillator ```@docs GeometricProblems.LennardJonesOscillator ``` ```@autodocs Modules = [GeometricProblems.LennardJonesOscillator] Order = [:constant, :type, :macro, :function] ``` ## Mathews-Lakshmanan Oscillator ```@docs GeometricProblems.MathewsLakshmananOscillator ``` ```@autodocs Modules = [GeometricProblems.MathewsLakshmananOscillator] Order = [:constant, :type, :macro, :function] ``` ## Morse Oscillator ```@docs GeometricProblems.MorseOscillator ``` ```@autodocs Modules = [GeometricProblems.MorseOscillator] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
129
# Mathematical Pendulum ```@autodocs Modules = [GeometricProblems.Pendulum] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
134
# Planar Point Vortices ```@autodocs Modules = [GeometricProblems.PointVortices] Order = [:constant, :type, :macro, :function] ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
461
# Release Notes ## 0.1.1 ### New Features - Poincaré invariants for Lotka-Volterra 2d model - More equation types for massless charged particle ### Fixes - Fixes in general plot recipes ## 0.1.0 Initial release with equations for - Exponential Growth, - Lorenz Attractor in 3D, - Lotka-Volterra in 2D, - Lotka-Volterra in 3D, - Lotka-Volterra in 4D, - Massless Charged Particle, - Harmonic Oscillator, - Mathematical Pendulum, - Planar Point Vortices.
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
1544
# The rigid body ```@example using GeometricProblems.RigidBody: odeensemble using GeometricIntegrators: integrate, ImplicitMidpoint using GeometricEquations: EnsembleProblem using GeometricSolutions: GeometricSolution using CairoMakie ics = [ [sin(1.1), 0., cos(1.1)], [sin(2.1), 0., cos(2.1)], [sin(2.2), 0., cos(2.2)], [0., sin(1.1), cos(1.1)], [0., sin(1.5), cos(1.5)], [0., sin(1.6), cos(1.6)] ] ensemble_problem = odeensemble(ics) ensemble_solution = integrate(ensemble_problem, ImplicitMidpoint()) function plot_geometric_solution!(p, solution::GeometricSolution; kwargs...) lines!(p, solution.q[:, 1].parent, solution.q[:, 2].parent, solution.q[:, 3].parent; kwargs...) end function sphere(r, C) # r: radius; C: center [cx,cy,cz] n = 100 u = range(-π, π; length = n) v = range(0, π; length = n) x = C[1] .+ r * cos.(u) * sin.(v)' y = C[2] .+ r * sin.(u) * sin.(v)' z = C[3] .+ r * ones(n) * cos.(v)' return x, y, z end fig, ax, plt = surface(sphere(1., [0., 0., 0.])..., alpha = .6) for (i, solution) in zip(1:length(ensemble_solution), ensemble_solution.s) plot_geometric_solution!(ax, solution; label = "trajectory "*string(i), linewidth=2) end fig ``` ## Library functions ```@docs GeometricProblems.RigidBody ``` ```@autodocs Modules = [GeometricProblems.RigidBody] Order = [:constant, :type, :macro, :function] ``` ```@bibliography Pages = [] bajars2023locally ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.6.5
c65d43b94d659c8454f851b09e79d514bc7a058d
docs
1754
# Toda Lattice The Toda lattice is a prime example of an *completely-integrable system*, i.e. a Hamiltonian system evolving in ``\mathbb{R}^{2n}`` that has ``n`` Poisson-commuting invariants of motion (see [arnold1978mathematical](@cite)). It is named after Morikazu Toda who used it to model a one-dimensional crystal [toda1967vibration](@cite). The Hamiltonian of the Toda lattice takes the following form: ```math H(q, p) = \sum_{n\in\mathbb{Z}}\left( \frac{p_n^2}{2} + \alpha e^{q_n - q_{n+1}} \right). ``` In practice we work with a finite number of particles ``N`` and impose periodic boundary conditions: ```math \begin{aligned} q_{n+N} & \equiv q_n \\ p_{n+N} & \equiv p_n. \end{aligned} ``` Hence we have: ```math H(q, p) = \sum_{n=1}^{N-1} \left( \frac{p_n^2}{2} + \alpha e^{q_n - q_{n+1}} \right) + \frac{p_N^2}{2} + \alpha e^{q_N - q_1}. ``` We can model the evolution of a thin pulse in this system: ```@example using GeometricProblems, GeometricIntegrators, Plots # hide problem = GeometricProblems.TodaLattice.hodeproblem() sol = integrate(problem, ImplicitMidpoint()) time_steps = (0, 200, 400, 600, 800, 1000, 1200) p = plot() for time_step in time_steps plot!(p, sol.q[time_step, :], label = "t = $(sol.t[time_step])") end p ``` As we can see the thin pulse separates into two smaller pulses an they start traveling in opposite directions until they meet again at time ``t\approx120``. But it is important to note that the right peak at time ``120`` is below the one at time ``0``. This is not a numerical artifact but a feature of the Toda lattice! ## Library functions ```@docs GeometricProblems.TodaLattice ``` ```@bibliography Pages = [] arnold1978mathematical toda1967vibration ```
GeometricProblems
https://github.com/JuliaGNI/GeometricProblems.jl.git
[ "MIT" ]
0.2.2
fe44922cacdf82833b9b322a9833fbe10d886577
code
1441
using SymbolicGA, BenchmarkTools macro cga3(args...) definitions = quote n = 1.0::e4 + 1.0::e5 n̄ = (-0.5)::e4 + 0.5::e5 n̅ = n̄ # n\bar !== n\overbar but they display exactly the same. embed(x) = x[1]::e1 + x[2]::e2 + x[3]::e3 magnitude2(x) = x ⦿ x point(x) = (embed(x) + (0.5::Scalar * magnitude2(embed(x))) * n + n̄)::Vector weight(X) = -X ⋅ n unitize(X) = X / weight(X) radius2(X) = (magnitude2(X) / magnitude2(X ∧ n))::Scalar center(X) = X * n * X # For spheres `S` defined as vectors, and points `X` defined as vectors as well. distance(S, X) = unitize(S) ⋅ unitize(X) end bindings = parse_bindings(definitions; warn_override = false) esc(codegen_expression((4, 1, 0), args...; bindings)) end function line_tests(A, B, P) t₁ = @cga3 begin L = point(A) ∧ point(B) ∧ n (point(A) ∧ point(P) ∧ n) ⟑ L end t₂ = @cga3 begin L = point(A) ∧ point(B) ∧ n (point(P) ∧ point(B) ∧ n) ⟑ L end (t₁, t₂) end is_zero(x, y) = isapprox(x, y; atol = 1e-15) is_positive(x::Number) = x ≥ -1e-15 is_zero_bivector(x) = is_zero(x, zero(KVector{2,Float64,5})) is_on_line((t₁, t₂)) = is_zero_bivector(t₁[2]) && is_zero_bivector(t₂[2]) is_within_segment((t₁, t₂)) = is_positive(t₁[1][]) && is_positive(t₂[1][]) function is_on_segment(P, A, B) ret = line_tests(A, B, P) is_on_line(ret) && is_within_segment(ret) end @btime is_on_segment($(rand(3)), $(rand(3)), $(rand(3)))
SymbolicGA
https://github.com/serenity4/SymbolicGA.jl.git
[ "MIT" ]
0.2.2
fe44922cacdf82833b9b322a9833fbe10d886577
code
2259
using SymbolicGA, LinearAlgebra, StaticArrays, BenchmarkTools x = (1.0, 2.0, 3.0) y = (50.0, 70.0, 70.0) f(x, y) = @ga 3 x::Vector ⟑ y::Vector @macroexpand @ga 3 x::Vector ⟑ y::Vector @btime f($x, $y) @code_typed f(x, y) # Determinant - rank 2 mydet(A₁, A₂) = @ga(2, Float64, A₁::Vector ∧ A₂::Vector) A₁ = @SVector rand(2) A₂ = @SVector rand(2) A = SMatrix([A₁ A₂]) @assert mydet(A₁, A₂) ≈ det(A) @btime det($A) @btime mydet($A₁, $A₂) # `Base.sub_float` is used instead of `Base.mul_float` with -1 and then `Base.add_float`, # but it seems like it's the same speed. @code_warntype optimize=true det(A) @code_warntype optimize=true mydet(A₁, A₂) # Determinant - rank 4 mydet(A₁, A₂, A₃, A₄) = @ga(4, Float64, A₁::Vector ∧ A₂::Vector ∧ A₃::Vector ∧ A₄::Vector) @macroexpand @ga(4, A₁::Vector ∧ A₂::Vector ∧ A₃::Vector ∧ A₄::Vector) A₁ = @SVector rand(4) A₂ = @SVector rand(4) A₃ = @SVector rand(4) A₄ = @SVector rand(4) A = SMatrix([A₁ A₂ A₃ A₄]) @assert mydet(A₁, A₂, A₃, A₄) ≈ det(A) @btime det($A) @btime mydet($A₁, $A₂, $A₃, $A₄) @code_warntype optimize=true det(A) @code_warntype optimize=true mydet(A₁, A₂, A₃, A₄) # Rotations - 3D function rot(a, b, x, α) # Define unit plane for the rotation. Π = @ga 3 a::Vector ∧ b::Vector # Define rotation generator. Ω = @ga 3 exp((-α::Scalar / 2::Scalar) ⟑ Π::Bivector) # Apply the rotation by sandwiching x with Ω. @ga 3 begin Ω::(0, 2) Ω ⟑ x::Vector ⟑ reverse(Ω) end end function rotate_3d(x, a, b, α) Π = @ga 3 unitize(a::1 ∧ b::1) Ω = @ga 3 exp(-(α::0 / 2::0) ⟑ Π::2) rotate_3d(x, Ω) end rotate_3d(x, Ω) = @ga 3 x::1 << Ω::(0, 2) a = (1.0, 0.0, 0.0) b = (2.0, 2.0, 0.0) x = (2.0, 0.0, 0.0) α = π / 6 x′ = rotate_3d(x, a, b, α) @assert x′ ≈ KVector{1,3}(2cos(π/6), 2sin(π/6), 0.0) @btime rotate_3d($a, $b, $x, $α) @code_warntype rotate_3d(a, b, x, α) Ω = @ga 3 exp(-(α::0 / 2::0) ⟑ (a::1 ∧ b::1)) @btime rotate_3d($x, $Ω) # @time @macroexpand @ga 3 begin # # Define unit plane for the rotation. # Π = a::Vector ⟑ b::Vector # # Define rotation generator. # Ω = exp((-α::Scalar / 2::Scalar) ⟑ Π) # # Apply the rotation by sandwhiching x with Ω. # Ω ⟑ x::Vector ⟑ reverse(Ω) # end; @time @macroexpand @ga 3 begin Π = a::Vector ⟑ b::Vector unitize(Π) end;
SymbolicGA
https://github.com/serenity4/SymbolicGA.jl.git
[ "MIT" ]
0.2.2
fe44922cacdf82833b9b322a9833fbe10d886577
code
171
# To be executed for local deployment. # Make sure you have LiveServer in your environment. using LiveServer servedocs(literate = "", skip_dir = joinpath("docs", "src"))
SymbolicGA
https://github.com/serenity4/SymbolicGA.jl.git