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
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
docs
2838
# OptimalTransmissionRouting.jl Status: [![CI](https://github.com/Electa-Git/OptimalTransmissionRouting.jl/workflows/CI/badge.svg)](https://github.com/Electa-Git/OptimalTransmissionRouting.jl/actions?query=workflow%3ACI) <a href="https://codecov.io/gh/Electa-Git/OptimalTransmissionRouting.jl"><img src="https://img.shields.io/codecov/c/github/Electa-Git/OptimalTransmissionRouting.jl?logo=Codecov"></img></a> <a href="https://electa-git.github.io/OptimalTransmissionRouting.jl/stable/"><img src="https://github.com/Electa-Git/OptimalTransmissionRouting.jl/workflows/Documentation/badge.svg"></img></a> OptimalTransmissionRouting.jl is a Julia/JuMP package to determine the optimal transmission system route considering spatial information. The underlying priciple is that spatial information coming from an image file is convertered to an array of installation cost weights (see io/spatial_image_files). To that end spatial infromation from http://www.eea.europa.eu/data-and-maps/data/corine-land-cover-2006-raster-2 is used. The created array represents a weighted graph connecting a number of nodes horizontally, vertiacally and diagonally with graph weights reflecting the installation costs for each region of the map. Using the A-star algorithm, the shortest path in this weighted graph is found, which provides the least cost transmission path. **Installation** The latest stable release of OptimalTransmissionRouting.jl can be installed using the Julia package manager with ```julia Pkg.add("OptimalTransmissionRouting") ``` The current version of OptimalTransmissionRouting.jl is 0.1.. ## Citing OptimalTransmissionRouting.jl If you find OptimalTransmissionRouting.jl useful in your work, we kindly request that you cite the following publications: [Detailed description of the mathematical model](https://ieeexplore.ieee.org/abstract/document/6746189): ``` @ARTICLE{6746189, author={Ergun, Hakan and Rawn, Barry and Belmans, Ronnie and Van Hertem, Dirk}, journal={IEEE Transactions on Power Systems}, title={Technology and Topology Optimization for Multizonal Transmission Systems}, year={2014}, volume={29}, number={5}, pages={2469-2477}, doi={10.1109/TPWRS.2014.2305174}} ``` and ``` @ARTICLE{7293709, author={Ergun, Hakan and Rawn, Barry and Belmans, Ronnie and Van Hertem, Dirk}, journal={IEEE Transactions on Power Systems}, title={Stepwise Investment Plan Optimization for Large Scale and Multi-Zonal Transmission System Expansion}, year={2016}, volume={31}, number={4}, pages={2726-2739}, doi={10.1109/TPWRS.2015.2480751}} ``` ## Acknowledgement This software implementation is conducted within the European Union’s Horizon 2020 research and innovation programme under the FlexPlan project (grantagreement no. 863819). ## License This code is provided under a BSD license.
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "BSD-3-Clause" ]
0.1.4
688e5028028e0dd8807efe6fff4a55a1a0832818
docs
5211
# OptimalTransmissionRouting.jl Documentation ```@meta CurrentModule = OptimalTransmissionRouting ``` ## Overview OptimalTransmissionRouting.jl is a Julia/JuMP package to determine the optimal transmission system route considering spatial information. The underlying priciple is that spatial information coming from an image file is convertered to an array of installation cost weights (see io/spatial_image_files). To that end spatial infromation from http://www.eea.europa.eu/data-and-maps/data/corine-land-cover-2006-raster-2 is used. The created array represents a weighted graph connecting a number of nodes horizontally, vertiacally and diagonally with graph weights reflecting the installation costs for each region of the map. Using the A-star algorithm, the shortest path in this weighted graph is found, which provides the least cost transmission path. Developed by: - Hakan Ergun KU Leuven / EnergyVille **Installation** The latest stable release of OptimalTransmissionRouting.jl can be installed using the Julia package manager with ```julia Pkg.add("OptimalTransmissionRouting") ``` ## Usage The first step is to define the locations of the sending and recieving end buses in latitude and longitude using a dictionary, e.g., ```julia bus1 = Dict{String, Any}() bus1["longitude"] = 16.2487678 bus1["latitude"] = 40.358515 bus2 = Dict{String, Any}() bus2["longitude"] = 14.1482998 bus2["latitude"] = 37.5900782 ``` First using: ```julia spatial_weights, voltages, resolution, impedances = OTR.define_weights_voltages(strategy) ``` the spatial weights can be defined, which uses the chosen strategy as input as a string. The possible options are: ```julia strategy = "all_permitted" strategy = "OHL_on_existing_corridors" strategy = "cables_only" ``` Furter the vertices of the graph are created, assinging each vertex to one or more spatial regions, e.g., urban, mountain, sea, ....., using: ```julia rgb_values, nodes_lp, boundaries, plot_dictionary = OTR.convert_image_files_to_weights(bus1, bus2) ``` Additional input data is required as a dictionary, which is provided below: ```julia #define inputs input_data = Dict{String, Any}() input_data["resolution_factor"] = 2 # resolution_factor 1,2,3, ... to speed up algorithm input_data["algorithm_factor"] = 1 # algorithm_factor 1.....1.3 to speed up Astar algorithm, goes at expense of accuracy input_data["distance"] = 2.5 # do not change: this is the standard resolution of the environmental data input_data["algorithm"] = "Astar" # "Astar" or "Dijkstra" input_data["voltages"] = voltages # transmission voltages input_data["spatial_weights"] = spatial_weights # spatial weights input_data["rgb_values"] = rgb_values # Spatial data as RGB values input_data["boundaries"] = boundaries # VBoundaries of the area (to avoid using full European range) input_data["overlapping_area_weight"] = "average" # "average" = average weight of the spatial weights; "minimum" = minimum of the overlapping weights input_data["strategy"] = strategy # or "OHL_on_existing_corridors" or "cables_only" input_data["losses"] = 0.01 # proxy for losses input_data["lifetime"] = 30 # lifetime: NOT USED in FLEXPLAN input_data["interest"] = 0.02 # Interest: NOT USED in FLEXPLAN input_data["technology"] = "dc" # or "dc" input_data["power_rating"] = 2000 # power rating input_data["start_node"] = Dict{String, Any}() input_data["start_node"]["x"] = nodes_lp["x1"] input_data["start_node"]["y"] = nodes_lp["y1"] input_data["end_node"] = Dict{String, Any}() input_data["end_node"]["x"] = nodes_lp["x2"] input_data["end_node"]["y"] = nodes_lp["y2"] input_data["impedances"] = impedances # Provide look-up table for OHL & OGC impedances ``` Finally, the creation of the edges of the graph and the optimisation of the route is carried out using: ```julia spatial_data, spatial_data_matrices, cost_data, equipment_data, c_tot, optimal_path, ac_dc, ac_cab, dc_cab, route_impedance, route_legnth = OTR.do_optimal_routing(input_data) ``` During the route optimisation, following aspects are considered: - Maximum offshore length for AC cables - Costs for switching between overhead lines and underground cables, e.g., transition station costs - In case of HVDC technology: Costs of the converter stations - Chosen strategy: -- OHL can be installed everywhere (depending on the chosen weights) -- OHL can only be installed in existing infrastructure corridors -- Only underground cables can be installed - If certain vertices belong to multiple spatial areas, which weight should be chosen: -- The average of both weights -- The minimum of both weights The tool delivers as output - ```julia c_tot ```, the total cost of the transmission link - ```julia cost_data ```, the per km cost of equipment - ```julia equipment_data ```, number of circuits, bundles and cross-sections - ```julia route_impedance ```, resistance, admittance and capaciatance in Ohm in pu (base power = 100 MVA) - ```julia route_legnth ```, the total length, as well as length of the OHL and UGC sections Also using the function: ```julia OTR.plot_result(plot_dictionary, input_data, spatial_data, spatial_data_matrices, optimal_path) ``` a PDF of the obtained solution can be created.
OptimalTransmissionRouting
https://github.com/Electa-Git/OptimalTransmissionRouting.jl.git
[ "MIT" ]
0.1.4
ae277f699ad0abb4743ee9bc7deeb89b554de867
code
16015
""" Created in July, 2022 by [chifi - an open source software dynasty.](https://github.com/orgs/ChifiSource) by team [toolips](https://github.com/orgs/ChifiSource/teams/toolips) This software is MIT-licensed. ### Toolips Markdown A simple markdown to Toolips Component parser. Wraps markdown components into a Toolips.div ##### Module Composition - [**ToolipsMarkdown**](https://github.com/ChifiSource/ToolipsMarkdown.jl) """ module ToolipsMarkdown using Toolips import Toolips: Modifier import Toolips: style!, string import Base: push! using Markdown """ **Toolips Markdown** ### @tmd_str -> ::Component ------------------ Turns a markdown string into a Toolips Component. Markdown will always use default styling. #### example ``` tmd\"#hello world\" ``` """ macro tmd_str(s::String) tmd("tmd", s)::Component{:div} end """ **Toolips Markdown** ### tmd(name::String = "tmd", s::String = "") -> ::Component ------------------ Turns a markdown string into a Toolips Component. Markdown will always use default styling. #### example ``` route("/") do c::Connection mymdcomp = tmd("mainmarkdown", "# Hello! [click](http://toolips.app/)") write!(c, mymdcomp) end ``` """ function tmd(name::String = "markdown", s::String = "", p::Pair{String, <:Any} ...; args ...) mddiv::Component{:div} = divider(name, p ..., args ...) md = Markdown.parse(replace(s, "<" => "", ">" => "", "\"" => "")) htm::String = html(md) mddiv[:text] = htm mddiv end """ **Toolips Markdown** ### itmd(name::String = "markdown", s::String = "", interpolators::Pair{String, Vector{Function}} ...) -> ::Component{:div} ------------------ Interpolated TMD! This method allows you to provide your own TextModifier functions in a Vector for each type of code block inside of a markdown document. #### example ``` route("/") do c::Connection mymdcomp = tmd("mainmarkdown", "# Hello! [click](http://toolips.app/)") write!(c, mymdcomp) end ``` """ function itmd(name::String = "markdown", interpolators::Pair{String, Vector{Function}} ...) throw("Interpolated TMD is a Toolips Markdown 0.1.3 feature. Not yet implemented.") mddiv::Component{:div} = divider(name) md = Markdown.parse(s) htm::String = html(md) htm = replace(htm, "&quot;" => "", "&#40;" => "(", "&#41;" => ")", "&#61;" => "=", "&#43;" => "+") codepos = findall("<code", htm) for code in codepos codeend = findnext("</code>", htm, code[2]) tgend = findnext(">", htm, code[2])[1] + 1 codeoutput = htm[tgend[1]:codeend[1] - 1] htm = htm[1:code[1] - 1] * "<code>" * String(b.data) * "</code>" * htm[maximum(codeend) + 1:length(htm)] end mddiv[:text] = htm mddiv end """ ### abstract type TextModifier <: Toolips.Modifier TextModifiers are modifiers that change outgoing text into different forms, whether this be in servables or web-formatted strings. These are unique in that they can be provided to `itmd` (`0.1.3`+) in order to create interpolated tmd blocks, or just handle these things on their own. ##### Consistencies - raw**::String** - marks**::Dict{UnitRange{Int64}, Symbol}** """ abstract type TextModifier <: Modifier end """ ### TextStyleModifier - raw**::String** - marks**::Dict{UnitRange{Int64}, Symbol}** - styles**::Dict{Symbol, Vector{Pair{String, String}}}** This type is provided ##### example ``` ``` ------------------ ##### constructors - TextStyleModifier(::String) """ mutable struct TextStyleModifier <: TextModifier raw::String taken::Vector{Int64} marks::Dict{UnitRange{Int64}, Symbol} styles::Dict{Symbol, Vector{Pair{String, String}}} function TextStyleModifier(raw::String) marks = Dict{Symbol, UnitRange{Int64}}() styles = Dict{Symbol, Vector{Pair{String, String}}}() new(replace(raw, "<br>" => "\n", "</br>" => "\n", "&nbsp;" => " "), Vector{Int64}(), marks, styles) end end set_text!(tm::TextModifier, s::String) = tm.raw = replace(s, "<br>" => "\n", "</br>" => "\n", "&nbsp;" => " ") clear!(tm::TextStyleModifier) = begin tm.marks = Dict{UnitRange{Int64}, Symbol}() tm.taken = Vector{Int64}() end function push!(tm::TextStyleModifier, p::Pair{UnitRange{Int64}, Symbol}) r = p[1] found = findfirst(mark -> mark in r, tm.taken) if isnothing(found) push!(tm.marks, p) vecp = Vector(p[1]) [push!(tm.taken, val) for val in p[1]] end end function push!(tm::TextStyleModifier, p::Pair{Int64, Symbol}) if ~(p[1] in tm.taken) push!(tm.marks, p[1]:p[1] => p[2]) push!(tm.taken, p[1]) end end """ **Toolips Markdown** ### style!(tm::TextStyleModifier, marks::Symbol, sty::Vector{Pair{String, String}}) ------------------ Styles marks assigned with symbol `marks` to `sty`. #### example ``` ``` """ function style!(tm::TextStyleModifier, marks::Symbol, sty::Vector{Pair{String, String}}) push!(tm.styles, marks => sty) end repeat_offenders = ['\n', ' ', ',', '(', ')', ';', '\"', ']', '['] """ **Toolips Markdown** ### mark_all!(tm::TextModifier, s::String, label::Symbol) ------------------ Marks all instances of `s` in `tm.raw` as `label`. #### example ``` ``` """ function mark_all!(tm::TextModifier, s::String, label::Symbol)::Nothing [begin if maximum(v) == length(tm.raw) && minimum(v) == 1 push!(tm, v => label) elseif maximum(v) == length(tm.raw) if tm.raw[v[1] - 1] in repeat_offenders push!(tm, v => label) end elseif minimum(v) == 1 if tm.raw[maximum(v) + 1] in repeat_offenders push!(tm, v => label) end else if tm.raw[v[1] - 1] in repeat_offenders && tm.raw[maximum(v) + 1] in repeat_offenders push!(tm, v => label) end end end for v in findall(s, tm.raw)] nothing end function mark_all!(tm::TextModifier, c::Char, label::Symbol) [begin push!(tm, v => label) end for v in findall(c, tm.raw)] end """ **Toolips Markdown** ### mark_between!(tm::TextModifier, s::String, label::Symbol; exclude::String = "\\"", excludedim::Int64 = 2) ------------------ Marks between each delimeter, unique in that this is done with by dividing the count by two. #### example ``` ``` """ function mark_between!(tm::TextModifier, s::String, label::Symbol) positions::Vector{UnitRange{Int64}} = findall(s, tm.raw) discounted::Vector{UnitRange{Int64}} = Vector{Int64}() [begin if ~(pos in discounted) nd = findnext(s, tm.raw, maximum(pos) + length(s)) if isnothing(nd) push!(tm, pos[1]:length(tm.raw) => label) else push!(discounted, nd) push!(tm, minimum(pos):maximum(nd) => label) end end end for pos in positions] nothing end function mark_between!(tm::TextModifier, s::String, s2::String, label::Symbol) positions::Vector{UnitRange{Int64}} = findall(s, tm.raw) [begin nd = findnext(s2, tm.raw, maximum(pos) + length(s)) if isnothing(nd) push!(tm, pos[1]:length(tm.raw) => label) else push!(tm, minimum(pos):maximum(nd) => label) end end for pos in positions] nothing end """ **Toolips Markdown** ```julia mark_before!(tm::TextModifier, s::String, label::Symbol; until::Vector{String}, includedims_l::Int64 = 0, includedims_r::Int64 = 0) ``` ------------------ marks before a given string until hitting any value in `until`. #### example ``` ``` """ function mark_before!(tm::TextModifier, s::String, label::Symbol; until::Vector{String} = Vector{String}(), includedims_l::Int64 = 0, includedims_r::Int64 = 0) chars = findall(s, tm.raw) for labelrange in chars previous = findprev(" ", tm.raw, labelrange[1]) if isnothing(previous) previous = length(tm.raw) else previous = previous[1] end if length(until) > 0 lens = [begin point = findprev(d, tm.raw, minimum(labelrange) - 1) if ~(isnothing(point)) minimum(point) + length(d) else 1 end end for d in until] previous = maximum(lens) end pos = previous - includedims_l:maximum(labelrange) - 1 + includedims_r push!(tm, pos => label) end end """ **Toolips Markdown** ```julia mark_after!(tm::TextModifier, s::String, label::Symbol; until::Vector{String}, includedims_l::Int64 = 0, includedims_r::Int64 = 0) ``` ------------------ marks after a given string until hitting any value in `until`. #### example ``` ``` """ function mark_after!(tm::TextModifier, s::String, label::Symbol; until::Vector{String} = Vector{String}(), includedims_r::Int64 = 0, includedims_l::Int64 = 0) chars = findall(s, tm.raw) for labelrange in chars ending = findnext(" ", tm.raw, labelrange[1]) if isnothing(ending) ending = length(tm.raw) else ending = ending[1] end if length(until) > 0 lens = [begin point = findnext(d, tm.raw, maximum(labelrange) + 1) if ~(isnothing(point)) maximum(point) - length(d) else length(tm.raw) end end for d in until] ending = minimum(lens) end pos = minimum(labelrange) - includedims_l:ending - includedims_r push!(tm, pos => label) end end """ **Toolips Markdown** ```julia mark_inside!(f::Function, tm::TextModifier) ``` ------------------ marks before a given string until hitting any value in `until`. #### example ``` ``` """ function mark_inside!(f::Function, tm::TextModifier, label::Symbol) end """ **Toolips Markdown** ### mark_for!(tm::TextModifier, s::String, f::Int64, label::Symbol) ------------------ Marks a certain number of characters after a given value. #### example ``` ``` """ function mark_for!(tm::TextModifier, ch::String, f::Int64, label::Symbol) if length(tm.raw) == 1 return end chars = findall(ch, tm.raw) [begin if ~(length(findall(i -> length(findall(n -> n in i, pos)) > 0, collect(keys(tm.marks)))) > 0) push!(tm.marks, minimum(pos):maximum(pos) + f => label) end end for pos in chars] end mark_line_after!(tm::TextModifier, ch::String, label::Symbol) = mark_between!(tm, ch, "\n", label) function mark_line_startswith!(tm::TextModifier, ch::String, label::Symbol) marks = findall("\n$ch", tm.raw) [push!(tm.marks, mark[2]:findnext("\n", mark[2], tm.raw) => label) for mark in marks] end """ **Toolips Markdown** ### clear_marks!(tm::TextModifier) ------------------ Clears all marks in text modifier. #### example ``` ``` """ clear_marks!(tm::TextModifier) = tm.marks = Dict{UnitRange{Int64}, Symbol}() """ **Toolips Markdown** ### mark_julia!(tm::TextModifier) ------------------ Marks julia syntax. #### example ``` ``` """ mark_julia!(tm::TextModifier) = begin tm.raw = replace(tm.raw, "<br>" => "\n", "</br>" => "\n", "&nbsp;" => " ") # delim mark_line_after!(tm, "#", :comment) mark_before!(tm, "(", :funcn, until = [" ", "\n", ",", ".", "\"", "&nbsp;", "<br>", "("]) mark_after!(tm, "::", :type, until = [" ", ",", ")", "\n", "<br>", "&nbsp;", "&nbsp;", ";"]) mark_after!(tm, "@", :type, until = [" ", ",", ")", "\n", "<br>", "&nbsp;", "&nbsp;", ";"]) mark_between!(tm, "\"", :string) mark_between!(tm, "'", :char) # keywords mark_all!(tm, "function", :func) mark_all!(tm, "import", :import) mark_all!(tm, "using", :using) mark_all!(tm, "end", :end) mark_all!(tm, "struct", :struct) mark_all!(tm, "abstract", :abstract) mark_all!(tm, "mutable", :mutable) mark_all!(tm, "if", :if) mark_all!(tm, "else", :if) mark_all!(tm, "elseif", :if) mark_all!(tm, "in", :in) mark_all!(tm, "export ", :using) mark_all!(tm, "try ", :if) mark_all!(tm, "catch ", :if) mark_all!(tm, "elseif", :if) mark_all!(tm, "for", :for) mark_all!(tm, "while", :for) mark_all!(tm, "quote", :for) mark_all!(tm, "begin", :begin) mark_all!(tm, "module", :module) # math [mark_all!(tm, Char('0' + dig), :number) for dig in digits(1234567890)] mark_all!(tm, "true", :number) mark_all!(tm, "false", :number) [mark_all!(tm, string(op), :op) for op in split( """<: = == < > => -> || -= += + / * - ~ <= >= &&""", " ")] mark_between!(tm, "#=", "=#", :comment) #= mark_inside!(tm, :string) do tm2 mark_for!(tm2, "\\", 1, :exit) end =# end """ **Toolips Markdown** ### highlight_julia!(tm::TextModifier) ------------------ Marks default style for julia code. #### example ``` ``` """ highlight_julia!(tm::TextStyleModifier) = begin style!(tm, :default, ["color" => "#3D3D3D"]) style!(tm, :func, ["color" => "#fc038c"]) style!(tm, :funcn, ["color" => "#2F387B"]) style!(tm, :using, ["color" => "#006C67"]) style!(tm, :import, ["color" => "#fc038c"]) style!(tm, :end, ["color" => "#b81870"]) style!(tm, :mutable, ["color" => "#006C67"]) style!(tm, :struct, ["color" => "#fc038c"]) style!(tm, :begin, ["color" => "#fc038c"]) style!(tm, :module, ["color" => "#b81870"]) style!(tm, :string, ["color" => "#007958"]) style!(tm, :if, ["color" => "#fc038c"]) style!(tm, :for, ["color" => "#fc038c"]) style!(tm, :in, ["color" => "#006C67"]) style!(tm, :abstract, ["color" => "#006C67"]) style!(tm, :number, ["color" => "#8b0000"]) style!(tm, :char, ["color" => "#8b0000"]) style!(tm, :type, ["color" => "#D67229"]) style!(tm, :exit, ["color" => "#006C67"]) style!(tm, :op, ["color" => "#0C023E"]) style!(tm, :comment, ["color" => "#808080"]) end """ **Toolips Markdown** ### julia_block!(tm::TextModifier) ------------------ Marks default style for julia code. #### example ``` ``` """ function julia_block!(tm::TextStyleModifier) mark_julia!(tm) highlight_julia!(tm) end """ **Toolips Markdown** ### string(tm::TextModifier) -> ::String ------------------ Styles marks together into `String`. #### example ``` ``` """ function string(tm::TextStyleModifier) if length(tm.marks) == 0 txt = a("modiftxt", text = rep_str(tm.raw)) style!(txt, tm.styles[:default] ...) sc = Toolips.SpoofConnection() write!(sc, txt) return(sc.http.text)::String end prev = 1 finales = Vector{Servable}() sortedmarks = sort(collect(tm.marks), by=x->x[1]) lastmax::Int64 = length(tm.raw) loop_len = length(keys(tm.marks)) [begin if length(mark) > 0 mname = tm.marks[mark] if minimum(mark) - prev > 0 txt = span("modiftxt", text = rep_str(tm.raw[prev:minimum(mark) - 1])) style!(txt, tm.styles[:default] ...) push!(finales, txt) end txt = span("modiftxt", text = rep_str(tm.raw[mark])) if mname in keys(tm.styles) style!(txt, tm.styles[mname] ...) else style!(txt, tm.styles[:default] ...) end push!(finales, txt) prev = maximum(mark) + 1 end if e == loop_len lastmax = maximum(mark) end end for (e, mark) in enumerate((k[1] for k in sortedmarks))] if lastmax != length(tm.raw) txt = span("modiftxt", text = rep_str(tm.raw[lastmax + 1:length(tm.raw)])) style!(txt, tm.styles[:default] ...) push!(finales, txt) end sc = Toolips.SpoofConnection() write!(sc, finales) sc.http.text::String end rep_str(s::String) = replace(s, " " => "&nbsp;", "\n" => "<br>", "\\" => "&bsol;") export tmd, @tmd_str end # module
ToolipsMarkdown
https://github.com/ChifiSource/ToolipsMarkdown.jl.git
[ "MIT" ]
0.1.4
ae277f699ad0abb4743ee9bc7deeb89b554de867
docs
1347
<div align="center"> <img src = "https://github.com/ChifiSource/image_dump/blob/main/toolips/toolipsmarkdown.png"></img> Parse markdown strings into Toolips Components. </div> - [Documentation]() - [Toolips](https://github.com/ChifiSource/Toolips.jl) - [Extension Gallery](https://toolips.app/?page=extensions&selected=markdown) ```julia using Toolips using ToolipsMarkdown markdownexample1 = tmd"""# Hello world, this is an example. This extension, **[toolips markdown](http://github.com/ChifiSource/ToolipsMarkdown.jl)** allows the conversion of regular markdown into Toolips components. """ heading1s = Style("h1", color = "pink") heading1s:"hover":["color" => "lightblue"] myroute = route("/") do c::Connection write!(c, heading1s) mdexample2 = tmd("mymarkdown", "### hello world!") write!(c, markdownexample1) write!(c, mdexample2) end st = ServerTemplate() st.add(myroute) st.start() [2022:07:01:17:22]: 🌷 toolips> Toolips Server starting on port 8000 [2022:07:01:17:22]: 🌷 toolips> /home/emmac/dev/toolips/ToolipsMarkdown/logs/log.txt not in current working directory. [2022:07:01:17:22]: 🌷 toolips> Successfully started server on port 8000 [2022:07:01:17:22]: 🌷 toolips> You may visit it now at http://127.0.0.1:8000 ``` <img src = "https://github.com/ChifiSource/ToolipsMarkdown.jl/blob/main/tgeregergerg.png"></img>
ToolipsMarkdown
https://github.com/ChifiSource/ToolipsMarkdown.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
1359
using Documenter, Gasdynamics1D #ENV["GKSwstype"] = "nul" # removes GKS warnings during plotting ENV["GKSwstype"] = "100" # removes GKS warnings during plotting makedocs( sitename = "Gasdynamics1D.jl", doctest = true, clean = true, pages = [ "Home" => "index.md", "Manual" => ["manual/0-BasicGasDynamics.md", "manual/1-IsentropicGasDynamics.md", "manual/2-ConvergingDivergingNozzle.md", "manual/3-NormalShocks.md", "manual/4-FannoFlow.md", "manual/5-RayleighFlow.md", "manual/functions.md" ] #"Internals" => [ "internals/properties.md"] ], #format = Documenter.HTML(assets = ["assets/custom.css"]) format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true", mathengine = MathJax(Dict( :TeX => Dict( :equationNumbers => Dict(:autoNumber => "AMS"), :Macros => Dict() ) )) ), #assets = ["assets/custom.css"], #strict = true ) #if "DOCUMENTER_KEY" in keys(ENV) deploydocs( repo = "github.com/UCLAMAEThreads/Gasdynamics1D.jl.git", target = "build", devbranch = "main", deps = nothing, make = nothing #versions = "v^" ) #end
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
1700
module Gasdynamics1D #= Quasi-1d gas dynamics routines =# using Roots using Requires using Reexport @reexport using ThermofluidQuantities import ThermofluidQuantities: Unitful, Temperature, Density, Pressure, StagnationTemperature, StagnationDensity, StagnationPressure, SoundSpeed, Enthalpy, StagnationEnthalpy, InternalEnergy, StagnationInternalEnergy, Velocity, MachNumber, MassFlowRate, Entropy, HeatFlux, FrictionFactor, Area, FLOverD, AreaRatio, TemperatureRatio, PressureRatio, StagnationPressureRatio, DensityRatio, VelocityRatio include("plot_recipes.jl") export ThermodynamicProcess, Isentropic, NormalShock, FannoFlow, RayleighFlow export SubsonicMachNumber,SupersonicMachNumber export SubsonicPOverP0,SupersonicPOverP0 export T0OverT,P0OverP,ρ0Overρ,AOverAStar,AStar export FLStarOverD,POverPStar,ρOverρStar,TOverTStar,P0OverP0Star export T0OverT0Star,VOverVStar function __init__() @require Plots="91a5bcdd-55d7-5caf-9e0b-520d859cae80" begin @reexport using LaTeXStrings Plots.default(markerstrokealpha = 0, legend = false, dpi = 100, size = (400, 300), grid = false) end end ###### THERMODYNAMIC PROCESSES ####### abstract type ThermodynamicProcess end abstract type Isentropic <: ThermodynamicProcess end abstract type NormalShock <: ThermodynamicProcess end abstract type FannoFlow <: ThermodynamicProcess end abstract type RayleighFlow <: ThermodynamicProcess end include("thermodynamics.jl") include("isentropic.jl") include("normalshocks.jl") include("fanno.jl") include("rayleigh.jl") include("nozzle.jl") include("vectors.jl") end
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
5909
######## FANNO FLOW ######## """ FLStarOverD(M::MachNumber,FannoFlow[;gas=Air]) Compute the friction factor times distance to sonic point, divided by diameter, for the given Mach number `M`, using the equation ``\\dfrac{fL^*}{D} = \\dfrac{1-M^2}{\\gamma M^2} + \\dfrac{\\gamma+1}{2\\gamma} \\ln \\left(\\dfrac{(\\gamma+1)M^2}{2+(\\gamma-1)M^2}\\right)`` """ function FLStarOverD(M::MachNumber,::Type{FannoFlow};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return FLOverD((1-M^2)/(γ*M^2) + (γ+1)/(2γ)*log((γ+1)*M^2/(2+(γ-1)*M^2))) end """ SubsonicMachNumber(fL_over_D::FLOverD,FannoFlow[;gas=Air]) -> MachNumber Compute the subsonic Mach number, given the ratio friction factor times distance to sonic point, divided by diameter, `fL_over_D`, by solving the equation ``\\dfrac{fL^*}{D} = \\dfrac{1-M^2}{\\gamma M^2} + \\dfrac{\\gamma+1}{2\\gamma} \\ln \\left(\\dfrac{(\\gamma+1)M^2}{2+(\\gamma-1)M^2}\\right)`` """ function SubsonicMachNumber(fL_over_D::FLOverD,::Type{FannoFlow};gas::PerfectGas=DefaultPerfectGas) value(fL_over_D) >= 0.0 || error("fL*/D must be positive") MachNumber(_subsonic_mach_number_fanno(fL_over_D,gas)) end """ SupersonicMachNumber(fL_over_D::FLOverD,FannoFlow[;gas=Air]) -> MachNumber Compute the supersonic Mach number, given the ratio friction factor times distance to sonic point, divided by diameter, `fL_over_D`, by solving the equation ``\\dfrac{fL^*}{D} = \\dfrac{1-M^2}{\\gamma M^2} + \\dfrac{\\gamma+1}{2\\gamma} \\ln \\left(\\dfrac{(\\gamma+1)M^2}{2+(\\gamma-1)M^2}\\right)`` """ function SupersonicMachNumber(fL_over_D::FLOverD,::Type{FannoFlow};gas::PerfectGas=DefaultPerfectGas) max_fLD = FLStarOverD(MachNumber(1e10),FannoFlow,gas=gas) value(fL_over_D) >= 0.0 || error("fL*/D must be positive") value(fL_over_D) > value(max_fLD) ? MachNumber(NaN) : MachNumber(_supersonic_mach_number_fanno(fL_over_D,gas)) end """ MachNumber(fL_over_D::FLOverD,FannoFlow[;gas=Air]) -> MachNumber, MachNumber Compute the subsonic and supersonic Mach numbers, given the ratio friction factor times distance to sonic point, divided by diameter, `fL_over_D`, by solving the equation ``\\dfrac{fL^*}{D} = \\dfrac{1-M^2}{\\gamma M^2} + \\dfrac{\\gamma+1}{2\\gamma} \\ln \\left(\\dfrac{(\\gamma+1)M^2}{2+(\\gamma-1)M^2}\\right)`` """ function MachNumber(fL_over_D::FLOverD,::Type{FannoFlow};gas::PerfectGas=DefaultPerfectGas) SubsonicMachNumber(fL_over_D,FannoFlow,gas=gas), SupersonicMachNumber(fL_over_D,FannoFlow,gas=gas) end _subsonic_mach_number_fanno(fL_over_D::FLOverD,gas::PerfectGas) = find_zero(x -> FLStarOverD(MachNumber(x),FannoFlow,gas=gas)-fL_over_D,(0.001,1),order=16) _supersonic_mach_number_fanno(fL_over_D::FLOverD,gas::PerfectGas) = find_zero(x -> FLStarOverD(MachNumber(x),FannoFlow,gas=gas)-fL_over_D,(1,1e10),order=16) FLOverD(f::FrictionFactor,L::Length,D::Diameter) = FLOverD(f*L/D) Length(fLoverD::FLOverD,D::Diameter,f::FrictionFactor) = Length(fLoverD*D/f) """ POverPStar(M::MachNumber,FannoFlow[;gas=PerfectGas]) -> PressureRatio Compute the ratio of pressure to the sonic pressure in Fanno flow, given Mach number `M`, from ``\\dfrac{p}{p^*} = \\dfrac{1}{M} \\left(\\dfrac{1+\\gamma}{2+(\\gamma-1)M^2}\\right)^{1/2}`` """ function POverPStar(M::MachNumber,::Type{FannoFlow};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return PressureRatio(1/M*sqrt((1+γ)/(2+(γ-1)*M^2))) end """ ρOverρStar(M::MachNumber,FannoFlow[;gas=PerfectGas]) -> DensityRatio Compute the ratio of density to the sonic density in Fanno flow, given Mach number `M`, from ``\\dfrac{\\rho}{\\rho^*} = \\dfrac{1}{M} \\left(\\dfrac{2+(\\gamma-1)M^2}{\\gamma+1}\\right)^{1/2}`` """ function ρOverρStar(M::MachNumber,::Type{FannoFlow};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return DensityRatio(1/M*sqrt((2+(γ-1)*M^2)/(γ+1))) end """ TOverTStar(M::MachNumber,FannoFlow[;gas=PerfectGas]) -> TemperatureRatio Compute the ratio of temperature to the sonic temperature in Fanno flow, given Mach number `M`, from ``\\dfrac{T}{T^*} =\\dfrac{\\gamma+1}{2+(\\gamma-1)M^2}`` """ function TOverTStar(M::MachNumber,::Type{FannoFlow};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return TemperatureRatio((γ+1)/(2+(γ-1)*M^2)) end """ MachNumber(T_over_Tstar::TemperatureRatio,FannoFlow[;gas=PerfectGas]) Compute the Mach number for a given ratio of temperature to the sonic temperature `T_over_Tstar` in Fanno flow, from the solution of ``\\dfrac{T}{T^*} = \\dfrac{\\gamma+1}{2+(\\gamma-1)M^2}`` """ function MachNumber(T_over_Tstar::TemperatureRatio,::Type{FannoFlow};gas::PerfectGas=DefaultPerfectGas) M = find_zero(x -> TOverTStar(MachNumber(x),FannoFlow,gas=gas)-T_over_Tstar,(1e-10,1e10),order=16) return MachNumber(M) end """ P0OverP0Star(M::MachNumber,FannoFlow[;gas=PerfectGas]) -> StagnationPressureRatio Compute the ratio of stagnation pressure to the sonic stagnation pressure in Fanno flow, given Mach number `M`, from ``\\dfrac{p_0}{p_0^*} = \\dfrac{1}{M} \\left(\\dfrac{2+(\\gamma-1)M^2}{\\gamma+1}\\right)^{(\\gamma+1)/2/(\\gamma-1)}`` """ function P0OverP0Star(M::MachNumber,::Type{FannoFlow};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return StagnationPressureRatio(1/M*((2+(γ-1)*M^2)/(γ+1))^((γ+1)/(2(γ-1)))) end function MachNumber(p0_over_p0star::StagnationPressureRatio,::Type{FannoFlow};gas::PerfectGas=DefaultPerfectGas) Msub = find_zero(x -> P0OverP0Star(MachNumber(x),FannoFlow,gas=gas)-p0_over_p0star,(0.001,1),order=16) max_p0_over_p0star = P0OverP0Star(MachNumber(1e10),FannoFlow,gas=gas) if value(p0_over_p0star) > value(max_p0_over_p0star) return MachNumber(Msub) else Msup = find_zero(x -> P0OverP0Star(MachNumber(x),FannoFlow,gas=gas)-p0_over_p0star,(1,1e10),order=16) return MachNumber(Msub), MachNumber(Msup) end end
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
16069
######## ISENTROPIC RELATIONS ######### """ TemperatureRatio(pr::PressureRatio,Isentropic[;gas=Air]) Compute the ratio of temperatures between two points connected isentropically, given the ratio of pressures `pr` between those two points, using the isentropic relation ``\\dfrac{T_2}{T_1} = \\left(\\dfrac{p_2}{p_1}\\right)^{(\\gamma-1)/\\gamma}`` """ function TemperatureRatio(pratio::PressureRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) TemperatureRatio(pratio^((γ-1)/γ)) end """ TemperatureRatio(dr::DensityRatio,Isentropic[;gas=Air]) Compute the ratio of temperatures between two points connected isentropically, given the ratio of densities `dr` between those two points, using the isentropic relation ``\\dfrac{T_2}{T_1} = \\left(\\dfrac{\\rho_2}{\\rho_1}\\right)^{\\gamma-1}`` """ function TemperatureRatio(ρratio::DensityRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) TemperatureRatio(ρratio^(γ-1)) end """ PressureRatio(Tr::TemperatureRatio,Isentropic[;gas=Air]) Compute the ratio of temperatures between two points connected isentropically, given the ratio of densities `dr` between those two points, using the isentropic relation ``\\dfrac{p_2}{p_1} = \\left(\\dfrac{T_2}{T_1}\\right)^{\\gamma/(\\gamma-1)}`` """ function PressureRatio(Tratio::TemperatureRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) PressureRatio(Tratio^(γ/(γ-1))) end """ PressureRatio(dr::DensityRatio,Isentropic[;gas=Air]) Compute the ratio of pressures between two points connected isentropically, given the ratio of densities `dr` between those two points, using the isentropic relation ``\\dfrac{p_2}{p_1} = \\left(\\dfrac{\\rho_2}{\\rho_1}\\right)^{\\gamma}`` """ function PressureRatio(ρratio::DensityRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas).val PressureRatio(ρratio^(γ)) end """ T0OverT(M::MachNumber,Isentropic[;gas=PerfectGas]) -> TemperatureRatio Compute the ratio of stagnation temperature to temperature for Mach number `M`. ``\\dfrac{T_0}{T} = 1 + \\dfrac{\\gamma-1}{2}M^2`` Can also omit the `Isentropic` argument, `T0OverT(M)` """ function T0OverT(M::MachNumber,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return TemperatureRatio(1+0.5*(γ-1)*M^2) end T0OverT(M::MachNumber;gas::PerfectGas=DefaultPerfectGas) = T0OverT(M,Isentropic,gas=gas) """ P0OverP(M::MachNumber,Isentropic[;gas=PerfectGas]) -> PressureRatio Compute the ratio of stagnation pressure to pressure for Mach number `M`. ``\\dfrac{p_0}{p} = \\left(1 + \\dfrac{\\gamma-1}{2}M^2 \\right)^{\\gamma/(\\gamma-1)}`` """ function P0OverP(M::MachNumber,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) Tratio = T0OverT(M,Isentropic,gas=gas) PressureRatio(Tratio,Isentropic,gas=gas) end """ DensityRatio(Tr::TemperatureRatio,Isentropic[;gas=Air]) Compute the ratio of densities between two points connected isentropically, given the ratio of temperatures `Tr` between those two points, using the isentropic relation ``\\dfrac{\\rho_2}{\\rho_1} = \\left(\\dfrac{T_2}{T_1}\\right)^{1/(\\gamma-1)}`` """ function DensityRatio(Tratio::TemperatureRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) DensityRatio(Tratio^(1/(γ-1))) end """ DensityRatio(pr::PressureRatio,Isentropic[;gas=Air]) Compute the ratio of densities between two points connected isentropically, given the ratio of pressures `pr` between those two points, using the isentropic relation ``\\dfrac{\\rho_2}{\\rho_1} = \\left(\\dfrac{p_2}{p_1}\\right)^{1/\\gamma}`` """ function DensityRatio(pratio::PressureRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) DensityRatio(pratio^(1/γ)) end """ ρ0Overρ(M::MachNumber,Isentropic[;gas=PerfectGas]) -> DensityRatio Compute the ratio of stagnation density to density for Mach number `M`. ``\\dfrac{\\rho_0}{\\rho} = \\left(1 + \\dfrac{\\gamma-1}{2}M^2 \\right)^{1/(\\gamma-1)}`` """ function ρ0Overρ(M::MachNumber,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) Tratio = T0OverT(M,Isentropic,gas=gas) DensityRatio(Tratio,Isentropic,gas=gas) end # Temperature relations """ StagnationTemperature(T::Temperature,M::MachNumber,Isentropic[;gas=Air]) Compute the stagnation temperature corresponding to temperature `T` and Mach number `M`, using ``T_0 = T \\left( 1 + \\dfrac{\\gamma-1}{2} M^2\\right)`` Can also omit the `Isentropic` argument, `StagnationTemperature(T,M)`. """ function StagnationTemperature(T::Temperature,M::MachNumber,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) StagnationTemperature(T*T0OverT(M,Isentropic,gas=gas)) end StagnationTemperature(T::Temperature,M::MachNumber;gas::PerfectGas=DefaultPerfectGas) = StagnationTemperature(T,M,Isentropic,gas=gas) """ Temperature(T0::StagnationTemperature,M::MachNumber,Isentropic[;gas=Air]) Compute the temperature corresponding to stagnation temperature `T0` and Mach number `M`, using ``T = T_0 \\left( 1 + \\dfrac{\\gamma-1}{2} M^2\\right)^{-1}`` Can also omit the `Isentropic` argument, `Temperature(T0,M)`. """ Temperature(T0::StagnationTemperature,M::MachNumber,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) = Temperature(T0/T0OverT(M,gas=gas)) Temperature(T0::StagnationTemperature,M::MachNumber;gas::PerfectGas=DefaultPerfectGas) = Temperature(T0,M,Isentropic,gas=gas) """ MachNumber(T_over_T0::TemperatureRatio,Isentropic[;gas=Air]) Compute the Mach number corresponding to the ratio of temperature to stagnation temperature `T_over_T0`, using ``M = \\left( \\dfrac{2}{\\gamma-1}\\left(\\dfrac{1}{T/T_0} - 1 \\right)\\right)^{1/2}`` Can also omit the `Isentropic` argument, `MachNumber(T_over_T0)`. Can also supply the arguments for `T` and `T0` separately, `MachNumber(T,T0)` """ function MachNumber(T_over_T0::TemperatureRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) value(T_over_T0) <= 1.0 || error("T/T0 must be 1 or smaller. Maybe you need to supply the inverse?") γ = SpecificHeatRatio(gas) M2 = ((1.0/T_over_T0)-1)*2/(γ-1) MachNumber(sqrt(M2)) end MachNumber(T_over_T0::TemperatureRatio;gas::PerfectGas=DefaultPerfectGas) = MachNumber(T_over_T0,Isentropic,gas=gas) MachNumber(T::Temperature,T0::StagnationTemperature,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) = MachNumber(TemperatureRatio(T/T0),gas=gas) MachNumber(T::Temperature,T0::StagnationTemperature;gas::PerfectGas=DefaultPerfectGas) = MachNumber(T,T0,Isentropic,gas=gas) # Pressure relations """ StagnationPressure(p::Pressure,M::MachNumber,Isentropic[;gas=Air]) Compute the stagnation pressure corresponding to pressure `p` and Mach number `M`, using ``p_0 = p \\left( 1 + \\dfrac{\\gamma-1}{2} M^2\\right)^{\\gamma/(\\gamma-1)}`` Can also omit the `Isentropic` argument, `StagnationTemperature(T,M)`. """ function StagnationPressure(p::Pressure,M::MachNumber,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) StagnationPressure(p*PressureRatio(T0OverT(M,gas=gas),Isentropic,gas=gas)) end """ Pressure(p0::StagnationPressure,M::MachNumber,Isentropic[;gas=Air]) Compute the pressure corresponding to stagnation pressure `p0` and Mach number `M`, using ``p = p_0 \\left( 1 + \\dfrac{\\gamma-1}{2} M^2\\right)^{-\\gamma/(\\gamma-1)}`` Can also omit the `Isentropic` argument, `Temperature(T0,M)`. """ function Pressure(p0::StagnationPressure,M::MachNumber,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) Pressure(p0/PressureRatio(T0OverT(M,gas=gas),Isentropic,gas=gas)) end """ MachNumber(p_over_p0::PressureRatio,Isentropic[;gas=Air]) Compute the Mach number corresponding to the ratio of pressure to stagnation pressure `p_over_p0`, using ``M = \\left( \\dfrac{2}{\\gamma-1}\\left(\\dfrac{1}{(p/p_0)^{(\\gamma-1)/\\gamma}} - 1 \\right)\\right)^{1/2}`` Can also supply the arguments for `p` and `p0` separately, `MachNumber(p,p0)` """ function MachNumber(p_over_p0::PressureRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) value(p_over_p0) <= 1.0 || error("p/p0 must be 1 or smaller. Maybe you need to supply the inverse?") γ = SpecificHeatRatio(gas) MachNumber(TemperatureRatio(p_over_p0,Isentropic,gas=gas),gas=gas) end MachNumber(p::Pressure,p0::StagnationPressure,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) = MachNumber(PressureRatio(p/p0),Isentropic,gas=gas) # Density relations """ StagnationDensity(ρ::Density,M::MachNumber,Isentropic[;gas=Air]) Compute the stagnation density corresponding to density `ρ` and Mach number `M`, using ``\\rho_0 = \\rho \\left( 1 + \\dfrac{\\gamma-1}{2} M^2\\right)^{1/(\\gamma-1)}`` """ function StagnationDensity(ρ::Density,M::MachNumber,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) StagnationDensity(ρ*DensityRatio(T0OverT(M,gas=gas),Isentropic,gas=gas)) end """ Density(ρ0::StagnationDensity,M::MachNumber,Isentropic[;gas=Air]) Compute the density corresponding to stagnation density `ρ0` and Mach number `M`, using ``\\rho = \\rho_0 \\left( 1 + \\dfrac{\\gamma-1}{2} M^2\\right)^{-1/(\\gamma-1)}`` """ function Density(ρ0::StagnationDensity,M::MachNumber,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) Density(ρ0/DensityRatio(T0OverT(M,gas=gas),Isentropic,gas=gas)) end """ MachNumber(ρ_over_ρ0::DensityRatio,Isentropic[;gas=Air]) Compute the Mach number corresponding to the ratio of density to stagnation density `ρ_over_ρ0`, using ``M = \\left( \\dfrac{2}{\\gamma-1}\\left(\\dfrac{1}{(\\rho/\\rho_0)^{(\\gamma-1)}} - 1 \\right)\\right)^{1/2}`` Can also supply the arguments for `ρ` and `ρ0` separately, `MachNumber(ρ,ρ0)` """ function MachNumber(ρ_over_ρ0::DensityRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) value(ρ_over_ρ0) <= 1.0 || error("ρ/ρ0 must be 1 or smaller. Maybe you need to supply the inverse?") γ = SpecificHeatRatio(gas) MachNumber(TemperatureRatio(ρ_over_ρ0,Isentropic,gas=gas)) end MachNumber(ρ::Density,ρ0::StagnationDensity,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) = MachNumber(DensityRatio(ρ/ρ0),gas=gas) # Area-Mach number relation """ AOverAStar(M::MachNumber,Isentropic[;gas=Air]) -> AreaRatio Compute the ratio of local area to the sonic area for the given Mach number `M`, using ``\\dfrac{A}{A^*} = \\dfrac{1}{M} \\left( \\dfrac{2}{\\gamma+1} \\left( 1 + \\dfrac{\\gamma-1}{2}M^2\\right)\\right)^{(\\gamma+1)/2/(\\gamma-1)}`` Can omit the `Isentropic` argument. """ function AOverAStar(M::MachNumber,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return AreaRatio(1/M*(2/(γ+1)*(T0OverT(M,gas=gas)))^(0.5*(γ+1)/(γ-1))) end AOverAStar(M::MachNumber;gas::PerfectGas=DefaultPerfectGas) = AOverAStar(M,Isentropic,gas=gas) """ AStar(A::Area,M::MachNumber,Isentropic[;gas=Air]) -> Area Compute the sonic area for the given area `A` and Mach number `M`, using ``A^* = A M \\left( \\dfrac{2}{\\gamma+1} \\left( 1 + \\dfrac{\\gamma-1}{2}M^2\\right)\\right)^{-(\\gamma+1)/2/(\\gamma-1)}`` Can omit the `Isentropic` argument. """ function AStar(A::Area,M::MachNumber,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) return Area(A/AOverAStar(M,gas=gas)) end AStar(A::Area,M::MachNumber;gas::PerfectGas=DefaultPerfectGas) = AStar(A,M,Isentropic,gas=gas) """ SubsonicMachNumber(A_over_Astar::AreaRatio,Isentropic[;gas=Air]) -> MachNumber Compute the subsonic Mach number for the given ratio of area to sonic area `A_over_Astar` by solving the equation ``\\dfrac{A}{A^*} = \\dfrac{1}{M} \\left( \\dfrac{2}{\\gamma+1} \\left( 1 + \\dfrac{\\gamma-1}{2}M^2\\right)\\right)^{(\\gamma+1)/2/(\\gamma-1)}`` """ function SubsonicMachNumber(A_over_Astar::AreaRatio,::Type{Isentropic}; gas::PerfectGas=DefaultPerfectGas) value(A_over_Astar) >= 1.0 || error("A/A* must be 1 or larger. Maybe you need to supply the inverse?") Msub = find_zero(x -> AOverAStar(MachNumber(x),gas=gas)-A_over_Astar,(0,1),order=16) return MachNumber(Msub) end """ SupersonicMachNumber(A_over_Astar::AreaRatio,Isentropic[;gas=Air]) -> MachNumber Compute the supersonic Mach number for the given ratio of area to sonic area `A_over_Astar` by solving the equation ``\\dfrac{A}{A^*} = \\dfrac{1}{M} \\left( \\dfrac{2}{\\gamma+1} \\left( 1 + \\dfrac{\\gamma-1}{2}M^2\\right)\\right)^{(\\gamma+1)/2/(\\gamma-1)}`` """ function SupersonicMachNumber(A_over_Astar::AreaRatio,::Type{Isentropic}; gas::PerfectGas=DefaultPerfectGas) value(A_over_Astar) >= 1.0 || error("A/A* must be 1 or larger. Maybe you need to supply the inverse?") Msup = find_zero(x -> AOverAStar(MachNumber(x),gas=gas)-A_over_Astar,(1,Inf),order=16) return MachNumber(Msup) end function SubsonicMachNumber(A::Area,Aloc::Area,ploc_over_p0::PressureRatio,::Type{Isentropic}; gas::PerfectGas=DefaultPerfectGas) Mloc = MachNumber(ploc_over_p0,Isentropic,gas=gas) Astar = AStar(Aloc,Mloc,gas=gas) SubsonicMachNumber(A,Astar,Isentropic,gas=gas) end function SupersonicMachNumber(A::Area,Aloc::Area,ploc_over_p0::PressureRatio,::Type{Isentropic}; gas::PerfectGas=DefaultPerfectGas) Mloc = MachNumber(ploc_over_p0,Isentropic,gas=gas) Astar = AStar(Aloc,Mloc,gas=gas) SupersonicMachNumber(A,Astar,Isentropic,gas=gas) end SubsonicMachNumber(A::Area,Astar::Area, ::Type{Isentropic}; gas::PerfectGas=DefaultPerfectGas) = SubsonicMachNumber(AreaRatio(A/Astar),Isentropic,gas=gas) SupersonicMachNumber(A::Area,Astar::Area, ::Type{Isentropic}; gas::PerfectGas=DefaultPerfectGas) = SupersonicMachNumber(AreaRatio(A/Astar),Isentropic,gas=gas) """ MachNumber(A_over_Astar::AreaRatio,Isentropic[;gas=Air]) -> MachNumber, MachNumber Compute the subsonic and supersonic Mach numbers for the given ratio of area to sonic area `A_over_Astar` by solving the equation ``\\dfrac{A}{A^*} = \\dfrac{1}{M} \\left( \\dfrac{2}{\\gamma+1} \\left( 1 + \\dfrac{\\gamma-1}{2}M^2\\right)\\right)^{(\\gamma+1)/2/(\\gamma-1)}`` Can omit the `Isentropic` argument. """ function MachNumber(A_over_Astar::AreaRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) return SubsonicMachNumber(A_over_Astar,Isentropic,gas=gas), SupersonicMachNumber(A_over_Astar,Isentropic,gas=gas) end MachNumber(A_over_Astar::AreaRatio;gas::PerfectGas=DefaultPerfectGas) = MachNumber(A_over_Astar,Isentropic,gas=gas) """ MachNumber(M1::MachNumber,A1::AreaRatio,A2::AreaRatio,Isentropic[;gas=Air]) -> MachNumber, MachNumber Compute the subsonic and supersonic Mach numbers at location 2 with area `A2`, when location 1 has Mach number `M1` and area `A1`. """ function MachNumber(M1::MachNumber,A1::Area,A2::Area,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) M2sub, M2sup = MachNumber(AreaRatio(A2/AStar(A1,M1,gas=gas)),gas=gas) end MachNumber(M1::MachNumber,A1::Area,A2::Area;gas::PerfectGas=DefaultPerfectGas) = MachNumber(M1,A2,A2,Isentropic,gas=gas) function SubsonicPOverP0(A::Area,Aloc::Area,ploc_over_p0::PressureRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) Mloc = MachNumber(ploc_over_p0,Isentropic,gas=gas) Astar = AStar(Aloc,Mloc,gas=gas) SubsonicPOverP0(A,Astar,Isentropic,gas=gas) end function SupersonicPOverP0(A::Area,Aloc::Area,ploc_over_p0::PressureRatio,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) Mloc = MachNumber(ploc_over_p0,Isentropic,gas=gas) Astar = AStar(Aloc,Mloc,gas=gas) SupersonicPOverP0(A,Astar,Isentropic,gas=gas) end function SubsonicPOverP0(A::Area,Astar::Area,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) M = SubsonicMachNumber(A,Astar,Isentropic,gas=gas) PressureRatio(1/P0OverP(M,Isentropic,gas=gas)) end function SupersonicPOverP0(A::Area,Astar::Area,::Type{Isentropic};gas::PerfectGas=DefaultPerfectGas) M = SupersonicMachNumber(A,Astar,Isentropic,gas=gas) PressureRatio(1/P0OverP(M,Isentropic,gas=gas)) end
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
3673
###### NORMAL SHOCK RELATIONS ####### """ MachNumber(M1::MachNumber,NormalShock[;gas=Air]) Return the Mach number after a normal shock, given the Mach number `M1` before the shock, using the equation ``M_2^2 = \\dfrac{2 + (\\gamma-1)M_1^2}{2\\gamma M_1^2 - (\\gamma-1)}`` """ function MachNumber(M1::MachNumber,::Type{NormalShock};gas::PerfectGas=DefaultPerfectGas) value(M1) >= 1.0 || error("M1 must be at least 1") Ξ³ = SpecificHeatRatio(gas) M2sq = (1 + 0.5*(Ξ³-1)*M1^2)/(Ξ³*M1^2-0.5*(Ξ³-1)) return MachNumber(sqrt(M2sq)) end """ TemperatureRatio(M1::MachNumber,NormalShock[;gas=Air]) Return the ratio of temperatures after and before a normal shock, given the Mach number `M1` before the shock, using the equation ``\\dfrac{T_2}{T_1} = 1 + 2\\dfrac{(\\gamma-1)}{(\\gamma+1)^2}\\dfrac{(1+\\gamma M_1^2)(M_1^2-1)}{M_1^2}`` """ function TemperatureRatio(M1::MachNumber,::Type{NormalShock};gas::PerfectGas=DefaultPerfectGas) value(M1) >= 1.0 || error("M1 must be at least 1") Ξ³ = SpecificHeatRatio(gas) return TemperatureRatio(1 + 2*(Ξ³-1)/(Ξ³+1)^2*((1+Ξ³*M1^2)/M1^2)*(M1^2-1)) end """ PressureRatio(M1::MachNumber,NormalShock[;gas=Air]) Return the ratio of pressures after and before a normal shock, given the Mach number `M1` before the shock, using the equation ``\\dfrac{p_2}{p_1} = 1 + 2\\dfrac{\\gamma}{\\gamma+1}(M_1^2-1)`` """ function PressureRatio(M1::MachNumber,::Type{NormalShock};gas::PerfectGas=DefaultPerfectGas) value(M1) >= 1.0 || error("M1 must be at least 1") Ξ³ = SpecificHeatRatio(gas) return PressureRatio(1 + 2*Ξ³/(Ξ³+1)*(M1^2-1)) end """ DensityRatio(M1::MachNumber,NormalShock[;gas=Air]) Return the ratio of densities after and before a normal shock, given the Mach number `M1` before the shock, using the equation ``\\dfrac{\\rho_2}{\\rho_1} = \\dfrac{(\\gamma+1)M_1^2}{2+(\\gamma-1)M_1^2}`` """ function DensityRatio(M1::MachNumber,::Type{NormalShock};gas::PerfectGas=DefaultPerfectGas) value(M1) >= 1.0 || error("M1 must be at least 1") Ξ³ = SpecificHeatRatio(gas) return DensityRatio((Ξ³+1)*M1^2/(2+(Ξ³-1)*M1^2)) end """ StagnationPressureRatio(M1::MachNumber,NormalShock[;gas=Air]) Return the ratio of stagnation pressures after and before a normal shock, given the Mach number `M1` before the shock, using the equation ``\\dfrac{p_{02}}{p_{01}} = \\left(\\dfrac{(\\gamma+1)M_1^2}{2+(\\gamma-1)M_1^2}\\right)^{\\gamma/(\\gamma-1)} \\left(\\dfrac{\\gamma+1}{2\\gamma M_1^2 - (\\gamma-1)}\\right)^{1/(\\gamma-1)}`` """ function StagnationPressureRatio(M1::MachNumber,::Type{NormalShock};gas::PerfectGas=DefaultPerfectGas) value(M1) >= 1.0 || error("M1 must be at least 1") M2 = MachNumber(M1,NormalShock,gas=gas) pratio = PressureRatio(M1,NormalShock,gas=gas) p01_unit = StagnationPressure(Pressure(1),M1,Isentropic,gas=gas) p02_unit = StagnationPressure(Pressure(1),M2,Isentropic,gas=gas) return StagnationPressureRatio(pratio*p02_unit/p01_unit) end """ Entropy(s1::Entropy,M1::MachNumber,NormalShock[;gas=Air]) Return the entropy after a normal shock, given the entropy before the shock `s1` and the Mach number before the shock `M1`, using the equation ``s_2 - s_1 = c_v \\ln \\left(1 + \\dfrac{2\\gamma}{\\gamma+1}(M_1^2-1)\\right) - c_p \\ln \\left( \\dfrac{(\\gamma+1)M_1^2}{2+(\\gamma-1)M_1^2}\\right)`` """ function Entropy(s1::Entropy,M1::MachNumber,::Type{NormalShock};gas::PerfectGas=DefaultPerfectGas) value(M1) >= 1.0 || error("M1 must be at least 1") Ξ³ = SpecificHeatRatio(gas) cv = SpecificHeatVolume(gas) ds = cv*(log(1+2*Ξ³/(Ξ³+1)*(M1^2-1)) - Ξ³*log((Ξ³+1)*M1^2/(2+(Ξ³-1)*M1^2))) return Entropy(s1+ds) end
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
14580
# Converging-diverging nozzles export Nozzle, areas, positions, converging, diverging, throat, nozzleexit, machnumber,temperature, density, massflowrate, flow_quality, NozzleProcess abstract type NozzleQuality end abstract type SubsonicIsentropicNozzle <: NozzleQuality end abstract type SupersonicWithShockNozzle <: NozzleQuality end abstract type SupersonicIsentropicNozzle <: NozzleQuality end struct Nozzle{T,S} Ai :: T At :: T Ae :: T x :: S areas :: Vector{T} throat_index :: Integer end function Nozzle(Ai::Area,At::Area,Ae::Area;xmin=-1.0,xmax=3.0,len=201) x = range(xmin,xmax,length=len) a = areas(x,Ai,At,Ae) Nozzle(Ai,At,Ae,x,a,_find_throat(a,At)) end function areas(x,Ai::Area,At::Area,Ae::Area) a = Array{Area,1}(undef,length(x)) araw = _nozzle_area(x,value(Ai),value(At),value(Ae)) a .= Area.(araw) end function _find_throat(a::AbstractVector{T},At::Area) where T <: Area indx = findall(x -> (value(x) β‰ˆ value(At)),a) isempty(indx) && error("Can't find the throat") return indx[1] end areas(n::Nozzle) = n.areas positions(n::Nozzle) = n.x throat(n::Nozzle) = n.At nozzleexit(n::Nozzle) = n.Ae inlet(n::Nozzle) = n.Ai converging(n::Nozzle) = view(areas(n),1:n.throat_index) diverging(n::Nozzle) = view(areas(n),n.throat_index+1:length(areas(n))) function Base.show(io::IO, noz::Nozzle) println(io, "Converging-diverging nozzle") println(io, " Inlet area (sq cm)= "*string(value(inlet(noz),u"cm^2"))) println(io, " Throat area (sq cm)= "*string(value(throat(noz),u"cm^2"))) println(io, " Exit area (sq cm)= "*string(value(nozzleexit(noz),u"cm^2"))) end # Shaping of nozzle cross-section _rad_conv(x,Rt,Ri) = Rt + (Ri-Rt)*x^2 _rad_div(x,Rt,Re,c) = Re + (Rt-Re)*exp(-c*x^2) _radius_shape(x,Ri,Rt,Re,c) = x <= 0 ? _rad_conv(x,Rt,Ri) : _rad_div(x,Rt,Re,c) function _nozzle_area(x,Ai,At,Ae;c=1) return Ο€*_radius_shape.(x,sqrt(Ai/Ο€),sqrt(At/Ο€),sqrt(Ae/Ο€),c).^2 end struct NozzleProcess{process_type,T,S,G} noz :: Nozzle{T,S} p :: Vector{Pressure} M :: Vector{MachNumber} p0 :: StagnationPressure T0 :: StagnationTemperature pb_subcrit :: Pressure pb_supcrit_exitshock :: Pressure pb_supcrit :: Pressure pb :: Pressure As :: T gas :: G #NozzleProcess{process_type}(noz,p,M,p0,T0,pb,As,gas) = new{process_type,} end function NozzleProcess(noz::Nozzle{T,S},pb::Pressure{PU},p0::StagnationPressure{PSU},T0::StagnationTemperature{PTU};gas::PerfectGas=DefaultPerfectGas) where {T,S,PU,PSU,PTU} pb_subcrit = _pressure_subsonic_critical(noz,p0,gas) pb_supcrit_exitshock = _pressure_supersonic_shock_critical(noz,p0,gas) pb_supcrit = _pressure_supersonic_critical(noz,p0,gas) process_type = pb > pb_subcrit ? SubsonicIsentropicNozzle : (pb > pb_supcrit_exitshock ? SupersonicWithShockNozzle : SupersonicIsentropicNozzle) As = _shock_area(noz,pb,p0,process_type,gas) p = pressure_nozzle(noz,pb,p0,As,process_type,gas) M = machnumber_nozzle(noz,pb,p0,As,process_type,gas) NozzleProcess{process_type,T,S,typeof(gas)}(noz,p,M,p0,T0, pb_subcrit,pb_supcrit_exitshock,pb_supcrit, pb,As,gas) end function Base.show(io::IO, nozproc::NozzleProcess) println(io, "Flow in a converging-diverging nozzle") println(io, " Inlet area (sq cm)= "*string(value(inlet(nozproc.noz),u"cm^2"))) println(io, " Throat area (sq cm)= "*string(value(throat(nozproc.noz),u"cm^2"))) println(io, " Exit area (sq cm)= "*string(value(nozzleexit(nozproc.noz),u"cm^2"))) println(io, " Stagnation pressure (KPa) = "*string(value(nozproc.p0,u"kPa"))) println(io, " Stagnation temperature (K) = "*string(value(nozproc.T0,u"K"))) println(io, " Subsonic choked isentropic (KPa) = "*string(value(nozproc.pb_subcrit,u"kPa"))) println(io, " Supersonic choked isentropic (KPa) = "*string(value(nozproc.pb_supcrit,u"kPa"))) println(io, " Back pressure (KPa) = "*string(value(nozproc.pb,u"kPa"))) println(io, " Behavior --> "*flow_quality(nozproc)) end machnumber(np::NozzleProcess) = np.M pressure(np::NozzleProcess) = np.p function temperature(np::NozzleProcess) Temp = Temperature[] for Mi in machnumber(np) T0_over_T = T0OverT(Mi,Isentropic,gas=np.gas) push!(Temp,Temperature(np.T0/T0_over_T)) end Temp end function density(np::NozzleProcess) ρ0 = StagnationDensity(np.p0,np.T0,gas=np.gas) ρ = Density[] for (pi,Ti) in zip(pressure(np),temperature(np)) push!(ρ,Density(pi,Ti,gas=np.gas)) end ρ end function massflowrate(np::NozzleProcess) idx = np.noz.throat_index Mt = machnumber(np)[idx] pt = pressure(np)[idx] T0_over_T = T0OverT(Mt,Isentropic,gas=np.gas) Tt = Temperature(np.T0/T0_over_T) at = SoundSpeed(Tt,gas=np.gas) ut = Velocity(at,Mt) ρt = Density(pt,Tt,gas=np.gas) MassFlowRate(ρt,ut,throat(np.noz)) end # --------------- function machnumber_nozzle(noz::Nozzle,pb::Pressure,p01::StagnationPressure,As::Area,::Type{SupersonicWithShockNozzle},gas::PerfectGas) vcat(_machnumber_subsonic(converging(noz),converging(noz)[end],gas), _machnumber_diverging_nozzle_with_shock(diverging(noz),As,throat(noz),p01,gas)) end function pressure_nozzle(noz::Nozzle,pb::Pressure,p01::StagnationPressure,As::Area,::Type{SupersonicWithShockNozzle},gas::PerfectGas) vcat(_pressure_subsonic(converging(noz),converging(noz)[end],p01,gas), _pressure_diverging_nozzle_with_shock(diverging(noz),As,throat(noz),p01,gas)) end # --- function machnumber_nozzle(noz::Nozzle,pb,p0,As,::Type{SupersonicIsentropicNozzle},gas::PerfectGas) vcat(_machnumber_subsonic(converging(noz),converging(noz)[end],gas), _machnumber_diverging_nozzle(diverging(noz),throat(noz),gas)) end function pressure_nozzle(noz::Nozzle,pb,p0::StagnationPressure,As,::Type{SupersonicIsentropicNozzle},gas::PerfectGas) vcat(_pressure_subsonic(converging(noz),converging(noz)[end],p0,gas), _pressure_diverging_nozzle(diverging(noz),throat(noz),p0,gas)) end # --- machnumber_nozzle(noz::Nozzle,pb::Pressure,p0::StagnationPressure,As,::Type{SubsonicIsentropicNozzle},gas::PerfectGas) = _machnumber_subsonic(areas(noz),pb,p0,gas) pressure_nozzle(noz::Nozzle,pb::Pressure,p0::StagnationPressure,As,::Type{SubsonicIsentropicNozzle},gas::PerfectGas) = _pressure_subsonic(areas(noz),pb,p0,gas) # Subsonic nozzle processes function _machnumber_subsonic(A::AbstractVector{T},pb::Pressure,p0::StagnationPressure,gas::PerfectGas) where T <: Area Mb = MachNumber(PressureRatio(pb/p0),Isentropic,gas=gas) Astar = AStar(A[end],Mb,gas=gas) _machnumber_subsonic(A,Astar,gas) end function _machnumber_subsonic(A::AbstractVector{T},Astar::Area,gas::PerfectGas) where T <: Area return SubsonicMachNumber(A,Astar,Isentropic,gas=gas) end function _pressure_subsonic(A::AbstractVector{T},pb::Pressure,p0::StagnationPressure,gas::PerfectGas) where T <: Area Mb = MachNumber(PressureRatio(pb/p0),Isentropic,gas=gas) Astar = AStar(A[end],Mb,gas=gas) _pressure_subsonic(A,Astar,p0,gas) end function _pressure_subsonic(A::AbstractVector{T},Astar::Area,p0::StagnationPressure,gas::PerfectGas) where {T <: Area} p_over_p0 = SubsonicPOverP0(A,Astar,Isentropic,gas=gas) p = Pressure[] for pr in p_over_p0 push!(p,Pressure(pr*p0)) end return p end function _pressure_subsonic_2(A::AbstractVector{T},Astar::Area,p0::StagnationPressure,gas::PerfectGas) where {T <: Area} p_over_p0 = SubsonicPOverP0(A,Astar,Isentropic,gas=gas) p = Pressure[] for pr in p_over_p0 push!(p,Pressure(pr*p0)) end return p end # Diverging nozzle processes function _pressure_diverging_nozzle(A::AbstractVector{T},Astar::Area,p0::StagnationPressure,gas::PerfectGas) where {T <: Area} p = Pressure[] p_over_p0 = SupersonicPOverP0(A,Astar,Isentropic,gas=gas) for pr in p_over_p0 push!(p,Pressure(pr*p0)) end return p end function _machnumber_diverging_nozzle(A::AbstractVector{T},Astar::Area,gas::PerfectGas) where T <: Area return SupersonicMachNumber(A,Astar,Isentropic,gas=gas) end function _pressure_diverging_nozzle_with_shock(A::AbstractVector{T},As::Area,Astar1::Area,p01::StagnationPressure,gas::PerfectGas) where {T <: Area} i1 = _index_upstream_of_shock(A,As) p = Pressure[] pup_over_p01 = SupersonicPOverP0(A[1:i1],Astar1,Isentropic,gas=gas) for pr in pup_over_p01 push!(p,Pressure(pr*p01)) end M1, M2, Astar2, p02_over_p01, _ = _shock(As,Astar1,gas) p02 = StagnationPressure(p02_over_p01*p01) pdown_over_p02 = SubsonicPOverP0(A[i1+1:end],Astar2,Isentropic,gas=gas) for pr in pdown_over_p02 push!(p,Pressure(pr*p02)) end return p end function _machnumber_diverging_nozzle_with_shock(A::AbstractVector{T},As::Area,Astar1::Area,p01::StagnationPressure,gas::PerfectGas) where T <: Area i1 = _index_upstream_of_shock(A,As) M = SupersonicMachNumber(A[1:i1],Astar1,Isentropic,gas=gas) M1, M2, Astar2, _, _ = _shock(As,Astar1,gas) Mdown = SubsonicMachNumber(A[i1+1:end],Astar2,Isentropic,gas=gas) for Mi in Mdown push!(M,Mi) end return M end # Given an exit area Ae, shock area As, and Astar1, p01 in upstream nozzle # return the pressure pe at exit function _pressure_diverging_nozzle_with_shock(Ae::Area,As::Area,Astar1::Area,p01::StagnationPressure,gas::PerfectGas) value(Astar1) <= value(As) <= value(Ae) || error("Shock area outside of bounds") M1, M2, Astar2, p02_over_p01, _ = _shock(As,Astar1,gas) # conditions downstream of shock p02 = StagnationPressure(p02_over_p01*p01) pe_over_p02 = SubsonicPOverP0(Ae,Astar2,Isentropic,gas=gas) return Pressure(pe_over_p02*p02) end # Given an exit area Ae, shock area As, and Astar1, p01 in upstream nozzle # return the Mach number Me at exit function _machnumber_diverging_nozzle_with_shock(Ae::Area,As::Area,Astar1::Area,p01::StagnationPressure,gas::PerfectGas) value(Astar1) <= value(As) <= value(Ae) || error("Shock area outside of bounds") M1, M2, Astar2, _, _ = _shock(As,Astar1,gas) return SubsonicMachNumber(Ae,Astar2,Isentropic,gas=gas) end function _shock(As::Area,Astar1::Area,gas::PerfectGas) M1 = SupersonicMachNumber(AreaRatio(As/Astar1),Isentropic,gas=gas) M2 = MachNumber(M1,NormalShock,gas=gas) Astar2 = AStar(As,M2,Isentropic,gas=gas) p02_over_p01 = StagnationPressureRatio(M1,NormalShock,gas=gas) T2_over_T1 = TemperatureRatio(M1,NormalShock,gas=gas) return M1, M2, Astar2, p02_over_p01, T2_over_T1 end # Find the index in array A corresponding to just before As. # Assumes that A is diverging nozzle. function _index_upstream_of_shock(A::AbstractVector{T},As::Area) where T <: Area value(A[1]) <= value(As) <= value(A[end]) || error("Shock area outside of bounds") indx = findall(x -> x >= 1.0,diff(sign.(value.(A) .- value(As)))) return indx[end] end #= Replace these in NozzleProcess... function machnumber_nozzle(noz::Nozzle,As::Area,pb::Pressure,p01::StagnationPressure;gas::PerfectGas=DefaultPerfectGas) pb_subcrit = _pressure_subsonic_critical(noz,p01,gas=gas) pb_supcrit = _pressure_supersonic_shock_critical(noz,p01,gas=gas) M = pb > pb_subcrit ? machnumber_subsonic(areas(noz),pb,p01,gas=gas) : (pb > pb_supcrit ? machnumber_nozzle_with_shock(noz,As,pb,p01,gas=gas) : machnumber_nozzle_supersonic(noz,gas=gas)) return M end function pressure_nozzle(noz::Nozzle,As::Area,pb::Pressure,p01::StagnationPressure;gas::PerfectGas=DefaultPerfectGas) pb_subcrit = _pressure_subsonic_critical(noz,p01,gas=gas) pb_supcrit = _pressure_supersonic_shock_critical(noz,p01,gas=gas) p = pb > pb_subcrit ? pressure_subsonic(areas(noz),pb,p01,gas=gas) : (pb > pb_supcrit ? pressure_nozzle_with_shock(noz,As,pb,p01,gas=gas) : pressure_nozzle_supersonic(noz,p01,gas=gas)) # Set the final pressure to the back pressure p[end] = pb return p end =# # Find area at which shock occurs function _shock_area(noz::Nozzle,pb::Pressure,p01::StagnationPressure,::Type{SupersonicWithShockNozzle},gas::PerfectGas) pb_crit = _pressure_subsonic_critical(noz,p01,gas) pb < pb_crit || error("Back pressure too large for a shock") return Area(find_zero(x -> value(_pressure_diverging_nozzle_with_shock(nozzleexit(noz),Area(x),throat(noz),p01,gas))-value(pb), (value(diverging(noz)[1]),value(diverging(noz)[end-1])),order=8)) end _shock_area(noz::Nozzle,pb,p01,::Type{SubsonicIsentropicNozzle},gas::PerfectGas) = throat(noz) _shock_area(noz::Nozzle,pb,p01,::Type{SupersonicIsentropicNozzle},gas::PerfectGas) = throat(noz) flow_quality(nozproc::NozzleProcess) = flow_quality(nozproc.noz,nozproc.pb,nozproc.p0,gas=nozproc.gas) function flow_quality(noz::Nozzle,pb::Pressure,p0::StagnationPressure;gas::PerfectGas=DefaultPerfectGas) pb_subcrit = _pressure_subsonic_critical(noz,p0,gas) pb_supcrit_exitshock = _pressure_supersonic_shock_critical(noz,p0,gas) pb_supcrit = _pressure_supersonic_critical(noz,p0,gas) if pb > p0 || pb < Pressure(0.0) return error("Invalid back pressure") elseif pb > pb_subcrit return "Unchoked subsonic" elseif pb β‰ˆ pb_subcrit return "Choked subsonic" elseif pb > pb_supcrit_exitshock return "Supersonic with normal shock" elseif pb > pb_supcrit return "Overexpanded supersonic" elseif pb β‰ˆ pb_supcrit return "Perfectly expanded supersonic" else return "Underexpanded supersonic" end #println(pb_supcrit) end # Find critical back pressure for subsonic isentropic branch function _pressure_subsonic_critical(noz::Nozzle,p0::StagnationPressure,gas::PerfectGas) pb_crit_over_p0 = SubsonicPOverP0(nozzleexit(noz),throat(noz),Isentropic,gas=gas) return Pressure(pb_crit_over_p0*p0) end # Find critical back pressure for supersonic isentropic branch with shock at exit function _pressure_supersonic_shock_critical(noz::Nozzle,p0::StagnationPressure,gas::PerfectGas) pe_supcrit = _pressure_supersonic_critical(noz,p0,gas) Me_supcrit = SupersonicMachNumber(nozzleexit(noz),throat(noz),Isentropic,gas=gas) pb_over_pe_supcrit = PressureRatio(Me_supcrit,NormalShock,gas=gas) return Pressure(pb_over_pe_supcrit*pe_supcrit) end # Find critical back pressure for supersonic isentropic branch function _pressure_supersonic_critical(noz::Nozzle,p0::StagnationPressure,gas::PerfectGas) pe_supcrit_over_p0 = SupersonicPOverP0(nozzleexit(noz),throat(noz),Isentropic,gas=gas) return Pressure(pe_supcrit_over_p0*p0) end
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
3192
using RecipesBase using ColorTypes import PlotUtils: cgrad, palette, color_list using LaTeXStrings @userplot NozzlePlot @recipe function f(h::NozzlePlot;fields=(),gas=DefaultPerfectGas) nfields = length(fields) + 1 if nfields == 1 length(h.args) == 1 || error("`nozzleplot` should be given one argument. Got: $(typeof(h.args))") noz, = h.args else length(h.args) == 4 || error("`nozzleplot` should be given four arguments. Got: $(typeof(h.args))") noz, pb, p0, T0 = h.args nozproc = NozzleProcess(noz,pb,p0,T0,gas=gas) end linecolor := 1 if plotattributes[:plot_object].n > 0 lc = plotattributes[:plot_object].series_list[end][:linecolor] idx = findall(x -> RGBA(x) == lc,color_list(palette(:default))) linecolor := idx[1] + 1 end layout := (nfields,1) size := (500,200*nfields) xticks := (0:0,["Throat"]) xline = [0,0] fields_lower = lowercase.(fields) subnum = 0 if in("pressure",fields_lower) subnum += 1 p = ustrip.(pressure(nozproc),u"kPa") pmax = maximum(p)+50 @series begin subplot := subnum linestyle --> :dash linecolor := :black #label := "" xline, [0,pmax] end @series begin subplot := subnum ylims --> (0,pmax) xlims := (-Inf,Inf) yguide := "Pressure (KPa)" #legend := true #annotations := (positions(noz)[end],p[end],nozzle_quality(noz,pb,p0)) positions(noz), p end end if in("temperature",fields_lower) subnum += 1 T = ustrip.(temperature(nozproc),u"K") Tmax = maximum(T)+100.0 @series begin subplot := subnum linestyle --> :dash linecolor := :black xline, [0,Tmax] end @series begin subplot := subnum ylims --> (0,Tmax) xlims := (-Inf,Inf) yguide := "Temperature (K)" positions(noz), T end end if in("density",fields_lower) subnum += 1 ρ = ustrip.(density(nozproc)) ρmax = maximum(ρ)+1.0 @series begin subplot := subnum linestyle --> :dash linecolor := :black xline, [0,ρmax] end @series begin subplot := subnum ylims --> (0,ρmax) xlims := (-Inf,Inf) yguide := "Density (kg/m3)" positions(noz), ρ end end if in("machnumber",fields_lower) || in("mach",fields_lower) subnum += 1 M = ustrip.(machnumber(nozproc)) Mmax = maximum(M)+1.0 @series begin subplot := subnum linestyle --> :dash linecolor := :black xline, [0,Mmax] end @series begin subplot := subnum linestyle --> :dash linecolor := :black positions(noz), ones(length(positions(noz))) end @series begin subplot := subnum ylims --> (0,Mmax) xlims := (-Inf,Inf) yguide := "Mach Number" positions(noz), M end end subnum += 1 A = ustrip.(areas(noz),u"cm^2") Amax = maximum(A)+10 @series begin subplot := subnum linestyle --> :dash linecolor := :black xline, [0,Amax] end #@series begin subplot := subnum ylims --> (0,Amax) xlims := (-Inf,Inf) yguide := "Area (sq cm)" positions(noz),A #end end
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
4121
####### RAYLEIGH FLOW ######## HeatFlux(h01::StagnationEnthalpy,h02::StagnationEnthalpy) = HeatFlux(h02-h01) """ HeatFlux(T01::StagnationTemperature,T02::StagnationTemperature[;gas=Air]) Compute the heat flux required to change stagnation temperature `T01` to stagnation temperature `T02`, using ``q = c_p(T_{02} - T_{01})`` """ function HeatFlux(T01::StagnationTemperature,T02::StagnationTemperature;gas::PerfectGas=DefaultPerfectGas) h01 = StagnationEnthalpy(T01;gas=gas) h02 = StagnationEnthalpy(T02;gas=gas) return HeatFlux(h01,h02) end # Fanno flow produces StagnationPressureRatio. There should also be a StagnationTemperatureRatio # defined in ThermofluidQuantities.jl """ T0OverT0Star(M::MachNumber,RayleighFlow[;gas=Air]) -> TemperatureRatio Compute the ratio of stagnation temperature to sonic stagnation temperature for the given Mach number for Rayleigh flow, using the equation ``\\dfrac{T_0}{T_0^*} = \\dfrac{(\\gamma+1)M^2 (2 + (\\gamma-1)M^2)}{(1+\\gamma M^2)^2}`` """ function T0OverT0Star(M::MachNumber,::Type{RayleighFlow};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return TemperatureRatio(((γ+1)*M^2*(2+(γ-1)*M^2))/(1+γ*M^2)^2) end """ TOverTStar(M::MachNumber,RayleighFlow[;gas=Air]) -> TemperatureRatio Compute the ratio of temperature to sonic temperature for the given Mach number for Rayleigh flow, using the equation ``\\dfrac{T}{T^*} = \\dfrac{(\\gamma+1)^2 M^2}{(1+\\gamma M^2)^2}`` """ function TOverTStar(M::MachNumber,::Type{RayleighFlow};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return TemperatureRatio(((γ+1)^2*M^2)/(1+γ*M^2)^2) end function MachNumber(T0_over_T0star::TemperatureRatio,::Type{RayleighFlow};gas::PerfectGas=DefaultPerfectGas) value(T0_over_T0star) <= 1.0 || error("T0/T0* must be 1 or smaller") Msub = find_zero(x -> T0OverT0Star(MachNumber(x),RayleighFlow,gas=gas)-T0_over_T0star,(0.001,1),order=16) max_T0ratio = T0OverT0Star(MachNumber(1e10),RayleighFlow,gas=gas) if value(T0_over_T0star) < value(max_T0ratio) return MachNumber(Msub) else Msup = find_zero(x -> T0OverT0Star(MachNumber(x),RayleighFlow,gas=gas)-T0_over_T0star,(1,1e10),order=16) return MachNumber(Msub), MachNumber(Msup) end end """ POverPStar(M::MachNumber,RayleighFlow[;gas=Air]) -> PressureRatio Compute the ratio of pressure to sonic pressure for the given Mach number for Rayleigh flow, using the equation ``\\dfrac{p}{p^*} = \\dfrac{\\gamma+1}{1+\\gamma M^2}`` """ function POverPStar(M::MachNumber,::Type{RayleighFlow};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return PressureRatio((γ+1)/(1+γ*M^2)) end """ VOverVStar(M::MachNumber,RayleighFlow[;gas=Air]) -> VelocityRatio Compute the ratio of velocity to sonic velocity for the given Mach number for Rayleigh flow, using the equation ``\\dfrac{V}{V^*} = \\dfrac{(\\gamma+1)M^2}{1+\\gamma M^2}`` """ function VOverVStar(M::MachNumber,::Type{RayleighFlow};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return VelocityRatio(((γ+1)*M^2)/(1+γ*M^2)) end """ ρOverρStar(M::MachNumber,RayleighFlow[;gas=Air]) -> DensityRatio Compute the ratio of density to sonic density for the given Mach number for Rayleigh flow, using the equation ``\\dfrac{\\rho}{\\rho^*} = \\dfrac{1+\\gamma M^2}{(\\gamma+1)M^2}`` """ function ρOverρStar(M::MachNumber,::Type{RayleighFlow};gas::PerfectGas=DefaultPerfectGas) return DensityRatio(1/VOverVStar(M,RayleighFlow,gas=gas)) end """ P0OverP0Star(M::MachNumber,RayleighFlow[;gas=Air]) -> PressureRatio Compute the ratio of stagnation pressure to sonic stagnation pressure for the given Mach number for Rayleigh flow, using the equation ``\\dfrac{p_0}{p_0^*} = \\dfrac{(\\gamma+1)}{1+\\gamma M^2} \\left[ \\left( \\dfrac{1}{\\gamma+1} \\right)\\left(2 + (\\gamma-1) M^2\\right)\\right]^{\\gamma/(\\gamma-1)}`` """ function P0OverP0Star(M::MachNumber,::Type{RayleighFlow};gas::PerfectGas=DefaultPerfectGas) γ = SpecificHeatRatio(gas) return PressureRatio((γ+1)/(1+γ*M^2)*((2+(γ-1)*M^2)/(γ+1))^(γ/(γ-1))) end
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
4819
#= Thermodynamic relationships =# ####### BASIC PERFECT GAS EQUATIONS OF STATE ####### """ Temperature(ρ::Density,p::Pressure[;gas=Air]) Compute the temperature from the density `ρ` and pressure `p`, using ``T = p/(\\rho R)`` Can also switch the order of the arguments. """ Temperature(ρ::Density,p::Pressure;gas::PerfectGas=DefaultPerfectGas) = Temperature(p/(ρ*GasConstant(gas))) Temperature(p::Pressure,ρ::Density;gas::PerfectGas=DefaultPerfectGas) = Temperature(ρ,p,gas=gas) """ Density(T::Temperature,p::Pressure[;gas=Air]) Compute the density from the temperature `T` and pressure `p`, using ``\\rho = p/(\\rho T)`` Can also switch the order of the arguments. """ Density(p::Pressure,T::Temperature;gas::PerfectGas=DefaultPerfectGas) = Density(p/(GasConstant(gas)*T)) Density(T::Temperature,p::Pressure;gas::PerfectGas=DefaultPerfectGas) = Density(p,T,gas=gas) """ Pressure(T::Temperature,ρ::Density[;gas=Air]) Compute the pressure from the temperature `T` and density `ρ`, using ``p = \\rho R T`` Can also switch the order of the arguments. """ Pressure(ρ::Density,T::Temperature;gas::PerfectGas=DefaultPerfectGas) = Pressure(ρ*GasConstant(gas)*T) Pressure(T::Temperature,ρ::Density;gas::PerfectGas=DefaultPerfectGas) = Pressure(ρ,T,gas=gas) """ StagnationTemperature(ρ0::StagnationDensity,p0::StagnationPressure[;gas=Air]) Compute the stagnation temperature from the stagnation density `ρ0` and stagnation pressure `p0`, using ``T_0 = p_0/(\\rho_0 R)`` Can also switch the order of the arguments. """ StagnationTemperature(ρ0::StagnationDensity,p0::StagnationPressure;gas::PerfectGas=DefaultPerfectGas) = StagnationTemperature(p0/(ρ0*GasConstant(gas))) StagnationTemperature(p0::StagnationPressure,ρ0::StagnationDensity;gas::PerfectGas=DefaultPerfectGas) = StagnationTemperature(ρ0,p0,gas=gas) """ StagnationDensity(T0::StagnationTemperature,p0::StagnationPressure[;gas=Air]) Compute the stagnation density from the stagnation temperature `T0` and stagnation pressure `p0`, using ``\\rho_0 = p_0/(\\rho T_0)`` Can also switch the order of the arguments. """ StagnationDensity(p0::StagnationPressure,T0::StagnationTemperature;gas::PerfectGas=DefaultPerfectGas) = StagnationDensity(p0/(GasConstant(gas)*T0)) StagnationDensity(T0::StagnationTemperature,p0::StagnationPressure;gas::PerfectGas=DefaultPerfectGas) = StagnationDensity(p0,T0,gas=gas) """ StagnationPressure(T0::StagnationTemperature,ρ0::StagnationDensity[;gas=Air]) Compute the stagnation pressure from the stagnation temperature `T0` and stagnation density `ρ0`, using ``p_0 = \\rho R T_0`` Can also switch the order of the arguments. """ StagnationPressure(ρ0::StagnationDensity,T0::StagnationTemperature;gas::PerfectGas=DefaultPerfectGas) = StagnationPressure(ρ0*GasConstant(gas)*T0) StagnationPressure(T0::StagnationTemperature,ρ0::StagnationDensity;gas::PerfectGas=DefaultPerfectGas) = StagnationPressure(ρ0,T0,gas=gas) """ SoundSpeed(T::Temperature[,γ::SpecificHeatRatio=1.4][,R::GasConstant=287]) Compute the speed of sound of a perfect gas, based on the absolute temperature `T`. The ratio of specific heats `γ` and `R` can also be supplied, but default to the values for air at standard conditions (1.4 and 287 J/kg.K, respectively). """ SoundSpeed(T::Temperature;gas::PerfectGas=DefaultPerfectGas) = SoundSpeed(sqrt(SpecificHeatRatio(gas)*GasConstant(gas)*T)) Enthalpy(T::Temperature;gas::PerfectGas=DefaultPerfectGas) = Enthalpy(SpecificHeatPressure(gas)*T) Temperature(h::Enthalpy;gas::PerfectGas=DefaultPerfectGas) = Temperature(h/SpecificHeatPressure(gas)) StagnationEnthalpy(T0::StagnationTemperature;gas::PerfectGas=DefaultPerfectGas) = StagnationEnthalpy(SpecificHeatPressure(gas)*T0) StagnationTemperature(h0::StagnationEnthalpy;gas::PerfectGas=DefaultPerfectGas) = StagnationTemperature(h0/SpecificHeatPressure(gas)) InternalEnergy(T::Temperature;gas::PerfectGas=DefaultPerfectGas) = InternalEnergy(SpecificHeatVolume(gas)*T) Temperature(e::InternalEnergy;gas::PerfectGas=DefaultPerfectGas) = Temperature(e/SpecificHeatVolume(gas)) StagnationInternalEnergy(T0::StagnationTemperature;gas::PerfectGas=DefaultPerfectGas) = StagnationInternalEnergy(SpecificHeatVolume(gas)*T0) StagnationTemperature(e0::StagnationInternalEnergy;gas::PerfectGas=DefaultPerfectGas) = StagnationTemperature(e0/SpecificHeatVolume(gas)) StagnationEnthalpy(h::Enthalpy,u::Velocity) = StagnationEnthalpy(value(h)+0.5*value(u)^2) Enthalpy(h0::StagnationEnthalpy,u::Velocity) = Enthalpy(value(h0)-0.5*value(u)^2) # Mach number - velocity relations Velocity(a::SoundSpeed,M::MachNumber) = Velocity(M*a) MachNumber(u::Velocity,a::SoundSpeed) = MachNumber(u/a) SoundSpeed(u::Velocity,M::MachNumber) = SoundSpeed(u/M) # mass flow rate MassFlowRate(ρ::Density,u::Velocity,A::Area) = MassFlowRate(ρ*u*A)
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
208
for f in (:SupersonicMachNumber,:SubsonicMachNumber, :SupersonicPOverP0,:SubsonicPOverP0) @eval $f(array::AbstractArray{T},args...;kwargs...) where T = map(x -> $f(x,args...;kwargs...),array) end
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
1106
using Gasdynamics1D @testset "Gases" begin @test typeof(Air) <: PerfectGas @test typeof(H2) <: PerfectGas @test typeof(O2) <: PerfectGas @test value(GasConstant(Air)) == 287u"J/kg/K" @test value(SpecificHeatRatio(Air)) == 1.4 @test isapprox(ustrip(GasConstant(Air),u"ft*lbf/(slug*Ra)"),1716.25,atol=1e-2) end @testset "Quantities" begin p = Pressure(50) @test ustrip(p) == 50 @test unit(p) == u"Pa" T = Temperature(20u"Β°F") @test ustrip(T) β‰ˆ 15989//60 @test unit(T) == u"K" @test ustrip(Temperature(20u"Β°F"),u"Β°C") β‰ˆ -20//3 s1 = Entropy(32) s2 = Entropy(45) @test ustrip(s1-s2) == -13 @test unit(s1-s2) == u"J/kg/K" h1 = Enthalpy(45) a = SoundSpeed(10) h2 = Enthalpy(h1 + a^2) @test ustrip(h2) == 145 @test unit(h2) == u"J/kg" p = Pressure(80u"kPa") ρ = Density(1.2) T = Temperature(p/ρ/GasConstant(287)) @test T == Temperature(p,ρ) end @testset "Isentropic relations" begin p = Pressure(10u"psi") p0 = StagnationPressure(14.7u"psi") M = MachNumber(PressureRatio(p/p0),Isentropic,gas=He) @test M β‰ˆ 0.7069936247021056 atol=1e-10 end
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
838
using Gasdynamics1D using Test using Literate const GROUP = get(ENV, "GROUP", "All") #ENV["GKSwstype"] = "nul" # removes GKS warnings during plotting ENV["GKSwstype"] = "100" notebookdir = "../notebook" docdir = "../docs/src/manual" litdir = "./literate" if GROUP == "All" || GROUP == "Basics" include("properties.jl") end if GROUP == "All" || GROUP == "Notebooks" for (root, dirs, files) in walkdir(litdir) for file in files #endswith(file,".jl") && startswith(file,"5") && Literate.notebook(joinpath(root, file),notebookdir) endswith(file,".jl") && Literate.notebook(joinpath(root, file),notebookdir) end end end if GROUP == "Documentation" for (root, dirs, files) in walkdir(litdir) for file in files endswith(file,".jl") && Literate.markdown(joinpath(root, file),docdir) end end end
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
2597
#= # Basic Tools for Quasi-1D Steady Compressible Flow This notebook demonstrates the basic syntax for some tools for computing quasi-1d steady compressible flow. =# # ### Set up the module using Gasdynamics1D #= ### Setting basic properties and states We can set thermodynamic properties and states in a straightforward manner. However, it is important to remember that we have to explicitly define the type of property or state we are setting. Examples below will show how this works. =# #= Let's say we wish to set the pressure to 10000 Pa. Pascals are the default units of pressure, as can be verified by using the `default_unit` function: =# default_unit(Pressure) #= So if we do not specify the unit, it is **automatically set to the default unit**: =# Pressure(10000) #= We can set a quantity with another unit using the syntax u"[unit]". For example, if we set pressure to 1 atm, it will still convert it to the default unit. =# p = Pressure(1u"atm") #= However, we can always report the quantity in some desired units with the `value` function: =# value(p,u"atm") #- value(p,u"psi") #- value(p,u"kPa") #= #### Other thermodynamic quantities We can set most any other thermodynamic quantity in similar fashion: =# T = Temperature(20u"Β°C") #- T0 = StagnationTemperature(20) #- MachNumber(2.0) #- Enthalpy(50) #- Entropy(10) #- Area(50u"cm^2") #- Length(5) #= and others... =# #= #### Gas properties We can set the properties of the gas that we are analyzing. (Note: It is assumed that the gas is perfect.) =# SpecificHeatRatio(1.3) #- GasConstant(320) #= and we can define a gas with these values: =# gas = PerfectGas(Ξ³=SpecificHeatRatio(1.3),R=GasConstant(320)) #= We have **pre-defined gases** (at standard conditions), as well, for convenience: =# Air #- He #- O2 #- CO2 #- H2 #- N2 #- Ar #= #### Equations of state We can apply the equation of state for a perfect gas to determine other quantities. For example, suppose we have carbon dioxide at 1.2 kg/m^3 and 80 kPa. What is the temperature? =# T = Temperature(Density(1.2),Pressure(80u"kPa"),gas=CO2) #= You can switch the order of the arguments and it will still work: =# T = Temperature(Pressure(80u"kPa"),Density(1.2),gas=CO2) #= Then we can calculate the enthalpy, for example: =# Enthalpy(T,gas=CO2) #= What is the speed of sound of air at 20 degrees Celsius? Let's find out: =# SoundSpeed(Temperature(20u"Β°C"),gas=Air) #= How about oxygen? =# SoundSpeed(Temperature(20u"Β°C"),gas=O2) #= **Note: the default gas is air. So if you do not put the `gas=` argument in, it will assume air at standard conditions.** =#
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
6374
#= # Isentropic quasi-1D steady compressible flow This notebook demonstrates the use of the compressible flow tools for computing states and processes in isentropic quasi-1d steady compressible flow. =# # ### Set up the module using Gasdynamics1D #- using Plots using LaTeXStrings #= ### Using isentropic relations Let us apply some basic isentropic relations. =# #= #### Example 1 Let's suppose two states of the flow in air, 1 and 2, are connected with each other by an isentropic process. We know the pressure p1 is 101 kPa, the temperature T1 is 20 degrees C, and the pressure p2 is 80 kPa. What is temperature T2? To answer this, we will use the relationship $$\dfrac{T_2}{T_1} = \left( \dfrac{p_2}{p_1}\right)^{(\gamma-1)/\gamma}$$ =# p1 = Pressure(101u"kPa") T1 = Temperature(20u"°C") p2 = Pressure(80u"kPa") #= First, let's set the pressure ratio: =# p2_over_p1 = PressureRatio(p2/p1) #= Now find the temperature ratio. Note below that we specify the argument `Isentropic` to make sure it is clear that we are using the isentropic relation. We only need this argument when it is needed for clarity. =# T2_over_T1 = TemperatureRatio(p2_over_p1,Isentropic) #= It is important to understand that the tools "know" what formula you want to use (the one listed above), based on the fact that (a) you supplied it with a pressure ratio (the purpose of the `PressureRatio` line above), and (b) you told it that the process is `Isentropic`. It figures out the rest. =# #= Finally, calculate $T_2 = T_1 (T_2/T_1)$: =# T2 = Temperature(T1*T2_over_T1) #= or, in Celsius, if desired =# value(T2,u"°C") #= We could also do all of this in one line, though it is a bit harder to debug if something goes wrong: =# T2 = Temperature(T1*TemperatureRatio(PressureRatio(p2/p1),Isentropic)) #= #### Example 2 If the temperature ratio $T/T_0$ is 0.2381, what is the Mach number? =# MachNumber(TemperatureRatio(0.2381),Isentropic) #= #### Example 3 If the Mach number is 4.4 and stagnation pressure is 800 kPa, what is the pressure? =# Pressure(StagnationPressure(800u"kPa"),MachNumber(4.4),Isentropic) #= ### Mach - area relations A big part of isentropic quasi-1D flow deals with changes of the flow in variable-area ducts. For these calculations, we make use of the *sonic area* $A_*$ as a reference area. Remember that, for any ratio of $A/A_*$, there are two possible Mach numbers, corresponding to a **subsonic flow** and a **supersonic flow**. Let us see that by plotting $A/A_*$ versus Mach number $M$. If, for example, $A/A_* = 2$, then note where the dashed line crosses the plot: =# Mrange = range(0,6,length=601) Aratio = [] for M in Mrange push!(Aratio,value(AOverAStar(MachNumber(M),Isentropic))) end plot(Mrange,Aratio,xlim=(0,4),ylim=(0,12),yticks=0:1:12,xlabel="Mach number",ylabel=L"A/A_*",legend=false) scatter!([1],[1]) plot!(Mrange,2*ones(length(Mrange)),style=:dash) #= #### Example 4 What are the subsonic and supersonic Mach numbers associated with, for example, an area ratio $A/A_*$ of 2 (the dashed line in the plot above)? We simply input the desired area ratio and find the two solutions: =# M1, M2 = MachNumber(AreaRatio(2),Isentropic); #- M1 #- M2 #= A related question: What is the local sonic reference area $A_*$ when the Mach number is 7.1 and the local area is 50 sq cm? We first compute $A/A_*$ from $M = 7.1$, then compute $A_* = A/(A/A_*)$: =# A = Area(50u"cm^2") M = MachNumber(7.1) A_over_Astar = AOverAStar(M,Isentropic) Astar = Area(A/A_over_Astar) value(Astar,u"cm^2") #= So the throat would have to be 0.45 sq cm, much smaller than 50 sq cm! =# #= Note that there is a convenience function to do those steps all in one: =# value(AStar(A,M),u"cm^2") #= #### Example 5 Consider the flow of air through a converging-diverging nozzle, leaving a stagnant reservoir at pressure $p_0$ = 700 kPa and temperature $T_0 = 30$ degrees C. The Mach number at a location (1) in the converging section with area 50 sq cm is equal to 0.4. The exit of the nozzle has area 60 sq cm. (a) What are the possible Mach numbers at the exit in choked isentropic conditions? What are the exit (i.e., "back") pressures $p_2$ associated with these two Mach numbers? (b) What is the mass flow rate through the nozzle in these conditions? =# # First, we set the known values p0 = StagnationPressure(700u"kPa") T0 = StagnationTemperature(30u"°C") A1 = Area(50u"cm^2") A2 = Area(60u"cm^2") M1 = MachNumber(0.4) #= Now, we compute $A_1/A_*$ from $M_1$. Use this to calculate $A_*$ from $A_1/(A_1/A_*)$. Then calculate $A_2/A_*$: =# A1_over_Astar = AOverAStar(M1,Isentropic,gas=Air) Astar = Area(A1/A1_over_Astar) A2_over_Astar = AreaRatio(A2/Astar) #= Now calculate the Mach numbers at location 2 (the nozzle exit): =# M2sub = SubsonicMachNumber(A2_over_Astar,Isentropic,gas=Air); #- M2sup = SupersonicMachNumber(A2_over_Astar,Isentropic,gas=Air); #= Actually, all of the last few steps can be done in *one step* with a different version of the function `MachNumber`: =# M2sub, M2sup = MachNumber(M1,A1,A2,Isentropic,gas=Air); #= Now let's determine the exit pressures (location 2) corresponding to these two Mach numbers: =# p0_over_p2sub = P0OverP(M2sub,Isentropic,gas=Air) p2sub = Pressure(p0/p0_over_p2sub) value(p2sub,u"kPa") #- p0_over_p2sup = P0OverP(M2sup,Isentropic,gas=Air) p2sup = Pressure(p0/p0_over_p2sup) value(p2sup,u"kPa") #= So if the exit pressure is 651 kPa, then the flow will remain choked and **subsonic** throughout, and if the exit pressure is 71.5 kPa, then the flow will remain choked and **supersonic** throughout. Note that, because the flow is choked, the mass flow rate is the same for both of these cases. Let's calculate that mass flow rate (using $\rho_1 u_1 A_1$). We need $\rho_1$ and $u_1$. First, calculate the stagnation density in this nozzle: =# ρ0 = StagnationDensity(p0,T0,gas=Air) # this uses the perfect gas law # Using $M_1$, find $\rho_0/\rho_1$: ρ0_over_ρ1 = ρ0Overρ(M1,Isentropic,gas=Air) # So we can get $\rho_1$ from $\rho_0/(\rho_0/\rho_1)$: ρ1 = Density(ρ0/ρ0_over_ρ1) # Now get $u_1$ from $M_1 c_1$, where $c_1$ is the speed of sound. For that, we need $T_1$: T0_over_T1 = T0OverT(M1,Isentropic,gas=Air) T1 = Temperature(T0/T0_over_T1) c1 = SoundSpeed(T1) #- u1 = Velocity(M1*c1) # And now we can put it all together: mdot = MassFlowRate(ρ1*u1*A1) # So the mass flow rate is stuck at 5.1 kg/s
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
4020
#= # Quasi-1D flow in a converging-diverging nozzle In this notebook we will explore the flow in a converging-diverging nozzle. The objective of this notebook is to explore the effect of *back pressure* relative to the upstream stagnation pressure. =# # ### Set up the module using Gasdynamics1D #- using Plots #= ### Set up a nozzle First, we will set up a nozzle. For this, we will create a representative nozzle shape: a bell-shaped converging inlet and a slowly increasing diverging section. We set the inlet area, the throat area, and the exit area: =# Ai = Area(100u"cm^2") At = Area(30u"cm^2") Ae = Area(60u"cm^2") noz = Nozzle(Ai,At,Ae) # Let's plot this nozzle to see its shape nozzleplot(noz) #= ### Create a flow through the nozzle Let's set the conditions to create a flow through this nozzle. We need to set the stagnation conditions upstream of the nozzle. We will use stagnation pressure and temperature. =# p0 = StagnationPressure(700u"kPa") T0 = StagnationTemperature(30u"Β°C") #= We also need a back pressure, outside of the nozzle exit. Let's try setting it to 660 kPa, a little bit below the stagnation pressure =# pb = Pressure(660u"kPa") #= Now we have enough information to solve this flow. Let's plot it. We need to specify which quantities we wish to show. We will show pressure and Mach number. We could also show temperature and density. The plot below shows that the pressure reaches a minimum in the throat and the Mach number reaches a maximum there. However, it does not quite get to sonic conditions. =# nozzleplot(noz,pb,p0,T0,fields=("pressure","machnumber")) # One note on the last plots: We could have specified the gas, but it defaults to air. #= ### Lowering the back pressure What happens if we lower the back pressure further? Let's try this. For several back pressures, we get a *shock* in the diverging section. As back pressure gets smaller, this shock appears closer to the exit. Finally, the shock leaves the nozzle entirely. =# nozzleplot(noz,Pressure(660u"kPa"),p0,T0,fields=("pressure","mach")) nozzleplot!(noz,Pressure(600u"kPa"),p0,T0,fields=("pressure","mach")) nozzleplot!(noz,Pressure(500u"kPa"),p0,T0,fields=("pressure","mach")) nozzleplot!(noz,Pressure(400u"kPa"),p0,T0,fields=("pressure","mach")) nozzleplot!(noz,Pressure(360u"kPa"),p0,T0,fields=("pressure","mach")) nozzleplot!(noz,Pressure(300u"kPa"),p0,T0,fields=("pressure","mach")) #= ### Mass flow rate What is the mass flow rate through the nozzle? Let's inspect this value for a few back pressures. First, the case with 660 kPa: =# nozproc = NozzleProcess(noz,Pressure(660u"kPa"),p0,T0) massflowrate(nozproc) # Now with 600 kPa nozproc = NozzleProcess(noz,Pressure(600u"kPa"),p0,T0) massflowrate(nozproc) # And now with 500 kPa nozproc = NozzleProcess(noz,Pressure(500u"kPa"),p0,T0) massflowrate(nozproc) #= Notice that the mass flow rate is stuck. No matter how much we lower the back pressure, we cannot increase the mass flow rate. The flow is *choked*. =# #= We can classify the type of flow with the `flow_quality` function: =# nozproc = NozzleProcess(noz,Pressure(600u"kPa"),p0,T0) flow_quality(nozproc) # There is a normal shock in the diverging section nozproc = NozzleProcess(noz,Pressure(100u"kPa"),p0,T0) flow_quality(nozproc) # This is over-expanded: the exit pressure is too small and the flow needs to pass # through shocks outside the nozzle to get up to the back pressure. nozproc = NozzleProcess(noz,Pressure(60u"kPa"),p0,T0) flow_quality(nozproc) # This is under-expanded: the exit pressure is not low enough and the flow needs # to pass through an *expansion fan* outside the nozzle to lower its pressure # further to get down to the back pressure. #= When we seek to generate a supersonic exit flow, as is often the case, then our goal is to design it so that the flow is *perfectly expanded*. We can find the required back pressure easily, using isentropic relations: =# Ae = nozzleexit(noz) Astar = throat(noz) pb = Pressure(SupersonicPOverP0(Ae,Astar,Isentropic)*p0)
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
3861
#= # Normal shocks In the last notebook, we saw that normal shocks develop in a nozzle when it is not perfectly expanded. This notebook demonstrates the use of the compressible tools for dealing with **normal shock waves**. =# # ### Set up the module using Gasdynamics1D #- using Plots #= ### General use of normal shock relations Normal shock relations are designated with the argument `NormalShock`. For example, let's look at the ratio of stagnation pressures $p_{02}/p_{01}$ across a normal shock with the Mach number $M_1$ entering the shock equal to 2: =# p02_over_p01 = StagnationPressureRatio(MachNumber(2),NormalShock) # and the density $\rho_2/\rho_1$ increases by the factor: ρ2_over_ρ1 = DensityRatio(MachNumber(2),NormalShock) # What is the entropy change across this shock? s2_minus_s1 = Entropy(Entropy(0),MachNumber(2),NormalShock) # Let's plot the entropy increase as a function of Mach number: M1 = range(1,3,length=101) s2 = [] pratio = [] for M in M1 push!(s2,ustrip(Entropy(Entropy(0),MachNumber(M),NormalShock))) push!(pratio,ustrip(PressureRatio(MachNumber(M),NormalShock))) end #- plot(M1,s2,xlim=(1,3),ylim=(0,400),xlabel="Mach number",ylabel="Entropy increase (J/kgK)") # Not surprisingly, the entropy jump gets bigger as the Mach number increases #= ### Example 1 For air entering a shock at Mach number 3, 1 atm, and 50 degrees F, what are the Mach number, pressure, and temperature on the other side of the shock? =# p1 = Pressure(1u"atm") M1 = MachNumber(3) T1 = Temperature(50u"°F") # The Mach number exiting the shock is M2 = MachNumber(M1,NormalShock) # Pressure exiting the shock (in atm) is p2 = Pressure(p1*PressureRatio(M1,NormalShock)) value(p2,u"atm") # and the temperature exiting the shock (in F) is T2 = Temperature(T1*TemperatureRatio(M1,NormalShock)) value(T2,u"°F") #= ### Example 2 A blow-down supersonic windtunnel is supplied with air from a large reservoir. A Pitot tube is placed at the exit plane of a converging-diverging nozzle. The test section lies at the end of the diverging section. The Mach number in the test section (M2) is 2 and the pressure is below atmospheric, so a shock is formed at the exit. The pressure just after the shock (p3) is 14.7 psi. Find the pressure in the reservoir (p01), the pressure in the throat (pth), the Mach number just after the shock (M3), the pressure at the Pitot tube (p4), and the temperature at the Pitot tube (T4). =# M2 = MachNumber(2) p3 = Pressure(14.7u"psi") #= First, let's find the pressure just before the shock and the Mach number just after the shock =# # p3/p2 p3_over_p2 = PressureRatio(M2,NormalShock) # p03/p02 p03_over_p02 = StagnationPressureRatio(M2,NormalShock) # M3 M3 = MachNumber(M2,NormalShock) # We can now calculate the pressure just before the shock, using $p_2 = p_3/(p_3/p_2)$ p2 = Pressure(p3/p3_over_p2) #= Now, let's find the conditions in the throat and reservoir, based on what we have been given here. We can immediately find the stagnation pressure upstream of the shock using the isentropic relation. This stagnation pressure is the same as the reservoir pressure. =# p02 = StagnationPressure(p2,M2,Isentropic) p01 = p02 #= We know that the throat is choked. It must be, because the flow is subsonic before and supersonic after the throat. Therefore, $M_{th}$ is 1, and we can get the local pressure ($p_{th}$) from knowing the stagnation pressure and Mach number there: =# Mth = MachNumber(1) p0th = p02 pth = Pressure(p0th,Mth,Isentropic) #= Now we can calculate the conditions at the Pitot tube at the exit. At the nose of the Pitot tube, the flow stagnates. Thus, the pressure and temperature are equal to the stagnation values. The stagnation pressure at the exit is the same as the stagnation pressure at point 3 (just after the shock): =# p03 = Pressure(p03_over_p02*p02) #- value(p03,u"psi")
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
4933
#= # Steady frictional flow through a constant-area duct This notebook demonstrates the use of tools for computing flow through a constant-area duct with frictional effects, also known as **Fanno flow** =# # ### Set up the module using Gasdynamics1D #- using Plots using LaTeXStrings #= ### Some general aspects of Fanno flow Most calculations with frictional flow involve the relationship between Mach number and the reference length $L^*$, representing the length required from that point to bring the flow to Mach number equal to 1. The relationship is based on the dimensionless parameter $$\dfrac{f L^*}{D}$$ where $f$ is the Darcy friction factor and $D$ is the duct diameter. Let's plot this relationship for air: =# Mrange = range(0.1,8,length=801) fLDarray = [] for M in Mrange push!(fLDarray,value(FLStarOverD(MachNumber(M),FannoFlow,gas=Air))) end #- plot(Mrange,fLDarray,xlim=(0,8),ylim=(0,10),xticks=0:1:8,xlabel="Mach number",ylabel=L"fL^*/D",legend=false) #= Notice that the reference length goes to zero at Mach number 1, as it should, by its definition. It should also be noted that there are a few values of $fL^*/D$ for which there are two possible Mach numbers---one subsonic and one supersonic. This is analogous to the situation in isentropic flow with area changes. =# #= ### Example 1 Flow enters a duct of diameter 2 cm at Mach number equal to 0.1 and leaves at Mach number equal to 0.5. Assume that the friction factor is equal to 0.024 throughout. (a) What is the length of the duct? (b) How much longer would the duct have to be to reach Mach number equal to 1 at the exit? =# #= First, we use $M_1 = 0.1$ to calculate $f L_1^*/D$. We will do the same with $M_2$ to calculate $f L_2^*/D$. The actual length $L$ is given by the difference between $L_1^*$ and $L_2^*$. =# f = FrictionFactor(0.024) D = Diameter(2u"cm") #- M1 = MachNumber(0.1) fL1star_over_D = FLStarOverD(M1,FannoFlow) #- M2 = MachNumber(0.5) fL2star_over_D = FLStarOverD(M2,FannoFlow) # Now calculate $L_1^*$ and $L_2^*$, and $L$ from their difference: L1star = Length(fL1star_over_D*D/f) L2star = Length(fL2star_over_D*D/f) L = Length(L1star-L2star) # The additional length needed to bring the flow to Mach number 1 is, by definition, $L_2^*$: L2star # So we only need 0.89 m more to bring the flow to sonic (choked) conditions. #= ### Example 2 Consider a flow of air through a circular pipe of diameter 3 cm, starting at stagnation pressure 200 kPa, stagnation temperature 500 K, and velocity 100 m/s. The friction factor in the pipe can be assumed to be 0.02 throughout. (a) What length of pipe would be needed to drive the flow to Mach number 1 at the exit? (b) What is the mass flow rate through the pipe at those conditions? (c) Suppose the pipe were 30 m long. How would the mass flow rate change? =# # For (a), we are seeking $L_1^*$. First set the known conditions: D = Diameter(3u"cm") p01 = StagnationPressure(200u"kPa") T01 = StagnationTemperature(500) u1 = Velocity(100) f = FrictionFactor(0.02) #= Now calculate the Mach number at the entrance. For this, we need $c_1$, the speed of sound. We get this by using the known stagnation temperature $T_{01} = 500$ K and velocity $u_1 = 100$ m/s. We will calculate the temperature $T_1$ from these (using $h_1 = h_{01} - u_1^2/2$), and $c_1$ from that: =# h01 = StagnationEnthalpy(T01) h1 = Enthalpy(h01,u1) # this computes h1 = h01 - u1^2/2 T1 = Temperature(h1) c1 = SoundSpeed(T1) M1 = MachNumber(u1/c1) # Now we can compute $fL_1^*/D$ and then $L_1^*$. This is what we seek. fL1starD = FLStarOverD(M1,FannoFlow) L1star = Length(fL1starD*D/f) #= so we need a pipe of 16.6 m to reach Mach number 1. Now let's compute the mass flow rate. We need the area and density. For the density, we will first get the stagnation density (from $p_{01}$ and $T_{01}$) and then get density from the isentropic relation. (We are not using isentropic relations between two different points in the duct; we are using it to relate *local* stagnation conditions to *local* conditions.) =# A = Area(D) ρ01 = StagnationDensity(p01,T01) ρ1 = Density(ρ01,M1,Isentropic) # and the mass flow rate is: mΜ‡ = MassFlowRate(ρ1*u1*A) #= (c) Now suppose the pipe is 30 m long. This becomes our new $L_1^*$, and all of the conditions at the entrance must adjust accordingly. First find the Mach number =# Lstar = L = Length(30u"m") fLstar_over_D = FLOverD(f*Lstar/D) M1 = SubsonicMachNumber(fLstar_over_D,FannoFlow) #= Note that the entrance Mach number is lower. The flow slows down due to the longer pipe. Now find the new values of $\rho_1$ and $u_1$ (by finding $c_1$): =# T1 = Temperature(T01,M1,Isentropic) ρ1 = Density(ρ01,M1,Isentropic) c1 = SoundSpeed(T1) u1 = Velocity(c1,M1) mΜ‡ = MassFlowRate(ρ1*u1*A) #= So the mass flow rate is smaller than it was with the shorter pipe! For the same reservoir conditions, less mass flow rate is delivered to a longer (choked) pipe. =#
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
code
4948
#= # Steady flow through a duct with heat transfer This notebook demonstrates the use of tools for computing steady compressible flow through a constant-area duct with heat transfer, commonly known as **Rayleigh flow**. =# # ### Set up the module using Gasdynamics1D #- using Plots using LaTeXStrings #= #### Simple example In a duct with helium, if the flow enters with stagnation temperature of 20 degrees C, how much does the stagnation temperature change if we add heat 400 kJ/kg? =# q = HeatFlux(400u"kJ/kg") T01 = StagnationTemperature(20u"Β°C") # starting stagnation enthalpy h01 = StagnationEnthalpy(T01,gas=He) # h01 = cp*T01 # add the heat h02 = StagnationEnthalpy(h01 + q) # calculate the final stagnation temperature T02 = StagnationTemperature(h02,gas=He) # T02 = h02/cp # Report the final value in Celsius: value(T02,u"Β°C") # so the flow exiting the duct has stagnation temperature 97 C. #= The sonic state is used as a reference, similar to Fanno flow and isentropic flow. All states share the same $T_{0}^*$, $p^*$, $u^*$, etc, so we can relate two points via this reference. We have functions that allow us to do this. For example, to find the ratio of the local stagnation temperature to its sonic reference value at Mach number 0.5 in air: =# T0OverT0Star(MachNumber(0.5),RayleighFlow,gas=Air) #= Note that the argument `RayleighFlow` was used to designate this function's use. If the Mach number is 1, then... =# T0OverT0Star(MachNumber(1),RayleighFlow,gas=Air) #= That is, $T_{0}$ is equal to $T_{0}^*$ when Mach number is 1, as it should be, by definition. =# #= Alternatively, if we know $T_0/T_0^*$, we can determine $M$. However, there are sometimes two possible values of Mach number, as with Fanno flow and isentropic flow. =# Mrange = range(0.001,8,length=801) T0_over_T0star = [] for M in Mrange push!(T0_over_T0star,value(T0OverT0Star(MachNumber(M),RayleighFlow,gas=Air))) end #- plot(Mrange,T0_over_T0star,xlim=(0,8),ylim=(0,2),xticks=0:1:8,xlabel="Mach number",ylabel=L"T_0/T_0^*",legend=false) plot!(Mrange,0.75*ones(length(Mrange)),style=:dash) #= For example, if $T_0/T_0^* = 0.75$, there are two possible Mach numbers, one subsonic and one supersonic. The correct one depends on the circumstances. =# Msub, Msup = MachNumber(TemperatureRatio(0.75),RayleighFlow,gas=Air) #- Msub #- Msup #= ### Example Suppose the flow of air in a duct enters with velocity 75 m/s at a pressure of 150 kPa and temperature 300 K. We add heat 900 kJ/kg. Find (a) The value of the Mach number at the entrance and exit (b) The velocity, pressure, and temperature at the exit (c) The maximum amount of heat we can add so that the flow is just choked =# # Set the given values u1 = Velocity(75u"m/s") p1 = Pressure(150u"kPa") T1 = Temperature(300) q = HeatFlux(900u"kJ/kg") # We can immediately find the Mach number at the location 1, by finding $c_1$: c1 = SoundSpeed(T1,gas=Air) M1 = MachNumber(u1/c1) # Now, use $M_1$ and $T_1$ to find $T_{01}$. T01 = StagnationTemperature(T1,M1,Isentropic,gas=Air) #= Now let's focus on state 2. We will use the basic relation $h_{02} = h_{01} + q$ to determine $T_{02}$. =# h01 = StagnationEnthalpy(T01,gas=Air) h02 = StagnationEnthalpy(h01+q) T02 = StagnationTemperature(h02,gas=Air) #= To get the other states at location 2, we need the sonic reference conditions. For example, we will find $$T_{02}/T_{0}^*$$ to determine $M_2$. We get this by calculating $$T_{0}^* = T_{01}/(T_{01}/T_{0}^*)$$ =# T0star = StagnationTemperature(T01/T0OverT0Star(M1,RayleighFlow,gas=Air)) #- T02_over_T0star = TemperatureRatio(T02/T0star) #- M2sub, M2sup = MachNumber(T02_over_T0star,RayleighFlow,gas=Air) #= The subsonic one is the only possible candidate, because the flow came in at subsonic speed and can't have passed through Mach number 1. Thus =# M2 = M2sub # We have increased the Mach number from 0.216 to 0.573 by adding heat. # Now find the other reference states that we will use: pstar = Pressure(p1/POverPStar(M1,RayleighFlow,gas=Air)) ustar = Velocity(u1/VOverVStar(M1,RayleighFlow,gas=Air)) Tstar = Temperature(T1/TOverTStar(M1,RayleighFlow,gas=Air)) #= and now the values themselves. For example, we use $M_2$ to calculate $p_2/p^*$ and then calculate $p_2 = p^*(p_2/p^*)$. =# p2 = Pressure(pstar*POverPStar(M2,RayleighFlow,gas=Air)) #- u2 = Velocity(ustar*VOverVStar(M2,RayleighFlow,gas=Air)) #- T2 = Temperature(Tstar*TOverTStar(M2,RayleighFlow,gas=Air)) #= Finally, let us calculate the maximum heat flux -- the heat flux that brings the flow just to sonic conditions when starting at the given conditions at location 1. This comes from $$q_{max} = h_{0}^* - h_{01} = c_p (T_0^* - T_{01})$$ We have a convenience function for that, based on stagnation temperature: =# qmax = HeatFlux(T01,T0star,gas=Air) #- value(qmax,u"kJ/kg") #= Thus, we can add up to 1223 kJ/kg before the flow gets choked. Any more than that will cause the entrance conditions to change. =#
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
docs
1264
# Gasdynamics1D.jl _Tools for analysis of 1d gasdynamics problems_ [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://uclamaethreads.github.io/Gasdynamics1D.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://uclamaethreads.github.io/Gasdynamics1D.jl/dev/) [![Build Status](https://github.com/UCLAMAEThreads/Gasdynamics1D.jl/workflows/CI/badge.svg)](https://github.com/UCLAMAEThreads/Gasdynamics1D.jl/actions) [![codecov](https://codecov.io/gh/UCLAMAEThreads/Gasdynamics1D.jl/branch/main/graph/badge.svg?token=m4pj7rjF0r)](https://codecov.io/gh/UCLAMAEThreads/Gasdynamics1D.jl) The tools in this package enable the user to - specify the thermodynamic state of a flow for a calorically perfect gas - convert the state variables between different units - find the change of flow state in various processes, including - quasi-1d isentropic flow with area changes - flows through normal shocks - flows in ducts with effects of wall friction (Fanno flow) - flows in ducts with effects of heat transfer (Rayleigh flow) The easiest way to get started is to follow the examples notebooks in the `notebook` directory. Also, please consult the [documentation](https://uclamaethreads.github.io/Gasdynamics1D.jl/dev/).
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
docs
528
# Gasdynamics1D.jl *tools for analysis of 1d gasdynamics problems* The purpose of this package is to enable easy analysis of 1-d gas dynamics problems. ## Installation This package works on Julia `1.0` and higher and is registered in the general Julia registry. To install, type ```julia ]add Gasdynamics1D ``` Then type ```julia julia> using Gasdynamics1D ``` The plots in this documentation are generated using [Plots.jl](http://docs.juliaplots.org/latest/). You might want to install that, too, to follow the examples.
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
docs
3720
```@meta EditURL = "../../../test/literate/0-BasicGasDynamics.jl" ``` # Basic Tools for Quasi-1D Steady Compressible Flow This notebook demonstrates the basic syntax for some tools for computing quasi-1d steady compressible flow. ### Set up the module ````@example 0-BasicGasDynamics using Gasdynamics1D ```` ### Setting basic properties and states We can set thermodynamic properties and states in a straightforward manner. However, it is important to remember that we have to explicitly define the type of property or state we are setting. Examples below will show how this works. Let's say we wish to set the pressure to 10000 Pa. Pascals are the default units of pressure, as can be verified by using the `default_unit` function: ````@example 0-BasicGasDynamics default_unit(Pressure) ```` So if we do not specify the unit, it is **automatically set to the default unit**: ````@example 0-BasicGasDynamics Pressure(10000) ```` We can set a quantity with another unit using the syntax u"[unit]". For example, if we set pressure to 1 atm, it will still convert it to the default unit. ````@example 0-BasicGasDynamics p = Pressure(1u"atm") ```` However, we can always report the quantity in some desired units with the `value` function: ````@example 0-BasicGasDynamics value(p,u"atm") ```` ````@example 0-BasicGasDynamics value(p,u"psi") ```` ````@example 0-BasicGasDynamics value(p,u"kPa") ```` #### Other thermodynamic quantities We can set most any other thermodynamic quantity in similar fashion: ````@example 0-BasicGasDynamics T = Temperature(20u"Β°C") ```` ````@example 0-BasicGasDynamics T0 = StagnationTemperature(20) ```` ````@example 0-BasicGasDynamics MachNumber(2.0) ```` ````@example 0-BasicGasDynamics Enthalpy(50) ```` ````@example 0-BasicGasDynamics Entropy(10) ```` ````@example 0-BasicGasDynamics Area(50u"cm^2") ```` ````@example 0-BasicGasDynamics Length(5) ```` and others... #### Gas properties We can set the properties of the gas that we are analyzing. (Note: It is assumed that the gas is perfect.) ````@example 0-BasicGasDynamics SpecificHeatRatio(1.3) ```` ````@example 0-BasicGasDynamics GasConstant(320) ```` and we can define a gas with these values: ````@example 0-BasicGasDynamics gas = PerfectGas(Ξ³=SpecificHeatRatio(1.3),R=GasConstant(320)) ```` We have **pre-defined gases** (at standard conditions), as well, for convenience: ````@example 0-BasicGasDynamics Air ```` ````@example 0-BasicGasDynamics He ```` ````@example 0-BasicGasDynamics O2 ```` ````@example 0-BasicGasDynamics CO2 ```` ````@example 0-BasicGasDynamics H2 ```` ````@example 0-BasicGasDynamics N2 ```` ````@example 0-BasicGasDynamics Ar ```` #### Equations of state We can apply the equation of state for a perfect gas to determine other quantities. For example, suppose we have carbon dioxide at 1.2 kg/m^3 and 80 kPa. What is the temperature? ````@example 0-BasicGasDynamics T = Temperature(Density(1.2),Pressure(80u"kPa"),gas=CO2) ```` You can switch the order of the arguments and it will still work: ````@example 0-BasicGasDynamics T = Temperature(Pressure(80u"kPa"),Density(1.2),gas=CO2) ```` Then we can calculate the enthalpy, for example: ````@example 0-BasicGasDynamics Enthalpy(T,gas=CO2) ```` What is the speed of sound of air at 20 degrees Celsius? Let's find out: ````@example 0-BasicGasDynamics SoundSpeed(Temperature(20u"Β°C"),gas=Air) ```` How about oxygen? ````@example 0-BasicGasDynamics SoundSpeed(Temperature(20u"Β°C"),gas=O2) ```` **Note: the default gas is air. So if you do not put the `gas=` argument in, it will assume air at standard conditions.** --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
docs
7689
```@meta EditURL = "../../../test/literate/1-IsentropicGasDynamics.jl" ``` # Isentropic quasi-1D steady compressible flow This notebook demonstrates the use of the compressible flow tools for computing states and processes in isentropic quasi-1d steady compressible flow. ### Set up the module ````@example 1-IsentropicGasDynamics using Gasdynamics1D ```` ````@example 1-IsentropicGasDynamics using Plots using LaTeXStrings ```` ### Using isentropic relations Let us apply some basic isentropic relations. #### Example 1 Let's suppose two states of the flow in air, 1 and 2, are connected with each other by an isentropic process. We know the pressure p1 is 101 kPa, the temperature T1 is 20 degrees C, and the pressure p2 is 80 kPa. What is temperature T2? To answer this, we will use the relationship $$\dfrac{T_2}{T_1} = \left( \dfrac{p_2}{p_1}\right)^{(\gamma-1)/\gamma}$$ ````@example 1-IsentropicGasDynamics p1 = Pressure(101u"kPa") T1 = Temperature(20u"°C") p2 = Pressure(80u"kPa") ```` First, let's set the pressure ratio: ````@example 1-IsentropicGasDynamics p2_over_p1 = PressureRatio(p2/p1) ```` Now find the temperature ratio. Note below that we specify the argument `Isentropic` to make sure it is clear that we are using the isentropic relation. We only need this argument when it is needed for clarity. ````@example 1-IsentropicGasDynamics T2_over_T1 = TemperatureRatio(p2_over_p1,Isentropic) ```` It is important to understand that the tools "know" what formula you want to use (the one listed above), based on the fact that (a) you supplied it with a pressure ratio (the purpose of the `PressureRatio` line above), and (b) you told it that the process is `Isentropic`. It figures out the rest. Finally, calculate $T_2 = T_1 (T_2/T_1)$: ````@example 1-IsentropicGasDynamics T2 = Temperature(T1*T2_over_T1) ```` or, in Celsius, if desired ````@example 1-IsentropicGasDynamics value(T2,u"°C") ```` We could also do all of this in one line, though it is a bit harder to debug if something goes wrong: ````@example 1-IsentropicGasDynamics T2 = Temperature(T1*TemperatureRatio(PressureRatio(p2/p1),Isentropic)) ```` #### Example 2 If the temperature ratio $T/T_0$ is 0.2381, what is the Mach number? ````@example 1-IsentropicGasDynamics MachNumber(TemperatureRatio(0.2381),Isentropic) ```` #### Example 3 If the Mach number is 4.4 and stagnation pressure is 800 kPa, what is the pressure? ````@example 1-IsentropicGasDynamics Pressure(StagnationPressure(800u"kPa"),MachNumber(4.4),Isentropic) ```` ### Mach - area relations A big part of isentropic quasi-1D flow deals with changes of the flow in variable-area ducts. For these calculations, we make use of the *sonic area* $A_*$ as a reference area. Remember that, for any ratio of $A/A_*$, there are two possible Mach numbers, corresponding to a **subsonic flow** and a **supersonic flow**. Let us see that by plotting $A/A_*$ versus Mach number $M$. If, for example, $A/A_* = 2$, then note where the dashed line crosses the plot: ````@example 1-IsentropicGasDynamics Mrange = range(0,6,length=601) Aratio = [] for M in Mrange push!(Aratio,value(AOverAStar(MachNumber(M),Isentropic))) end plot(Mrange,Aratio,xlim=(0,4),ylim=(0,12),yticks=0:1:12,xlabel="Mach number",ylabel=L"A/A_*",legend=false) scatter!([1],[1]) plot!(Mrange,2*ones(length(Mrange)),style=:dash) ```` #### Example 4 What are the subsonic and supersonic Mach numbers associated with, for example, an area ratio $A/A_*$ of 2 (the dashed line in the plot above)? We simply input the desired area ratio and find the two solutions: ````@example 1-IsentropicGasDynamics M1, M2 = MachNumber(AreaRatio(2),Isentropic); nothing #hide ```` ````@example 1-IsentropicGasDynamics M1 ```` ````@example 1-IsentropicGasDynamics M2 ```` A related question: What is the local sonic reference area $A_*$ when the Mach number is 7.1 and the local area is 50 sq cm? We first compute $A/A_*$ from $M = 7.1$, then compute $A_* = A/(A/A_*)$: ````@example 1-IsentropicGasDynamics A = Area(50u"cm^2") M = MachNumber(7.1) A_over_Astar = AOverAStar(M,Isentropic) Astar = Area(A/A_over_Astar) value(Astar,u"cm^2") ```` So the throat would have to be 0.45 sq cm, much smaller than 50 sq cm! Note that there is a convenience function to do those steps all in one: ````@example 1-IsentropicGasDynamics value(AStar(A,M),u"cm^2") ```` #### Example 5 Consider the flow of air through a converging-diverging nozzle, leaving a stagnant reservoir at pressure $p_0$ = 700 kPa and temperature $T_0 = 30$ degrees C. The Mach number at a location (1) in the converging section with area 50 sq cm is equal to 0.4. The exit of the nozzle has area 60 sq cm. (a) What are the possible Mach numbers at the exit in choked isentropic conditions? What are the exit (i.e., "back") pressures $p_2$ associated with these two Mach numbers? (b) What is the mass flow rate through the nozzle in these conditions? First, we set the known values ````@example 1-IsentropicGasDynamics p0 = StagnationPressure(700u"kPa") T0 = StagnationTemperature(30u"°C") A1 = Area(50u"cm^2") A2 = Area(60u"cm^2") M1 = MachNumber(0.4) ```` Now, we compute $A_1/A_*$ from $M_1$. Use this to calculate $A_*$ from $A_1/(A_1/A_*)$. Then calculate $A_2/A_*$: ````@example 1-IsentropicGasDynamics A1_over_Astar = AOverAStar(M1,Isentropic,gas=Air) Astar = Area(A1/A1_over_Astar) A2_over_Astar = AreaRatio(A2/Astar) ```` Now calculate the Mach numbers at location 2 (the nozzle exit): ````@example 1-IsentropicGasDynamics M2sub = SubsonicMachNumber(A2_over_Astar,Isentropic,gas=Air); nothing #hide ```` ````@example 1-IsentropicGasDynamics M2sup = SupersonicMachNumber(A2_over_Astar,Isentropic,gas=Air); nothing #hide ```` Actually, all of the last few steps can be done in *one step* with a different version of the function `MachNumber`: ````@example 1-IsentropicGasDynamics M2sub, M2sup = MachNumber(M1,A1,A2,Isentropic,gas=Air); nothing #hide ```` Now let's determine the exit pressures (location 2) corresponding to these two Mach numbers: ````@example 1-IsentropicGasDynamics p0_over_p2sub = P0OverP(M2sub,Isentropic,gas=Air) p2sub = Pressure(p0/p0_over_p2sub) value(p2sub,u"kPa") ```` ````@example 1-IsentropicGasDynamics p0_over_p2sup = P0OverP(M2sup,Isentropic,gas=Air) p2sup = Pressure(p0/p0_over_p2sup) value(p2sup,u"kPa") ```` So if the exit pressure is 651 kPa, then the flow will remain choked and **subsonic** throughout, and if the exit pressure is 71.5 kPa, then the flow will remain choked and **supersonic** throughout. Note that, because the flow is choked, the mass flow rate is the same for both of these cases. Let's calculate that mass flow rate (using $\rho_1 u_1 A_1$). We need $\rho_1$ and $u_1$. First, calculate the stagnation density in this nozzle: ````@example 1-IsentropicGasDynamics ρ0 = StagnationDensity(p0,T0,gas=Air) # this uses the perfect gas law ```` Using $M_1$, find $\rho_0/\rho_1$: ````@example 1-IsentropicGasDynamics ρ0_over_ρ1 = ρ0Overρ(M1,Isentropic,gas=Air) ```` So we can get $\rho_1$ from $\rho_0/(\rho_0/\rho_1)$: ````@example 1-IsentropicGasDynamics ρ1 = Density(ρ0/ρ0_over_ρ1) ```` Now get $u_1$ from $M_1 c_1$, where $c_1$ is the speed of sound. For that, we need $T_1$: ````@example 1-IsentropicGasDynamics T0_over_T1 = T0OverT(M1,Isentropic,gas=Air) T1 = Temperature(T0/T0_over_T1) c1 = SoundSpeed(T1) ```` ````@example 1-IsentropicGasDynamics u1 = Velocity(M1*c1) ```` And now we can put it all together: ````@example 1-IsentropicGasDynamics mdot = MassFlowRate(ρ1*u1*A1) ```` So the mass flow rate is stuck at 5.1 kg/s --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
docs
4819
```@meta EditURL = "../../../test/literate/2-ConvergingDivergingNozzle.jl" ``` # Quasi-1D flow in a converging-diverging nozzle In this notebook we will explore the flow in a converging-diverging nozzle. The objective of this notebook is to explore the effect of *back pressure* relative to the upstream stagnation pressure. ### Set up the module ````@example 2-ConvergingDivergingNozzle using Gasdynamics1D ```` ````@example 2-ConvergingDivergingNozzle using Plots ```` ### Set up a nozzle First, we will set up a nozzle. For this, we will create a representative nozzle shape: a bell-shaped converging inlet and a slowly increasing diverging section. We set the inlet area, the throat area, and the exit area: ````@example 2-ConvergingDivergingNozzle Ai = Area(100u"cm^2") At = Area(30u"cm^2") Ae = Area(60u"cm^2") noz = Nozzle(Ai,At,Ae) ```` Let's plot this nozzle to see its shape ````@example 2-ConvergingDivergingNozzle nozzleplot(noz) ```` ### Create a flow through the nozzle Let's set the conditions to create a flow through this nozzle. We need to set the stagnation conditions upstream of the nozzle. We will use stagnation pressure and temperature. ````@example 2-ConvergingDivergingNozzle p0 = StagnationPressure(700u"kPa") T0 = StagnationTemperature(30u"Β°C") ```` We also need a back pressure, outside of the nozzle exit. Let's try setting it to 660 kPa, a little bit below the stagnation pressure ````@example 2-ConvergingDivergingNozzle pb = Pressure(660u"kPa") ```` Now we have enough information to solve this flow. Let's plot it. We need to specify which quantities we wish to show. We will show pressure and Mach number. We could also show temperature and density. The plot below shows that the pressure reaches a minimum in the throat and the Mach number reaches a maximum there. However, it does not quite get to sonic conditions. ````@example 2-ConvergingDivergingNozzle nozzleplot(noz,pb,p0,T0,fields=("pressure","machnumber")) ```` One note on the last plots: We could have specified the gas, but it defaults to air. ### Lowering the back pressure What happens if we lower the back pressure further? Let's try this. For several back pressures, we get a *shock* in the diverging section. As back pressure gets smaller, this shock appears closer to the exit. Finally, the shock leaves the nozzle entirely. ````@example 2-ConvergingDivergingNozzle nozzleplot(noz,Pressure(660u"kPa"),p0,T0,fields=("pressure","mach")) nozzleplot!(noz,Pressure(600u"kPa"),p0,T0,fields=("pressure","mach")) nozzleplot!(noz,Pressure(500u"kPa"),p0,T0,fields=("pressure","mach")) nozzleplot!(noz,Pressure(400u"kPa"),p0,T0,fields=("pressure","mach")) nozzleplot!(noz,Pressure(360u"kPa"),p0,T0,fields=("pressure","mach")) nozzleplot!(noz,Pressure(300u"kPa"),p0,T0,fields=("pressure","mach")) ```` ### Mass flow rate What is the mass flow rate through the nozzle? Let's inspect this value for a few back pressures. First, the case with 660 kPa: ````@example 2-ConvergingDivergingNozzle nozproc = NozzleProcess(noz,Pressure(660u"kPa"),p0,T0) massflowrate(nozproc) ```` Now with 600 kPa ````@example 2-ConvergingDivergingNozzle nozproc = NozzleProcess(noz,Pressure(600u"kPa"),p0,T0) massflowrate(nozproc) ```` And now with 500 kPa ````@example 2-ConvergingDivergingNozzle nozproc = NozzleProcess(noz,Pressure(500u"kPa"),p0,T0) massflowrate(nozproc) ```` Notice that the mass flow rate is stuck. No matter how much we lower the back pressure, we cannot increase the mass flow rate. The flow is *choked*. We can classify the type of flow with the `flow_quality` function: ````@example 2-ConvergingDivergingNozzle nozproc = NozzleProcess(noz,Pressure(600u"kPa"),p0,T0) flow_quality(nozproc) ```` There is a normal shock in the diverging section ````@example 2-ConvergingDivergingNozzle nozproc = NozzleProcess(noz,Pressure(100u"kPa"),p0,T0) flow_quality(nozproc) ```` This is over-expanded: the exit pressure is too small and the flow needs to pass through shocks outside the nozzle to get up to the back pressure. ````@example 2-ConvergingDivergingNozzle nozproc = NozzleProcess(noz,Pressure(60u"kPa"),p0,T0) flow_quality(nozproc) ```` This is under-expanded: the exit pressure is not low enough and the flow needs to pass through an *expansion fan* outside the nozzle to lower its pressure further to get down to the back pressure. When we seek to generate a supersonic exit flow, as is often the case, then our goal is to design it so that the flow is *perfectly expanded*. We can find the required back pressure easily, using isentropic relations: ````@example 2-ConvergingDivergingNozzle Ae = nozzleexit(noz) Astar = throat(noz) pb = Pressure(SupersonicPOverP0(Ae,Astar,Isentropic)*p0) ```` --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
docs
4626
```@meta EditURL = "../../../test/literate/3-NormalShocks.jl" ``` # Normal shocks In the last notebook, we saw that normal shocks develop in a nozzle when it is not perfectly expanded. This notebook demonstrates the use of the compressible tools for dealing with **normal shock waves**. ### Set up the module ````@example 3-NormalShocks using Gasdynamics1D ```` ````@example 3-NormalShocks using Plots ```` ### General use of normal shock relations Normal shock relations are designated with the argument `NormalShock`. For example, let's look at the ratio of stagnation pressures $p_{02}/p_{01}$ across a normal shock with the Mach number $M_1$ entering the shock equal to 2: ````@example 3-NormalShocks p02_over_p01 = StagnationPressureRatio(MachNumber(2),NormalShock) ```` and the density $\rho_2/\rho_1$ increases by the factor: ````@example 3-NormalShocks ρ2_over_ρ1 = DensityRatio(MachNumber(2),NormalShock) ```` What is the entropy change across this shock? ````@example 3-NormalShocks s2_minus_s1 = Entropy(Entropy(0),MachNumber(2),NormalShock) ```` Let's plot the entropy increase as a function of Mach number: ````@example 3-NormalShocks M1 = range(1,3,length=101) s2 = [] pratio = [] for M in M1 push!(s2,ustrip(Entropy(Entropy(0),MachNumber(M),NormalShock))) push!(pratio,ustrip(PressureRatio(MachNumber(M),NormalShock))) end ```` ````@example 3-NormalShocks plot(M1,s2,xlim=(1,3),ylim=(0,400),xlabel="Mach number",ylabel="Entropy increase (J/kgK)") ```` Not surprisingly, the entropy jump gets bigger as the Mach number increases ### Example 1 For air entering a shock at Mach number 3, 1 atm, and 50 degrees F, what are the Mach number, pressure, and temperature on the other side of the shock? ````@example 3-NormalShocks p1 = Pressure(1u"atm") M1 = MachNumber(3) T1 = Temperature(50u"°F") ```` The Mach number exiting the shock is ````@example 3-NormalShocks M2 = MachNumber(M1,NormalShock) ```` Pressure exiting the shock (in atm) is ````@example 3-NormalShocks p2 = Pressure(p1*PressureRatio(M1,NormalShock)) value(p2,u"atm") ```` and the temperature exiting the shock (in F) is ````@example 3-NormalShocks T2 = Temperature(T1*TemperatureRatio(M1,NormalShock)) value(T2,u"°F") ```` ### Example 2 A blow-down supersonic windtunnel is supplied with air from a large reservoir. A Pitot tube is placed at the exit plane of a converging-diverging nozzle. The test section lies at the end of the diverging section. The Mach number in the test section (M2) is 2 and the pressure is below atmospheric, so a shock is formed at the exit. The pressure just after the shock (p3) is 14.7 psi. Find the pressure in the reservoir (p01), the pressure in the throat (pth), the Mach number just after the shock (M3), the pressure at the Pitot tube (p4), and the temperature at the Pitot tube (T4). ````@example 3-NormalShocks M2 = MachNumber(2) p3 = Pressure(14.7u"psi") ```` First, let's find the pressure just before the shock and the Mach number just after the shock p3/p2 ````@example 3-NormalShocks p3_over_p2 = PressureRatio(M2,NormalShock) ```` p03/p02 ````@example 3-NormalShocks p03_over_p02 = StagnationPressureRatio(M2,NormalShock) ```` M3 ````@example 3-NormalShocks M3 = MachNumber(M2,NormalShock) ```` We can now calculate the pressure just before the shock, using $p_2 = p_3/(p_3/p_2)$ ````@example 3-NormalShocks p2 = Pressure(p3/p3_over_p2) ```` Now, let's find the conditions in the throat and reservoir, based on what we have been given here. We can immediately find the stagnation pressure upstream of the shock using the isentropic relation. This stagnation pressure is the same as the reservoir pressure. ````@example 3-NormalShocks p02 = StagnationPressure(p2,M2,Isentropic) p01 = p02 ```` We know that the throat is choked. It must be, because the flow is subsonic before and supersonic after the throat. Therefore, $M_{th}$ is 1, and we can get the local pressure ($p_{th}$) from knowing the stagnation pressure and Mach number there: ````@example 3-NormalShocks Mth = MachNumber(1) p0th = p02 pth = Pressure(p0th,Mth,Isentropic) ```` Now we can calculate the conditions at the Pitot tube at the exit. At the nose of the Pitot tube, the flow stagnates. Thus, the pressure and temperature are equal to the stagnation values. The stagnation pressure at the exit is the same as the stagnation pressure at point 3 (just after the shock): ````@example 3-NormalShocks p03 = Pressure(p03_over_p02*p02) ```` ````@example 3-NormalShocks value(p03,u"psi") ```` --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
docs
5503
```@meta EditURL = "../../../test/literate/4-FannoFlow.jl" ``` # Steady frictional flow through a constant-area duct This notebook demonstrates the use of tools for computing flow through a constant-area duct with frictional effects, also known as **Fanno flow** ### Set up the module ````@example 4-FannoFlow using Gasdynamics1D ```` ````@example 4-FannoFlow using Plots using LaTeXStrings ```` ### Some general aspects of Fanno flow Most calculations with frictional flow involve the relationship between Mach number and the reference length $L^*$, representing the length required from that point to bring the flow to Mach number equal to 1. The relationship is based on the dimensionless parameter $$\dfrac{f L^*}{D}$$ where $f$ is the Darcy friction factor and $D$ is the duct diameter. Let's plot this relationship for air: ````@example 4-FannoFlow Mrange = range(0.1,8,length=801) fLDarray = [] for M in Mrange push!(fLDarray,value(FLStarOverD(MachNumber(M),FannoFlow,gas=Air))) end ```` ````@example 4-FannoFlow plot(Mrange,fLDarray,xlim=(0,8),ylim=(0,10),xticks=0:1:8,xlabel="Mach number",ylabel=L"fL^*/D",legend=false) ```` Notice that the reference length goes to zero at Mach number 1, as it should, by its definition. It should also be noted that there are a few values of $fL^*/D$ for which there are two possible Mach numbers---one subsonic and one supersonic. This is analogous to the situation in isentropic flow with area changes. ### Example 1 Flow enters a duct of diameter 2 cm at Mach number equal to 0.1 and leaves at Mach number equal to 0.5. Assume that the friction factor is equal to 0.024 throughout. (a) What is the length of the duct? (b) How much longer would the duct have to be to reach Mach number equal to 1 at the exit? First, we use $M_1 = 0.1$ to calculate $f L_1^*/D$. We will do the same with $M_2$ to calculate $f L_2^*/D$. The actual length $L$ is given by the difference between $L_1^*$ and $L_2^*$. ````@example 4-FannoFlow f = FrictionFactor(0.024) D = Diameter(2u"cm") ```` ````@example 4-FannoFlow M1 = MachNumber(0.1) fL1star_over_D = FLStarOverD(M1,FannoFlow) ```` ````@example 4-FannoFlow M2 = MachNumber(0.5) fL2star_over_D = FLStarOverD(M2,FannoFlow) ```` Now calculate $L_1^*$ and $L_2^*$, and $L$ from their difference: ````@example 4-FannoFlow L1star = Length(fL1star_over_D*D/f) L2star = Length(fL2star_over_D*D/f) L = Length(L1star-L2star) ```` The additional length needed to bring the flow to Mach number 1 is, by definition, $L_2^*$: ````@example 4-FannoFlow L2star ```` So we only need 0.89 m more to bring the flow to sonic (choked) conditions. ### Example 2 Consider a flow of air through a circular pipe of diameter 3 cm, starting at stagnation pressure 200 kPa, stagnation temperature 500 K, and velocity 100 m/s. The friction factor in the pipe can be assumed to be 0.02 throughout. (a) What length of pipe would be needed to drive the flow to Mach number 1 at the exit? (b) What is the mass flow rate through the pipe at those conditions? (c) Suppose the pipe were 30 m long. How would the mass flow rate change? For (a), we are seeking $L_1^*$. First set the known conditions: ````@example 4-FannoFlow D = Diameter(3u"cm") p01 = StagnationPressure(200u"kPa") T01 = StagnationTemperature(500) u1 = Velocity(100) f = FrictionFactor(0.02) ```` Now calculate the Mach number at the entrance. For this, we need $c_1$, the speed of sound. We get this by using the known stagnation temperature $T_{01} = 500$ K and velocity $u_1 = 100$ m/s. We will calculate the temperature $T_1$ from these (using $h_1 = h_{01} - u_1^2/2$), and $c_1$ from that: ````@example 4-FannoFlow h01 = StagnationEnthalpy(T01) h1 = Enthalpy(h01,u1) # this computes h1 = h01 - u1^2/2 T1 = Temperature(h1) c1 = SoundSpeed(T1) M1 = MachNumber(u1/c1) ```` Now we can compute $fL_1^*/D$ and then $L_1^*$. This is what we seek. ````@example 4-FannoFlow fL1starD = FLStarOverD(M1,FannoFlow) L1star = Length(fL1starD*D/f) ```` so we need a pipe of 16.6 m to reach Mach number 1. Now let's compute the mass flow rate. We need the area and density. For the density, we will first get the stagnation density (from $p_{01}$ and $T_{01}$) and then get density from the isentropic relation. (We are not using isentropic relations between two different points in the duct; we are using it to relate *local* stagnation conditions to *local* conditions.) ````@example 4-FannoFlow A = Area(D) ρ01 = StagnationDensity(p01,T01) ρ1 = Density(ρ01,M1,Isentropic) ```` and the mass flow rate is: ````@example 4-FannoFlow mΜ‡ = MassFlowRate(ρ1*u1*A) ```` (c) Now suppose the pipe is 30 m long. This becomes our new $L_1^*$, and all of the conditions at the entrance must adjust accordingly. First find the Mach number ````@example 4-FannoFlow Lstar = L = Length(30u"m") fLstar_over_D = FLOverD(f*Lstar/D) M1 = SubsonicMachNumber(fLstar_over_D,FannoFlow) ```` Note that the entrance Mach number is lower. The flow slows down due to the longer pipe. Now find the new values of $\rho_1$ and $u_1$ (by finding $c_1$): ````@example 4-FannoFlow T1 = Temperature(T01,M1,Isentropic) ρ1 = Density(ρ01,M1,Isentropic) c1 = SoundSpeed(T1) u1 = Velocity(c1,M1) mΜ‡ = MassFlowRate(ρ1*u1*A) ```` So the mass flow rate is smaller than it was with the shorter pipe! For the same reservoir conditions, less mass flow rate is delivered to a longer (choked) pipe. --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
docs
5936
```@meta EditURL = "../../../test/literate/5-RayleighFlow.jl" ``` # Steady flow through a duct with heat transfer This notebook demonstrates the use of tools for computing steady compressible flow through a constant-area duct with heat transfer, commonly known as **Rayleigh flow**. ### Set up the module ````@example 5-RayleighFlow using Gasdynamics1D ```` ````@example 5-RayleighFlow using Plots using LaTeXStrings ```` #### Simple example In a duct with helium, if the flow enters with stagnation temperature of 20 degrees C, how much does the stagnation temperature change if we add heat 400 kJ/kg? ````@example 5-RayleighFlow q = HeatFlux(400u"kJ/kg") T01 = StagnationTemperature(20u"Β°C") ```` starting stagnation enthalpy ````@example 5-RayleighFlow h01 = StagnationEnthalpy(T01,gas=He) # h01 = cp*T01 ```` add the heat ````@example 5-RayleighFlow h02 = StagnationEnthalpy(h01 + q) ```` calculate the final stagnation temperature ````@example 5-RayleighFlow T02 = StagnationTemperature(h02,gas=He) # T02 = h02/cp ```` Report the final value in Celsius: ````@example 5-RayleighFlow value(T02,u"Β°C") ```` so the flow exiting the duct has stagnation temperature 97 C. The sonic state is used as a reference, similar to Fanno flow and isentropic flow. All states share the same $T_{0}^*$, $p^*$, $u^*$, etc, so we can relate two points via this reference. We have functions that allow us to do this. For example, to find the ratio of the local stagnation temperature to its sonic reference value at Mach number 0.5 in air: ````@example 5-RayleighFlow T0OverT0Star(MachNumber(0.5),RayleighFlow,gas=Air) ```` Note that the argument `RayleighFlow` was used to designate this function's use. If the Mach number is 1, then... ````@example 5-RayleighFlow T0OverT0Star(MachNumber(1),RayleighFlow,gas=Air) ```` That is, $T_{0}$ is equal to $T_{0}^*$ when Mach number is 1, as it should be, by definition. Alternatively, if we know $T_0/T_0^*$, we can determine $M$. However, there are sometimes two possible values of Mach number, as with Fanno flow and isentropic flow. ````@example 5-RayleighFlow Mrange = range(0.001,8,length=801) T0_over_T0star = [] for M in Mrange push!(T0_over_T0star,value(T0OverT0Star(MachNumber(M),RayleighFlow,gas=Air))) end ```` ````@example 5-RayleighFlow plot(Mrange,T0_over_T0star,xlim=(0,8),ylim=(0,2),xticks=0:1:8,xlabel="Mach number",ylabel=L"T_0/T_0^*",legend=false) plot!(Mrange,0.75*ones(length(Mrange)),style=:dash) ```` For example, if $T_0/T_0^* = 0.75$, there are two possible Mach numbers, one subsonic and one supersonic. The correct one depends on the circumstances. ````@example 5-RayleighFlow Msub, Msup = MachNumber(TemperatureRatio(0.75),RayleighFlow,gas=Air) ```` ````@example 5-RayleighFlow Msub ```` ````@example 5-RayleighFlow Msup ```` ### Example Suppose the flow of air in a duct enters with velocity 75 m/s at a pressure of 150 kPa and temperature 300 K. We add heat 900 kJ/kg. Find (a) The value of the Mach number at the entrance and exit (b) The velocity, pressure, and temperature at the exit (c) The maximum amount of heat we can add so that the flow is just choked Set the given values ````@example 5-RayleighFlow u1 = Velocity(75u"m/s") p1 = Pressure(150u"kPa") T1 = Temperature(300) q = HeatFlux(900u"kJ/kg") ```` We can immediately find the Mach number at the location 1, by finding $c_1$: ````@example 5-RayleighFlow c1 = SoundSpeed(T1,gas=Air) M1 = MachNumber(u1/c1) ```` Now, use $M_1$ and $T_1$ to find $T_{01}$. ````@example 5-RayleighFlow T01 = StagnationTemperature(T1,M1,Isentropic,gas=Air) ```` Now let's focus on state 2. We will use the basic relation $h_{02} = h_{01} + q$ to determine $T_{02}$. ````@example 5-RayleighFlow h01 = StagnationEnthalpy(T01,gas=Air) h02 = StagnationEnthalpy(h01+q) T02 = StagnationTemperature(h02,gas=Air) ```` To get the other states at location 2, we need the sonic reference conditions. For example, we will find $$T_{02}/T_{0}^*$$ to determine $M_2$. We get this by calculating $$T_{0}^* = T_{01}/(T_{01}/T_{0}^*)$$ ````@example 5-RayleighFlow T0star = StagnationTemperature(T01/T0OverT0Star(M1,RayleighFlow,gas=Air)) ```` ````@example 5-RayleighFlow T02_over_T0star = TemperatureRatio(T02/T0star) ```` ````@example 5-RayleighFlow M2sub, M2sup = MachNumber(T02_over_T0star,RayleighFlow,gas=Air) ```` The subsonic one is the only possible candidate, because the flow came in at subsonic speed and can't have passed through Mach number 1. Thus ````@example 5-RayleighFlow M2 = M2sub ```` We have increased the Mach number from 0.216 to 0.573 by adding heat. Now find the other reference states that we will use: ````@example 5-RayleighFlow pstar = Pressure(p1/POverPStar(M1,RayleighFlow,gas=Air)) ustar = Velocity(u1/VOverVStar(M1,RayleighFlow,gas=Air)) Tstar = Temperature(T1/TOverTStar(M1,RayleighFlow,gas=Air)) ```` and now the values themselves. For example, we use $M_2$ to calculate $p_2/p^*$ and then calculate $p_2 = p^*(p_2/p^*)$. ````@example 5-RayleighFlow p2 = Pressure(pstar*POverPStar(M2,RayleighFlow,gas=Air)) ```` ````@example 5-RayleighFlow u2 = Velocity(ustar*VOverVStar(M2,RayleighFlow,gas=Air)) ```` ````@example 5-RayleighFlow T2 = Temperature(Tstar*TOverTStar(M2,RayleighFlow,gas=Air)) ```` Finally, let us calculate the maximum heat flux -- the heat flux that brings the flow just to sonic conditions when starting at the given conditions at location 1. This comes from $$q_{max} = h_{0}^* - h_{01} = c_p (T_0^* - T_{01})$$ We have a convenience function for that, based on stagnation temperature: ````@example 5-RayleighFlow qmax = HeatFlux(T01,T0star,gas=Air) ```` ````@example 5-RayleighFlow value(qmax,u"kJ/kg") ```` Thus, we can add up to 1223 kJ/kg before the flow gets choked. Any more than that will cause the entrance conditions to change. --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "MIT" ]
0.2.7
8ed5f1e73ceb98ad0681250460a5c310af508149
docs
138
# Types and Functions ```@meta CurrentModule = Gasdynamics1D ``` ```@autodocs Modules = [Gasdynamics1D] Order = [:type, :function] ```
Gasdynamics1D
https://github.com/UCLAMAEThreads/Gasdynamics1D.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
777
using DifferentiableMetabolism using Documenter DocMeta.setdocmeta!( DifferentiableMetabolism, :DocTestSetup, :(using DifferentiableMetabolism); recursive = true, ) makedocs(; modules = [DifferentiableMetabolism], authors = "St. Elmo Wilken <[email protected]> and contributors", repo = "https://github.com/stelmo/DifferentiableMetabolism.jl/blob/{commit}{path}#{line}", sitename = "DifferentiableMetabolism.jl", format = Documenter.HTML(; prettyurls = get(ENV, "CI", "false") == "true", canonical = "https://stelmo.github.io/DifferentiableMetabolism.jl", assets = String[], ), pages = ["Home" => "index.md"], ) deploydocs(; repo = "github.com/stelmo/DifferentiableMetabolism.jl", devbranch = "master")
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
832
module DifferentiableMetabolism using COBREXA, JuMP # using Enzyme: jacobian, Forward, Val, Reverse using ForwardDiff using Symbolics using LinearAlgebra, SparseArrays, RowEchelon using DocStringExtensions include("DifferentiableModel.jl") include("Enzyme.jl") include("differentiate.jl") include("scale.jl") include("utils.jl") include("update.jl") include("differentiable_models/gecko.jl") include("differentiable_models/smoment.jl") include("analytic_derivatives/analytic_derivatives.jl") include("analytic_derivatives/analytic_derivatives_with_scaling.jl") # export everything that isn't prefixed with _ (inspired by JuMP.jl, thanks!) for sym in names(@__MODULE__, all = true) if sym in [Symbol(@__MODULE__), :eval, :include] || startswith(string(sym), ['_', '#']) continue end @eval export $sym end end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
1366
""" $(TYPEDEF) A struct representing a generalized differentiable constraint based model. Format of the model is: ``` minimize Β½ * x' * Q(ΞΈ) * x + c(ΞΈ)' * x s.t. E(ΞΈ) * x = d(ΞΈ) M(ΞΈ) * x ≀ h(ΞΈ) ``` Nominally, every component can be differentiated. $(TYPEDFIELDS) Note, to ensure differentiability, preprocessing of the model used to derive the [`DifferentiableModel`](@ref) is required. In short, only an active solution may be differentiated, this requires that: - the base model does not possess any isozymes, each reaction may be catalyzed by one enzyme (complex) only, - all the reactions should be unidirectinal, - the kcats in `rid_enzyme` are for the appropriate direction used in the model, - all rids in `rid_enzyme` are used in the model. """ mutable struct DifferentiableModel Q::Function c::Function E::Function d::Function M::Function h::Function ΞΈ::Vector{Float64} analytic_var_derivs::Function analytic_par_derivs::Function var_ids::Vector{String} param_ids::Vector{String} end """ Pretty printing of a differentiable model. """ function Base.show(io::IO, ::MIME"text/plain", m::DifferentiableModel) println(io, "", "Differentiable metabolic with: ") println(io, " ", length(m.var_ids), " variables") println(io, " ", length(m.param_ids), " parameters") end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
1229
""" $(TYPEDEF) A struct used to store information about an enzyme. A simplified version of [`COBREXA.Isozyme`](@ref), which stores only the turnover number (kcat) that should be used by the differentiable model, as well as information about the protein complex (stoichiometry and molar mass). $(TYPEDFIELDS) """ mutable struct Enzyme kcat::Float64 gene_product_count::Dict{String,Int} gene_product_mass::Dict{String,Float64} end """ $(TYPEDSIGNATURES) Convert a [`COBREXA.Isozyme`](@ref) to an [`Enzyme`](@ref) using the turnover number in `direction` (either `:forward` or `:reverse`), as well as `gene_product_mass_lookup`, which is either a function or a dictionary mapping a gene product id to its molar mass. """ function isozyme_to_enzyme( isozyme::Isozyme, gene_product_mass_lookup::Union{Function,Dict{String,Float64}}; direction = :forward, ) _gpmlu = gene_product_mass_lookup isa Function ? gene_product_mass_lookup : (gid -> gene_product_mass_lookup[gid]) Enzyme( direction == :forward ? isozyme.kcat_forward : isozyme.kcat_reverse, isozyme.gene_product_count, Dict(gid => _gpmlu(gid) for gid in keys(isozyme.gene_product_count)), ) end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
6684
""" $(TYPEDSIGNATURES) Solve and differentiate an optimization problem using the optimality conditions. The output can be scaled relative to the parameters and the solved variables with `scale_output`. *Optimizer* modifications (from COBREXA.jl) can be supplied through `modifications`. Analytic derivatives of the optimality conditions can be used by setting `use_analytic` to true. Internally calls [`differentiate!`](@ref), the in-place variant of this function, constructs the arguments internally. """ function differentiate( diffmodel::DifferentiableModel, optimizer; use_analytic = false, scale_output = true, modifications = [], ) x = zeros(length(diffmodel.var_ids)) Ξ½ = zeros(length(diffmodel.d(diffmodel.ΞΈ))) Ξ» = zeros(length(diffmodel.h(diffmodel.ΞΈ))) nA = length(x) + length(Ξ½) + length(Ξ») A = spzeros(nA, nA) B = zeros(nA, length(diffmodel.param_ids)) dx = zeros(size(A, 1), size(B, 2)) differentiate!( x, Ξ½, Ξ», A, B, dx, diffmodel, optimizer; modifications, use_analytic, scale_output, ) return x, dx end """ $(TYPEDSIGNATURES) Differentiates `diffmodel` using in-place functions as much as possible. The meaning of the variables are: - `x`: primal variables - `Ξ½`: equality dual variables - `Ξ»`: inequality dual variables - `A`: variable derivatives - `B`: parameter derivitives - `dx`: the sensitivities of the variables - `diffmodel`: the model to differantiate - `optimizer`: the solver used in the forward pass - `modifications`: COBREXA functions forwarded to the *solver* - `use_analytic`: use the analytic derivatives (need to be supplied) - `scale_output`: flag if the primal variable sensitivities should be scaled by `dx/dy => dlog(x)/dlog(y)` """ function differentiate!( x, Ξ½, Ξ», A, B, dx, diffmodel::DifferentiableModel, optimizer; modifications = [], use_analytic = false, scale_output = true, ) DifferentiableMetabolism._solve_model!(x, Ξ½, Ξ», diffmodel, optimizer; modifications) DifferentiableMetabolism._differentiate_kkt!( x, Ξ½, Ξ», A, B, dx, diffmodel; use_analytic, ) #: Scale dx/dy => dlog(x)/dlog(y) scale_output && _scale_derivatives(x, dx, diffmodel) nothing end """ $(TYPEDSIGNATURES) Solve the optimization problem, aka the forward pass. This function is called by [`differentiate!`](@ref). """ function _solve_model!( x, Ξ½, Ξ», diffmodel::DifferentiableModel, optimizer; modifications = [], ) #: forward pass, solve the optimization problem opt_model = JuMP.Model(optimizer) set_silent(opt_model) @variable(opt_model, z[1:length(diffmodel.var_ids)]) if all(diffmodel.Q(diffmodel.ΞΈ) .== 0) # is LP @objective(opt_model, Min, diffmodel.c(diffmodel.ΞΈ)' * z) else @objective( opt_model, Min, 0.5 * z' * diffmodel.Q(diffmodel.ΞΈ) * z + diffmodel.c(diffmodel.ΞΈ)' * z ) end @constraint(opt_model, eq, diffmodel.E(diffmodel.ΞΈ) * z .== diffmodel.d(diffmodel.ΞΈ)) @constraint(opt_model, ineq, diffmodel.M(diffmodel.ΞΈ) * z .<= diffmodel.h(diffmodel.ΞΈ)) # apply the modifications for mod in modifications mod(nothing, opt_model) end optimize!(opt_model) if termination_status(opt_model) βˆ‰ [JuMP.OPTIMAL, JuMP.LOCALLY_SOLVED] throw(DomainError(termination_status(opt_model), " model not solved optimally!")) end #: differentiate the optimal solution x .= value.(opt_model[:z]) Ξ½ .= dual.(opt_model[:eq]) Ξ» .= dual.(opt_model[:ineq]) nothing end """ $(TYPEDSIGNATURES) Implicitly differentiate a convex quadratic or linear program using the KKT conditions. Suppose `F(z(ΞΈ), ΞΈ) = 0` represents the optimality (KKT) conditions of some optimization problem specified by `diffmodel`, where `z` is a vector of the primal, `x`, and dual, `Ξ½` and `Ξ»`, solutions. Then, mutate `A = βˆ‚β‚F(z(ΞΈ), ΞΈ)`, `B = βˆ‚β‚‚F(z(ΞΈ), ΞΈ)`, and the optimal solution. This function is called by [`differentiate!`](@ref). """ function _differentiate_kkt!( x, Ξ½, Ξ», A, B, dx, diffmodel::DifferentiableModel; use_analytic = false, ) #= The analytic approaches are much faster than using automatic differentiation, but more labor intensive because the derivative of the parameters with respect to the KKT function needs to be manually supplied. Ideally, use symbolic code to generate the derivatives for you. However, the autodiff works for any model and the user does not have to supply any analytic derivatives. However, any sparse arrays encoded in the model structure must be cast to dense arrays for ForwardDiff to work. The densification restriction can be dropped once #481 here https://github.com/JuliaDiff/ForwardDiff.jl/pull/481 gets merged into ForwardDiff. =# if use_analytic A .= diffmodel.analytic_var_derivs(x, Ξ½, Ξ», diffmodel.ΞΈ) B .= diffmodel.analytic_par_derivs(x, Ξ½, Ξ», diffmodel.ΞΈ) else kkt(x, Ξ½, Ξ», ΞΈ) = [ Array(diffmodel.Q(ΞΈ)) * x + Array(diffmodel.c(ΞΈ)) - Array(diffmodel.E(ΞΈ))' * Ξ½ - Array(diffmodel.M(ΞΈ))' * Ξ» Array(diffmodel.E(ΞΈ)) * x - Array(diffmodel.d(ΞΈ)) diagm(Ξ») * (Array(diffmodel.M(ΞΈ)) * x - Array(diffmodel.h(ΞΈ))) ] A = make_analytic_var_derivative(diffmodel)(x, Ξ½, Ξ», diffmodel.ΞΈ) B = ForwardDiff.jacobian(ΞΈ -> kkt(x, Ξ½, Ξ», ΞΈ), diffmodel.ΞΈ) end #= Solve the linear system of equations. This is the most time intensive operation, accounting for 75% of the run time on iML1515. Iterative solvers, and other indirect approaches did not speed up the solving process. Separating out the factorization also does not help that much, because the pattern changes, requiring frequent refactorizations. Sadly, Pardiso is no longer free for academics. Hence, the standard solve is used. =# _linear_solver(A, B, dx) nothing end """ $(TYPEDSIGNATURES) Separate linear solve to have the ability to swap it our for something faster. """ function _linear_solver(A, B, dx) ldiv!(dx, lu(-A), B) nothing end """ $(TYPEDSIGNATURES) Scale the derivatives: `dx/dy => dlog(x)/dlog(y)`. Note, only scales the primal variables, *not* the duals. """ function _scale_derivatives(x, dx, diffmodel::DifferentiableModel) for i = 1:length(x) for j = 1:size(dx, 2) dx[i, j] *= diffmodel.ΞΈ[j] / x[i] end end nothing end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
2361
""" $(TYPEDSIGNATURES) Return scaling factor used to rescale constraints in matrix format (row-wise). Arguments are assumed to be of the form `A ∝ b` where `∝` are usually `=` or `≀` in the context of an optimization problem. To set the cut-off for when a coefficient is considered to be zero, change `atol`. See also [`check_scaling`](@ref). """ function scaling_factor(A, b; atol = 1e-8) mat = [A b] max_coeff_range, _ = check_scaling(mat; atol) lb = -round(max_coeff_range, RoundUp) / 2.0 ub = round(max_coeff_range, RoundUp) / 2.0 sfs = zeros(size(mat, 1)) for (j, row) in enumerate(eachrow(mat)) llv, luv = extrema(log10 ∘ abs, row) if lb <= llv && luv <= ub sf = 0.0 else # scale to upper bound sf = ub - luv end sfs[j] = 10^sf end return sfs end """ $(TYPEDSIGNATURES) Return `log₁₀(|x|)` or `x` if `|x| ≀ atol`. """ _get_exponent_or_cutoff(x; atol = 1e-8) = abs(x) > atol && log10(abs(x)) """ $(TYPEDSIGNATURES) Return the best case (if rescaled using [`scaling_factor`](@ref)) and current scaling of a matrix `mat`. Scaling is defined as the largest difference between the exponent of the smallest and largest value in each row of a matrix. To set the cut-off for when a coefficient is considered to be zero, change `atol`. """ function check_scaling(mat; atol = 1e-8) best_case = maximum( maximum(_get_exponent_or_cutoff.(mat; atol), dims = 2)[:] - minimum(_get_exponent_or_cutoff.(mat; atol), dims = 2)[:], ) rlb, rub = log10.(extrema(filter(x -> x > atol, abs.(mat)))) worst_case = rub - rlb return best_case, worst_case end """ $(TYPEDSIGNATURES) Helper function to check the scaling of the equality constraint matrix. """ function check_scaling(diffmodel::DifferentiableModel; atol = 1e-8, verbose = false) eq = check_scaling([diffmodel.E(diffmodel.ΞΈ) diffmodel.d(diffmodel.ΞΈ)]; atol) ineq = check_scaling([diffmodel.M(diffmodel.ΞΈ) diffmodel.h(diffmodel.ΞΈ)]; atol) obj = all(diffmodel.Q(diffmodel.ΞΈ) .== 0.0) ? (0.0, 0.0) : check_scaling(diffmodel.Q(diffmodel.ΞΈ); atol) if verbose println("Equality: ", eq) println("Inequality: ", ineq) println("Quadratic objective: ", obj) return nothing else return eq, ineq, obj end end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
611
""" $(TYPEDSIGNATURES) Update Q. """ update_Q!(diffmodel::DifferentiableModel, Q) = diffmodel.Q = Q """ $(TYPEDSIGNATURES) Update c. """ update_c!(diffmodel::DifferentiableModel, c) = diffmodel.c = c """ $(TYPEDSIGNATURES) Update E. """ update_E!(diffmodel::DifferentiableModel, E) = diffmodel.E = E """ $(TYPEDSIGNATURES) Update d. """ update_d!(diffmodel::DifferentiableModel, d) = diffmodel.d = d """ $(TYPEDSIGNATURES) Update M. """ update_M!(diffmodel::DifferentiableModel, M) = diffmodel.M = M """ $(TYPEDSIGNATURES) Update h. """ update_h!(diffmodel::DifferentiableModel, h) = diffmodel.h = h
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
5584
""" $(TYPEDSIGNATURES) Remove linearly dependent rows in `A` deduced by reducing the matrix to row echelon form. Adjust sensitivity to numerical issues with `Ο΅`. After row echelon reduction, all elements are rounded to `digits` after the decimal. Rows of all zeros (absolute value of the each element in row ≀ `atol`) are removed. Beware, this operation is expensive for very large matrices. """ function _remove_lin_dep_rows(A; Ο΅ = 1e-8, atol = 1e-8, digits = 16) #TODO this method is suboptimal and can be improved for numerical stability #TODO improve RowEchelon, SVD does not work due to column reordering rA = round.(rref!(copy(Array(A)), Ο΅); digits) idxs = Int[] for i = 1:size(rA, 1) if !all(abs.(rA[i, :]) .<= atol) # remove rows of all zero push!(idxs, i) end end return rA[idxs, :] end """ $(TYPEDSIGNATURES) Helper function to assign the thermodynamic driving force to a reaction. """ function _dg( model, rid_enzyme, rid_dg0, rid, mangled_rid, ΞΈ; RT = 298.15 * 8.314e-3, ignore_reaction_ids = [], ignore_metabolite_ids = [], ) if !haskey(rid_dg0, rid) || rid in ignore_reaction_ids # no thermo info or should be ignored return 1.0 end _rs = reaction_stoichiometry(model, rid) rs = Dict(k => v for (k, v) in _rs if k βˆ‰ ignore_metabolite_ids) stoich = values(rs) mids = collect(keys(rs)) midxs = Int.(indexin(mids, metabolites(model))) .+ length(rid_enzyme) dir = contains(mangled_rid, "#forward") ? 1 : -1 dg_val = rid_dg0[rid] + RT * sum(nu * log(ΞΈ[midx]) for (nu, midx) in zip(stoich, midxs)) 1.0 - exp(dir * dg_val / RT) end """ $(TYPEDSIGNATURES) A helper function to incorporate saturation effects. """ function _saturation( model, rid_enzyme, rid_km, rid, mangled_rid, ΞΈ; ignore_reaction_ids = [], ignore_metabolite_ids = [], ) if !haskey(rid_km, rid) || rid in ignore_reaction_ids # no kinetic info or should be ignored return 1.0 end _rs = reaction_stoichiometry(model, rid) rs = Dict(k => v for (k, v) in _rs if k βˆ‰ ignore_metabolite_ids) stoich = values(rs) mids = collect(keys(rs)) midxs = Int.(indexin(mids, metabolites(model))) .+ length(rid_enzyme) is_forward = contains(mangled_rid, "#forward") ? true : false @assert(contains(mangled_rid, rid)) #TODO sanity check, remove s_term = prod( (ΞΈ[midx] / rid_km[rid][mid])^(-1*nu) for (nu, midx, mid) in zip(stoich, midxs, mids) if nu < 0 ) p_term = prod( (ΞΈ[midx] / rid_km[rid][mid])^nu for (nu, midx, mid) in zip(stoich, midxs, mids) if nu > 0 ) is_forward ? s_term / (1.0 + s_term + p_term) : p_term / (1.0 + s_term + p_term) end """ $(TYPEDSIGNATURES) Return a simplified version of `model` that contains only reactions (and the associated genes and metabolites) that are active, i.e. carry fluxes (from `reaction_fluxes`) absolutely bigger than `atol`. All reactions are set unidirectional based on `reaction_fluxes`. """ function prune_model(model::StandardModel, reaction_fluxes; atol = 1e-9, verbose = true) pruned_model = StandardModel("pruned_model") rxns = Vector{Reaction}() mets = Vector{Metabolite}() gs = Vector{Gene}() mids = String[] gids = String[] for rid in reactions(model) abs(reaction_fluxes[rid]) <= atol && continue rxn = deepcopy(model.reactions[rid]) if reaction_fluxes[rid] > 0 rxn.lb = max(0, rxn.lb) else rxn.ub = min(0, rxn.ub) end push!(rxns, rxn) rs = reaction_stoichiometry(model, rid) for mid in keys(rs) push!(mids, mid) end grrs = reaction_gene_association(model, rid) isnothing(grrs) && continue for grr in grrs append!(gids, grr) end end for mid in unique(mids) push!(mets, model.metabolites[mid]) end for gid in unique(gids) push!(gs, model.genes[gid]) end add_reactions!(pruned_model, rxns) add_metabolites!(pruned_model, mets) add_genes!(pruned_model, gs) #: print some info about process if verbose rrn = n_reactions(model) - n_reactions(pruned_model) @info "Removed $rrn reactions." end return pruned_model end """ $(TYPEDSIGNATURES) Internal helper function to construct a basic linear program representing a differentiable metabolic model. """ function _make_differentiable_model( c, _E, _d, _M, _h, ΞΈ, var_ids, param_ids; scale_equality = false, scale_inequality = false, ) Q = _ -> spzeros(length(var_ids), length(var_ids)) if scale_equality eq_row_factors = scaling_factor(_E(ΞΈ), _d(ΞΈ)) else eq_row_factors = fill(1.0, size(_E(ΞΈ), 1)) end if scale_inequality ineq_row_factors = scaling_factor(_M(ΞΈ), _h(ΞΈ)) else ineq_row_factors = fill(1.0, size(_M(ΞΈ), 1)) end E(ΞΈ) = eq_row_factors .* _E(ΞΈ) d(ΞΈ) = eq_row_factors .* _d(ΞΈ) M(ΞΈ) = ineq_row_factors .* _M(ΞΈ) h(ΞΈ) = ineq_row_factors .* _h(ΞΈ) return DifferentiableModel( Q, c, E, d, M, h, ΞΈ, (_, _, _, _) -> throw(MissingException("Missing method: analytic derivatives of variables.")), (_, _, _, _) -> throw(MissingException("Missing method: analytic derivatives of parameters.")), var_ids, param_ids, ) end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
2185
""" $(TYPEDSIGNATURES) Creates analytic derivative functions of the `diffmodel` internals, using symbolic variables. Note, this function can take some time to construct the derivatives, but substantially speeds up repeated calls to [`differentiate`](@ref). See also [`make_derivatives_with_equality_scaling`](@ref) for a variant that allows the equality constraints to be rescaled. """ function make_derivatives(diffmodel::DifferentiableModel) diffmodel.analytic_par_derivs = make_symbolic_param_derivative(diffmodel) diffmodel.analytic_var_derivs = make_analytic_var_derivative(diffmodel) return nothing end """ $(TYPEDSIGNATURES) Creates the analytic derivatives of the parameters using symbolic programming. """ function make_symbolic_param_derivative(dm::DifferentiableModel) xidxs = 1:length(dm.c(dm.ΞΈ)) Ξ½idxs = last(xidxs) .+ (1:length(dm.d(dm.ΞΈ))) Ξ»idxs = last(Ξ½idxs) .+ (1:length(dm.h(dm.ΞΈ))) ΞΈidxs = last(Ξ»idxs) .+ (1:length(dm.ΞΈ)) Symbolics.@variables begin sx[1:length(xidxs)] sΞ½[1:length(Ξ½idxs)] sΞ»[1:length(Ξ»idxs)] sΞΈ[1:length(ΞΈidxs)] end sparse_F(z) = Array( [ dm.Q(z[ΞΈidxs]) * z[xidxs] + dm.c(z[ΞΈidxs]) - dm.E(z[ΞΈidxs])' * z[Ξ½idxs] - dm.M(z[ΞΈidxs])' * z[Ξ»idxs] dm.E(z[ΞΈidxs]) * z[xidxs] - dm.d(z[ΞΈidxs]) z[Ξ»idxs] .* (dm.M(z[ΞΈidxs]) * z[xidxs] - dm.h(z[ΞΈidxs])) ], ) sz = [sx; sΞ½; sΞ»; sΞΈ] #TODO only get jacobian of theta (slower, see #580 in Symbolics.jl) sj = Symbolics.sparsejacobian(sparse_F(sz), sz)[:, ΞΈidxs] f_expr = build_function(sj, sz, expression = Val{false}) myf = first(f_expr) (x, Ξ½, Ξ», ΞΈ) -> reshape(myf([x; Ξ½; Ξ»; ΞΈ]), size(sj)...) #TODO fix this, wait for #587 in Symbolics.jl to get fixed end """ $(TYPEDSIGNATURES) Creates the analytic derivatives of the variables. """ make_analytic_var_derivative(dm::DifferentiableModel) = (x, Ξ½, Ξ», ΞΈ) -> [ dm.Q(ΞΈ) -dm.E(ΞΈ)' -dm.M(ΞΈ)' dm.E(ΞΈ) spzeros(size(dm.E(ΞΈ), 1), length(Ξ½)) spzeros(size(dm.E(ΞΈ), 1), length(Ξ»)) spdiagm(Ξ»)*dm.M(ΞΈ) spzeros(size(dm.M(ΞΈ), 1), length(Ξ½)) spdiagm(dm.M(ΞΈ) * x - dm.h(ΞΈ)) ]
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
2775
""" $(TYPEDEF) A struct used to store information the original optimization problem. $(TYPEDFIELDS) """ struct ReferenceFunctions Q::Function c::Function E::Function d::Function M::Function h::Function nx::Int neq::Int nineq::Int nΞΈ::Int end function Base.show(io::IO, ::MIME"text/plain", m::ReferenceFunctions) println(io, "", "A reference function collection.") end """ $(TYPEDSIGNATURES) A constructor for [`ReferenceFunctions`](@ref). """ function ReferenceFunctions(dm::DifferentiableModel) ReferenceFunctions( dm.Q, dm.c, dm.E, dm.d, dm.M, dm.h, length(dm.c(dm.ΞΈ)), length(dm.d(dm.ΞΈ)), length(dm.h(dm.ΞΈ)), length(dm.ΞΈ), ) end """ $(TYPEDSIGNATURES) Returns analytic derivatives that allow the equality constraint to be scaled. See also [`make_derivatives`](@ref). """ function make_derivatives_with_equality_scaling(rf::ReferenceFunctions) param_derivs = make_param_deriv_with_scaling(rf) var_derivs = make_var_deriv_with_scaling(rf) return var_derivs, param_derivs end """ $(TYPEDSIGNATURES) Return the parameter derivative that allows scaling of the equality constraint. """ function make_param_deriv_with_scaling(rf::ReferenceFunctions) xidxs = 1:rf.nx Ξ½idxs = last(xidxs) .+ (1:rf.neq) Ξ»idxs = last(Ξ½idxs) .+ (1:rf.nineq) ΞΈidxs = last(Ξ»idxs) .+ (1:rf.nΞΈ) rfidxs = last(ΞΈidxs) .+ (1:rf.neq) Symbolics.@variables begin sx[1:length(xidxs)] sΞ½[1:length(Ξ½idxs)] sΞ»[1:length(Ξ»idxs)] sΞΈ[1:length(ΞΈidxs)] srowfacts[1:length(Ξ½idxs)] # row rescaler end sparse_F(z) = Array( [ rf.Q(z[ΞΈidxs]) * z[xidxs] + rf.c(z[ΞΈidxs]) - (z[rfidxs] .* rf.E(z[ΞΈidxs]))' * z[Ξ½idxs] - rf.M(z[ΞΈidxs])' * z[Ξ»idxs] (z[rfidxs] .* rf.E(z[ΞΈidxs])) * z[xidxs] - rf.d(z[ΞΈidxs]) z[Ξ»idxs] .* (rf.M(z[ΞΈidxs]) * z[xidxs] - rf.h(z[ΞΈidxs])) ], ) sz = [sx; sΞ½; sΞ»; sΞΈ; srowfacts] # sparse_F(sz) sj = Symbolics.sparsejacobian(sparse_F(sz), sz)[:, ΞΈidxs] f_expr = build_function(sj, [sx; sΞ½; sΞ»; sΞΈ; srowfacts], expression = Val{false}) myf = first(f_expr) (x, Ξ½, Ξ», ΞΈ, rfs) -> reshape(myf([x; Ξ½; Ξ»; ΞΈ; rfs]), size(sj)...) end """ $(TYPEDSIGNATURES) Return the variable derivative that allows scaling of the equality constraint. """ function make_var_deriv_with_scaling(rf::ReferenceFunctions) (x, Ξ½, Ξ», ΞΈ, rfs) -> [ rf.Q(ΞΈ) -(rfs .* rf.E(ΞΈ))' -rf.M(ΞΈ)' (rfs.*rf.E(ΞΈ)) spzeros(size(rf.E(ΞΈ), 1), length(Ξ½)) spzeros(size(rf.E(ΞΈ), 1), length(Ξ»)) spdiagm(Ξ»)*rf.M(ΞΈ) spzeros(size(rf.M(ΞΈ), 1), length(Ξ½)) spdiagm(rf.M(ΞΈ) * x - rf.h(ΞΈ)) ] end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
6904
""" $(TYPEDSIGNATURES) Construct a [`DifferentiableModel`](@ref) from a [`COBREXA.GeckoModel`](@ref). Each variable in `gm` is differentiated with respect to the kcats in the dictionary `rid_enzyme`, which is a dictionary mapping reaction ids to [`Enzyme`](@ref)s. Enzyme constraints are only taken with respect to the entries of `rid_enzyme`. Optionally, incorporate thermodynamic and saturation constraints through `rid_dg0` and `rid_km`. If either thermodynamic or saturation (or both) constraints are added, then metabolite concentrations, `mid_concentration`, need to be supplied as well. Note, thermodynamic parameters require special attention. To ignore some reactions when calculating the thermodynamic factor, include them in `ignore_reaction_ids`. The units used for the Gibbs free energy are kJ/mol, and concentrations should be in molar. Importantly, the standard Gibbs free energy of reaction is assumed to be given *in the forward direction of the reaction* in the model. Internally, `Ο΅`, `atol`, and `digits`, are forwarded to [`_remove_lin_dep_rows`](@ref). Optionally, scale the equality constraints with `scale_equality`, see [`scaling_factor`](@ref) for more information. """ function with_parameters( gm::GeckoModel, rid_enzyme::Dict{String,Enzyme}; rid_dg0 = Dict{String,Float64}(), rid_km = Dict{String,Dict{String,Float64}}(), mid_concentration = Dict{String,Float64}(), scale_equality = false, scale_inequality = false, Ο΅ = 1e-8, atol = 1e-12, digits = 8, RT = 298.15 * 8.314e-3, ignore_reaction_ids = [], ignore_metabolite_ids = [], ) if isempty(rid_dg0) && isempty(rid_km) # no concentration parameters param_ids = "k#" .* collect(keys(rid_enzyme)) ΞΈ = [x.kcat for x in values(rid_enzyme)] else # has concentration parameters isempty(mid_concentration) && throw(error("Missing metabolite concentrations.")) param_ids = [ "k#" .* collect(keys(rid_enzyme)) "c#" .* metabolites(gm.inner) ] ΞΈ = [ [x.kcat for x in values(rid_enzyme)] [mid_concentration[mid] for mid in metabolites(gm.inner)] ] end c, E, d, M, h, var_ids = _differentiable_michaelis_menten_gecko_opt_problem( gm, rid_enzyme, rid_dg0, rid_km; Ο΅, atol, digits, RT, ignore_reaction_ids, ignore_metabolite_ids, ) _make_differentiable_model( c, E, d, M, h, ΞΈ, var_ids, param_ids; scale_equality, scale_inequality, ) end """ $(TYPEDSIGNATURES) Return optimization problem where thermodynamic and saturation effects are incorporated into the gecko problem, but in differentiable format. """ function _differentiable_michaelis_menten_gecko_opt_problem( gm::GeckoModel, rid_enzyme::Dict{String,Enzyme}, rid_dg0::Dict{String,Float64}, rid_km::Dict{String,Dict{String,Float64}}; Ο΅ = 1e-8, atol = 1e-12, digits = 8, RT = 298.15 * 8.314e-3, ignore_reaction_ids = [], ignore_metabolite_ids = [], ) #: get irreverible stoichiometric matrix from model irrev_S = stoichiometry(gm.inner) * COBREXA._gecko_reaction_column_reactions(gm) #: make full rank S = DifferentiableMetabolism._remove_lin_dep_rows(irrev_S; Ο΅, digits, atol) #: size of resultant model num_reactions = n_reactions(gm) - n_genes(gm) num_genes = n_genes(gm) num_metabolites = size(S, 1) # take into account removed linear dependencies num_vars = n_reactions(gm) #: equality lhs E_components, kcat_rid_ridx_stoich = DifferentiableMetabolism._build_gecko_equality_enzyme_constraints(gm, rid_enzyme) Se(ΞΈ) = sparse( E_components.row_idxs, E_components.col_idxs, [ stoich / ( ΞΈ[ridx] * DifferentiableMetabolism._dg( gm, rid_enzyme, rid_dg0, rid, mangled_rid, ΞΈ; RT, ignore_reaction_ids, ignore_metabolite_ids, ) * DifferentiableMetabolism._saturation( gm, rid_enzyme, rid_km, rid, mangled_rid, ΞΈ; ignore_reaction_ids, ignore_metabolite_ids, ) ) for (mangled_rid, (rid, ridx, stoich)) in zip(reactions(gm)[E_components.col_idxs], kcat_rid_ridx_stoich) ], num_genes, num_reactions, ) E(ΞΈ) = [ S spzeros(num_metabolites, num_genes) Se(ΞΈ) spdiagm(fill(1.0, num_genes)) ] #: equality rhs d = _ -> spzeros(num_metabolites + num_genes) #TODO handle fixed variables #: objective inferred from model c = _ -> -objective(gm) #: inequality constraints Cp = coupling(gm) clb, cub = coupling_bounds(gm) xlb, xub = bounds(gm) M = _ -> [ -spdiagm(fill(1.0, num_vars)) spdiagm(fill(1.0, num_vars)) -Cp Cp ] h = _ -> [-xlb; xub; -clb; cub] return c, E, d, M, h, reactions(gm) end """ $(TYPEDSIGNATURES) Helper function to add an column into the enzyme stoichiometric matrix parametrically. """ function _add_gecko_enzyme_variable_as_function( rid_enzyme, original_rid, E_components, col_idx, gene_ids, ) for (gid, stoich) in rid_enzyme[original_rid].gene_product_count push!(E_components.row_idxs, first(indexin([gid], gene_ids))) push!(E_components.col_idxs, col_idx) push!(E_components.coeff_tuple, (-stoich, original_rid)) end end """ $(TYPEDSIGNATURES) Helper function to build the equality enzyme constraints. """ function _build_gecko_equality_enzyme_constraints(gm::GeckoModel, rid_enzyme) E_components = ( #TODO add size hints if possible row_idxs = Vector{Int}(), col_idxs = Vector{Int}(), coeff_tuple = Vector{Tuple{Float64,String}}(), ) gids = genes(gm) for (col_idx, rid) in enumerate(reactions(gm)) original_rid = string(first(split(rid, "#"))) !haskey(rid_enzyme, original_rid) && continue #: add all entries to column of matrix DifferentiableMetabolism._add_gecko_enzyme_variable_as_function( rid_enzyme, original_rid, E_components, col_idx, gids, ) end kcat_rid_ridx_stoich = [ (rid, first(indexin([rid], collect(keys(rid_enzyme)))), stoich) for (stoich, rid) in E_components.coeff_tuple ] return E_components, kcat_rid_ridx_stoich end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
6215
""" $(TYPEDSIGNATURES) Construct a [`DifferentiableModel`](@ref) from a [`COBREXA.SMomentModel`](@ref). Each variable in `smm` is differentiated with respect to the kcats in the dictionary `rid_enzyme`, which is a dictionary mapping reaction ids to [`Enzyme`](@ref)s. Enzyme constraints are only taken with respect to the entries of `rid_enzyme`. Optionally, include thermodynamic parameters. Add the standard Gibbs free energy of reactions with `rid_dg0`, and the metabolite concentrations that are to be used as parameters with `mid_concentration` (both arguments are dictionaries mapping reaction or metabolite ids to values). Note, thermodynamic parameters require special attention. To ignore some reactions when calculating the thermodynamic factor, include them in `ignore_reaction_ids`. The units used for the Gibbs free energy are kJ/mol, and concentrations should be in molar. Importantly, the standard Gibbs free energy of reaction is assumed to be given *in the forward direction of the reaction* in the model. The analytic derivative of the optimality conditions with respect to the parameters can be supplied through `analytic_parameter_derivatives`. Internally, `Ο΅`, `atol`, and `digits`, are forwarded to [`_remove_lin_dep_rows`](@ref). Note, to ensure differentiability, preprocessing of the model is required. In short, only an active solution may be differentiated, this required that: - the model does not possess any isozymes - all the reactions should be unidirectinal - the kcats in `rid_enzyme` are for the appropriate direction used in the model - all rids in `rid_enzyme` are used in the model """ function with_parameters( smm::SMomentModel, rid_enzyme::Dict{String,Enzyme}; rid_dg0 = Dict{String,Float64}(), mid_concentration = Dict{String,Float64}(), scale_equality = false, scale_inequality = false, Ο΅ = 1e-8, atol = 1e-12, digits = 8, RT = 298.15 * 8.314e-3, ignore_reaction_ids = [], ignore_metabolite_ids = [], ) if isempty(rid_dg0) # no concentration parameters param_ids = "k#" .* collect(keys(rid_enzyme)) ΞΈ = [x.kcat for x in values(rid_enzyme)] else # has concentration parameters isempty(mid_concentration) && throw(error("Missing metabolite concentrations.")) param_ids = [ "k#" .* collect(keys(rid_enzyme)) "c#" .* metabolites(smm) ] ΞΈ = [ [x.kcat for x in values(rid_enzyme)] [mid_concentration[mid] for mid in metabolites(smm)] ] end c, E, d, M, h, var_ids = _differentiable_thermodynamic_smoment_opt_problem( smm, rid_enzyme, rid_dg0; Ο΅, atol, digits, RT, ignore_reaction_ids, ignore_metabolite_ids, ) _make_differentiable_model( c, E, d, M, h, ΞΈ, var_ids, param_ids; scale_equality, scale_inequality, ) end """ $(TYPEDSIGNATURES) Return structures that will allow the most basic form of smoment to be solved. No enzyme constraints allowed. Most effective enzyme is the only GRR. Assume unidirectional reactions. """ function _differentiable_thermodynamic_smoment_opt_problem( smm::SMomentModel, rid_enzyme::Dict{String,Enzyme}, rid_dg0::Dict{String,Float64}; Ο΅ = 1e-8, atol = 1e-12, digits = 8, RT = 298.15 * 8.314e-3, ignore_reaction_ids = [], ignore_metabolite_ids = [], ) #: get irreverible stoichiometric matrix from model irrev_S = stoichiometry(smm.inner) * COBREXA._smoment_column_reactions(smm) #: make full rank S = sparse(DifferentiableMetabolism._remove_lin_dep_rows(irrev_S; Ο΅, digits, atol)) #: size of resultant model num_reactions = size(S, 2) num_eq_cons = size(S, 1) #: equality lhs E = _ -> S #: equality rhs d = _ -> spzeros(num_eq_cons) #TODO handle fixed variables #: objective inferred from model c = _ -> -objective(smm) #: coupling kcats and thermodynamics col_idxs, kcat_idxs = DifferentiableMetabolism._build_smoment_kcat_coupling(smm, rid_enzyme) kcat_thermo_coupling(ΞΈ) = sparsevec( col_idxs, [ mw / ( (ΞΈ[rid_idx]) * DifferentiableMetabolism._dg( smm, rid_enzyme, rid_dg0, rid, mangled_rid, ΞΈ; RT, ignore_reaction_ids, ignore_metabolite_ids, ) ) for (mangled_rid, (rid, rid_idx, mw)) in zip(reactions(smm)[col_idxs], kcat_idxs) ], n_reactions(smm), ) #: inequality rhs Cp = coupling(smm.inner) M(ΞΈ) = [ -1.0 * spdiagm(fill(1.0, num_reactions)) 1.0 * spdiagm(fill(1.0, num_reactions)) Cp -kcat_thermo_coupling(ΞΈ)' kcat_thermo_coupling(ΞΈ)' ] #: inequality lhs xlb, xub = bounds(smm) clb, cub = coupling_bounds(smm.inner) h = _ -> [-xlb; xub; -clb; cub; 0; smm.total_enzyme_capacity] return c, E, d, M, h, reactions(smm) end """ $(TYPEDSIGNATURES) Helper function to build kcat coupling in parametric form for smoment problems. """ function _build_smoment_kcat_coupling(smm::SMomentModel, rid_enzyme) kcat_original_rid_order = String[] col_idxs = Int[] mws = Float64[] for (col_idx, rid) in enumerate(reactions(smm)) original_rid = string(first(split(rid, "#"))) # skip these entries !haskey(rid_enzyme, original_rid) && continue # these entries have kcats, only one GRR by assumption mw = sum([ pstoich * rid_enzyme[original_rid].gene_product_mass[gid] for (gid, pstoich) in rid_enzyme[original_rid].gene_product_count ]) push!(kcat_original_rid_order, original_rid) push!(col_idxs, col_idx) push!(mws, mw) end kcat_idxs = [ (rid, first(indexin([rid], collect(keys(rid_enzyme)))), mw) for (rid, mw) in zip(kcat_original_rid_order, mws) ] return col_idxs, kcat_idxs end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
2495
@testset "Analytic derivatives with scaling" begin #= Note, the analytic derivatives that don't use scaling are tested in the model tests. The scaling derivatives get special treatment, because they are more of a pain to setup. =# #: Set problem up stdmodel, reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound = create_test_model() gm = make_gecko_model( stdmodel; reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound, ) rid_enzyme = Dict( k => isozyme_to_enzyme(first(v), gene_product_molar_mass; direction = :forward) for (k, v) in reaction_isozymes ) #: Differentiate an optimal solution diffmodel = with_parameters(gm, rid_enzyme) update_Q!(diffmodel, _ -> spdiagm(fill(0.1, length(diffmodel.var_ids)))) rf = ReferenceFunctions(diffmodel) #: Get reference solution (the unscaled derivatives) x = zeros(rf.nx) Ξ½ = zeros(rf.neq) Ξ» = zeros(rf.nineq) A = spzeros(rf.nx + rf.neq + rf.nineq, rf.nx + rf.neq + rf.nineq) B = zeros(rf.nx + rf.neq + rf.nineq, rf.nΞΈ) dx = zeros(rf.nx + rf.neq + rf.nineq, rf.nΞΈ) make_derivatives(diffmodel) differentiate!( x, Ξ½, Ξ», A, B, dx, diffmodel, Ipopt.Optimizer; scale_output = false, use_analytic = true, ) x_ref = deepcopy(x) dx_ref = deepcopy(dx) #: Now use the scaling variants rescale_factors = scaling_factor(rf.E(diffmodel.ΞΈ), rf.d(diffmodel.ΞΈ)) update_E!(diffmodel, ΞΈ -> rescale_factors .* rf.E(ΞΈ)) update_d!(diffmodel, ΞΈ -> rescale_factors .* rf.d(ΞΈ)) var_derivs, par_derivs = make_derivatives_with_equality_scaling(rf) diffmodel.analytic_var_derivs = (x, Ξ½, Ξ», ΞΈ) -> var_derivs(x, Ξ½, Ξ», ΞΈ, rescale_factors) diffmodel.analytic_par_derivs = (x, Ξ½, Ξ», ΞΈ) -> par_derivs(x, Ξ½, Ξ», ΞΈ, rescale_factors) differentiate!( x, Ξ½, Ξ», A, B, dx, diffmodel, Ipopt.Optimizer; scale_output = false, use_analytic = true, ) # test if reproduceable solutions @test all([isapprox(x_ref[i], x[i]; atol = TEST_TOLERANCE) for i in eachindex(x)]) @test all([ isapprox(dx_ref[1:11, :][i], dx[1:11, :][i]; atol = TEST_TOLERANCE) for i in eachindex(dx[1:11, :]) ]) end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
768
@testset "Enzyme type and conversion" begin # create dummy isozyme isozyme = Isozyme(Dict("g1" => 1, "g2" => 3), 10.0, 2.0) # create dummy molar masses gene_product_mass_lookup = Dict("g1" => 5.0, "g2" => 7.0) # convert isozyme to enzyme with forward kcat enz_for = isozyme_to_enzyme(isozyme, gene_product_mass_lookup; direction = :forward) @test enz_for.kcat == 10.0 @test enz_for.gene_product_count["g1"] == 1 @test enz_for.gene_product_count["g2"] == 3 @test enz_for.gene_product_mass["g1"] == 5.0 @test enz_for.gene_product_mass["g2"] == 7.0 # convert isozyme to enzyme with reverse kcat enz_rev = isozyme_to_enzyme(isozyme, gene_product_mass_lookup; direction = :reverse) @test enz_rev.kcat == 2.0 end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
1233
@testset "Prune model" begin m = StandardModel("SmallModel") m1 = Metabolite("m1") m2 = Metabolite("m2") m3 = Metabolite("m3") m4 = Metabolite("m4") m5 = Metabolite("m5") @add_reactions! m begin "r1", nothing β†’ m1, 0, 100 "r2", nothing β†’ m2, 0, 100 "r3", m1 + m2 β†’ m3, 0, 100 "r4", m3 β†’ m4, 0, 100 "r5", m3 β†’ m5, 0, 100 "r6", m5 β†’ m4, 0, 100 "r7", m4 β†’ nothing, 0, 100 end gs = [Gene("g$i") for i = 1:4] m.reactions["r3"].grr = [["g1"], ["g2"]] m.reactions["r4"].grr = [["g3", "g4"]] m.reactions["r7"].objective_coefficient = 1.0 add_genes!(m, gs) add_metabolites!(m, [m1, m2, m3, m4, m5]) reaction_fluxes = Dict( "r1" => 1.0, "r2" => 1.0, "r3" => -1.0, "r4" => 1.0, "r5" => -0.01, "r6" => 0.01, "r7" => 1.0, ) pruned_model = prune_model(m, reaction_fluxes; atol = 1e-2) @test !haskey(pruned_model.reactions, "r5") @test !haskey(pruned_model.reactions, "r6") @test haskey(pruned_model.reactions, "r1") @test !isempty(genes(pruned_model)) @test "m1" in metabolites(pruned_model) @test "m5" βˆ‰ metabolites(pruned_model) end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
993
using DifferentiableMetabolism using Test using Tulip, Ipopt using COBREXA using SparseArrays, LinearAlgebra # Testing infrastructure taken from COBREXA TEST_TOLERANCE = 1e-6 TEST_TOLERANCE_RELAXED = 1e-3 print_timing(fn, t) = @info "$(fn) done in $(round(t; digits = 2))s" # Helper functions for running tests en masse function run_test_file(path...) fn = joinpath(path...) t = @elapsed include(fn) print_timing(fn, t) end run_test_file("static_data.jl") @testset "DifferentiableMetabolism.jl" begin run_test_file("enzyme.jl") run_test_file("prune.jl") run_test_file("update.jl") run_test_file("differentiable_models/basic_gecko.jl") run_test_file("differentiable_models/basic_smoment.jl") run_test_file("differentiable_models/thermodynamic_smoment.jl") run_test_file("differentiable_models/thermodynamic_gecko.jl") run_test_file("differentiable_models/michaelis_menten_gecko.jl") run_test_file("analytic_derivatives_with_scaling.jl") end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
2693
@testset "Differentiable GECKO" begin #: Set problem up stdmodel, reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound = create_test_model() gm = make_gecko_model( stdmodel; reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound, ) rid_enzyme = Dict( k => isozyme_to_enzyme(first(v), gene_product_molar_mass; direction = :forward) for (k, v) in reaction_isozymes ) #: Get classic GECKO solution opt_model = flux_balance_analysis( gm, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) gecko_fluxes = flux_dict(gm, opt_model) gecko_gps = gene_product_dict(gm, opt_model) #: Differentiate an optimal solution diffmodel = with_parameters(gm, rid_enzyme; scale_equality = false) x_noscaling, dx_noscaling = differentiate( diffmodel, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) (slb, sub), _, _ = check_scaling(diffmodel) @test isapprox(slb, 1.845098040014257; atol = TEST_TOLERANCE) @test isapprox(sub, 2.146128035678238; atol = TEST_TOLERANCE) #: scale equality diffmodel = with_parameters(gm, rid_enzyme; scale_equality = true) x_scaling_eq, dx_scaling_eq = differentiate( diffmodel, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) #: Note, the duals are scaled, so they will not be the same @test all([ isapprox( dx_noscaling[1:11, :][i], dx_scaling_eq[1:11, :][i]; atol = TEST_TOLERANCE, ) for i in eachindex(dx_noscaling[1:11, :]) ]) @test all([ isapprox(x_noscaling[i], x_scaling_eq[i]; atol = TEST_TOLERANCE) for i in eachindex(x_noscaling) ]) #: scale both Inequality and equality diffmodel = with_parameters(gm, rid_enzyme; scale_equality = true, scale_inequality = true) x_scaling_eqineq, dx_scaling_eqineq = differentiate( diffmodel, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) @test all([ isapprox( dx_noscaling[1:11, :][i], dx_scaling_eqineq[1:11, :][i]; atol = TEST_TOLERANCE, ) for i in eachindex(dx_noscaling[1:11, :]) ]) @test all([ isapprox(x_noscaling[i], x_scaling_eqineq[i]; atol = TEST_TOLERANCE) for i in eachindex(x_noscaling) ]) end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
1635
function create_test_model() #= Implement the small model based on model found in the supplement in the original GECKO paper. This model is nice to troubleshoot with, because the stoich matrix is small. All the reactions are active by design and each reaction that has a kcat has only one grr. =# m = StandardModel("SmallModel") m1 = Metabolite("m1") m2 = Metabolite("m2") m3 = Metabolite("m3") m4 = Metabolite("m4") m5 = Metabolite("m5") m6 = Metabolite("m6") @add_reactions! m begin "r1", nothing β†’ m1, 0, 100 "r2", nothing β†’ m2, 0, 100 "r3", m1 + m2 β†’ m3, 0, 100 "r4", m3 β†’ m4 + m5, 0, 100 "r5", m2 β†’ m4 + m6, 0, 100 "r6", m4 β†’ nothing, 0, 100 "biomass", m6 + m5 β†’ nothing, 0, 100 end gs = [Gene("g$i") for i = 1:4] m.reactions["biomass"].objective_coefficient = 1.0 add_genes!(m, gs) add_metabolites!(m, [m1, m2, m3, m4, m5, m6]) reaction_isozymes = Dict( "r3" => [Isozyme(Dict("g1" => 1), 10.0, 10.0)], "r4" => [Isozyme(Dict("g2" => 1, "g3" => 3), 30.0, 20.0)], "r5" => [Isozyme(Dict("g3" => 1, "g4" => 2), 70.0, 30.0)], ) gene_product_bounds = Dict( "g1" => (0.0, 0.2), "g2" => (0.0, 0.1), "g3" => (0.0, 10.0), "g4" => (0.0, 1000.0), ) gene_product_molar_mass = Dict("g1" => 1.0, "g2" => 2.0, "g3" => 3.0, "g4" => 4.0) gene_product_mass_group_bound = Dict("uncategorized" => 1.0) return m, reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
1401
@testset "Update" begin #: Set problem up stdmodel, reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound = create_test_model() gm = make_gecko_model( stdmodel; reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound, ) rid_enzyme = Dict( k => isozyme_to_enzyme(first(v), gene_product_molar_mass; direction = :forward) for (k, v) in reaction_isozymes ) #: Differentiate an optimal solution diffmodel = with_parameters(gm, rid_enzyme;) #: Test if update works n_vars = length(diffmodel.c(diffmodel.ΞΈ)) n_eqs = size(diffmodel.E(diffmodel.ΞΈ), 1) n_ineqs = size(diffmodel.M(diffmodel.ΞΈ), 1) ΞΈ = diffmodel.ΞΈ _Q = rand(n_vars, n_vars) _c = rand(n_vars) _E = rand(n_eqs, n_vars) _d = rand(n_eqs) _M = rand(n_ineqs, n_vars) _h = rand(n_ineqs) update_Q!(diffmodel, _ -> _Q) update_c!(diffmodel, _ -> _c) update_E!(diffmodel, _ -> _E) update_d!(diffmodel, _ -> _d) update_M!(diffmodel, _ -> _M) update_h!(diffmodel, _ -> _h) @test all(diffmodel.Q(ΞΈ) .== _Q) @test all(diffmodel.c(ΞΈ) .== _c) @test all(diffmodel.E(ΞΈ) .== _E) @test all(diffmodel.d(ΞΈ) .== _d) @test all(diffmodel.M(ΞΈ) .== _M) @test all(diffmodel.h(ΞΈ) .== _h) end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
2993
@testset "Differentiable GECKO" begin #: Set problem up stdmodel, reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound = create_test_model() gm = make_gecko_model( stdmodel; reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound, ) rid_enzyme = Dict( k => isozyme_to_enzyme(first(v), gene_product_molar_mass; direction = :forward) for (k, v) in reaction_isozymes ) #: Get classic GECKO solution opt_model = flux_balance_analysis( gm, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) gecko_fluxes = flux_dict(gm, opt_model) gecko_gps = gene_product_dict(gm, opt_model) gene_product_mass_group_dict(gm, opt_model) #: Differentiate an optimal solution diffmodel = with_parameters(gm, rid_enzyme;) x_auto, dx_auto = differentiate( diffmodel, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) # test if solution is the same between gecko and differentiable gecko sol = Dict(diffmodel.var_ids .=> x_auto) @test isapprox(sol["g1"], gecko_gps["g1"]; atol = TEST_TOLERANCE) @test isapprox(sol["r3#forward#1"], gecko_fluxes["r3"]; atol = TEST_TOLERANCE) # test if automatic and symbolic derivatives are the same make_derivatives(diffmodel) x_anal, dx_anal = differentiate(diffmodel, Tulip.Optimizer; use_analytic = true) @test all([ isapprox(dx_auto[i], dx_anal[i]; atol = TEST_TOLERANCE) for i in eachindex(dx_anal) ]) #: Add a regularizer and test QP update_Q!(diffmodel, _ -> spdiagm(fill(0.1, length(diffmodel.var_ids)))) x_qp, dx_qp = differentiate(diffmodel, Ipopt.Optimizer) # test if reproduceable solutions x_qp_ref = [ 0.7677550153758821 1.5355100307517642 0.7677550153758821 0.7677550153758821 0.7677550153758821 1.5355100307517642 0.7677550153758821 0.07677550153758822 0.025591833845862735 0.08774343032867224 0.02193585758216806 ] @test all([ isapprox(x_qp_ref[i], x_qp[i]; atol = TEST_TOLERANCE) for i in eachindex(x_qp) ]) dx_qp_ref = [ 0.000376045 0.00153551 0.00192548 0.000376045 0.00153551 0.00192548 0.000376045 0.00153551 0.00192548 0.000376045 0.00153551 0.00192548 0.000376045 0.00153551 0.00192548 0.000376045 0.00153551 0.00192548 0.000376045 0.00153551 0.00192548 0.000376045 -0.998464 0.00192548 0.000376045 0.00153551 -0.998075 -0.124624 0.00153551 -0.873075 -0.999624 0.00153551 0.00192548 ] @test all([ isapprox(dx_qp_ref[i], dx_qp[1:11, :][i]; atol = TEST_TOLERANCE) for i in eachindex(dx_qp_ref) ]) end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
1916
@testset "Differentiable SMOMENT" begin #: Set problem up stdmodel, reaction_isozymes, _, gene_product_molar_mass, _ = create_test_model() smm = make_smoment_model( stdmodel; reaction_isozyme = Dict(k => first(v) for (k, v) in reaction_isozymes), gene_product_molar_mass, total_enzyme_capacity = 1.0, ) rid_enzyme = Dict( k => isozyme_to_enzyme(first(v), gene_product_molar_mass; direction = :forward) for (k, v) in reaction_isozymes ) #: Get SMoment solution for comparison fluxes = flux_balance_analysis_dict( smm, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) #: Diffeentiate model diffmodel = with_parameters(smm, rid_enzyme) x, dx = differentiate( diffmodel, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) # test if COBREXA Smoment is the same as the differentiable one sol = Dict(reactions(smm) .=> x) @test isapprox(sol["r1"], fluxes["r1"]; atol = TEST_TOLERANCE) @test isapprox(sol["r6"], fluxes["r6"]; atol = TEST_TOLERANCE) # test if automatic and symbolic derivatives are the same make_derivatives(diffmodel) _, dx_sym = differentiate(diffmodel, Tulip.Optimizer; use_analytic = true) @test all([ isapprox(dx_sym[i], dx[i]; atol = TEST_TOLERANCE) for i in eachindex(dx_sym) ]) # test if reference solution is attained dx_ref = [ 0.251908 0.160305 0.587786 0.251908 0.160305 0.587786 0.251908 0.160305 0.587786 0.251908 0.160305 0.587786 0.251908 0.160305 0.587786 0.251908 0.160305 0.587786 0.251908 0.160305 0.587786 ] @test all([ isapprox(dx_ref[i], dx[1:7, :][i]; atol = TEST_TOLERANCE) for i in eachindex(dx_ref) ]) end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
3910
@testset "Differentiable Michaelis Menten GECKO" begin #: Set problem up stdmodel, reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound = create_test_model() gm = make_gecko_model( stdmodel; reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound, ) rid_enzyme = Dict( k => isozyme_to_enzyme(first(v), gene_product_molar_mass; direction = :forward) for (k, v) in reaction_isozymes ) rid_dg0 = Dict("r4" => -1.0, "r5" => -10.0, "r6" => 10.0) mid_concentration = Dict( "m6" => 0.001, "m3" => 0.001, "m2" => 1.0, "m4" => 0.01, "m5" => 0.05, "m1" => 1.0, ) rid_km = Dict( "r4" => Dict("m3" => 0.007, "m4" => 0.02, "m5" => 0.03), "r5" => Dict("m2" => 0.4, "m4" => 0.02, "m6" => 0.01), ) #: Solve normal gecko model without thermodynamic effects opt_model = flux_balance_analysis( gm, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) gecko_fluxes = flux_dict(gm, opt_model) gecko_gps = gene_product_dict(gm, opt_model) #: Differentiate model normal gecko diffmodel = with_parameters( gm, rid_enzyme; rid_dg0, rid_km, mid_concentration, ignore_reaction_ids = ["r6"], ) x, dx = differentiate( diffmodel, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) sol = Dict(diffmodel.var_ids .=> x) # check if x, dx can be reproduced x_ref = [ 0.1259560041366511 0.2519120082733372 0.12595600413638888 0.1259560041369218 0.1259560041365431 0.2519120082733372 0.1259560041366511 0.012595600412036653 0.08720892830551037 0.26418189287384747 0.0051102159284440365 ] @test all([isapprox(x_ref[i], x[i]; atol = TEST_TOLERANCE) for i in eachindex(x)]) dx_ref = [ 0.0281062 0.0125956 0.959298 -0.0 0.0083131 1.37108 -0.886044 -0.885648 -0.000395867 0.0281062 0.0125956 0.959298 -0.0 0.0083131 1.37108 -0.886044 -0.885648 -0.000395867 0.0281062 0.0125956 0.959298 -0.0 0.0083131 1.37108 -0.886044 -0.885648 -0.000395867 0.0281062 0.0125956 0.959298 -0.0 0.0083131 1.37108 -0.886044 -0.885648 -0.000395867 0.0281062 0.0125956 0.959298 -0.0 0.0083131 1.37108 -0.886044 -0.885648 -0.000395867 0.0281062 0.0125956 0.959298 -0.0 0.0083131 1.37108 -0.886044 -0.885648 -0.000395867 0.0281062 0.0125956 0.959298 0.0 0.0083131 1.37108 -0.886044 -0.885648 -0.000395867 0.0281062 -0.987404 0.959298 -0.0 0.0083131 1.37108 -0.886044 -0.885648 -0.000395867 0.0281062 0.0125956 -0.0407018 -0.0 0.0083131 -0.058173 0.0371811 0.0375769 -0.000395867 0.0184344 0.0125956 -0.03103 -0.0 0.00545244 -0.0443496 0.028388 0.0286477 -0.000259643 -0.971894 0.0125956 0.959298 -0.0 -0.287462 1.37108 -0.87196 -0.885648 0.0136888 ] @test all([ isapprox(dx_ref[i], dx[1:11, :][i]; atol = TEST_TOLERANCE_RELAXED) for i in eachindex(dx_ref) ]) # test if automatic and symbolic derivatives are the same make_derivatives(diffmodel) _, dx_sym = differentiate( diffmodel, Tulip.Optimizer; use_analytic = true, modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) @test all([ isapprox(dx_sym[i], dx[i]; atol = TEST_TOLERANCE) for i in eachindex(dx_ref) ]) end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
3628
@testset "Differentiable Thermodynamic GECKO" begin #: Set problem up stdmodel, reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound = create_test_model() gm = make_gecko_model( stdmodel; reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound, ) rid_enzyme = Dict( k => isozyme_to_enzyme(first(v), gene_product_molar_mass; direction = :forward) for (k, v) in reaction_isozymes ) rid_dg0 = Dict("r4" => -1.0, "r5" => -10.0, "r6" => 10.0) mid_concentration = Dict( "m6" => 0.001, "m3" => 0.001, "m2" => 1.0, "m4" => 0.01, "m5" => 0.05, "m1" => 1.0, ) #: Solve normal gecko model without thermodynamic effects opt_model = flux_balance_analysis( gm, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) gecko_fluxes = flux_dict(gm, opt_model) gecko_gps = gene_product_dict(gm, opt_model) #: Differentiate model normal gecko diffmodel = with_parameters( gm, rid_enzyme; rid_dg0, mid_concentration, ignore_reaction_ids = ["r6"], ) x, dx = differentiate( diffmodel, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) sol = Dict(diffmodel.var_ids .=> x) #= sanity check reaction 4 should require more enzyme due to it being closer to equilibrium grr reaction 4: (1 * g2 && 3 * g3) =# @test sol["g2"] > gecko_gps["g2"] @test sol["g3"] > gecko_gps["g3"] # check if x, dx can be reproduced x_ref = [ 1.2380726767460195 2.476145353495478 1.2380726767411319 1.2380726767489294 1.2380726767312122 2.476145353495478 1.2380726767460195 0.12380726766577349 0.061967128585559375 0.2035881413551585 0.03537351102455509 ] @test all([isapprox(x_ref[i], x[i]; atol = TEST_TOLERANCE) for i in eachindex(x)]) dx_ref = [ 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 -0.876193 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 -0.318362 -0.0 3.44365e-8 -0.159671 0.159671 0.159671 -3.44365e-8 0.107679 0.123807 -0.231486 -0.0 1.90594e-8 -0.116099 0.116099 0.116099 -1.90594e-8 -0.805446 0.123807 0.681638 -0.0 -1.42566e-7 0.341868 -0.341868 -0.341868 1.42566e-7 ] @test all([ isapprox(dx_ref[i], dx[1:11, :][i]; atol = TEST_TOLERANCE) for i in eachindex(dx_ref) ]) # test if automatic and symbolic derivatives are the same make_derivatives(diffmodel) _, dx_sym = differentiate(diffmodel, Tulip.Optimizer; use_analytic = true) @test all([ isapprox(dx_sym[i], dx[i]; atol = TEST_TOLERANCE) for i in eachindex(dx_sym) ]) end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
code
2483
@testset "Differentiable Thermodynamic SMOMENT" begin #: Set problem up stdmodel, reaction_isozymes, _, gene_product_molar_mass, _ = create_test_model() smm = make_smoment_model( stdmodel; reaction_isozyme = Dict(k => first(v) for (k, v) in reaction_isozymes), gene_product_molar_mass, total_enzyme_capacity = 1.0, ) rid_enzyme = Dict( k => isozyme_to_enzyme(first(v), gene_product_molar_mass; direction = :forward) for (k, v) in reaction_isozymes ) rid_dg0 = Dict("r4" => -1.0, "r5" => -10.0, "r6" => 10.0) mid_concentration = Dict( "m6" => 0.001, "m3" => 0.001, "m2" => 1.0, "m4" => 0.01, "m5" => 0.05, "m1" => 1.0, ) #: Differentiate model diffmodel = with_parameters( smm, rid_enzyme; rid_dg0, mid_concentration, ignore_reaction_ids = ["r6"], ) x, dx = differentiate( diffmodel, Tulip.Optimizer; modifications = [change_optimizer_attribute("IPM_IterationsLimit", 1000)], ) # test if can reproduce answers x_ref = [ 1.2380726841130605 2.4761453682260397 1.2380726841129737 1.2380726841134497 1.2380726841130556 2.4761453682260397 1.2380726841130605 ] @test all([isapprox(x_ref[i], x[i]; atol = TEST_TOLERANCE) for i in eachindex(x)]) dx_ref = [ 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 -0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 0.194554 0.123807 0.681638 0.0 3.44365e-8 0.341868 -0.341868 -0.341868 -3.44365e-8 ] @test all([ isapprox(dx_ref[i], dx[1:7, :][i]; atol = TEST_TOLERANCE) for i in eachindex(dx_ref) ]) # test if automatic and symbolic derivatives are the same make_derivatives(diffmodel) _, dx_sym = differentiate(diffmodel, Tulip.Optimizer; use_analytic = true) @test all([isapprox(dx_sym[i], dx[i]; atol = TEST_TOLERANCE) for i in eachindex(dx)]) end
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
docs
4061
# DifferentiableMetabolism.jl This package extends [COBREXA.jl](https://github.com/LCSB-BioCore/COBREXA.jl) with the ability to differentiate an optimal solution of an enzyme constrained metabolic model. Currently, there is support for differentiating both `SMomentModel` and `GeckoModel`, where both turnover numbers and/or intracellular metabolite concentrations can be taken as parameters. If the latter are parameters, then generalized Michaelis-Menten kinetics (saturation and thermodynamic) are assumed. Note, this package is under active development. Only non-degenerate models can be differentiated. This means that you will only be able to differentiate the model if you find an active solution, prune the inactive reactions from the model, and then differentiate the resulting model. Work is planned to drop this restriction. To use this package, [download and install Julia](https://julialang.org/downloads/), and add the following packages using the built in package manager: ```julia ] add COBREXA, DifferentiableMetabolism, Tulip ``` Note, any optimization solver that is compatible with [JuMP](https://jump.dev/) can be used. Here we have opted to use [Tulip.jl](https://github.com/ds4dm/Tulip.jl). To run the tests, [Ipopt](https://github.com/jump-dev/Ipopt.jl) is also required. ```julia ] test DifferentiableMetabolism ``` ## Differentiating a simple model In this example, a simple model will be differentiated. ```julia using DifferentiableMetabolism using Tulip using COBREXA # Create model model = StandardModel("SmallModel") m1 = Metabolite("m1") m2 = Metabolite("m2") m3 = Metabolite("m3") m4 = Metabolite("m4") m5 = Metabolite("m5") m6 = Metabolite("m6") @add_reactions! model begin "r1", nothing β†’ m1, 0, 100 "r2", nothing β†’ m2, 0, 100 "r3", m1 + m2 β†’ m3, 0, 100 "r4", m3 β†’ m4 + m5, 0, 100 "r5", m2 β†’ m4 + m6, 0, 100 "r6", m4 β†’ nothing, 0, 100 "r7", m2 β†’ m4 + m6, 0, 100 "biomass", m6 + m5 β†’ nothing, 0, 100 end gs = [Gene("g$i") for i = 1:5] model.reactions["biomass"].objective_coefficient = 1.0 add_genes!(model, gs) add_metabolites!(model, [m1, m2, m3, m4, m5, m6]) reaction_isozymes = Dict( "r3" => [Isozyme(Dict("g1" => 1), 10.0, 10.0)], "r4" => [Isozyme(Dict("g2" => 1, "g3" => 3), 30.0, 20.0)], "r5" => [Isozyme(Dict("g3" => 1, "g4" => 2), 70.0, 30.0)], "r7" => [Isozyme(Dict("g5" => 1), 50.0, 20.0)], ) gene_product_bounds = Dict( "g1" => (0.0, 0.2), "g2" => (0.0, 0.1), "g3" => (0.0, 10.0), "g4" => (0.0, 1000.0), "g5" => (0.0, 1000.0), ) gene_product_molar_mass = Dict("g1" => 1.0, "g2" => 2.0, "g3" => 3.0, "g4" => 4.0, "g5" => 5.0) gene_product_mass_group_bound = Dict("uncategorized" => 1.0) model # Construct and simulate a GECKO model gecko_model = make_gecko_model( model; reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound, ) # Get classic GECKO solution optimized_model = flux_balance_analysis( gecko_model, Tulip.Optimizer; ) gecko_fluxes = flux_dict(gecko_model, optimized_model) # notice that r5 is inactive! # Prune away inactive reactions pruned_model = prune_model(model, gecko_fluxes) # Differentiate an optimal solution pruned_gecko_model = make_gecko_model( pruned_model; reaction_isozymes, gene_product_bounds, gene_product_molar_mass, gene_product_mass_group_bound, ) rid_enzyme = Dict( k => isozyme_to_enzyme(first(v), gene_product_molar_mass; direction = :forward) for (k, v) in reaction_isozymes ) diffmodel = with_parameters(gecko_model, rid_enzyme) x, dx = differentiate( diffmodel, Tulip.Optimizer ) ``` Here, `x` are the variables, corresponding to `diffmodel.var_ids`, and `dx` are the derivatives, where rows correspond to `diffmodel.param_ids`, and columns correspond to `diffmodel.var_ids`. While this package is under development, you can already use more advanced functionality. Look at the tests to see how to incorporate thermodynamic and/or saturation effects these differentiable models.
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "Apache-2.0" ]
0.1.1
67fef652da188fec439462b55f9015a7d05653e5
docs
254
```@meta CurrentModule = DifferentiableMetabolism ``` # DifferentiableMetabolism Documentation for [DifferentiableMetabolism](https://github.com/stelmo/DifferentiableMetabolism.jl). ```@index ``` ```@autodocs Modules = [DifferentiableMetabolism] ```
DifferentiableMetabolism
https://github.com/stelmo/DifferentiableMetabolism.jl.git
[ "MIT" ]
0.1.0
0bdda826dee28f5e839c5c38b1e7096bd079216e
code
685
import PyCall # , Conda # Conda.add("git") # Conda.add("pip") # Conda.add("cython") # Conda.add("numpy") # const pip = joinpath(Conda.BINDIR, "pip") # proxy_arg = String[] # if haskey(ENV, "http_proxy") # push!(proxy_arg, "--proxy") # push!(proxy_arg, ENV["http_proxy"]) # end pip = `$(PyCall.python) -m pip` run(`$pip install --user --upgrade pip setuptools`) run(`$pip install --user cython numpy`) # Install pyconcorde (The Concorde TSP Solver + QSOpt LP Library) # https://github.com/jvkersch/pyconcorde run(`$pip install git+git://github.com/jvkersch/pyconcorde.git`) # Install elkai (The LKH Solver) # https://github.com/filipArena/elkai run(`$pip install elkai`)
PyTSP
https://github.com/chkwon/PyTSP.jl.git
[ "MIT" ]
0.1.0
0bdda826dee28f5e839c5c38b1e7096bd079216e
code
197
module PyTSP # Write your package code here. using PyCall include("tsp_solvers.jl") export solve_TSP_Concorde, solve_TSP_LKH, distance_matrix, tour_length, distance_matrix_float end
PyTSP
https://github.com/chkwon/PyTSP.jl.git
[ "MIT" ]
0.1.0
0bdda826dee28f5e839c5c38b1e7096bd079216e
code
1603
function distance_matrix_float(x, y) @assert length(x) == length(y) n = length(x) M = zeros(n, n) for i in 1:n for j in i+1:n if i != j M[i, j] = sqrt( (x[i]-x[j])^2 + (y[i]-y[j])^2 ) M[j, i] = M[i, j] end end end return M end function distance_matrix(x, y) M = distance_matrix_float(x, y) return Int.(round.(M)) end function tour_length(tour, M::Matrix{T}) where T sum = zero(T) for i in 1:length(tour) if i < length(tour) sum += M[tour[i], tour[i+1]] else sum += M[tour[i], tour[1]] end end return sum end # function tour_length(tour, x, y) # M = distance_matrix(x, y) # return tour_length(tour, M) # end function solve_TSP_Concorde(x, y; norm="EUC_2D",) Concorde = pyimport("concorde.tsp") solver = Concorde.TSPSolver.from_data(x, y, norm) tour_data = solver.solve() tour_concorde = tour_data[1] .+ 1 # 0-index -> 1-index # length_concorde = tour_length(tour_concorde, x, y) length_concorde = Int(tour_data[2]) return tour_concorde, length_concorde end function solve_TSP_LKH(M::Matrix{T}) where T Elkai = pyimport("elkai") if T == Int tour_LKH = Elkai.solve_int_matrix(M) .+ 1 #adding 1 for indexing else tour_LKH = Elkai.solve_float_matrix(M) .+ 1 #adding 1 for indexing end length_LKH = tour_length(tour_LKH, M) return tour_LKH, length_LKH end function solve_TSP_LKH(x, y) M = distance_matrix(x, y) return solve_TSP_LKH(M) end
PyTSP
https://github.com/chkwon/PyTSP.jl.git
[ "MIT" ]
0.1.0
0bdda826dee28f5e839c5c38b1e7096bd079216e
code
1678
using PyTSP using Test @testset "PyTSP.jl" begin @testset "Basic TSP solver tests" begin # random TSP instance n_cities = 20 factor = 1e5 x = rand(n_cities) .* factor y = rand(n_cities) .* factor # The Concorde TSL Solver via pyconcorde time_concorde = @elapsed tour_concorde, length_concorde = solve_TSP_Concorde(x, y, norm="EUC_2D") # The LKH Heuristic via elkai time_LKH = @elapsed tour_LKH, length_LKH = solve_TSP_LKH(x, y) gap = (length_LKH - length_concorde) / length_LKH * 100 gap = round(gap * 100) / 100 # Compare the solutions println("============ n_cities = $n_cities ======================") @show tour_concorde @show tour_LKH println("Concorde Tour Length: $length_concorde ($time_concorde seconds)") println("LKH Tour Length: $length_LKH ($time_LKH seconds) (gap = $gap %)") @test isapprox(length_concorde, length_LKH; atol=2) end @testset "LKH type tests" begin # random TSP instance n_cities = 20 factor = 1e5 x = rand(n_cities) .* factor y = rand(n_cities) .* factor tour_LKH_int1, length_LKH_int1 = solve_TSP_LKH(x, y) M = distance_matrix(x, y) tour_LKH_int2, length_LKH_int2 = solve_TSP_LKH(M) N = distance_matrix(x, y) .* 1.0 tour_LKH_float, length_LKH_float = solve_TSP_LKH(N) @test isa(length_LKH_int1, Int) @test isa(length_LKH_int2, Int) @test isa(length_LKH_float, Float64) @test isapprox(length_LKH_int1, length_LKH_int2) end end
PyTSP
https://github.com/chkwon/PyTSP.jl.git
[ "MIT" ]
0.1.0
0bdda826dee28f5e839c5c38b1e7096bd079216e
docs
2348
# PyTSP [![Build Status](https://github.com/chkwon/PyTSP.jl/workflows/CI/badge.svg?branch=master)](https://github.com/chkwon/PyTSP.jl/actions?query=workflow%3ACI) [![codecov](https://codecov.io/gh/chkwon/PyTSP.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/chkwon/PyTSP.jl) This Julia package provides access to the [Concorde TSP Solver](http://www.math.uwaterloo.ca/tsp/concorde/index.html) and the [Lin-Kernighan-Held (LKH) solver](http://webhotel4.ruc.dk/~keld/research/LKH/) via [PyConcorde](https://github.com/jvkersch/pyconcorde) and [elkai](https://github.com/filipArena/elkai), respectively. As both PyConcorde and elkai are Python libraries, this package merely provides a Julia wrapper using PyCall. In Windows, this package does not work. Consider using Windows Subsystem for Linux (WSL). ## License MIT License only applies to PyTSP.jl. The Python parts, PyConcorde and elkai, come in difference licenses. The underlying solvers, the Conrcorde TSP Solver and LKH, require special licenses for commercial usage. Please check their websites. ## Installation `] add https://github.com/chkwon/PyTSP.jl` ## Usage ### Concorde Concorde uses integers for distance calculation. Your `(x, y)` coordinate inputs should be scaled appropriately. ```julia using PyTSP n_cities = 20 factor = 1e5 x = rand(n_cities) .* factor y = rand(n_cities) .* factor # The Concorde TSL Solver via pyconcorde tour, len = solve_TSP_Concorde(x, y, norm="EUC_2D") ``` ```julia ([1, 2, 19, 13, 18, 11, 4, 14, 7, 6, 15, 10, 8, 16, 20, 5, 9, 3, 12, 17], 389803) ``` ### LKH Since LKH also benefits from integer inputs, this package uses integer as default. ```julia using PyTSP n_cities = 20 factor = 1e5 x = rand(n_cities) .* factor y = rand(n_cities) .* factor # The LKH heuristic solver via elkai tour_LKH, length_LKH = solve_TSP_LKH(x, y) ``` ```julia ([1, 2, 19, 13, 18, 11, 4, 14, 7, 6, 15, 10, 8, 16, 20, 5, 9, 3, 12, 17], 389803) ``` You can also input a distance matrix, either `Matrix{Int}` or `Matrix{Float64}`. ```julia using PyTSP n_cities = 20 factor = 1e5 x = rand(n_cities) .* factor y = rand(n_cities) .* factor M = distance_matrix(x, y) # returns a rounded Matrix{Int} tour_LKH, length_LKH = solve_TSP_LKH(M) N = distance_matrix_float(x, y) # returns a Matrix{Float64} tour_LKH, length_LKH = solve_TSP_LKH(N) ```
PyTSP
https://github.com/chkwon/PyTSP.jl.git
[ "MIT" ]
0.3.0
553be75f181bf33a0816833e2244b82f3a80da4f
code
629
module DashCytoscape using Dash const resources_path = realpath(joinpath( @__DIR__, "..", "deps")) const version = "0.3.0" include("jl/cyto_cytoscape.jl") function __init__() DashBase.register_package( DashBase.ResourcePkg( "dash_cytoscape", resources_path, version = version, [ DashBase.Resource( relative_package_path = "dash_cytoscape.min.js", external_url = "https://unpkg.com/[email protected]/dash_cytoscape/dash_cytoscape.min.js", dynamic = nothing, async = nothing, type = :js ) ] ) ) end end
DashCytoscape
https://github.com/plotly/DashCytoscape.jl.git
[ "MIT" ]
0.3.0
553be75f181bf33a0816833e2244b82f3a80da4f
code
15357
# AUTO GENERATED FILE - DO NOT EDIT export cyto_cytoscape """ cyto_cytoscape(;kwargs...) A Cytoscape component. A Component Library for Dash aimed at facilitating network visualization in Python, wrapped around [Cytoscape.js](http://js.cytoscape.org/). Keyword arguments: - `id` (String; optional): The ID used to identify this component in Dash callbacks. - `autoRefreshLayout` (Bool; optional): Whether the layout should be refreshed when elements are added or removed. - `autolock` (Bool; optional): Whether nodes should be locked (not draggable at all) by default (if true, overrides individual node state). - `autoungrabify` (Bool; optional): Whether nodes should be ungrabified (not grabbable by user) by default (if true, overrides individual node state). - `autounselectify` (Bool; optional): Whether nodes should be unselectified (immutable selection state) by default (if true, overrides individual element state). - `boxSelectionEnabled` (Bool; optional): Whether box selection (i.e. drag a box overlay around, and release it to select) is enabled. If enabled, the user must taphold to pan the graph. - `className` (String; optional): Sets the class name of the element (the value of an element's html class attribute). - `elements` (optional): A list of dictionaries representing the elements of the networks. Each dictionary describes an element, and specifies its purpose. The [official Cytoscape.js documentation](https://js.cytoscape.org/#notation/elements-json) offers an extensive overview and examples of element declaration. Alternatively, a dictionary with the format { 'nodes': [], 'edges': [] } is allowed at initialization, but arrays remain the recommended format.. elements has the following type: Array of lists containing elements 'group', 'data', 'position', 'selected', 'selectable', 'locked', 'grabbable', 'classes'. Those elements have the following types: - `group` (String; optional): Either 'nodes' or 'edges'. If not given, it's automatically inferred. - `data` (optional): Element specific data.. data has the following type: lists containing elements 'id', 'label', 'parent', 'source', 'target'. Those elements have the following types: - `id` (String; optional): Reference to the element, useful for selectors and edges. Randomly assigned if not given. - `label` (String; optional): Optional name for the element, useful when `data(label)` is given to a style's `content` or `label`. It is only a convention. - `parent` (String; optional): Only for nodes. Optional reference to another node. Needed to create compound nodes. - `source` (String; optional): Only for edges. The id of the source node, which is where the edge starts. - `target` (String; optional): Only for edges. The id of the target node, where the edge ends. - `position` (optional): Only for nodes. The position of the node.. position has the following type: lists containing elements 'x', 'y'. Those elements have the following types: - `x` (Real; optional): The x-coordinate of the node. - `y` (Real; optional): The y-coordinate of the node. - `selected` (Bool; optional): If the element is selected upon initialisation. - `selectable` (Bool; optional): If the element can be selected. - `locked` (Bool; optional): Only for nodes. If the position is immutable. - `grabbable` (Bool; optional): Only for nodes. If the node can be grabbed and moved by the user. - `classes` (String; optional): Space separated string of class names of the element. Those classes can be selected by a style selector.s | lists containing elements 'nodes', 'edges'. Those elements have the following types: - `nodes` (Array; optional) - `edges` (Array; optional) - `generateImage` (optional): Dictionary specifying options to generate an image of the current cytoscape graph. Value is cleared after data is received and image is generated. This property will be ignored on the initial creation of the cytoscape object and must be invoked through a callback after it has been rendered. If the app does not need the image data server side and/or it will only be used to download the image, it may be prudent to invoke `'download'` for `action` instead of `'store'` to improve performance by preventing transfer of data to the server.. generateImage has the following type: lists containing elements 'type', 'options', 'action', 'filename'. Those elements have the following types: - `type` (a value equal to: 'svg', 'png', 'jpg', 'jpeg'; optional): File type to output - `options` (Dict; optional): Dictionary of options to cy.png() / cy.jpg() or cy.svg() for image generation. See https://js.cytoscape.org/#core/export for details. For `'output'`, only 'base64' and 'base64uri' are supported. Default: `{'output': 'base64uri'}`. - `action` (a value equal to: 'store', 'download', 'both'; optional): `'store'`: Stores the image data (only jpg and png are supported) in `imageData` and invokes server-side Dash callbacks. `'download'`: Downloads the image as a file with all data handling done client-side. No `imageData` callbacks are fired. `'both'`: Stores image data and downloads image as file. The default is `'store'` - `filename` (String; optional): Name for the file to be downloaded. Default: 'cyto'. - `imageData` (String; optional): String representation of the image requested with generateImage. Null if no image was requested yet or the previous request failed. Read-only. - `layout` (optional): A dictionary specifying how to set the position of the elements in your graph. The `'name'` key is required, and indicates which layout (algorithm) to use. The keys accepted by `layout` vary depending on the algorithm, but these keys are accepted by all layouts: `fit`, `padding`, `animate`, `animationDuration`, `boundingBox`. The complete list of layouts and their accepted options are available on the [Cytoscape.js docs](https://js.cytoscape.org/#layouts) . For the external layouts, the options are listed in the "API" section of the README. Note that certain keys are not supported in Dash since the value is a JavaScript function or a callback. Please visit this [issue](https://github.com/plotly/dash-cytoscape/issues/25) for more information.. layout has the following type: lists containing elements 'name', 'fit', 'padding', 'animate', 'animationDuration', 'boundingBox'. Those elements have the following types: - `name` (a value equal to: 'random', 'preset', 'circle', 'concentric', 'grid', 'breadthfirst', 'cose', 'close-bilkent', 'cola', 'euler', 'spread', 'dagre', 'klay'; required): The layouts available by default are: `random`: Randomly assigns positions. `preset`: Assigns position based on the `position` key in element dictionaries. `circle`: Single-level circle, with optional radius. `concentric`: Multi-level circle, with optional radius. `grid`: Square grid, optionally with numbers of `rows` and `cols`. `breadthfirst`: Tree structure built using BFS, with optional `roots`. `cose`: Force-directed physics simulation. Some external layouts are also included. To use them, run `dash_cytoscape.load_extra_layouts()` before creating your Dash app. Be careful about using the extra layouts when not necessary, since they require supplementary bandwidth for loading, which impacts the startup time of the app. The external layouts are: [cose-bilkent](https://github.com/cytoscape/cytoscape.js-cose-bilkent), [cola](https://github.com/cytoscape/cytoscape.js-cola), [euler](https://github.com/cytoscape/cytoscape.js-dagre), [spread](https://github.com/cytoscape/cytoscape.js-spread), [dagre](https://github.com/cytoscape/cytoscape.js-dagre), [klay](https://github.com/cytoscape/cytoscape.js-klay), - `fit` (Bool; optional): Whether to render the nodes in order to fit the canvas. - `padding` (Real; optional): Padding around the sides of the canvas, if fit is enabled. - `animate` (Bool; optional): Whether to animate change in position when the layout changes. - `animationDuration` (Real; optional): Duration of animation in milliseconds, if enabled. - `boundingBox` (Dict; optional): How to constrain the layout in a specific area. Keys accepted are either `x1, y1, x2, y2` or `x1, y1, w, h`, all of which receive a pixel value. - `maxZoom` (Real; optional): A maximum bound on the zoom level of the graph. The viewport can not be scaled larger than this zoom level. - `minZoom` (Real; optional): A minimum bound on the zoom level of the graph. The viewport can not be scaled smaller than this zoom level. - `mouseoverEdgeData` (Dict; optional): The data dictionary of an edge returned when you hover over it. Read-only. - `mouseoverNodeData` (Dict; optional): The data dictionary of a node returned when you hover over it. Read-only. - `pan` (optional): Dictionary indicating the initial panning position of the graph. The following keys are accepted:. pan has the following type: lists containing elements 'x', 'y'. Those elements have the following types: - `x` (Real; optional): The x-coordinate of the node - `y` (Real; optional): The y-coordinate of the node - `panningEnabled` (Bool; optional): Whether panning the graph is enabled (i.e., the position of the graph is mutable overall). - `responsive` (Bool; optional): Toggles intelligent responsive resize of Cytoscape graph with viewport size change - `selectedEdgeData` (Array; optional): The list of data dictionaries of all selected edges (e.g. using Shift+Click to select multiple nodes, or Shift+Drag to use box selection). Read-only. - `selectedNodeData` (Array; optional): The list of data dictionaries of all selected nodes (e.g. using Shift+Click to select multiple nodes, or Shift+Drag to use box selection). Read-only. - `style` (Dict; optional): Add inline styles to the root element. - `stylesheet` (optional): A list of dictionaries representing the styles of the elements. Each dictionary requires the following keys: `selector` and `style`. Both the [selector](https://js.cytoscape.org/#selectors) and the [style](https://js.cytoscape.org/#style/node-body) are exhaustively documented in the Cytoscape.js docs. Although methods such as `cy.elements(...)` and `cy.filter(...)` are not available, the selector string syntax stays the same.. stylesheet has the following type: Array of lists containing elements 'selector', 'style'. Those elements have the following types: - `selector` (String; required): Which elements you are styling. Generally, you select a group of elements (node, edges, both), a class (that you declare in the element dictionary), or an element by ID. - `style` (Dict; required): What aspects of the elements you want to modify. This could be the size or color of a node, the shape of an edge arrow, or many more.s - `tapEdge` (optional): The complete edge dictionary returned when you tap or click it. Read-only.. tapEdge has the following type: lists containing elements 'isLoop', 'isSimple', 'midpoint', 'sourceData', 'sourceEndpoint', 'targetData', 'targetEndpoint', 'timeStamp', 'classes', 'data', 'grabbable', 'group', 'locked', 'selectable', 'selected', 'style'. Those elements have the following types: - `isLoop` (Bool; optional): Edge-specific item - `isSimple` (Bool; optional): Edge-specific item - `midpoint` (Dict; optional): Edge-specific item - `sourceData` (Dict; optional): Edge-specific item - `sourceEndpoint` (Dict; optional): Edge-specific item - `targetData` (Dict; optional): Edge-specific item - `targetEndpoint` (Dict; optional): Edge-specific item - `timeStamp` (Real; optional): Edge-specific item - `classes` (String; optional): General item (for all elements) - `data` (Dict; optional): General item (for all elements) - `grabbable` (Bool; optional): General item (for all elements) - `group` (String; optional): General item (for all elements) - `locked` (Bool; optional): General item (for all elements) - `selectable` (Bool; optional): General item (for all elements) - `selected` (Bool; optional): General item (for all elements) - `style` (Dict; optional): General item (for all elements) - `tapEdgeData` (Dict; optional): The data dictionary of an edge returned when you tap or click it. Read-only. - `tapNode` (optional): The complete node dictionary returned when you tap or click it. Read-only.. tapNode has the following type: lists containing elements 'edgesData', 'renderedPosition', 'timeStamp', 'classes', 'data', 'grabbable', 'group', 'locked', 'position', 'selectable', 'selected', 'style', 'ancestorsData', 'childrenData', 'descendantsData', 'parentData', 'siblingsData', 'isParent', 'isChildless', 'isChild', 'isOrphan', 'relativePosition'. Those elements have the following types: - `edgesData` (Array; optional): node specific item - `renderedPosition` (Dict; optional): node specific item - `timeStamp` (Real; optional): node specific item - `classes` (String; optional): General item (for all elements) - `data` (Dict; optional): General item (for all elements) - `grabbable` (Bool; optional): General item (for all elements) - `group` (String; optional): General item (for all elements) - `locked` (Bool; optional): General item (for all elements) - `position` (Dict; optional): General item (for all elements) - `selectable` (Bool; optional): General item (for all elements) - `selected` (Bool; optional): General item (for all elements) - `style` (Dict; optional): General item (for all elements) - `ancestorsData` (Dict | Array; optional): Item for compound nodes - `childrenData` (Dict | Array; optional): Item for compound nodes - `descendantsData` (Dict | Array; optional): Item for compound nodes - `parentData` (Dict | Array; optional): Item for compound nodes - `siblingsData` (Dict | Array; optional): Item for compound nodes - `isParent` (Bool; optional): Item for compound nodes - `isChildless` (Bool; optional): Item for compound nodes - `isChild` (Bool; optional): Item for compound nodes - `isOrphan` (Bool; optional): Item for compound nodes - `relativePosition` (Dict; optional): Item for compound nodes - `tapNodeData` (Dict; optional): The data dictionary of a node returned when you tap or click it. Read-only. - `userPanningEnabled` (Bool; optional): Whether user events (e.g. dragging the graph background) are allowed to pan the graph. - `userZoomingEnabled` (Bool; optional): Whether user events (e.g. dragging the graph background) are allowed to pan the graph. - `zoom` (Real; optional): The initial zoom level of the graph. You can set `minZoom` and `maxZoom` to set restrictions on the zoom level. - `zoomingEnabled` (Bool; optional): Whether zooming the graph is enabled (i.e., the zoom level of the graph is mutable overall). """ function cyto_cytoscape(; kwargs...) available_props = Symbol[:id, :autoRefreshLayout, :autolock, :autoungrabify, :autounselectify, :boxSelectionEnabled, :className, :elements, :generateImage, :imageData, :layout, :maxZoom, :minZoom, :mouseoverEdgeData, :mouseoverNodeData, :pan, :panningEnabled, :responsive, :selectedEdgeData, :selectedNodeData, :style, :stylesheet, :tapEdge, :tapEdgeData, :tapNode, :tapNodeData, :userPanningEnabled, :userZoomingEnabled, :zoom, :zoomingEnabled] wild_props = Symbol[] return Component("cyto_cytoscape", "Cytoscape", "dash_cytoscape", available_props, wild_props; kwargs...) end
DashCytoscape
https://github.com/plotly/DashCytoscape.jl.git
[ "MIT" ]
0.3.0
553be75f181bf33a0816833e2244b82f3a80da4f
docs
9384
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [0.3.0] - 2021-05-19 ### Added * Contributed initial build of Julia package. * R package now includes an example application for `cytoCytoscape`. ### Changed * Dash has been upgraded to 1.* in requirements.txt and tests/requirements.txt (#123) * React/react-dom have been upgraded to 16.14+ (#117) * Docgen upgraded to 5.3.0 (#117) * Improved prop typing (#117) ### Fixed * Various security fixes ## [0.2.0] - 2020-07-09 ### Added * Contributed initial build of R package. * Added access to cytoscape.js PNG and JPG image generation API through `generateImage` and `imageData` properties (PR [#88](https://github.com/plotly/dash-cytoscape/pull/88)). * Added ability to download image files generated with `generateImage` client-side without sending data to the server (PR [#88](https://github.com/plotly/dash-cytoscape/pull/88)). * Used the newly added `generateImage` and `imageData` properties to enable svg generation using [cytoscape-svg](https://github.com/kinimesi/cytoscape-svg). * Added responsive cytoscape.js graph feature toggled using the `responsive` property (PR [#93](https://github.com/plotly/dash-cytoscape/pull/92)). * One new demo: * `demos/usage-responsive-graph.py`: Example of graph with the ability to toggle the responsive feature on and off. * `demos/usage-image-export.py`: Shows how to export images as JPG, PNG or SVG. ### Changed * Changed the official package manager from `yarn` to `npm`. * `utils.Tree`: v0.1.1 broke compatibility with Python 2. Therefore, modified code to be compatible with Python 2. Added `props` and `edge_props` properties to accept arguments passed directly to the node's and edge's dictionaries, respectively (e.g., 'classes', 'positions', etc.). * Removed `Tree`'s method `add_child`, because it is redundant with `add_children` called with an argument of length 1. * `setup.py`: Remove `dash-html-components` and `dash_renderer` from `install_requires`. * `usage-events.py`: Fix the size of the cytoscape graph to 500px by 500px. * Upgrade `react-cytoscape.js` to latest. ### Fixed * `setup.py`: Use `packages=find_packages(include=[package_name, package_name + ".*"])` so that all subpackages like `utils` will be included when you `pip install dash-cytoscape`. * Issue where `dash-cytoscape` cannot read property of 'length' of undefined when elements is not specified. * `tests.test_interactions`. ## [0.1.1] - 2019-04-05 ### Fixed * Error where `dash_cytoscape.utils` cannot be imported. ## [0.1.0] - 2019-04-05 ### Added * Four new demos: * `demos/usage-dag-edges.py`: Example of edges in a directed acyclic graph (DAG). It uses the new `dash_cytoscape.utils.Tree` class. * `demos/usage-elements-extra.py`: Example of loading external layouts. * `demos/usage-preset-animation.py`: Example of animating nodes using the preset layout. * `demos/usage-reset-button.py`: Example of resetting the graph position using a button. * `demos/usage-remove-selected-elements.py`: Example to show how to remove selected elements with button. * `dash_cytoscape/dash_cytoscape_extra.[min|dev].js`: New bundles containing the extra layouts. Those bundles are double in size compared to the default bundles. Therefore, they are only loaded when the user uses `load_extra_layouts()` to limit bandwidth usage and maximize loading speed. Please view [fast3g-cytoscape](demos/images/fast3g-cytoscape.PNG) for an example of the impact on loading time. * `dash_cytoscape._display_default_values()`: A helper function to display the default prop values by reading `metadata.json`. Useful for documentation. * `dash_cytoscape.load_extra_layouts()`: A function that can be called before initializing the Dash app (`app = dash.Dash(__name__)`) to load the JS bundle containing the external layouts. * `src/lib/extra_index.js`: Loads external layouts before exporting the `Cytoscape` class. Needed to generate the new bundles. * `webpack.[dev|prod].extra.config.js`: Two new webpack config files for external layouts. * Images of new external layouts. * The ability for the user to feed a dictionary with keys `nodes` and `edges` to the `elements` prop of `Cytoscape`, instead of a list. The values corresponding to these keys will be, respectively, lists of nodes and edges in the graph. ### Changed * `usage-events.py`: Added IDs for the edges in order to pass Percy tests. * `src/lib/components/Cytoscape.react.js`: Updated component docstring to include information about new external layouts and a warning about nodes that can't be modified by a callback. Added more default props for a better expected behavior. * `package.json`: Added new builds for the extra layouts, modified `npm build:all` to include new builds. Added external layouts as dependencies. * `MANIFEST.in`: Included new `dash_cytoscape.[min|dev].js` files. * `README.md`: Moved images, added more images at the end, added useful links. ### Fixed * Removing selected elements will now cause the corresponding JSON data to be cleared. Fixed by [PR #49](https://github.com/plotly/dash-cytoscape/pull/49), fixes [issue #45](https://github.com/plotly/dash-cytoscape/issues/45). ## [0.0.5] - 2019-03-08 ### Added * Two new demos: `usage-grid-social-network.py` and `usage-concentric-social-network.py` * Add Issue and PR templates for Github (located in `.github`) * `tests.test_usage`: Tests for rendering usage files. * `tests.test_callbacks`: Tests for updating `Cytoscape` with callbacks. * `tests.test_interactions`: Tests for interacting with `Cytoscape`, and evaluating its event callbacks. * `tests.test_percy_snapshot`: Creates a Percy build using screenshots from other tests. ### Changed * `usage-*.py`: Modified all the import statements from `import dash_cytoscape` to `import dash_cytoscape as cyto`. Optimized imports. They are now linted with pylint/flake8. * `demos/usage-*`: Formatted all demo apps in order to respect pylint and flake8. * `usage-phylogeny.py`: Clear callback conditional statement * `CONTRIBUTING.md`: changed `dash-cytoscape-0.0.1` to `dash-cytoscape-x.x.x`. Added a **Code quality & design** section. Changed the **Making a contribution** section and updated title to **Publishing**. Updated **Pre-Release checklist**. Added the **Development** section from `README.md` (renamed **Setting up the environment**). Added a **Tests** section. * `npmignore`: Added `venv` to avoid venvs to be included in the npm distribution package, which makes us a large amount of space and many unnecessary files being distributed. * `config.yml`: Added steps to run the new tests. Added coverage for Python 3.7. Included `demos` and all usage examples in `pylint` and `flake8`. Increased line limit to 100. * `README.md`: Moved the **Development** section to `CONTRIBUTING.md`. Modified the dash version in **Prerequisites**. * `requirements.txt`: Updated the dash version to latest. * `tests/requiremens.txt`: Updated the dash version to latest. * `package.json`: Removed `"prepublish": "npm run validate-init"` due to conflict with CircleCI build. This script will be deprecated in favor of the upcoming Dash Component CLI. * `tests/IntegrationTests.py`: Moved the `percy_snapshot` method to `test_percy_snapshot` in order to avoid duplicate (failing) builds on Percy. Decrease the number of processes to 1. * `setup.py`: Added classifiers and download_url. ### Removed * `extract-meta.js`, `extract-meta` - they were moved to the dash component CLI, thus are not needed anymore * `config.py`, `runtime.txt`, `Procfile`, `index.html` - only needed for hosting `usage-*.py` on DDS, they are now moved to `plotly/dash-cytoscape-demos`. * `review_checklist.md` - redundant since all the information is already contained in CONTRIBUTING.md * `tests.test_render`: Removed unused test ## [0.0.4] - 2019-01-19 ### Added * Homepage URL for PyPi * Long Description for PyPi ### Changed * Cytoscape component docstring for thorough and well-formatted references (#26) * Refactored code base to match the up-to-date version of `dash-component-boilerplate` (#27) ### Fixed * Console error where `setProps` gets called even when it is undefined (# 28) * Incorrect setProps assignment that causes `setProps` to not be properly defined when nested in bigger apps (e.g. `dash-docs`) (#28) ## [0.0.3] - 2018-12-29 ### Added * Detailed usage example for rendering Biopython's Phylo object (phylogeny trees) into a Cytoscape graph, with interactive features such as highlighting. ### Updated * React-Cytoscapejs version, from 1.0.1 to 1.1.0 ## [0.0.2] - 2018-11-08 ### Added * Author email and improve description * Data section of demos readme * Added the components "dash", "dash-html-components", and "dash-renderer" as explicit package requirements. ### Changed * Move grid layout data file * Change App.js react demo data to be local * Installation steps in readme to use yarn ### Updated * Cytoscape.js version, correct component import ### Fixed * Correct unpkg link error * Markdown formatting for CONTRIBUTING.md ## [0.0.1] - 2018-11-03 ### Added - First pre-release version of dash-cytoscape. Still WIP, so prepare to see it break πŸ”§
DashCytoscape
https://github.com/plotly/DashCytoscape.jl.git
[ "MIT" ]
0.3.0
553be75f181bf33a0816833e2244b82f3a80da4f
docs
3885
# Dash Cytoscape [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/plotly/DashCytoscape.jl/blob/main/LICENSE) A Dash component library for creating interactive and customizable networks in Julia, wrapped around [Cytoscape.js](http://js.cytoscape.org/). ![usage-stylesheet-demo](https://raw.githubusercontent.com/plotly/dash-cytoscape/master/demos/images/usage-stylesheet-demo.gif) * 🌟 [Medium Article](https://medium.com/@plotlygraphs/introducing-dash-cytoscape-ce96cac824e4) * πŸ“£ [Community Announcement](https://community.plotly.com/t/announcing-dash-cytoscape/19095) * πŸ’» [Github Repository](https://github.com/plotly/DashCytoscape.jl) * πŸ“š [User Guide](https://dash-julia-docs.herokuapp.com/cytoscape) * πŸ—Ί [Component Reference](https://dash-julia-docs.herokuapp.com/cytoscape/reference) * πŸ“Ί [Webinar Recording](https://www.youtube.com/watch?v=snXcIsCMQgk) ## Documentation The [Dash Cytoscape User Guide](https://dash.plotly.com/cytoscape/) contains everything you need to know about the library. It contains useful examples, functioning code, and is fully interactive. You can also use the [component reference](https://dash.plotly.com/cytoscape/reference/) for a complete and concise specification of the API. To learn more about the core Dash components and how to use callbacks, view the [Dash documentation](https://dash.plotly.com/). For supplementary information about the underlying Javascript API, view the [Cytoscape.js documentation](http://js.cytoscape.org/). ## Contributing Make sure that you have read and understood our [code of conduct](CODE_OF_CONDUCT.md), then head over to [CONTRIBUTING](CONTRIBUTING.md) to get started. ### Testing Instructions on how to run [tests](CONTRIBUTING.md#tests) are given in [CONTRIBUTING.md](CONTRIBUTING.md). ## License Dash, Cytoscape.js and Dash Cytoscape are licensed under MIT. Please view [LICENSE](LICENSE) for more details. ## Contact and Support See https://plotly.com/dash/support for ways to get in touch. ## Acknowledgments Huge thanks to the Cytoscape Consortium and the Cytoscape.js team for their contribution in making such a complete API for creating interactive networks. This library would not have been possible without their massive work! The Pull Request and Issue Templates were inspired from the [scikit-learn project](https://github.com/scikit-learn/scikit-learn). ## Gallery ### Dynamically expand elements [Code](usage-elements.py) | [Demo](https://dash-gallery.plotly.host/cytoscape-elements) ![View usage-elements on Github](demos/images/usage-elements-demo.gif) ### Interactively update stylesheet [Code](usage-stylesheet.py) | [Demo](https://dash-gallery.plotly.host/cytoscape-stylesheet) ![View usage-stylesheet on Github](demos/images/usage-stylesheet.gif) ### Automatically generate interactive phylogeny trees [Code](demos/usage-phylogeny.py) | [Demo](https://dash-gallery.plotly.host/cytoscape-phylogeny/) ![View usage-phylogeny on Github](demos/images/usage-phylogeny.gif) ### Create your own stylesheet [Code](usage-advanced.py) | [Demo](https://dash-gallery.plotly.host/cytoscape-advanced) ![View usage-advanced on Github](demos/images/usage-advanced.gif) ### Use event callbacks [Code](usage-events.py) | [Demo](https://dash-gallery.plotly.host/cytoscape-events) ![View usage-events on Github](demos/images/usage-events.gif) ### Use external layouts [Code](demos/usage-elements-extra.py) ![View usage-elements-extra on Github](demos/images/usage-elements-extra.gif) ### Use export graph as image [Code](demos/usage-image-export.py) ![View usage-image-export on Github](demos/images/usage-image-export.gif) ### Make graph responsive [Code](demos/usage-responsive-graph.py) ![View usage-responsive-graph on Github](demos/images/usage-responsive-graph.gif) For an extended gallery, visit the [demos' readme](demos/README.md).
DashCytoscape
https://github.com/plotly/DashCytoscape.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
2043
include("../examples/smiley_examples.jl") using .SmileyExample22, .SmileyExample52, .SmileyExample54, .SmileyExample55 using BenchmarkTools using ForwardDiff using IntervalArithmetic using IntervalRootFinding import Random const SUITE = BenchmarkGroup() Random.seed!(0) # Seed the RNG to get consistent results tol = 1e-15 include("dietmar_ratz_functions.jl") S = SUITE["Smiley"] = BenchmarkGroup() for example in (SmileyExample22, SmileyExample52, SmileyExample54) #, SmileyExample55) s = S[example.title] = BenchmarkGroup() for method in (Newton, Krawczyk) s[string(method)] = @benchmarkable roots($(example.f), $(example.region), $method, $tol) end end S = SUITE["Rastigrin stationary points"] = BenchmarkGroup() # Rastrigin function: const A = 10 f(x, y) = 2A + x^2 - A*cos(2Ο€*x) + y^2 - A*cos(2Ο€*y) f(X) = f(X...) ForwardDiff.gradient(f, X::IntervalBox) = ForwardDiff.gradient(f, X.v) βˆ‡f = X -> ForwardDiff.gradient(f, X) L = 5.0 X = IntervalBox(-L..(L+1), 2) for method in (Newton, Krawczyk) S[string(method)] = @benchmarkable roots($(βˆ‡(f)), $X, $method, 1e-5) end S = SUITE["Linear equations"] = BenchmarkGroup() sizes = (2, 5, 10) for n in sizes s = S["n = $n"] = BenchmarkGroup() A = Interval.(randn(n, n)) b = Interval.(randn(n)) s["Gauss seidel"] = @benchmarkable gauss_seidel_interval($A, $b) s["Gauss seidel contractor"] = @benchmarkable gauss_seidel_contractor($A, $b) s["Gauss elimination"] = @benchmarkable gauss_elimination_interval($A, $b) end S = SUITE["Dietmar-Ratz"] = BenchmarkGroup() X = Interval(0.75, 1.75) for (k, dr) in enumerate(dr_functions) s = S["Dietmar-Ratz $k"] = BenchmarkGroup() if k != 8 # dr8 is excluded as it has too many roots for method in (Newton, Krawczyk) s[string(method)] = @benchmarkable roots($dr, $X, $method, $tol) end end s["Automatic differentiation"] = @benchmarkable ForwardDiff.derivative($dr, $X) s["Slope expansion"] = @benchmarkable slope($dr, $X, $(mid(X))) end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
480
# Example functions from Dietmar Ratz - An Optimized Interval Slope Arithmetic and its Application dr1(x) = (x + sin(x)) * exp(-x^2) dr2(x) = x^4 - 10x^3 + 35x^2 - 50x + 24 dr3(x) = (log(x + 1.25) - 0.84x) ^ 2 dr4(x) = 0.02x^2 - 0.03exp(-(20(x - 0.875))^2) dr5(x) = exp(x^2) dr6(x) = x^4 - 12x^3 + 47x^2 - 60x - 20exp(-x) dr7(x) = x^6 - 15x^4 + 27x^2 + 250 dr8(x) = atan(cos(tan(x))) dr9(x) = asin(cos(acos(sin(x)))) dr_functions = [dr1, dr2, dr3, dr4, dr5, dr6, dr7, dr8, dr9]
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
652
using Documenter using IntervalArithmetic, IntervalRootFinding makedocs( modules = [IntervalRootFinding], doctest = true, format = Documenter.HTML(prettyurls = get(ENV, "CI", nothing) == "true"), sitename = "IntervalRootFinding.jl", authors = "David P. Sanders and Luis Benet", pages = Any[ "Home" => "index.md", "`roots` interface" => "roots.md", "Internals" => "internals.md", "Bibliography" => "biblio.md", "API" => "api.md" ] ) deploydocs( repo = "github.com/JuliaIntervals/IntervalRootFinding.jl.git", target = "build", deps = nothing, make = nothing )
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
1998
# Examples from Luc Jaulin, Michel Kieffer, Olivier Didrit and Eric Walter - Applied Interval Analysis using IntervalArithmetic, IntervalRootFinding, StaticArrays A = [4..5 -1..1 1.5..2.5; -0.5..0.5 -7.. -5 1..2; -1.5.. -0.5 -0.7.. -0.5 2..3] sA = SMatrix{3}{3}(A) mA = MMatrix{3}{3}(A) b = [3..4, 0..2, 3..4] sb = SVector{3}(b) mb = MVector{3}(b) p = fill(-1e16..1e16, 3) rts = gauss_seidel_interval!(p, A, b, precondition=true) # Gauss-Seidel Method; precondition=true by default rts = gauss_seidel_interval!(p, sA, sb, precondition=true) # Gauss-Seidel Method; precondition=true by default rts = gauss_seidel_interval!(p, mA, mb, precondition=true) # Gauss-Seidel Method; precondition=true by default rts = gauss_seidel_interval(A, b, precondition=true) # Gauss-Seidel Method; precondition=true by default rts = gauss_seidel_interval(sA, sb, precondition=true) # Gauss-Seidel Method; precondition=true by default rts = gauss_seidel_interval(mA, mb, precondition=true) # Gauss-Seidel Method; precondition=true by default rts = gauss_seidel_contractor!(p, A, b, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default rts = gauss_seidel_contractor!(p, sA, sb, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default rts = gauss_seidel_contractor!(p, mA, mb, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default rts = gauss_seidel_contractor(A, b, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default rts = gauss_seidel_contractor(sA, sb, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default rts = gauss_seidel_contractor(mA, mb, precondition=true) # Gauss-Seidel Method (Vectorized); precondition=true by default rts = gauss_elimination_interval!(p, A, b, precondition=true) # Gaussian Elimination; precondition=true by default rts = gauss_elimination_interval(A, b, precondition=true) # Gaussian Elimination; precondition=true by default
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
2713
using IntervalArithmetic using IntervalRootFinding ## # Available strategies ## f(x) = sin(x) contractor = Newton(f, cos) @info "Breadth first search." # A search takes a starting region, a contractor and a tolerance as argument search = BreadthFirstSearch(-10..10, contractor, 1e-10) # This is needed to avoid the data being discarded at the end of the loop use # `local tree` instead inside a function. global endtree for (k, tree) in enumerate(search) println("Tree at iteration $k") println(tree) # The tree has custom printing global endtree = tree end rts = data(endtree) # Use `data` to only get the leaves marked as `:final` println("Final $(length(rts)) roots: $rts") println() @info "Depth first search." # The second available type of root search is depth first search = DepthFirstSearch(-10..10, contractor, 1e-10) for tree in search global endtree = tree end # Go to the end of the iteration # Since the index of each node is printed and indices are attributed in the # order nodes are processed, comparing this tree with the last iteration of the # preceding show the difference between breadth first and depth first searches. println(endtree) ## # Custom strategy ## # Define custom BBSearch that store empty intervals rather than discarding it # Functions of the interface must be explicitely imported import IntervalRootFinding struct MySearch{R <: Region, C <: Contractor, T <: Real} <: BreadthFirstBBSearch{Root{R}} initial::Root{R} contractor::C tol::T end # This must be implemented, other functions needed are already implemented for # BBSearch using Root as data (bisect function) or the general fallback match # this case (root_element function) function IntervalRootFinding.process(search::MySearch, r::Root) contracted_root = search.contractor(r, search.tol) status = root_status(contracted_root) # We only store the unrefined intervals so the final intervals cover all # the initial region unrefined_root = Root(r.interval, status) status == :unique && return :store, unrefined_root status == :empty && return :store, unrefined_root # Store largest known empty intervals status == :unknown && diam(contracted_root) < search.tol && return :store, unrefined_root return :bisect, unrefined_root # Always bisect the original interval to bypass [NaN, NaN] end @info "Search with no interval discarded." search = MySearch(Root(-10..10, :unknown), contractor, 1e-10) for tree in search global endtree = tree end # Go to the end of the iteration # In these tree we can see that the union of the resulting intervals (including # those containing no solution) covers the starting interval. println(endtree)
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
1704
using IntervalArithmetic, IntervalRootFinding, StaticArrays rts = roots(sin, -5..5) rts = roots(sin, -5..6, Bisection) rts = roots(sin, rts, Newton) # 2D: f(x, y) = SVector(x^2 + y^2 - 1, y - x) f(X) = f(X...) rts = roots(f, (-5..5) Γ— (-5..5)) rts = roots(f, rts, Bisection) # complex: x = -5..6 Xc = Complex(x, x) f(z) = z^3 - 1 rts = roots(f, Xc, Bisection) rts = roots(f, rts, Newton) rts = roots(f, Xc) # From R docs: # https://www.rdocumentation.org/packages/pracma/versions/1.9.9/topics/broyden function g(x) (x1, x2, x3) = x SVector( x1^2 + x2^2 + x3^2 - 1, x1^2 + x3^2 - 0.25, x1^2 + x2^2 - 4x3 ) end X = (-5..5) @time rts = roots(g, X Γ— X Γ— X) h(xv) = ((x,y) = xv; SVector(2*x - y - exp(-x), -x + 2*y - exp(-y))) rts = roots(h, X Γ— X, Bisection) rts = roots(h, rts, Newton) # Dennis-Schnabel: h(xv) = ((x, y) = xv; SVector(x^2 + y^2 - 2, exp(x - 1) + y^3 - 2)) rts = roots(h, X Γ— X, Bisection) rts = roots(h, rts, Newton) # Test suites: # http://folk.uib.no/ssu029/Pdf_file/Testproblems/testprobRheinboldt03.pdf # http://www.mat.univie.ac.at/~neum/glopt/test.html # http://titan.princeton.edu/TestProblems/ # http://www-sop.inria.fr/saga/POL/ ## MINPACK benchmarks: https://github.com/JuliaNLSolvers/NLsolve.jl/blob/master/test/minpack.jl rosenbrock(x, y) = SVector( 1 - x, 10 * (y - x^2) ) rosenbrock(X) = rosenbrock(X...) rosenbrock(xx) = ( (x, y) = xx; SVector( 1 - x, 1000 * (y - x^2) ) ) X = IntervalBox(-1e5..1e5, 2) rts = roots(rosenbrock, X) # and other files in NLsolve test suite # Testing unconstrained optimization software, MorΓ©, Garbow, Hillstrom ACM Trans. Math. Soft. 7 (1), 17-41 (1981)
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
8460
# examples from # M. W. Smiley and C. Chun, J. Comput. Appl. Math. **137**, 293 (2001). # https://doi.org/10.1016/S0377-0427(00)00711-1 module SmileyExample22 using IntervalArithmetic using StaticArrays const title = "Smiley and Chun (2001), Example 2.2" f(x) = SVector( x[1]^2 + 4 * x[2]^2 - 4, x[2] * (x[1] - 1.995) * (x[2] - x[1]^2) * (x[2] - x[1] + 1) ) # contains all 8 reported roots const region = IntervalBox(-3..3, -3..3) # only three roots are reported explicitely: # (2, 0) and (1.995, ±0.071) end module SmileyExample52 using IntervalArithmetic using StaticArrays const title = "Smiley and Chun (2001), Example 5.2" const c0 = 1 const a0 = 0.5 const b0 = 0.5 const d01 = 0.2 const d02 = -0.7 const r1 = 1 const r2 = 2 const m = 3 const θs = [i * pi / m for i in 1:m] _v(θ) = -(a0 * cos(θ) + b0 * sin(θ)) / c0 const vs = _v.(θs) _a(θ, v) = b0 * v - c0 * sin(θ) const as = _a.(θs, vs) _b(θ, v) = c0 * cos(θ) - a0 * v const bs = _b.(θs, vs) _c(θ) = a0 * sin(θ) - b0 * cos(θ) const cs = _c.(θs) _d(c) = d01 * c / c0 const ds = _d.(cs) f(x) = SVector( (x[1]^2 + x[2]^2 + x[3]^2 - r1^2) * (x[1]^2 + x[2]^2 + x[3]^2 - r2^2), (a0 * x[1] + b0 * x[2] + c0 * x[3] - d01) * (a0 * x[1] + b0 * x[2] + c0 * x[3] - d02), prod(as[i] * x[1] + bs[i] * x[2] + cs[i] * x[3] - ds[i] for i in 1:m) ) # contains all 24 reported roots const region = IntervalBox(-3..3, -3..3, -3..3) const known_roots = [ IntervalBox(-1.933009 ± 1e-6, -0.300000 ± 1e-6, 0.416504 ± 1e-6), IntervalBox(-1.701684 ± 1e-6, 0.000000 ± 1e-6, 1.050842 ± 1e-6), IntervalBox(-1.258803 ± 1e-6, 1.360696 ± 1e-6, -0.750946 ± 1e-6), IntervalBox(-1.044691 ± 1e-6, -1.589843 ± 1e-6, 0.617267 ± 1e-6), IntervalBox(-0.996600 ± 1e-6, 1.726162 ± 1e-6, -0.164780 ± 1e-6), IntervalBox(-0.951026 ± 1e-6, -0.300000 ± 1e-6, -0.074486 ± 1e-6), IntervalBox(-0.800000 ± 1e-6, -0.000000 ± 1e-6, 0.600000 ± 1e-6), IntervalBox(-0.776373 ± 1e-6, -1.344718 ± 1e-6, 1.260546 ± 1e-6), IntervalBox(-0.717665 ± 1e-6, 0.423418 ± 1e-6, -0.552876 ± 1e-6), IntervalBox(-0.592072 ± 1e-6, -0.805884 ± 1e-6, -0.001021 ± 1e-6), IntervalBox(-0.499927 ± 1e-6, 0.865900 ± 1e-6, 0.017013 ± 1e-6), IntervalBox(-0.360640 ± 1e-6, -0.624646 ± 1e-6, 0.692643 ± 1e-6), IntervalBox( 0.082249 ± 1e-6, -0.962075 ± 1e-6, -0.260086 ± 1e-6), IntervalBox( 0.085220 ± 1e-6, 0.367221 ± 1e-6, -0.926221 ± 1e-6), IntervalBox( 0.453788 ± 1e-6, 0.785984 ± 1e-6, -0.419886 ± 1e-6), IntervalBox( 0.464511 ± 1e-6, -0.804557 ± 1e-6, 0.370022 ± 1e-6), IntervalBox( 0.511026 ± 1e-6, -0.300000 ± 1e-6, -0.805513 ± 1e-6), # the following two roots are suspect, first column probably reported in error #IntervalBox( 0.623386 ± 1e-6, 1.151180 ± 1e-6, -1.544510 ± 1e-6), #IntervalBox( 0.869521 ± 1e-6, -1.899353 ± 1e-6, -0.062016 ± 1e-6), IntervalBox( 0.537839 ± 1e-6, 1.151180 ± 1e-6, -1.544510 ± 1e-6), IntervalBox( 0.623386 ± 1e-6, -1.899353 ± 1e-6, -0.062016 ± 1e-6), IntervalBox( 0.869521 ± 1e-6, 1.506056 ± 1e-6, -0.987788 ± 1e-6), IntervalBox( 0.960000 ± 1e-6, 0.000000 ± 1e-6, -0.280000 ± 1e-6), IntervalBox( 0.961183 ± 1e-6, -1.664819 ± 1e-6, 0.551817 ± 1e-6), IntervalBox( 1.493009 ± 1e-6, -0.300000 ± 1e-6, -1.296504 ± 1e-6), IntervalBox( 1.861684 ± 1e-6, 0.000000 ± 1e-6, -0.730842 ± 1e-6), ] end # example 5.4, rescaled form module SmileyExample54 using IntervalArithmetic using StaticArrays const title = "Smiley and Chun (2001), Example 5.4" const c11 = 1.069e-5 const c12 = 2e2 const c13 = 1e5 const c14 = -1.8e5 const c15 = -1.283e-4 const c21 = 2e-2 const c22 = 1e1 const c23 = -1e1 f(t) = SVector( c11 * t[1]^4 + c12 * t[1]^3 * t[2] + c13 * t[1]^3 + c14 * t[1] + c15, c21 * t[1] * t[2]^2 + c22 * t[2]^2 + c23 ) # contains all 7 reported roots const region = IntervalBox(-5.1e2..1.4, -5.1e2..1.1) const known_roots = [ IntervalBox(-1.34298 ± 1e-5, -1.00134 ± 1e-5), IntervalBox(-1.34030 ± 1e-5, 1.00134 ± 1e-5), IntervalBox( 1.34030 ± 1e-5, 0.99866 ± 1e-5), IntervalBox( 1.34298 ± 1e-5, -0.99866 ± 1e-5), # following three roots are not reported precisely IntervalBox(-7e-10 ± 1e-10, 1 ± 1e-5), IntervalBox(-7e-10 ± 1e-10, -1 ± 1e-5), IntervalBox(-5e2 ± 1, -5e2 ± 1) ] end module SmileyExample55 using IntervalArithmetic using StaticArrays const title = "Smiley and Chun (2001), Example 5.5" const μ1 = pi / 10 const μ2 = pi / 5 const α = 5 const D1 = exp(-2μ1) const D2 = exp(-2μ2) const C1 = (1 - D1) / 2μ1 const C2 = (1 - D2) / 2μ2 g(x) = SVector(C1 * (x[3] - α * sin(x[1]) * cos(x[2])) + x[1], C2 * (x[4] - α * cos(x[1]) * sin(x[2])) + x[2], D1 * (x[3] - α * sin(x[1]) * cos(x[2])), D2 * (x[4] - α * cos(x[1]) * sin(x[2]))) f(x) = (g ∘ g)(x) .- SVector(x...) # contains all 41 reported roots of f const region = IntervalBox(-1.02pi..1.02pi, -1.02pi..1.02pi, -0.5pi..0.5pi, -0.5pi..0.5pi) # roots from # C. S. Hsu and R. S. Guttalu, Trans. ASME **50**, 858 (1983). # http://dx.doi.org/10.1115/1.3167157 const known_roots = [ # period 1 points IntervalBox(-pi ± 0, -pi ± 0, 0 ± 0, 0 ± 0), IntervalBox(-pi ± 0, 0 ± 0, 0 ± 0, 0 ± 0), IntervalBox(-pi ± 0, pi ± 0, 0 ± 0, 0 ± 0), IntervalBox(-0.5pi ± 0, -0.5pi ± 0, 0 ± 0, 0 ± 0), IntervalBox(-0.5pi ± 0, 0.5pi ± 0, 0 ± 0, 0 ± 0), IntervalBox( 0 ± 0, -pi ± 0, 0 ± 0, 0 ± 0), IntervalBox( 0 ± 0, 0 ± 0, 0 ± 0, 0 ± 0), IntervalBox( 0 ± 0, pi ± 0, 0 ± 0, 0 ± 0), IntervalBox( 0.5pi ± 0, -0.5pi ± 0, 0 ± 0, 0 ± 0), IntervalBox( 0.5pi ± 0, 0.5pi ± 0, 0 ± 0, 0 ± 0), IntervalBox( pi ± 0, -pi ± 0, 0 ± 0, 0 ± 0), IntervalBox( pi ± 0, 0 ± 0, 0 ± 0, 0 ± 0), IntervalBox( pi ± 0, pi ± 0, 0 ± 0, 0 ± 0), # period 2 points IntervalBox( (0.33419 ± 1e-5)pi, 0 ± 0, (0.48025 ± 1e-5)pi, 0 ± 0), IntervalBox(-(0.33419 ± 1e-5)pi, 0 ± 0, -(0.48025 ± 1e-5)pi, 0 ± 0), IntervalBox( 0 ± 0, (0.24702 ± 1e-5)pi, 0 ± 0, (0.24699 ± 1e-5)pi), IntervalBox( 0 ± 0, -(0.24702 ± 1e-5)pi, 0 ± 0, -(0.24699 ± 1e-5)pi), IntervalBox( (0.09648 ± 1e-5)pi, (0.18318 ± 1e-5)pi, (0.13864 ± 1e-5)pi, (0.18316 ± 1e-5)pi), IntervalBox(-(0.09648 ± 1e-5)pi, -(0.18318 ± 1e-5)pi, -(0.13864 ± 1e-5)pi, -(0.18316 ± 1e-5)pi), IntervalBox(-(0.09648 ± 1e-5)pi, (0.18318 ± 1e-5)pi, -(0.13864 ± 1e-5)pi, (0.18316 ± 1e-5)pi), IntervalBox( (0.09648 ± 1e-5)pi, -(0.18318 ± 1e-5)pi, (0.13864 ± 1e-5)pi, -(0.18316 ± 1e-5)pi), IntervalBox(-(0.66580 ± 1e-5)pi, -(1 ± 0)pi, (0.48025 ± 1e-5)pi, 0 ± 0), IntervalBox( (0.66580 ± 1e-5)pi, -(1 ± 0)pi, -(0.48025 ± 1e-5)pi, 0 ± 0), IntervalBox(-(0.66580 ± 1e-5)pi, (1 ± 0)pi, (0.48025 ± 1e-5)pi, 0 ± 0), IntervalBox( (0.66580 ± 1e-5)pi, (1 ± 0)pi, -(0.48025 ± 1e-5)pi, 0 ± 0), IntervalBox( (1 ± 0)pi, -(0.75298 ± 1e-5)pi, 0 ± 0, (0.24699 ± 1e-5)pi), IntervalBox( (1 ± 0)pi, (0.75298 ± 1e-5)pi, 0 ± 0, -(0.24699 ± 1e-5)pi), IntervalBox(-(1 ± 0)pi, -(0.75298 ± 1e-5)pi, 0 ± 0, (0.24699 ± 1e-5)pi), IntervalBox(-(1 ± 0)pi, (0.75298 ± 1e-5)pi, 0 ± 0, -(0.24699 ± 1e-5)pi), IntervalBox( (0.90352 ± 1e-5)pi, (0.81682 ± 1e-5)pi, -(0.13864 ± 1e-5)pi, -(0.18316 ± 1e-5)pi), IntervalBox(-(0.90352 ± 1e-5)pi, -(0.81682 ± 1e-5)pi, (0.13864 ± 1e-5)pi, (0.18316 ± 1e-5)pi), IntervalBox( (0.90352 ± 1e-5)pi, -(0.81682 ± 1e-5)pi, -(0.13864 ± 1e-5)pi, (0.18316 ± 1e-5)pi), IntervalBox(-(0.90352 ± 1e-5)pi, (0.81682 ± 1e-5)pi, (0.13864 ± 1e-5)pi, -(0.18316 ± 1e-5)pi), IntervalBox( (0.34989 ± 1e-5)pi, -(0.64408 ± 1e-5)pi, -(0.21572 ± 1e-5)pi, -(0.14406 ± 1e-5)pi), IntervalBox( (0.65011 ± 1e-5)pi, -(0.35592 ± 1e-5)pi, (0.21572 ± 1e-5)pi, (0.14406 ± 1e-5)pi), IntervalBox( (0.34989 ± 1e-5)pi, (0.64408 ± 1e-5)pi, -(0.21572 ± 1e-5)pi, (0.14406 ± 1e-5)pi), IntervalBox( (0.65011 ± 1e-5)pi, (0.35592 ± 1e-5)pi, (0.21572 ± 1e-5)pi, -(0.14406 ± 1e-5)pi), IntervalBox(-(0.34989 ± 1e-5)pi, -(0.64408 ± 1e-5)pi, (0.21572 ± 1e-5)pi, -(0.14406 ± 1e-5)pi), IntervalBox(-(0.65011 ± 1e-5)pi, -(0.35592 ± 1e-5)pi, -(0.21572 ± 1e-5)pi, (0.14406 ± 1e-5)pi), IntervalBox(-(0.34989 ± 1e-5)pi, (0.64408 ± 1e-5)pi, (0.21572 ± 1e-5)pi, (0.14406 ± 1e-5)pi), IntervalBox(-(0.65011 ± 1e-5)pi, (0.35592 ± 1e-5)pi, -(0.21572 ± 1e-5)pi, -(0.14406 ± 1e-5)pi) ] end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
1795
using BenchmarkTools, Compat, DataFrames, IntervalRootFinding, IntervalArithmetic, StaticArrays function randVec(n::Int) a = randn(n) A = Interval.(a) mA = MVector{n}(A) sA = SVector{n}(A) return A, mA, sA end function randMat(n::Int) a = randn(n, n) A = Interval.(a) mA = MMatrix{n, n}(A) sA = SMatrix{n, n}(A) return A, mA, sA end function benchmark(max=10) df = DataFrame() df[:Method] = ["Array", "MArray", "SArray", "Contractor", "ContractorMArray", "ContractorSArray"] for n in 1:max A, mA, sA = randMat(n) b, mb, sb = randVec(n) t1 = @belapsed gauss_seidel_interval($A, $b) t2 = @belapsed gauss_seidel_interval($mA, $mb) t3 = @belapsed gauss_seidel_interval($sA, $sb) t4 = @belapsed gauss_seidel_contractor($A, $b) t5 = @belapsed gauss_seidel_contractor($mA, $mb) t6 = @belapsed gauss_seidel_contractor($sA, $sb) df[Symbol("$n")] = [t1, t2, t3, t4, t5, t6] end a = [] for i in 1:max push!(a, Symbol("$i")) end df1 = stack(df, a) dfnew = unstack(df1, :variable, :Method, :value) dfnew = rename(dfnew, :variable => :n) println(dfnew) dfnew end function benchmark_elimination(max=10) df = DataFrame() df[:Method] = ["Gauss Elimination", "Base.\\"] for n in 1:max A, mA, sA = randMat(n) b, mb, sb = randVec(n) t1 = @belapsed gauss_elimination_interval($A, $b) t2 = @belapsed gauss_elimination_interval1($A, $b) df[Symbol("$n")] = [t1, t2] end a = [] for i in 1:max push!(a, Symbol("$i")) end df1 = stack(df, a) dfnew = unstack(df1, :variable, :Method, :value) dfnew = rename(dfnew, :variable => :n) println(dfnew) dfnew end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
2148
using BenchmarkTools, Compat, DataFrames, IntervalRootFinding, IntervalArithmetic, StaticArrays function benchmark_results() f = [] # Example functions from Dietmar Ratz - An Optimized Interval Slope Arithmetic and its Application push!(f, x->((x + sin(x)) * exp(-x^2))) push!(f, x->(x^4 - 10x^3 + 35x^2 - 50x + 24)) push!(f, x->((log(x + 1.25) - 0.84x) ^ 2)) push!(f, x->(0.02x^2 - 0.03exp(-(20(x - 0.875))^2))) push!(f, x->(exp(x^2))) push!(f, x->(x^4 - 12x^3 + 47x^2 - 60x - 20exp(-x))) push!(f, x->(x^6 - 15x^4 + 27x^2 + 250)) push!(f, x->(atan(cos(tan(x))))) push!(f, x->(asin(cos(acos(sin(x)))))) s = interval(0.75, 1.75) df = DataFrame() df[:Method] = ["Automatic Differentiation", "Slope Expansion"] for n in 1:length(f) t1 = ForwardDiff.derivative(f[n], s) t2 = slope(f[n], s, mid(s)) df[Symbol("f" * "$n")] = [t1, t2] end a = [] for i in 1:length(f) push!(a, Symbol("f" * "$i")) end df1 = stack(df, a) dfnew = unstack(df1, :variable, :Method, :value) dfnew = rename(dfnew, :variable => :Function) println(dfnew) dfnew end function benchmark_time() f = [] push!(f, x->((x + sin(x)) * exp(-x^2))) push!(f, x->(x^4 - 10x^3 + 35x^2 - 50x + 24)) push!(f, x->((log(x + 1.25) - 0.84x) ^ 2)) push!(f, x->(0.02x^2 - 0.03exp(-(20(x - 0.875))^2))) push!(f, x->(exp(x^2))) push!(f, x->(x^4 - 12x^3 + 47x^2 - 60x - 20exp(-x))) push!(f, x->(x^6 - 15x^4 + 27x^2 + 250)) push!(f, x->(atan(cos(tan(x))))) push!(f, x->(asin(cos(acos(sin(x)))))) s = interval(0.75, 1.75) df = DataFrame() df[:Method] = ["Automatic Differentiation", "Slope Expansion"] for n in 1:length(f) t1 = @belapsed ForwardDiff.derivative($f[$n], $s) t2 = @belapsed slope($f[$n], $s, mid($s)) df[Symbol("f" * "$n")] = [t1, t2] end a = [] for i in 1:length(f) push!(a, Symbol("f" * "$i")) end df1 = stack(df, a) dfnew = unstack(df1, :variable, :Method, :value) dfnew = rename(dfnew, :variable => :Function) println(dfnew) dfnew end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
3838
# This file is part of the ValidatedNumerics.jl package; MIT licensed module IntervalRootFinding using IntervalArithmetic using ForwardDiff using StaticArrays using LinearAlgebra: I, Diagonal import Base: βŠ†, show, big, \ import Polynomials: roots ## Root finding export derivative, jacobian, # reexport derivative from ForwardDiff Root, is_unique, roots, find_roots, bisect, newton1d, quadratic_roots, gauss_seidel_interval, gauss_seidel_interval!, gauss_seidel_contractor, gauss_seidel_contractor!, gauss_elimination_interval, gauss_elimination_interval!, slope export isunique, root_status using Reexport @reexport using IntervalArithmetic import IntervalArithmetic: interval, wideinterval const derivative = ForwardDiff.derivative const D = derivative const where_bisect = IntervalArithmetic.where_bisect ## 127//256 include("root_object.jl") include("newton.jl") include("krawczyk.jl") include("complex.jl") include("contractors.jl") include("branch_and_bound.jl") include("roots.jl") include("newton1d.jl") include("quadratic.jl") include("linear_eq.jl") include("slopes.jl") gradient(f) = X -> ForwardDiff.gradient(f, X[:]) ForwardDiff.jacobian(f, X::IntervalBox) = ForwardDiff.jacobian(f, X.v) const βˆ‡ = gradient export βˆ‡ function find_roots(f::Function, a::Interval{T}, method::Function = newton; tolerance = eps(T), debug = false, maxlevel = 30) where {T} method(f, a; tolerance=tolerance, debug=debug, maxlevel=maxlevel) end function find_roots(f::Function, f_prime::Function, a::Interval{T}, method::Function=newton; tolerance=eps(T), debug=false, maxlevel=30) where {T} method(f, f_prime, a; tolerance=tolerance, debug=debug, maxlevel=maxlevel) end function find_roots(f::Function, a::Real, b::Real, method::Function=newton; tolerance=eps(1.0*a), debug=false, maxlevel=30, precision::Int=-1) if precision >= 0 setprecision(Interval, precision) do find_roots(f, @interval(a, b), method; tolerance=tolerance, debug=debug, maxlevel=maxlevel) end else # use current precision find_roots(f, @interval(a, b), method; tolerance=tolerance, debug=debug, maxlevel=maxlevel) end end function find_roots_midpoint(f::Function, a::Real, b::Real, method::Function=newton; tolerance=eps(1.0*a), debug=false, maxlevel=30, precision=-1) roots = find_roots(f, a, b, method; tolerance=tolerance, debug=debug, maxlevel=maxlevel, precision=precision) T = eltype(roots[1].interval) midpoints = T[] radii = T[] root_symbols = Symbol[] # :unique or :unknown if length(roots) == 0 return (midpoints, radii, root_symbols) # still empty end for root in roots midpoint, radius = midpoint_radius(root.interval) push!(midpoints, midpoint) push!(radii, radius) push!(root_symbols, root.status) end (midpoints, radii, root_symbols) end function clean_roots(f, roots) # order, remove duplicates, and include intervals X only if f(X) contains 0 sort!(roots, lt=lexless) roots = unique(roots) roots = filter(x -> 0 ∈ f(x.interval), roots) # merge neighbouring roots if they touch: if length(roots) < 2 return roots end new_roots = eltype(roots)[] base_root = roots[1] for i in 2:length(roots) current_root = roots[i] if isempty(base_root.interval ∩ current_root.interval) || (base_root.status != current_root.status) push!(new_roots, base_root) base_root = current_root else base_root = Root(hull(base_root.interval, current_root.interval), base_root.status) end end push!(new_roots, base_root) return new_roots end end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
10157
import Base: copy, eltype, iterate, IteratorSize import Base: getindex, setindex!, delete! export BBSearch, BreadthFirstBBSearch, DepthFirstBBSearch export data export copy, eltype, iterate, IteratorSize abstract type AbstractBBNode end """ BBNode <: AbstractBBNode Intermediate node of a `BBTree`. Does not contain any data by itself, only redirect toward its children. """ struct BBNode <: AbstractBBNode parent::Int children::Vector{Int} end """ BBLeaf{DATA} <: AbstractBBLeaf Leaf node of a `BBTree` that contains some data. Its status is either - `:working`: the leaf will be further processed. - `:final`: the leaf won't be touched anymore. """ struct BBLeaf{DATA} <: AbstractBBNode data::DATA parent::Int status::Symbol end function BBLeaf(data::DATA, parent::Int) where {DATA} BBLeaf{DATA}(data, parent, :working) end function BBNode(leaf::BBLeaf, child1::Int, child2::Int) BBNode(leaf.parent, Int[child1, child2]) end """ BBTree{DATA} Tree storing the data used and produced by a branch and bound search in a structured way. Nodes and leaves can be accessed using their index using the bracket syntax `wt[node_id]`. However this is slow, as nodes and leaves are stored separately. Support the iterator interface. The element yielded by the iteration are tuples `(node_id, lvl)` where `lvl` is the depth of the node in the tree. """ struct BBTree{DATA} nodes::Dict{Int, BBNode} leaves::Dict{Int, BBLeaf{DATA}} working_leaves::Vector{Int} end function BBTree(rootdata::DATA) where {DATA} rootleaf = BBLeaf(rootdata, 0) BBTree{DATA}(Dict{Int, BBNode}(), Dict(1 => rootleaf), Int[1]) end show(io::IO, wn::BBNode) = print(io, "Node with children $(wn.children)") function show(io::IO, wl::BBLeaf) print(io, "Leaf (:$(wl.status)) with data $(wl.data)") end function show(io::IO, wt::BBTree{DATA}) where {DATA} println(io, "Working tree with $(nnodes(wt)) elements of type $DATA") if nnodes(wt) > 0 println(io, "Indices: ", vcat(collect(keys(wt.nodes)), collect(keys(wt.leaves))) |> sort) println(io, "Structure:") for (id, lvl) in wt println(io, " "^lvl * "[$id] $(wt[id])") end end end # Root node has id 1 and parent id 0 root(wt::BBTree) = wt[1] is_root(wt::BBTree, id::Int) = (id == 1) """ nnodes(wt::BBTree) Number of nodes (including leaves) in a `BBTree`. """ nnodes(wt::BBTree) = length(wt.nodes) + length(wt.leaves) """ data(leaf::BBLeaf) Return the data stored in the leaf. """ data(leaf::BBLeaf) = leaf.data """ data(wt::BBTree) Return all the data stored in a `BBTree` as a list. The ordering of the elements is arbitrary. """ data(wt::BBTree) = data.(values(wt.leaves)) function newid(wt::BBTree) k1 = keys(wt.nodes) k2 = keys(wt.leaves) if length(k1) > 0 m1 = maximum(k1) else m1 = 0 end if length(k2) > 0 m2 = maximum(k2) else m2 = 0 end return max(m1, m2) + 1 end # Index operations (slower than manipulating the node directly in the correct # dictionary) function getindex(wt::BBTree, id) haskey(wt.nodes, id) && return wt.nodes[id] haskey(wt.leaves, id) && return wt.leaves[id] error("getindex failed: no index $id") # TODO: make better error end setindex!(wt::BBTree, val::BBNode, id) = setindex!(wt.nodes, val, id) setindex!(wt::BBTree, val::BBLeaf, id) = setindex!(wt.leaves, val, id) function delete!(wt::BBTree, id) if haskey(wt.nodes, id) delete!(wt.nodes, id) elseif haskey(wt.leaves, id) delete!(wt.leaves, id) else error("delete! failed: no index $id") # TODO: make better error end end """ discard_leaf!(wt::BBTree, id::Int) Delete the `BBLeaf` with index `id` and all its ancestors to which it is the last descendant. """ function discard_leaf!(wt::BBTree, id::Int) leaf = wt.leaves[id] delete!(wt.leaves, id) recursively_delete_parent!(wt, leaf.parent, id) end function recursively_delete_parent!(wt, id_parent, id_child) if !is_root(wt, id_child) parent = wt.nodes[id_parent] siblings = parent.children if length(parent.children) == 1 # The child has no siblings, so delete the parent delete!(wt.nodes, id_parent) recursively_delete_parent!(wt, parent.parent, id_parent) else # The child has siblings so remove it from the children list deleteat!(parent.children, searchsortedfirst(parent.children, id_child)) end end end function iterate(wt::BBTree, (id, lvl)=(0, 0)) id, lvl = next_id(wt, id, lvl) lvl == 0 && return nothing return (id, lvl), (id, lvl) end function next_id(wt::BBTree, id, lvl) lvl == 0 && return (1, 1) node = wt[id] isa(node, BBNode) && return (node.children[1], lvl + 1) return next_sibling(wt, id, lvl) end function next_sibling(wt::BBTree, sibling, lvl) parent = wt[sibling].parent parent == 0 && return (0, 0) children = wt[parent].children maximum(children) == sibling && return next_sibling(wt, parent, lvl - 1) id = minimum(filter(x -> x > sibling, children)) return (id, lvl) end """ BBSearch{DATA} Branch and bound search interface in element of type DATA. This interface provide an iterable that perform the search. There is currently three types of search supported `BreadFirstBBSearch`, `DepthFirstBBSearch` and `KeyBBSearch`, each one processing the element of the tree in a different order. When subtyping one of these, the following methods must be implemented: - `root_element(::BBSearch)`: return the element with which the search is started - `process(::BBSearch, elem::DATA)`: return a symbol representing the action to perform with the element `elem` and an object of type `DATA` reprensenting the state of the element after processing (may return `elem` unchanged). - `bisect(::BBSearch, elem::DATA)`: return two elements of type `DATA` build by bisecting `elem` Subtyping `BBSearch` directly allows to have control over the order in which the elements are process. To do this the following methods must be implemented: - `root_element(::BBSearch)`: return the first element to be processed. Use to build the initial tree. - `get_leaf_id!(::BBSearch, wt::BBTree)`: return the id of the next leaf that will be processed and remove it from the list of working leaves of `wt`. - `insert_leaf!(::BBSearch, wt::BBTree, leaf::BBLeaf)`: insert a leaf in the list of working leaves. # Valid symbols returned by the process function - `:store`: the element is considered as final and is stored, it will not be further processed - `:bisect`: the element is bisected and each of the two resulting part will be processed - `:discard`: the element is discarded from the tree, allowing to free memory """ abstract type BBSearch{DATA} end abstract type BreadthFirstBBSearch{DATA} <: BBSearch{DATA} end abstract type DepthFirstBBSearch{DATA} <: BBSearch{DATA} end """ KeyBBSearch{DATA} <: BBSearch{DATA} Interface to a branch and bound search that use a key function to decide which element to process first. The search process first the element with the largest key as computed by `keyfunc(ks::KeyBBSearch, elem)`. !!! warning Untested. """ abstract type KeyBBSearch{DATA} <: BBSearch{DATA} end """ root_element(search::BBSearch) Return the initial element of the search. The `BBTree` will be build around it. Can be define for custom searches that are direct subtype of `BBSearch`, default behavior is to fetch the field `initial` of the search. """ root_element(search::BBSearch) = search.initial """ get_leaf_id!(::BBSearch, wt::BBTree) Return the id of the next leaf that will be processed and remove it from the list of working leaves. Must be define for custom searches that are direct subtype of `BBSearch`. """ get_leaf_id!(::BreadthFirstBBSearch, wt::BBTree) = popfirst!(wt.working_leaves) get_leaf_id!(::DepthFirstBBSearch, wt::BBTree) = pop!(wt.working_leaves) get_leaf_id!(::KeyBBSearch, wt::BBTree) = popfirst!(wt.working_leaves) """ insert_leaf!(::BBSearch, wt::BBTree, leaf::BBLeaf) Insert the id of a new leaf that has been produced by bisecting an older leaf into the list of working leaves. Must be define for custom searches that are direct subtype of `BBSearch`. """ function insert_leaf!(::Union{BreadthFirstBBSearch{DATA}, DepthFirstBBSearch{DATA}}, wt::BBTree{DATA}, leaf::BBLeaf{DATA}) where {DATA} id = newid(wt) wt.leaves[id] = leaf push!(wt.working_leaves, id) return id end function insert_leaf!(::KS, wt::BBTree{DATA}, leaf::BBLeaf{DATA}) where {DATA, KS <: KeyBBSearch{DATA}} id = newid(wt) wt.leaves[id] = leaf keys = keyfunc.(KS, wt.working_leaves) current = keyfunc(KS, leaf) # Keep the working_leaves sorted insert!(wt.working_leaves, searchsortedfirst(keys, current), id) return id end eltype(::Type{BBS}) where {DATA, BBS <: BBSearch{DATA}} = BBTree{DATA} IteratorSize(::Type{BBS}) where {BBS <: BBSearch} = Base.SizeUnknown() function iterate(search::BBSearch{DATA}, wt::BBTree=BBTree(root_element(search))) where {DATA} isempty(wt.working_leaves) && return nothing id = get_leaf_id!(search, wt) X = wt.leaves[id] action, newdata = process(search, data(X)) if action == :store wt.leaves[id] = BBLeaf(newdata, X.parent, :final) elseif action == :bisect child1, child2 = bisect(search, newdata) leaf1 = BBLeaf(child1, id, :working) leaf2 = BBLeaf(child2, id, :working) id1 = insert_leaf!(search, wt, leaf1) id2 = insert_leaf!(search, wt, leaf2) wt.nodes[id] = BBNode(X, id1, id2) delete!(wt.leaves, id) elseif action == :discard discard_leaf!(wt, id) else error("Branch and bound: process function of the search object return " * "unknown action: $action for element $X. Valid actions are " * ":store, :bisect and :discard.") end return wt, wt end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
1310
""" Complex numbers as 2-vectors, enough for polynomials. """ struct Compl{T} <: Number re::T im::T end Base.promote_rule(::Type{Compl{T}}, ::Type{S}) where {T, S<:Real} = Compl{T} Base.convert(::Type{Compl{T}}, x::Real) where {T} = Compl{T}(x, 0) Base.show(io::IO, c::Compl) = println(io, c.re, " + ", c.im, "im") Base.:+(a::Compl{T}, b::Compl{T}) where {T} = Compl{T}(a.re+b.re, a.im+b.im) Base.:-(a::Compl{T}, b::Compl{T}) where {T} = Compl{T}(a.re-b.re, a.im-b.im) Base.:*(a::Compl{T}, b::Compl{T}) where {T} = Compl{T}(a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re) Base.:*(Ξ±::Number, z::Compl{T}) where {T} = Compl{T}(Ξ±*z.re, Ξ±*z.im) Base.one(z::Compl{T}) where {T} = Compl{T}(one(T), zero(T)) Base.copy(z::Compl{T}) where {T} = Compl{T}(z.re, z.im) """ Takes a complex (polynomial) function f and returns a function g:R^2 -> R^2 that implements it. """ function realify(f) function g(x) z = Compl(x[1], x[2]) z2 = f(z) SVector(z2.re, z2.im) end return g end """ Takes the derivative of a complex function and returns the real jacobian that implements it. """ function realify_derivative(fp) function g_jac(x) z = Compl(x[1], x[2]) fpz = fp(z) SMatrix{2, 2}(fpz.re, fpz.im, -fpz.im, fpz.re) end return g_jac end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
4499
export Contractor export Bisection, Newton, Krawczyk """ 𝒩(f, fβ€², X, Ξ±) Single-variable Newton operator. The symbol for the operator is accessed with `\\scrN<tab>`. """ function 𝒩(f, fβ€², X::Interval{T}, Ξ±) where {T} m = Interval(mid(X, Ξ±)) return m - (f(m) / fβ€²(X)) end """ 𝒩(f, jacobian, X, Ξ±) Multi-variable Newton operator. """ function 𝒩(f::Function, jacobian::Function, X::IntervalBox, Ξ±) # multidimensional Newton operator m = Interval.(mid(X, Ξ±)) J = jacobian(X) y = gauss_elimination_interval(J, f(m)) # J \ f(m) return IntervalBox(m .- y) end """ 𝒦(f, fβ€², X, Ξ±) Single-variable Krawczyk operator. The symbol for the operator is accessed with `\\scrK<tab>`. """ function 𝒦(f, fβ€², X::Interval{T}, Ξ±) where {T} m = Interval(mid(X, Ξ±)) Y = 1 / fβ€²(m) return m - Y*f(m) + (1 - Y*fβ€²(X)) * (X - m) end """ 𝒦(f, jacobian, X, Ξ±) Multi-variable Krawczyk operator. """ function 𝒦(f, jacobian, X::IntervalBox{T}, Ξ±) where {T} m = mid(X, Ξ±) mm = IntervalBox(m) J = jacobian(X) Y = mid.(inv(jacobian(mm))) return m - Y*f(mm) + (I - Y*J) * (X.v - m) end """ Contractor{F} Abstract type for contractors. """ abstract type Contractor{F} end """ Bisection{F} <: Contractor{F} Contractor type for the bisection method. """ struct Bisection{F} <: Contractor{F} f::F end function (contractor::Bisection)(r, tol) X = interval(r) image = (contractor.f)(X) if root_status(r) == :empty || !(contains_zero(image)) return Root(X, :empty) end return Root(X, :unknown) end for (Method, π’ͺ) in ((:Newton, 𝒩), (:Krawczyk, 𝒦)) doc = """ $Method{F, FP} <: Contractor{F} Contractor type for the $Method method. # Fields - `f::F`: function whose roots are searched - `f::FP`: derivative or jacobian of `f` ----- (C::$Method)(X, tol, Ξ±=where_bisect) Contract an interval `X` using $Method operator and return the contracted interval together with its status. # Inputs - `R`: Root object containing the interval to contract. - `tol`: Precision to which unique solutions are refined. - `Ξ±`: Point of bisection of intervals. """ @eval begin struct $Method{F, FP} <: Contractor{F} f::F fβ€²::FP # use \prime<TAB> for β€² end function (C::$Method)(R, tol, Ξ±=where_bisect) op = x -> $π’ͺ(C.f, C.fβ€², x, Ξ±) rt = determine_region_status(op, C.f, R) return refine(op, rt, tol) end @doc $doc $Method end end """ safe_isempty(X) Similar to `isempty` function for `IntervalBox`, but also works for `SVector` of `Interval`. """ safe_isempty(X) = isempty(IntervalBox(X)) """ determine_region_status(contract, f, R) Contraction operation for contractors using the first derivative of the function. Currently `Newton` and `Krawczyk` contractors use this. """ function determine_region_status(op, f, R) X = interval(R) former_status = root_status(R) imX = f(X) if former_status == :empty || !(contains_zero(imX)) return Root(X, :empty) end safe_isempty(imX) && return Root(X, :empty) # X is fully outside of the domain of f contracted_X = op(X) # Only happens if X is partially out of the domain of f safe_isempty(contracted_X) && return Root(X, :unknown) # force bisection # given that have the Jacobian, can also do mean value form NX = contracted_X ∩ X isinf(X) && return Root(NX, :unknown) # force bisection safe_isempty(NX) && return Root(X, :empty) if former_status == :unique || NX βͺ½ X # isinterior; know there's a unique root inside return Root(NX, :unique) end return Root(NX, :unknown) end """ refine(op, X::Region, tol) Generic refine operation for Krawczyk and Newton. This function assumes that it is already known that `X` contains a unique root. """ function refine(op, X::Region, tol) while diam(X) > tol # avoid problem with tiny floating-point numbers if 0 is a root NX = op(X) ∩ X NX == X && break # reached limit of precision X = NX end return X end """ refine(op, X::Tuple{Symbol, Region}, tol) Wrap the refine method to leave unchanged intervals that are not guaranteed to contain an unique solution. """ function refine(op, R::Root, tol) root_status(R) != :unique && return R return Root(refine(op, interval(R), tol), :unique) end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
3291
# This file is part of the ValidatedNumerics.jl package; MIT licensed # Krawczyk method, following Tucker # const D = differentiate """Returns two intervals, the first being a point within the interval x such that the interval corresponding to the derivative of f there does not contain zero, and the second is the inverse of its derivative""" function guarded_derivative_midpoint(f::Function, f_prime::Function, x::Interval{T}) where {T} Ξ± = convert(T, 0.46875) # close to 0.5, but exactly representable as a floating point m = Interval(mid(x)) C = inv(f_prime(m)) # Check that 0 is not in C; if so, consider another point rather than m i = 0 while zero(T) ∈ C || isempty(C) m = Interval( Ξ±*x.lo + (one(T)-Ξ±)*x.hi ) C = inv(f_prime(m)) i += 1 Ξ± /= 2 i > 20 && error("""Error in guarded_deriv_midpoint: the derivative of the function seems too flat""") end return m, C end function K(f::Function, f_prime::Function, x::Interval{T}) where {T} m, C = guarded_derivative_midpoint(f, f_prime, x) deriv = f_prime(x) Kx = m - C*f(m) + (one(T) - C*deriv) * (x - m) Kx end function krawczyk_refine(f::Function, f_prime::Function, x::Interval{T}; tolerance=eps(one(T)), debug=false) where {T} debug && (print("Entering krawczyk_refine:"); @show x) while diam(x) > tolerance # avoid problem with tiny floating-point numbers if 0 is a root Kx = K(f, f_prime, x) debug && @show(x, Kx) Kx = Kx ∩ x Kx == x && break x = Kx end return [Root(x, :unique)] end function krawczyk(f::Function, f_prime::Function, x::Interval{T}, level::Int=0; tolerance=eps(one(T)), debug=false, maxlevel=30) where {T} debug && (print("Entering krawczyk:"); @show(level); @show(x)) # Maximum level of bisection level >= maxlevel && return [Root(x, :unknown)] isempty(x) && return Root{typeof(x)}[] # [(x, :none)] Kx = K(f, f_prime, x) ∩ x isempty(Kx ∩ x) && return Root{typeof(x)}[] # [(x, :none)] if Kx βͺ½ x # isinterior debug && (print("Refining "); @show(x)) return krawczyk_refine(f, f_prime, Kx, tolerance=tolerance, debug=debug) end m = mid(x) debug && @show(x,m) isthin(x) && return [Root(x, :unknown)] # bisecting roots = vcat( krawczyk(f, f_prime, Interval(x.lo, m), level+1, tolerance=tolerance, debug=debug, maxlevel=maxlevel), krawczyk(f, f_prime, Interval(m, x.hi), level+1, tolerance=tolerance, debug=debug, maxlevel=maxlevel) ) roots = clean_roots(f, roots) return roots end # use automatic differentiation if no derivative function given krawczyk(f::Function,x::Interval{T}; args...) where {T} = krawczyk(f, x->D(f,x), x; args...) # krawczyk for vector of intervals: krawczyk(f::Function, f_prime::Function, xx::Vector{Interval{T}}; args...) where {T} = vcat([krawczyk(f, f_prime, @interval(x); args...) for x in xx]...) krawczyk(f::Function, xx::Vector{Interval{T}}, level; args...) where {T} = krawczyk(f, x->D(f,x), xx; args...) krawczyk(f::Function, xx::Vector{Root{T}}; args...) where {T} = krawczyk(f, x->D(f,x), [x.interval for x in xx]; args...)
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
4218
""" Preconditions the matrix A and b with the inverse of mid(A) """ function preconditioner(A::AbstractMatrix, b::AbstractArray) Aᢜ = mid.(A) B = inv(Aᢜ) return B*A, B*b end function gauss_seidel_interval(A::AbstractMatrix, b::AbstractArray; precondition=true, maxiter=100) n = size(A, 1) x = similar(b) x .= -1e16..1e16 gauss_seidel_interval!(x, A, b, precondition=precondition, maxiter=maxiter) return x end """ Iteratively solves the system of interval linear equations and returns the solution set. Uses the Gauss-Seidel method (Hansen-Sengupta version) to solve the system. Keyword `precondition` to turn preconditioning off. Eldon Hansen and G. William Walster : Global Optimization Using Interval Analysis - Chapter 5 - Page 115 """ function gauss_seidel_interval!(x::AbstractArray, A::AbstractMatrix, b::AbstractArray; precondition=true, maxiter=100) precondition && ((A, b) = preconditioner(A, b)) n = size(A, 1) @inbounds for iter in 1:maxiter x¹ = copy(x) for i in 1:n Y = b[i] for j in 1:n (i == j) || (Y -= A[i, j] * x[j]) end Z = extended_div(Y, A[i, i]) x[i] = hull((x[i] ∩ Z[1]), x[i] ∩ Z[2]) end if all(x .== x¹) break end end x end function gauss_seidel_contractor(A::AbstractMatrix, b::AbstractArray; precondition=true, maxiter=100) n = size(A, 1) x = similar(b) x .= -1e16..1e16 x = gauss_seidel_contractor!(x, A, b, precondition=precondition, maxiter=maxiter) return x end function gauss_seidel_contractor!(x::AbstractArray, A::AbstractMatrix, b::AbstractArray; precondition=true, maxiter=100) precondition && ((A, b) = preconditioner(A, b)) n = size(A, 1) diagA = Diagonal(A) extdiagA = copy(A) for i in 1:n if (typeof(b) <: SArray) extdiagA = setindex(extdiagA, Interval(0), i, i) else extdiagA[i, i] = Interval(0) end end inv_diagA = inv(diagA) for iter in 1:maxiter x¹ = copy(x) x = x .∩ (inv_diagA * (b - extdiagA * x)) if all(x .== x¹) break end end x end function gauss_elimination_interval(A::AbstractMatrix, b::AbstractArray; precondition=true) x = similar(b) x .= -Inf..Inf x = gauss_elimination_interval!(x, A, b, precondition=precondition) return x end """ Solves the system of linear equations using Gaussian Elimination. Preconditioning is used when the `precondition` keyword argument is `true`. REF: Luc Jaulin et al., *Applied Interval Analysis*, pg. 72 """ function gauss_elimination_interval!(x::AbstractArray, A::AbstractMatrix, b::AbstractArray; precondition=true) if precondition (A, b) = preconditioner(A, b) end _A = A _b = b A = similar(A) b = similar(b) A .= _A b .= _b n = size(A, 1) p = similar(b) p .= 0 for i in 1:(n-1) if 0 ∈ A[i, i] # diagonal matrix is not invertible p .= entireinterval(b[1]) return p .∩ x # return x? end for j in (i+1):n α = A[j, i] / A[i, i] b[j] -= α * b[i] for k in (i+1):n A[j, k] -= α * A[i, k] end end end for i in n:-1:1 temp = zero(b[1]) for j in (i+1):n temp += A[i, j] * p[j] end p[i] = (b[i] - temp) / A[i, i] end return p .∩ x end function gauss_elimination_interval1(A::AbstractMatrix, b::AbstractArray; precondition=true) n = size(A, 1) x = fill(-1e16..1e16, n) x = gauss_elimination_interval1!(x, A, b, precondition=precondition) return x end """ Using `Base.\`` """ function gauss_elimination_interval1!(x::AbstractArray, a::AbstractMatrix, b::AbstractArray; precondition=true) precondition && ((a, b) = preconditioner(a, b)) a \ b end \(A::SMatrix{S, S, Interval{T}}, b::SVector{S, Interval{T}}; kwargs...) where {S, T} = gauss_elimination_interval(A, b, kwargs...) \(A::Matrix{Interval{T}}, b::Vector{Interval{T}}; kwargs...) where T = gauss_elimination_interval(A, b, kwargs...)
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
3659
# This file is part of the ValidatedNumerics.jl package; MIT licensed # Newton method """If a root is known to be inside an interval, `newton_refine` iterates the interval Newton method until that root is found.""" function newton_refine(f::Function, f_prime::Function, X::Union{Interval{T}, IntervalBox{N,T}}; tolerance=eps(T), debug=false) where {N,T} debug && (print("Entering newton_refine:"); @show X) while diam(X) > tolerance # avoid problem with tiny floating-point numbers if 0 is a root deriv = f_prime(X) NX = 𝒩(f, X, deriv) debug && @show(X, NX) NX = NX ∩ X NX == X && break X = NX end debug && @show "Refined root", X return [Root(X, :unique)] end """`newton` performs the interval Newton method on the given function `f` with its optional derivative `f_prime` and initial interval `x`. Optional keyword arguments give the `tolerance`, `maxlevel` at which to stop subdividing, and a `debug` boolean argument that prints out diagnostic information.""" function newton(f::Function, f_prime::Function, x::Interval{T}, level::Int=0; tolerance=eps(T), debug=false, maxlevel=30) where {T} debug && (print("Entering newton:"); @show(level); @show(x)) isempty(x) && return Root{typeof(x)}[] #[(x, :none)] z = zero(x.lo) tolerance = abs(tolerance) # Tolerance reached or maximum level of bisection (diam(x) < tolerance || level >= maxlevel) && return [Root(x, :unknown)] deriv = f_prime(x) debug && @show(deriv) if !(z in deriv) Nx = 𝒩(f, x, deriv) debug && @show(Nx, Nx βŠ† x, Nx ∩ x) isempty(Nx ∩ x) && return Root{typeof(x)}[] if Nx βŠ† x debug && (print("Refining "); @show(x)) return newton_refine(f, f_prime, Nx, tolerance=tolerance, debug=debug) end m = mid(x) debug && @show(x,m) # bisect: roots = vcat( newton(f, f_prime, Interval(x.lo, m), level+1, tolerance=tolerance, debug=debug, maxlevel=maxlevel), newton(f, f_prime, Interval(m, x.hi), level+1, tolerance=tolerance, debug=debug, maxlevel=maxlevel) # note the nextfloat here to prevent repetition ) debug && @show(roots) else # 0 in deriv; this does extended interval division by hand y1 = Interval(deriv.lo, -z) y2 = Interval(z, deriv.hi) if debug @show (y1, y2) @show N(f, x, y1) @show N(f, x, y2) end y1 = 𝒩(f, x, y1) ∩ x y2 = 𝒩(f, x, y2) ∩ x debug && @show(y1, y2) roots = vcat( newton(f, f_prime, y1, level+1, tolerance=tolerance, debug=debug, maxlevel=maxlevel), newton(f, f_prime, y2, level+1, tolerance=tolerance, debug=debug, maxlevel=maxlevel) ) debug && @show(roots) end roots = clean_roots(f, roots) return roots end # use automatic differentiation if no derivative function given: newton(f::Function, x::Interval{T}; args...) where {T} = newton(f, x->D(f,x), x; args...) # newton for vector of intervals: newton(f::Function, f_prime::Function, xx::Vector{Interval{T}}; args...) where {T} = vcat([newton(f, f_prime, @interval(x); args...) for x in xx]...) newton(f::Function, xx::Vector{Interval{T}}, level; args...) where {T} = newton(f, x->D(f,x), xx, 0, args...) newton(f::Function, xx::Vector{Root{T}}; args...) where {T} = newton(f, x->D(f,x), [x.interval for x in xx], args...)
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
7317
"""`newton1d` performs the interval Newton method on the given function `f` with its derivative `fβ€²` and initial interval `x`. Optional keyword arguments give the tolerances `reltol` and `abstol`. `reltol` is the tolerance on the relative error whereas `abstol` is the tolerance on |f(X)|, and a `debug` boolean argument that prints out diagnostic information.""" function newton1d(f::Function, fβ€²::Function, x::Interval{T}; reltol=eps(T), abstol=eps(T), debug=false, debugroot=false) where {T} L = Interval{T}[] # Array to hold the intervals still to be processed R = Root{Interval{T}}[] # Array to hold the `root` objects obtained reps = reps1 = 0 push!(L, x) # Initialize initial_width = ∞ X = emptyinterval(T) # Initialize while !isempty(L) # Until all intervals have been processed X = pop!(L) # Process next interval debug && (print("Current interval popped: "); @show X) m = mid(X) if (isempty(X)) continue end if 0 βˆ‰ fβ€²(X) # if 0 βˆ‰ fβ€²(X), Newton steps can be made normally until either X becomes empty, or is known to contain a unique root debug && println("0 βˆ‰ fβ€²(X)") while true m = mid(X) N = m - (f(interval(m)) / fβ€²(X)) # Newton step debug && (print("Newton step1: "); @show (X, X ∩ N)) if X == X ∩ N # Checking if Newton step was redundant reps1 += 1 if reps1 > 20 reps1 = 0 break end end X = X ∩ N if (isempty(X)) # No root in X break elseif 0 ∈ f(wideinterval(mid(X))) # Root guaranteed to be in X n = fa = fb = 0 root_exist = true while (n < 4 && (fa == 0 || fb == 0)) # Narrowing the interval further if fa == 0 if 0 ∈ f(wideinterval(X.lo)) fa = 1 else N = X.lo - (f(interval(X.lo)) / fβ€²(X)) X = X ∩ N if (isempty(X)) root_exist = false break end end end if fb == 0 if 0 ∈ f(wideinterval(X.hi)) fb = 1 else if 0 ∈ f(wideinterval(mid(X))) N = X.hi - (f(interval(X.hi)) / fβ€²(X)) else N = mid(X) - (f(interval(mid(X))) / fβ€²(X)) end X = X ∩ N if (isempty(X)) root_exist = false break end end end N = mid(X) - (f(interval(mid(X))) / fβ€²(X)) X = X ∩ N if (isempty(X)) root_exist = false break end n += 1 end if root_exist push!(R, Root(X, :unique)) debugroot && @show "Root found", X # Storing determined unique root end break end end else # 0 ∈ fβ€²(X) if diam(X) == initial_width # if no improvement occuring for a number of iterations reps += 1 if reps > 10 push!(R, Root(X, :unknown)) debugroot && @show "Repeated root found", X reps = 0 continue end end initial_width = diam(X) debug && println("0 ∈ f'(X)") expansion_pt = Inf # expansion point for the newton step might be m, X.lo or X.hi according to some conditions if 0 ∈ f(wideinterval(mid(X))) # if root in X, narrow interval further # 0 ∈ fⁱ(x) debug && println("0 ∈ fⁱ(x)") if 0 βˆ‰ f(wideinterval(X.lo)) expansion_pt = X.lo elseif 0 βˆ‰ f(wideinterval(X.hi)) expansion_pt = X.hi else x1 = mid(interval(X.lo, mid(X))) x2 = mid(interval(mid(X), X.hi)) if 0 βˆ‰ f(wideinterval(x1)) || 0 βˆ‰ f(wideinterval(x2)) push!(L, interval(X.lo, m)) push!(L, interval(m, X.hi)) continue else push!(R, Root(X, :unknown)) debugroot && @show "Multiple root found", X continue end end else # 0 βˆ‰ fⁱ(x) debug && println("0 βˆ‰ fⁱ(x)") if (diam(X)/mag(X)) < reltol && diam(f(X)) < abstol # checking if X is still within tolerances push!(R, Root(X, :unknown)) debugroot && @show "Tolerance root found", X continue end end # Step 8 if isinf(expansion_pt) expansion_pt = mid(X) end a = f(interval(expansion_pt)) b = fβ€²(X) # Newton steps with extended division creating two intervals if 0 < b.hi && 0 > b.lo && 0 βˆ‰ a if a.hi < 0 push!(L, X ∩ (expansion_pt - interval(-Inf, a.hi / b.hi))) push!(L, X ∩ (expansion_pt - interval(a.hi / b.lo, Inf))) elseif a.lo > 0 push!(L, X ∩ (expansion_pt - interval(-Inf, a.lo / b.lo))) push!(L, X ∩ (expansion_pt - interval(a.lo / b.hi, Inf))) end continue else N = expansion_pt - (f(interval(expansion_pt))/fβ€²(X)) debug && (print("Newton step2: "); @show (X, X ∩ N)) X = X ∩ N m = mid(X) if isempty(X) continue end end push!(L, X) # Pushing X into L to be processed again end end return R end """`newton1d` performs the interval Newton method on the given function `f` and initial interval `x`. Optional keyword arguments give the tolerances `reltol` and `abstol`. `reltol` is the tolerance on the relative error whereas `abstol` is the tolerance on |f(X)|, and a `debug` boolean argument that prints out diagnostic information.""" newton1d(f::Function, x::Interval{T}; args...) where {T} = newton1d(f, x->D(f,x), x; args...)
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
2025
""" Helper function for quadratic_interval that computes roots of a real quadratic using interval arithmetic to bound rounding errors. """ function quadratic_helper!(a::Interval{T}, b::Interval{T}, c::Interval{T}, L::Array{Interval{T}}) where {T} Ξ” = b^2 - 4*a*c Ξ”.hi < 0 && return Ξ” = sqrt(Ξ”) if (b.lo >= 0) x0 = -0.5 * (b + Ξ”) else x0 = -0.5 * (b - Ξ”) end if (0 ∈ x0) push!(L, x0) else x1 = c / x0 x0 = x0 / a push!(L, x0, x1) end end """ Function to solve a quadratic equation where the coefficients are intervals. Returns an array of intervals of the roots. Arguments `a`, `b` and `c` are interval coefficients of `xΒ²`, `x` and `1` respectively. The interval case differs from the non-interval case in that there might be three disjoint interval roots. In the third case, one interval root extends to βˆ’βˆž and another extends to +∞. This algorithm finds the set of points where `F.lo(x) β‰₯ 0` and the set of points where `F.hi(x) ≀ 0` and takes the intersection of these two sets. Eldon Hansen and G. William Walster : Global Optimization Using Interval Analysis - Chapter 8 """ function quadratic_roots(a::Interval{T}, b::Interval{T}, c::Interval{T}) where {T} L = Interval{T}[] R = Interval{T}[] quadratic_helper!(Interval(a.lo), Interval(b.lo), Interval(c.lo), L) quadratic_helper!(Interval(a.hi), Interval(b.hi), Interval(c.hi), L) quadratic_helper!(Interval(a.lo), Interval(b.hi), Interval(c.lo), L) quadratic_helper!(Interval(a.hi), Interval(b.lo), Interval(c.hi), L) if (length(L) == 8) resize!(L, 4) end if (a.lo < 0 || (a.lo == 0 && b.hi == 0) || (a.lo == 0 && b.hi == 0 && c.lo ≀ 0)) push!(L, Interval(-∞)) end if (a.lo < 0 || (a.lo == 0 && b.lo == 0) || (a.lo == 0 && b.lo == 0 && c.lo ≀ 0)) push!(L, Interval(∞)) end sort!(L, by = x -> x.lo) for i in 1:2:length(L) push!(R, Interval(L[i].lo, L[i+1].hi)) end R end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
1400
""" Root Object representing a possible root inside a given region. The field `status` is either `:unknown` or `:unique`. If `status` is `:unique` then we know that there is a unique root of the function in question inside the given region. Internally the status may also be `:empty` for region guaranteed to contain no root, however such `Root`s are discarded by default and thus never returned by the `roots` function. # Fields - `interval`: a region (either `Interval` of `IntervalBox`) searched for roots. - `status`: the status of the region, valid values are `:empty`, `unkown` and `:unique`. """ struct Root{T} interval::T status::Symbol end interval(rt::Root) = rt.interval """ root_status(rt) Return the status of a `Root`. """ root_status(rt::Root) = rt.status # Use root_status since just `status` is too generic """ root_region(rt) Return the region associated to a `Root`. """ root_region(rt::Root) = rt.interval # More generic name than `interval`. """ isunique(rt) Return whether a `Root` is unique. """ isunique(rt::Root{T}) where {T} = (rt.status == :unique) show(io::IO, rt::Root) = print(io, "Root($(rt.interval), :$(rt.status))") βŠ†(a::Interval, b::Root) = a βŠ† b.interval # the Root object has the interval in the first entry βŠ†(a::Root, b::Root) = a.interval βŠ† b.interval big(a::Root) = Root(big(a.interval), a.status)
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
8340
import IntervalArithmetic: diam, isinterior, bisect, isnan export branch_and_prune, Bisection, Newton export BreadthFirstSearch, DepthFirstSearch diam(r::Root) = diam(interval(r)) isnan(X::IntervalBox) = any(isnan.(X)) isnan(r::Root) = isnan(interval(r)) """ BreadthFirstSearch <: BreadthFirstBBSearch Type implementing the `BreadthFirstBBSearch` interface for interval roots finding. # Fields: - `initial`: region (as a `Root` object) in which roots are searched. - `contractor`: contractor to use (`Bisection`, `Newton` or `Krawczyk`) - `tol`: tolerance of the search """ struct BreadthFirstSearch{R <: Region, C <: Contractor, T <: Real} <: BreadthFirstBBSearch{Root{R}} initial::Root{R} contractor::C tol::T end """ DepthFirstSearch <: DepthFirstBBSearch Type implementing the `DepthFirstBBSearch` interface for interval roots finding. # Fields: - `initial`: region (as a `Root` object) in which roots are searched. - `contractor`: contractor to use (`Bisection`, `Newton` or `Krawczyk`) - `tol`: tolerance of the search """ struct DepthFirstSearch{R <: Region, C <: Contractor, T <: Real} <: DepthFirstBBSearch{Root{R}} initial::Root{R} contractor::C tol::T end BreadthFirstSearch(X::Region, C::Contractor, tol::Real) = BreadthFirstSearch(Root(X, :unknown), C, tol) DepthFirstSearch(X::Region, C::Contractor, tol::Real) = DepthFirstSearch(Root(X, :unknown), C, tol) root_element(search::BBSearch{Root{R}}) where {R <: Region} = search.initial function bisect(r::Root) Y1, Y2 = bisect(interval(r)) return Root(Y1, :unknown), Root(Y2, :unknown) end bisect(::BBSearch, r::Root) = bisect(r::Root) function process(search::Union{BreadthFirstSearch, DepthFirstSearch}, r::Root) contracted_root = search.contractor(r, search.tol) status = root_status(contracted_root) status == :unique && return :store, contracted_root status == :empty && return :discard, contracted_root if status == :unknown # Avoid infinite division of intervals with singularity isnan(contracted_root) && diam(r) < search.tol && return :store, r diam(contracted_root) < search.tol && return :store, contracted_root return :bisect, r else error("Unrecognized root status: $status") end end """ branch_and_prune(X, contractor, strategy, tol) Generic branch and prune routine for finding isolated roots using the given contractor to determine the status of a given box `X`. See the documentation of the `roots` function for explanation of the other arguments. """ function branch_and_prune(r::Root, contractor, search, tol) iter = search(r, contractor, tol) local endstate # complete iteration for state in iter endstate = state end return data(endstate) end const NewtonLike = Union{Type{Newton}, Type{Krawczyk}} const default_strategy = DepthFirstSearch const default_tolerance = 1e-7 const default_contractor = Newton """ roots(f, X, contractor=Newton, strategy=BreadthFirstSearch, tol=1e-15) roots(f, deriv, X, contractor=Newton, strategy=BreadthFirstSearch, tol=1e-15) roots(f, X, contractor, tol) roots(f, deriv, X, contractor, tol) Uses a generic branch and prune routine to find in principle all isolated roots of a function `f:R^n β†’ R^n` in a region `X`, if the number of roots is finite. Inputs: - `f`: function whose roots will be found - `X`: `Interval` or `IntervalBox` in which roots are searched - `contractor`: function that, when applied to the function `f`, determines the status of a given box `X`. It returns the new box and a symbol indicating the status. Current possible values are `Bisection`, `Newton` and `Krawczyk` - `deriv`: explicit derivative of `f` for `Newton` and `Krawczyk` - `strategy`: `SearchStrategy` determining the order in which regions are processed. - `tol`: Absolute tolerance. If a region has a diameter smaller than `tol`, it is returned with status `:unknown`. """ function roots(f::Function, X, contractor::Type{C}=default_contractor, strategy::Type{S}=default_strategy, tol::Float64=default_tolerance) where {C <: Contractor, S <: BBSearch} _roots(f, X, contractor, strategy, tol) end function roots(f::Function, deriv::Function, X, contractor::Type{C}=default_contractor, strategy::Type{S}=default_strategy, tol::Float64=default_tolerance) where {C <: Contractor, S <: BBSearch} _roots(f, deriv, X, contractor, strategy, tol) end function roots(f::Function, X, contractor::Type{C}, tol::Float64) where {C <: Contractor} _roots(f, X, contractor, default_strategy, tol) end function roots(f::Function, deriv::Function, X, contractor::Type{C}, tol::Float64) where {C <: Contractor} _roots(f, deriv, X, contractor, default_strategy, tol) end #=== More specific `roots` methods (all parameters are present) These functions are called `_roots` to avoid recursive calls. ===# # For `Bisection` method function _roots(f, r::Root{T}, ::Type{Bisection}, strategy::Type{S}, tol::Float64) where {T, S <: BBSearch} branch_and_prune(r, Bisection(f), strategy, tol) end # For `NewtonLike` acting on `Interval` function _roots(f, r::Root{Interval{T}}, contractor::NewtonLike, strategy::Type{S}, tol::Float64) where {T, S <: BBSearch} deriv = x -> ForwardDiff.derivative(f, x) _roots(f, deriv, r, contractor, strategy, tol) end function _roots(f, deriv, r::Root{Interval{T}}, contractor::NewtonLike, strategy::Type{S}, tol::Float64) where {T, S <: BBSearch} branch_and_prune(r, contractor(f, deriv), strategy, tol) end # For `NewtonLike` acting on `IntervalBox` function _roots(f, r::Root{IntervalBox{N, T}}, contractor::NewtonLike, strategy::Type{S}, tol::Float64) where {N, T, S <: BBSearch} deriv = x -> ForwardDiff.jacobian(f, x) _roots(f, deriv, r, contractor, strategy, tol) end function _roots(f, deriv, r::Root{IntervalBox{N, T}}, contractor::NewtonLike, strategy::Type{S}, tol::Float64) where {N, T, S <: BBSearch} branch_and_prune(r, contractor(f, deriv), strategy, tol) end # Acting on `Interval` function _roots(f, X::Region, contractor::Type{C}, strategy::Type{S}, tol::Float64) where {C <: Contractor, S <: BBSearch} _roots(f, Root(X, :unknown), contractor, strategy, tol) end function _roots(f, deriv, X::Region, contractor::Type{C}, strategy::Type{S}, tol::Float64) where {C <: Contractor, S <: BBSearch} _roots(f, deriv, Root(X, :unknown), contractor, strategy, tol) end # Acting on `Vector` of `Root` function _roots(f, V::Vector{Root{T}}, contractor::Type{C}, strategy::Type{S}, tol::Float64) where {T, C <: Contractor, S <: BBSearch} vcat(_roots.(f, V, contractor, strategy, tol)...) end function _roots(f, deriv, V::Vector{Root{T}}, contractor::Type{C}, strategy::Type{S}, tol::Float64) where {T, C <: Contractor, S <: BBSearch} vcat(_roots.(f, deriv, V, contractor, strategy, tol)...) end # Acting on complex `Interval` function _roots(f, Xc::Complex{Interval{T}}, contractor::Type{C}, strategy::Type{S}, tol::Float64) where {T, C <: Contractor, S <: BBSearch} g = realify(f) Y = IntervalBox(reim(Xc)...) rts = _roots(g, Root(Y, :unknown), contractor, strategy, tol) return [Root(Complex(root.interval...), root.status) for root in rts] end function _roots(f, Xc::Complex{Interval{T}}, contractor::NewtonLike, strategy::Type{S}, tol::Float64) where {T, S <: BBSearch} g = realify(f) g_prime = x -> ForwardDiff.jacobian(g, x) Y = IntervalBox(reim(Xc)...) rts = _roots(g, g_prime, Root(Y, :unknown), contractor, strategy, tol) return [Root(Complex(root.interval...), root.status) for root in rts] end function _roots(f, deriv, Xc::Complex{Interval{T}}, contractor::NewtonLike, strategy::Type{S}, tol::Float64) where {T, S <: BBSearch} g = realify(f) g_prime = realify_derivative(deriv) Y = IntervalBox(reim(Xc)...) rts = _roots(g, g_prime, Root(Y, :unknown), contractor, strategy, tol) return [Root(Complex(root.interval...), root.status) for root in rts] end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
4149
# Reference : Dietmar Ratz - An Optimized Interval Slope Arithmetic and its Application using IntervalArithmetic, ForwardDiff import Base: +, -, *, /, ^, sqrt, exp, log, sin, cos, tan, asin, acos, atan import IntervalArithmetic: mid, interval function slope(f::Function, x::Interval, c::Number) f(slope_var(x, c)).s end struct Slope{T} x::Interval{T} # Interval on which slope is evaluated c::Interval{T} # Point about which slope is evaluated (Interval to get bounded rounding errors) s::Interval{T} # Variable which propogates the slope information end Slope(c) = Slope(c, c, 0) Slope(a, b, c) = Slope(promote(convert(Interval, a), b, c)...) function slope_var(v::Number) Slope(v, v, 1) end function slope_var(v::Interval, c::Number) Slope(v, c, 1) end function interval(u::Slope) u.x end function mid(u::Slope) u.c end function slope(u::Slope) u.s end function +(u::Slope, v::Slope) Slope(u.x + v.x, u.c + v.c, u.s + v.s) end function -(u::Slope, v::Slope) Slope(u.x - v.x, u.c - v.c, u.s - v.s) end function *(u::Slope, v::Slope) Slope(u.x * v.x, u.c * v.c, u.s * v.c + u.x * v.s) end function /(u::Slope, v::Slope) Slope(u.x / v.x, u.c / v.c, (u.s - (u.c / v.c) * v.s) / v.x) end function +(u, v::Slope) Slope(u + v.x, u + v.c, v.s) end function -(u, v::Slope) Slope(u - v.x, u - v.c, -v.s) end function *(u, v::Slope) Slope(u * v.x, u * v.c, u * v.s) end function /(u, v::Slope) Slope(u / v.x, u / v.c, -(u / v.c) * (v.s / v.x)) end +(v::Slope, u) = u + v *(v::Slope, u) = u * v function -(u::Slope, v) Slope(u.x - v, u.c - v, u.s) end function -(u::Slope) Slope(-u.x, -u.c, -u.s) end function /(u::Slope, v) Slope(u.x / v, u.c / v, u.s / v) end function sqr(u::Slope) Slope(u.x ^ 2, u.c ^ 2, (u.x + u.c) * u.s) end function ^(u::Slope, k::Integer) if k == 0 return Slope(1) elseif k == 1 return u elseif k == 2 return sqr(u) else hxi = interval(u.x.lo) ^ k hxs = interval(u.x.hi) ^ k hx = hull(hxi, hxs) if (k % 2 == 0) && (0 ∈ u.x) hx = interval(0, hx.hi) end hc = u.c ^ k i = u.x.lo - u.c.lo s = u.x.hi - u.c.hi if ((i == 0) || (s == 0) || (k % 2 == 1 && zero(u.x) βͺ½ u.x)) h1 = k * (u.x ^ (k - 1)) else if k % 2 == 0 || u.x.lo >= 0 h1 = interval((hxi.hi - hc.lo) / i, (hxs.hi - hc.lo) / s) else h1 = interval((hxs.lo - hc.hi) / s, (hxi.lo - hc.hi) / i) end end return Slope(hx, hc, h1 * u.s) end end function sqrt(u::Slope) Slope(sqrt(u.x), sqrt(u.c), u.s / (sqrt(u.x) + sqrt(u.c))) end function exp(u::Slope) hx = exp(u.x) hc = exp(u.c) i = u.x.lo - u.c.lo s = u.x.hi - u.c.hi if (i == 0 || s == 0) h1 = hx else h1 = interval((hx.lo - hc.lo) / i, (hx.hi - hc.hi) / s) end Slope(hx, hc, h1 * u.s) end function log(u::Slope) hx = log(u.x) hc = log(u.c) i = u.x.lo - u.c.lo s = u.x.hi - u.c.hi if (i == 0 || s == 0) h1 = 1 / u.x else h1 = interval((hx.hi - hc.hi) / s, (hx.lo - hc.lo) / i) end Slope(hx, hc, h1 * u.s) end function sin(u::Slope) # Using derivative to upper bound the slope expansion for now hx = sin(u.x) hc = sin(u.c) hs = cos(u.x) Slope(hx, hc, hs) end function cos(u::Slope) # Using derivative to upper bound the slope expansion for now hx = cos(u.x) hc = cos(u.c) hs = -sin(u.x) Slope(hx, hc, hs) end function tan(u::Slope) # Using derivative to upper bound the slope expansion for now hx = tan(u.x) hc = tan(u.c) hs = (sec(u.x)) ^ 2 Slope(hx, hc, hs) end function asin(u::Slope) hx = asin(u.x) hc = asin(u.c) hs = 1 / sqrt(1 - (u.x ^ 2)) Slope(hx, hc, hs) end function acos(u::Slope) hx = acos(u.x) hc = acos(u.c) hs = -1 / sqrt(1 - (u.x ^ 2)) Slope(hx, hc, hs) end function atan(u::Slope) hx = atan(u.x) hc = atan(u.c) hs = 1 / 1 + (u.x ^ 2) Slope(hx, hc, hs) end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
1513
using ValidatedNumerics, ValidatedNumerics.RootFinding using Test @testset "Bisection tests" begin @testset "Single variable" begin f(x) = sin(x) + cos(x/2) + x/5 roots = bisection(f, -∞..∞, tolerance=1e-3) roots2 = [root.interval for root in roots] @test roots2 == [ Interval(-0.8408203124999999, -0.8398437499999999), Interval(3.6425781249999996, 3.6435546874999996), Interval(6.062499999999999, 6.063476562499999) ] end @testset "Two variables" begin @intervalbox g(x, y) = (x^2 + y^2 - 1, y - x) X = (-∞..∞) Γ— (-∞..∞) roots = bisection(g, X, tolerance=1e-3) roots2 = [root.interval for root in roots] @test roots2 == [IntervalBox(Interval(-0.7080078124999999, -0.7070312499999999), Interval(-0.7080078124999999, -0.7070312499999999)), IntervalBox(Interval(-0.7080078124999999, -0.7070312499999999), Interval(-0.7070312499999999, -0.7060546874999999)), IntervalBox(Interval(-0.7070312499999999, -0.7060546874999999), Interval(-0.7080078124999999, -0.7070312499999999)), IntervalBox(Interval(0.7060546874999999, 0.7070312499999999), Interval(0.7070312499999999, 0.7080078124999999)), IntervalBox(Interval(0.7070312499999999, 0.7080078124999999), Interval(0.7060546874999999, 0.7070312499999999)), IntervalBox(Interval(0.7070312499999999, 0.7080078124999999), Interval(0.7070312499999999, 0.7080078124999999))] end end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
3409
import IntervalRootFinding: BBLeaf, BBNode, BBTree import IntervalRootFinding: root, nnodes, data, newid, discard_leaf! import IntervalRootFinding: BreadthFirstBBSearch import IntervalRootFinding: process, bisect @testset "Branch and bound tree" begin #= Manually create a simple tree with the following structure (1) | (2) =# leaf = BBLeaf("I'm a leaf", 1, :final) node = BBNode(0, [2]) tree = BBTree(Dict(1 => node), Dict(2 => leaf), [2]) # Check that printing does not error io = IOBuffer() println(io, leaf) println(io, node) println(io, tree) @test root(tree) == node @test nnodes(tree) == 2 d = data(tree) @test length(d) == 1 @test d[1] == "I'm a leaf" k = newid(tree) @test k βˆ‰ 0:2 # The new ID must be new and not 0 @test isa(k, Integer) discard_leaf!(tree, 2) # The last leaf was deleted so the tree should be empty @test nnodes(tree) == 0 #= Tests on a slighty more complicated tree (1) / \ (2) (8) / \ \ (3) (5) (9) | | \ \ (4) (6) (7) (10) =# n1 = BBNode(0, [2, 8]) n2 = BBNode(1, [3, 5]) n3 = BBNode(2, [4]) n4 = BBLeaf("Leaf 4", 3, :working) n5 = BBNode(2, [6, 7]) n6 = BBLeaf("Leaf 6", 5, :final) n7 = BBLeaf("Leaf 7", 5, :working) n8 = BBNode(1, [9]) n9 = BBNode(8, [10]) n10 = BBLeaf("Leaf 10", 9, :working) tree = BBTree(Dict(1 => n1, 2 => n2, 3 => n3, 5 => n5, 8 => n8, 9 => n9), Dict(4 => n4, 6 => n6, 7 => n7, 10 => n10), [3, 4, 8]) # Check that printing does not error io = IOBuffer() println(io, tree) @test newid(tree) βˆ‰ 0:10 @test length(data(tree)) == 4 @test nnodes(tree) == 10 discard_leaf!(tree, 6) @test nnodes(tree) == 9 discard_leaf!(tree, 4) @test nnodes(tree) == 7 discard_leaf!(tree, 10) @test nnodes(tree) == 4 @test length(data(tree)) == 1 end # Implement the interface for breadth first in a dummy way struct DummySearch <: BreadthFirstBBSearch{Symbol} end process(::DummySearch, s::Symbol) = s, s bisect(::DummySearch, s::Symbol) = :store, :store @testset "Interface functions" begin #= Build the following tree for testing (1) / \ (2) (5: to_bisect) / \ (3: to_store) (4: to_discard) =# rt = BBNode(0, [2, 5]) node = BBNode(1, [3, 4]) to_store = BBLeaf(:store, 2, :working) to_discard = BBLeaf(:discard, 2, :working) to_bisect = BBLeaf(:bisect, 1, :working) tree = BBTree(Dict(1 => rt, 2 => node), Dict(3 => to_store, 4 => to_discard, 5 => to_bisect), [3, 4, 5]) search = DummySearch() # First iteration processes the to_store leaf tree, _ = iterate(search, tree) @test nnodes(tree) == 5 @test tree[3].status == :final @test length(tree.working_leaves) == 2 # Second iteration processes the to_discard leaf tree, _ = iterate(search, tree) @test nnodes(tree) == 4 @test length(tree.working_leaves) == 1 # Second iteration processes the to_bisect leaf tree, _ = iterate(search, tree) @test nnodes(tree) == 6 @test length(tree.working_leaves) == 2 @test isa(tree[5], BBNode) end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
5168
using IntervalArithmetic, IntervalRootFinding using ForwardDiff using Test const D = IntervalRootFinding.derivative include("wilkinson.jl") function generate_wilkinson(n)#, T=BigFloat) # SLOW p = poly(collect(1:n)) p_prime = polyder(p) coeffs = p.a #[convert(T, coeff) for coeff in p.a] # coeffs_prime = [convert(T, coeff) for coeff in p_prime.a] function f(x) total = coeffs[1] for i in 2:length(coeffs) total += coeffs[i]*x^(i-1) end total end f end setprecision(Interval, Float64) float_pi = @interval(pi) setprecision(Interval, 10000) big_pi = @interval(pi) # Using precision "only" 256 leads to overestimation of the true roots for `cos` # i.e the Newton method gives more accurate results! half_pi = big_pi / 2 three_halves_pi = 3*big_pi/2 # Format: (function, derivative, lower_bound, upper_bound, [true_roots]) function_list = [ (sin, cos, -5, 5, [ -big_pi, @interval(0), big_pi ] ) , (cos, x->D(cos, x), -7.5, 7.5, [ -three_halves_pi, -half_pi, half_pi, three_halves_pi ] ), (W₃, x->D(W₃, x), -10, 10, [ @interval(1), @interval(2), @interval(3) ] ), (W₇, x->D(W₇, x), -10, 10, [ @interval(i) for i in 1:7 ] ), (x->exp(x)-2, y->D(x->exp(x),y), -20, 20, [log(@biginterval(2))] ), (x->asin(sin(x)) - 0.1, y->D(x->asin(sin(x)),y), 0, 1, [@biginterval(0.1)]) ] @testset "Testing root finding" begin for rounding_type in (:wide, :narrow) @testset "Interval rounding: $rounding_type" begin # setrounding(Interval, rounding_type) for prec in ( (BigFloat,53), (BigFloat,256), (Float64,64) ) @testset "Precision: $prec" begin setprecision(Interval, prec) for method in (IntervalRootFinding.newton, IntervalRootFinding.krawczyk) @testset "Method $method" begin for func in function_list f, f_prime, a_lower, a_upper, true_roots = func a = @interval(a_lower, a_upper) @testset "Function $f; interval $a" begin for autodiff in (false, true) @testset "With autodiff=$autodiff" begin if autodiff rts = find_roots(f, a, method) else rts = find_roots(f, f_prime, a, method) end @test length(rts) == length(true_roots) for i in 1:length(rts) root = rts[i] @test isa(root, Root) @test is_unique(root) @test true_roots[i] βŠ† root.interval end end end end end end end end end end end end setprecision(Interval, Float64) @testset "find_roots tests" begin f(x) = x^2 - 2 rts = IntervalRootFinding.newton(f, @interval(10, 11)) @test length(rts) == 0 rts = IntervalRootFinding.find_roots_midpoint(f, -5, 5) @test length(rts) == 3 @test length(rts[1]) == 2 rts = find_roots(f, -5, 5) @test length(rts) == 2 setprecision(Interval, 256) for method in (IntervalRootFinding.newton, IntervalRootFinding.krawczyk) new_roots = method(f, rts) @test length(new_roots) == length(rts) for (root1, root2) in zip(new_roots, rts) @test root1 βŠ† root2 end end end @testset "Multiple roots" begin setprecision(Interval, Float64) let f(x) = (x-1) * (x^2 - 2)^3 * (x^3 - 2)^4 rts = IntervalRootFinding.newton(f, -5..5.1, maxlevel=1000) @test length(rts) == 4 @test rts[1].status == :unknown @test rts[1].interval == Interval(-1.4142135623730954, -1.414213562373095) @test rts[3].interval == Interval(1.259921049894873, 1.2599210498948734) end end @testset "Iterated logistic function fixed points" begin ∘(f, g) = x -> f(g(x)) iterate(f, n) = n == 1 ? f : f ∘ iterate(f, n-1) f(x) = 4x*(1-x) # logistic map for n in 1:10 g = x -> iterate(f, n)(x) - x # look for fixed points of f^n rts = IntervalRootFinding.newton(g, 0..1) @test length(rts) == 2^n rts = IntervalRootFinding.krawczyk(g, 0..1) @test length(rts) == 2^n end end # Example of a function with a double root at 0 from Burden & Faires, 9th ed, p.84 # exp(x) - x - 1
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
1083
using IntervalArithmetic, StaticArrays, IntervalRootFinding using Test function rand_vec(n::Int) a = randn(n) A = Interval.(a) mA = MVector{n}(A) sA = SVector{n}(A) return A, mA, sA end function rand_mat(n::Int) a = randn(n, n) A = Interval.(a) mA = MMatrix{n, n}(A) sA = SMatrix{n, n}(A) return A, mA, sA end @testset "Linear Equations" begin As = [[2..3 0..1; 1..2 2..3], ] bs = [[0..120, 60..240], ] xs = [[-120..90, -60..240], ] for i in 1:10 rand_A = rand_mat(i)[1] rand_x = rand_vec(i)[1] rand_b = rand_A * rand_x push!(As, rand_A) push!(bs, rand_b) push!(xs, rand_x) end n = length(As) for solver in (gauss_seidel_interval, gauss_seidel_contractor, gauss_elimination_interval, \) @testset "Solver $solver" begin #for precondition in (false, true) for i in 1:n soln = solver(As[i], bs[i]) @test all(xs[i] .βŠ† soln) end #end end end end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
2641
using IntervalArithmetic, IntervalRootFinding using ForwardDiff using Test const D = IntervalRootFinding.derivative setprecision(Interval, Float64) float_pi = @interval(pi) setprecision(Interval, 10000) big_pi = @interval(pi) # Using precision "only" 256 leads to overestimation of the true roots for `cos` # i.e the Newton method gives more accurate results! half_pi = big_pi / 2 three_halves_pi = 3*big_pi/2 @testset "Testing newton1d" begin f(x) = exp(x^2) - cos(x) #double root fβ€²(x) = 2*x*exp(x^2) + sin(x) f1(x) = x^4 - 10x^3 + 35x^2 - 50x + 24 #four unique roots f1β€²(x) = 4x^3 - 30x^2 + 70x - 50 f2(x) = 4567x^2 - 9134x + 4567 #double root f2β€²(x) = 9134x - 9134 f3(x) = (x^2 - 2)^2 #two double roots f3β€²(x) = 4x * (x^2 - 2) f4(x) = sin(x) - x #triple root at 0 f4β€²(x) = cos(x) - 1 f5(x) = (x^2 - 1)^4 * (x^2 - 2)^4 #two quadruple roots f5β€²(x) = 8x * (-3 + 2x^2) * (2 - 3x^2 + x^4)^3 for autodiff in (false, true) if autodiff rts1 = newton1d(sin, -5..5) rts2 = newton1d(f, -∞..∞) rts3 = newton1d(f1, -10..10) rts4 = newton1d(f2, -10..11) rts5 = newton1d(f3, -10..10) rts6 = newton1d(f4, -10..10) rts7 = newton1d(f5, -10..10) else rts1 = newton1d(sin, cos, -5..5) rts2 = newton1d(f, fβ€², -∞..∞) rts3 = newton1d(f1, f1β€², -10..10) rts4 = newton1d(f2, f2β€², -10..11) rts5 = newton1d(f3, f3β€², -10..10) rts6 = newton1d(f4, f4β€², -10..10) rts7 = newton1d(f5, f5β€², -10..10, reltol=0) end @test length(rts1) == 3 L = [-pi, 0, pi] for i = 1:length(rts1) @test L[i] in rts1[i].interval && :unique == rts1[i].status end @test length(rts2) == 1 @test (0..0) == rts2[1].interval && :unknown == rts2[1].status @test length(rts3) == 4 L = [1, 2, 3, 4] for i = 1:length(rts3) @test L[i] in rts3[i].interval && :unique == rts3[i].status end @test length(rts4) == 1 @test 1 in rts4[1].interval && :unknown == rts4[1].status L1 = [-sqrt(2), sqrt(2)] for i = 1:length(rts5) @test L1[i] in rts5[i].interval && :unknown == rts5[i].status end @test length(rts6) == 1 @test 0 in rts6[1].interval && :unknown == rts6[1].status @test length(rts7) == 4 L = [-sqrt(2), -1, 1, sqrt(2)] for i = 1:length(rts7) @test L[i] in rts7[i].interval && :unknown == rts7[i].status end end end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
770
using IntervalArithmetic, IntervalRootFinding struct Quad{T} a::Interval{T} b::Interval{T} c::Interval{T} x::Vector{Interval{T}} end @testset "Quadratic Interval Equations" begin rts = Quad{Float64}[] push!(rts, Quad(interval(1, 5), interval(2, 4), interval(0, 2), [interval(-4, -2), interval(-0, -0)])) push!(rts, Quad(interval(-1, 1), interval(-2, 2), interval(-1, 1), [interval(-∞, -1), interval(-1, -1), interval(-1, ∞)])) push!(rts, Quad(interval(1, 2), interval(1, 3), interval(2, 6), [interval(-2, -1)])) push!(rts, Quad(interval(1, 1), interval(2, 2), interval(1, 1), [interval(-1, -1), interval(-1, -1)])) for i in 1:length(rts) @test quadratic_roots(rts[i].a, rts[i].b, rts[i].c) == rts[i].x end end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
4081
using IntervalArithmetic, IntervalRootFinding, StaticArrays, ForwardDiff using Test function all_unique(rts) all(root_status.(rts) .== :unique) end function roots_dist(rt1::Root{T}, rt2::Root{T}) where {T <: Interval} d = dist(interval(rt1), interval(rt2)) return sum(d) end function roots_dist(rt1::Root{T}, rt2::Root{T}) where {T <: IntervalBox} return sum(dist.(interval(rt1), interval(rt2))) end function roots_dist(rt1::Root{Complex{T}}, rt2::Root{Complex{T}}) where {T <: Interval} dreal = dist(real(interval(rt1)), real(interval(rt2))) dimag = dist(imag(interval(rt1)), imag(interval(rt2))) return sum(dreal) + sum(dimag) end function test_newtonlike(f, deriv, X, method, nsol, tol=1e-10) rts = roots(f, X, method) @test length(rts) == nsol @test all_unique(rts) @test sum(roots_dist.(rts, roots(f, deriv, X, method))) < tol end newtonlike_methods = [Newton, Krawczyk] @testset "1D roots" begin # Default rts = roots(sin, -5..5) @test length(rts) == 3 @test all_unique(rts) # Bisection rts = roots(sin, -5..6, Bisection, 1e-3) @test length(rts) == 3 # Refinement rts = roots(sin, rts, Newton) @test all_unique(rts) for method in newtonlike_methods test_newtonlike(sin, cos, -5..5, method, 3) end # Infinite interval rts = roots(x -> x^2 - 2, -∞..∞) @test length(rts) == 2 end in_solution_set(point, solution_intervals) = any(interval -> point in interval, solution_intervals) @testset "2D roots" begin f(x, y) = SVector(x^2 + y^2 - 1, y - 2x) f(X) = f(X...) X = (-6..6) Γ— (-6..6) # Bisection rts = roots(f, X, Bisection, 1e-3) exact_sol = [sqrt(1/5), 2sqrt(1/5)] @test in_solution_set(exact_sol, interval.(rts)) @test in_solution_set(-exact_sol, interval.(rts)) for method in newtonlike_methods deriv = xx -> ForwardDiff.jacobian(f, xx) test_newtonlike(f, deriv, X, method, 2) end # Infinite interval X = IntervalBox(-∞..∞, 2) rts = roots(f, X, Newton) @test length(rts) == 2 end # From R docs: # https://www.rdocumentation.org/packages/pracma/versions/1.9.9/topics/broyden @testset "3D roots" begin function g(x) (x1, x2, x3) = x SVector( x1^2 + x2^2 + x3^2 - 1, x1^2 + x3^2 - 0.25, x1^2 + x2^2 - 4x3 ) end X = (-5..5) XX = IntervalBox(X, 3) for method in newtonlike_methods rts = roots(g, XX, method) @test length(rts) == 4 @test all_unique(rts) deriv = xx -> ForwardDiff.jacobian(g, xx) @test rts == roots(g, deriv, XX, method) end end @testset "Out of domain" begin for method in newtonlike_methods @test length(roots(log, -100..2, method)) == 1 @test length(roots(log, -100..(-1), method)) == 0 end end @testset "Infinite domain" begin for method in newtonlike_methods rts = roots(x -> x^2 - 2, -∞..∞, method) @test length(filter(isunique, rts)) == 2 end end @testset "NaN return value" begin f(xx) = ( (x, y) = xx; SVector(log(y/x) + 3x, y - 2x) ) X = IntervalBox(-100..100, 2) for method in newtonlike_methods rts = roots(f, X, method) @test length(filter(isunique, rts)) == 1 @test length(filter(x -> contains_zero(x.interval), rts)) == 1 end end @testset "Stationary points" begin f(xx) = ( (x, y) = xx; sin(x) * sin(y) ) gradf = βˆ‡(f) XX = IntervalBox(-5..6, 2) tol = 1e-5 for method in newtonlike_methods deriv = xx -> ForwardDiff.jacobian(gradf, xx) test_newtonlike(gradf, deriv, XX, method, 25, tol) end end @testset "Complex roots" begin X = -5..5 Xc = Complex(X, X) f(z) = z^3 - 1 # Default rts = roots(f, Xc) @test length(rts) == 3 # Bisection rts = roots(f, Xc, Bisection, 1e-3) @test length(rts) == 7 for method in newtonlike_methods deriv = z -> 3*z^2 test_newtonlike(f, deriv, Xc, method, 3, 1e-10) end end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
238
using IntervalRootFinding using Test include("branch_and_bound.jl") include("search_interface.jl") include("roots.jl") include("test_smiley.jl") include("newton1d.jl") include("quadratic.jl") include("linear_eq.jl") include("slopes.jl")
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
594
using IntervalArithmetic using IntervalRootFinding @testset "Root search iterator interface" begin contractor = Newton(sin, cos) search = BreadthFirstSearch(-10..10, contractor, 1e-3) # First iteration of the search elem, state = iterate(search) # Optional iterator methods @test eltype(search) != Any end @testset "Search strategies" begin # DepthFristSearch and BreadthFristSearch should return the same results X = -5..5 rts = roots(sin, cos, X, Newton, DepthFirstSearch) @test Set(rts) == Set(roots(sin, cos, X, Newton, BreadthFirstSearch)) end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
1365
using IntervalArithmetic, IntervalRootFinding using ForwardDiff using Test struct Slopes{T} f::Function x::Interval{T} c::T sol::Interval{T} end @testset "Automatic slope expansion" begin for T in [Float64, BigFloat] s = interval(T(0.75), T(1.75)) example = Slopes{T}[] push!(example, Slopes(x->((x + sin(x)) * exp(-x^2)), s, mid(s), interval(T(-2.8), T(0.1)))) push!(example, Slopes(x->(x^4 - 10x^3 + 35x^2 - 50x + 24), s, mid(s), interval(T(-44), T(38.5)))) push!(example, Slopes(x->((log(x + 1.25) - 0.84x) ^ 2), s, mid(s), interval(T(-0.16), T(0.44)))) push!(example, Slopes(x->(0.02x^2 - 0.03exp(-(20(x - 0.875))^2)), s, mid(s), interval(T(0.03), T(0.33)))) push!(example, Slopes(x->(exp(x^2)), s, mid(s), interval(T(6.03), T(33.23)))) push!(example, Slopes(x->(x^4 - 12x^3 + 47x^2 - 60x - 20exp(-x)), s, mid(s), interval(T(-39), T(65.56)))) push!(example, Slopes(x->(x^6 - 15x^4 + 27x^2 + 250), s, mid(s), interval(T(-146.9), T(67.1)))) push!(example, Slopes(x->(atan(cos(tan(x)))), s, mid(s), interval(T(1), T(2)))) push!(example, Slopes(x->(asin(cos(acos(sin(x))))), s, mid(s), interval(T(1.36), T(∞)))) for i in 1:length(example) @test slope(example[i].f, example[i].x, example[i].c) βŠ† example[i].sol end end end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
1193
include("../examples/smiley_examples.jl") using Test using IntervalArithmetic, IntervalRootFinding using .SmileyExample22, .SmileyExample52, .SmileyExample54, .SmileyExample55 function test_all_unique(xs) for x in xs @test x.status == :unique end return nothing end const tol = 1e-6 for method in (Newton, Krawczyk) # NOTE: Bisection method performs badly in all examples @info("Testing method $(method)") @testset "$(SmileyExample22.title)" begin roots_found = roots(SmileyExample22.f, SmileyExample22.region, method, tol) @test length(roots_found) == 8 test_all_unique(roots_found) # no reference data for roots given end for example in (SmileyExample52, SmileyExample54)#, SmileyExample55) @testset "$(example.title)" begin roots_found = roots(example.f, example.region, method, tol) @test length(roots_found) == length(example.known_roots) test_all_unique(roots_found) for rf in roots_found # check there is exactly one known root for each found root @test sum(!isempty(rk ∩ rf.interval) for rk in example.known_roots) == 1 end end end end # method loop
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
code
1115
# Wilkinson-type polynomial defined by its roots: # wβ‚™(x) = (x-1)β‹…(x-2)β‹… β‹― β‹… (x-n) using Polynomials # function generate_wilkinson(n)#, T=BigFloat) # SLOW # p = poly(collect(1:n)) # p_prime = polyder(p) # coeffs = p.a #[convert(T, coeff) for coeff in p.a] # # coeffs_prime = [convert(T, coeff) for coeff in p_prime.a] # function f(x) # total = coeffs[1] # for i in 2:length(coeffs) # total += coeffs[i]*x^(i-1) # end # total # end # f # end function generate_wilkinson_horner(n) p = poly(collect(1:n)) # make polynomial with roots 1 to n coeffs = p.a expr = :($(coeffs[end])) for i in length(coeffs)-1:-1:1 expr = :($expr*x + $(coeffs[i])) end expr end function subscriptify(n::Int) subscript_digits = [c for c in "β‚€β‚β‚‚β‚ƒβ‚„β‚…β‚†β‚‡β‚ˆβ‚‰"] dig = reverse(digits(n)) join([subscript_digits[i+1] for i in dig]) end # Generate Wilkinson functions W₃ etc.: for n in 1:15 fn_name = Symbol("W", subscriptify(n)) expr = generate_wilkinson_horner(n) @eval $(fn_name)(x) = $(expr) end
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git
[ "MIT" ]
0.5.11
b92e9e2b356146918c4f3f3845571abcf0501594
docs
215
# Updates to `IntervalRootFinding.jl` ## v0.2 The package has been completely rewritten for v0.2. It now contains basic bisection and Newton interval routines for functions with an arbitrary number of parameters.
IntervalRootFinding
https://github.com/JuliaIntervals/IntervalRootFinding.jl.git