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",
"MIT"
] | 0.3.0 | 18f351cf7c965887503553d2bccb0fbc7ede13b3 | docs | 6698 | [](https://codecov.io/gh/jessymilare/FlagSets.jl)
[](https://travis-ci.com/jessymilare/FlagSets.jl)
# FlagSets.jl
`FlagSet.jl` provides an `Enum`-like type for bit flag option values. The main features
are:
1. Flags have implicit numbering with incrementing powers of 2.
2. Binary OR (`|`), AND (`&`) and XOR(`⊻`) operations are supported among members.
3. Set operations like `union`, `intersect`, `setdiff`, `in` and `issubset` are also
supported.
4. Values are pretty-printed, showing the FlagSet type and each flag set.
This implementation is based on [BitFlags](https://github.com/jmert/BitFlags.jl), with
some differences:
1. Each flag set is treated as a set of flags and internally represented as an `Integer`
(whose bits 1 corresponds to the flags in the set).
2. The empty flag set (corresponding to 0) is always valid.
3. The macros `@symbol_flagset` and `@flagset` don't create a constant for each flag.
4. Each flag can be represented by objects of arbitrary type (new in 0.3).
_Note:_ A breaking change has been introduced in version 0.3. The macro `@symbol_flagset`
corresponds to the old `@flagset` macro and the latter has been made more general.
## Symbol flag sets
To create a new `FlagSet{Symbol}` type, you can use the `@symbol_flagset` macro
(old syntax) or the more general and flexible `@flagset` macro.
You need to provide a type name, an optional integer type, and a list of the flag
names (with optional associated bits).
A new definition can be given in inline form:
```julia
@symbol_flagset FlagSetName[::BaseType] flag_1[=bit_1] flag_2[=bit_2] ...
@flagset FlagSetName [{Symbol,BaseType}] [bit_1 -->] :flag_1 [bit_2 -->] :flag_2 ...
```
or as a block definition:
```julia
@symbol_flagset FlagSetName[::BaseType] begin
flag_1[=bit_1]
flag_2[=bit_2]
...
end
@flagset FlagSetName [{Symbol,BaseType}] begin
[bit_1 -->] :flag_1
[bit_2 -->] :flag_2
...
end
```
Automatic numbering starts at 1. In the following example, we build an 8-bit `FlagSet`
with no value for bit 3 (value of 4).
```julia
julia> @flagset FontFlags1 :bold :italic 8 --> :large
```
Instances can be created from integers or flag names and composed with bitwise operations.
Flag names can be symbols or keyword arguments.
```julia
julia> FontFlags1(1)
FontFlags1 with 1 element:
:bold
julia> FontFlags1(:bold, :italic)
FontFlags1 with 2 elements:
:bold
:italic
julia> FontFlags1(bold = true, italic = false, large = true)
FontFlags1 with 2 elements:
:bold
:large
julia> FontFlags1(3) | FontFlags1(8)
FontFlags1 with 3 elements:
:bold
:italic
:large
```
Flag sets support iteration and other set operations
```julia
julia> for flag in FontFlags1(3); println(flag) end
bold
italic
julia> :bold in FontFlags1(3)
true
```
Conversion to and from integers is permitted, but only when the integer contains valid
bits for the flag set type.
```julia
julia> Int(FontFlags1(:bold))
1
julia> Integer(FontFlags1(:italic)) # Abstract Integer uses base type
0x00000002
julia> FontFlags1(9)
FontFlags1 with 2 elements:
:bold
:large
julia> FontFlags1(4)
ERROR: ArgumentError: invalid value for FlagSet FontFlags1: 4
Stacktrace:
...
```
Supplying a different BaseType:
```
julia> @flagset FontFlags2 {Symbol,UInt8} :bold :italic 8 --> :large
# Or let the macro infer the flag type
julia> @flagset FontFlags3 {_,UInt8} :bold :italic 8 --> :large
julia> Integer(FontFlags2(:italic))
0x02
julia> Integer(FontFlags3(:italic))
0x02
julia> eltype(FontFlags2) == eltype(FontFlags3) == Symbol
true
```
The empty and the full set can be created with `typemin` and `typemax`:
```julia
julia> typemin(FontFlags1)
FontFlags1([])
julia> typemax(FontFlags1)
FontFlags1 with 3 elements:
:bold
:italic
:large
```
## Flag sets with custom flag type
The syntax of `@flagset` macro is similar (but incompatible) with `@symbol_flagset`.
These are the most important differences:
1. The flags are evaluated (during macroexpansion).
2. The creator from flag values is absent, used `T([flags...])` instead.
3. To provide an explicit associated bit, use the following syntax: `bit --> flag`.
4. To provide a key to be used as keyword argument, use the following syntax:
`key = [bit -->] flag` (note that the key comes before the bit, if it is also supplied).
5. `FlagType` and/or `BaseType` can be supplied between braces.
In the example below, the type `RoundingFlags1` is created only from flag values.
```julia
julia> @flagset RoundingFlags1 RoundDown RoundUp RoundNearest
julia> RoundingFlags1([RoundDown, RoundUp])
RoundingFlags1 with 2 elements:
RoundingMode{:Down}()
RoundingMode{:Up}()
julia> Integer(RoundingFlags1([RoundDown, RoundUp]))
0x00000003
```
`RoundingFlags2` uses flags with custom bits for some flags:
```
julia> @flagset RoundingFlags2 RoundDown 4--> RoundUp 8 --> RoundNearest
julia> Integer(RoundingFlags2([RoundDown, RoundUp]))
0x00000005
```
`RoundingFlags3` also specifies keys for flags (except the last), flag and base types:
```
julia> @flagset RoundingFlags3 {Any,UInt8} begin
down = RoundDown
up = RoundUp
near = 16 --> RoundNearest
64 --> RoundNearestTiesUp
end
julia> RoundingFlags3(up = true, near = true)
RoundingFlags3 with 2 elements:
RoundingMode{:Up}()
RoundingMode{:Nearest}()
julia> eltype(RoundingFlags3)
Any
julia> typeof(Integer(RoundingFlags3()))
UInt8
```
## Printing
Printing a `FlagSet` subtype shows usefull information about it:
```julia
julia> FontFlags1
FlagSet FontFlags1:
0x01 --> :bold
0x02 --> :italic
0x08 --> :large
julia> RoundingFlags3
FlagSet RoundingFlags3:
0x00000001 --> RoundingMode{:Down}()
0x00000002 --> RoundingMode{:Up}()
0x00000010 --> RoundingMode{:Nearest}()
0x00000040 --> RoundingMode{:NearestTiesUp}()
```
In a compact context (such as in multi-dimensional arrays), the pretty-printing
takes on a shorter form:
```julia
julia> [FontFlags1(), FontFlags1(:bold, :large)]
2-element Vector{FontFlags1}:
FontFlags1([])
FontFlags1([:bold, :large])
julia> [RoundingFlags3() RoundingFlags3([RoundUp, RoundNearest])]
1×2 Matrix{RoundingFlags3}:
RoundingFlags3(0x00000000) RoundingFlags3(0x00000012)
julia> show(IOContext(stdout, :compact => true), FontFlags1(:bold, :large))
FontFlags1(0x09)
```
## Input/Output
`FlagSet`s support writing to and reading from streams as integers:
```julia
julia> io = IOBuffer();
julia> write(io, UInt8(9));
julia> seekstart(io);
julia> read(io, FontFlags1)
FontFlags1 with 2 elements:
:bold
:large
```
| FlagSets | https://github.com/jessymilare/FlagSets.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 3951 | using Documenter
using BasicBSpline
using BasicBSplineExporter
using BasicBSplineFitting
using InteractiveUtils
using Plots
using Random
gr()
plotly()
Random.seed!(42)
# Setup for doctests in docstrings
DocMeta.setdocmeta!(BasicBSpline, :DocTestSetup, :(using LinearAlgebra, BasicBSpline, StaticArrays, BasicBSplineFitting))
DocMeta.setdocmeta!(BasicBSplineFitting, :DocTestSetup, :(using LinearAlgebra, BasicBSpline, StaticArrays, BasicBSplineFitting))
function generate_indexmd_from_readmemd()
path_readme = "README.md"
path_index = "docs/src/index.md"
# open README.md
text_readme = read(path_readme, String)
# generate text for index.md
text_index = text_readme
text_index = replace(text_index, r"\$\$((.|\n)*?)\$\$" => s"```math\1```")
text_index = replace(text_index, "(https://hyrodium.github.io/BasicBSpline.jl/dev/math/bsplinebasis/#Differentiability-and-knot-duplications)" => "(@ref differentiability-and-knot-duplications)")
text_index = replace(text_index, r"https://github.com/hyrodium/BasicBSpline\.jl/assets/.*" => "")
text_index = replace(text_index, "```julia\njulia>" => "```julia-repl\njulia>")
text_index = replace(text_index, "```julia\n" => "```@example readme\n")
text_index = replace(text_index, r"```\n!\[\]\(docs/src/img/(.*?)plotly\.png\)" => s"savefig(\"readme-\1plotly.html\") # hide\nnothing # hide\n```\n```@raw html\n<object type=\"text/html\" data=\"readme-\1plotly.html\" style=\"width:100%;height:420px;\"></object>\n```")
text_index = replace(text_index, r"```\n!\[\]\(docs/src/img/(.*?)\.png\)" => s"savefig(\"readme-\1.png\") # hide\nnothing # hide\n```\n")
text_index = replace(text_index, "
text_index = replace(text_index, "" => "")
text_index = replace(text_index, "" => "")
text_index = """
```@meta
EditURL = "https://github.com/hyrodium/BasicBSpline.jl/blob/main/README.md"
```
""" * text_index
# save index.md
open(path_index, "w") do f
write(f,text_index)
end
end
generate_indexmd_from_readmemd()
makedocs(;
modules = [BasicBSpline, BasicBSplineFitting],
format = Documenter.HTML(
ansicolor=true,
canonical = "https://hyrodium.github.io/BasicBSpline.jl",
assets = ["assets/favicon.ico", "assets/custom.css"],
edit_link="main",
repolink="https://github.com/hyrodium/BasicBSpline.jl"
),
pages = [
"Home" => "index.md",
"Mathematical properties of B-spline" => [
"Introduction" => "math/introduction.md",
"Knot vector" => "math/knotvector.md",
"B-spline space" => "math/bsplinespace.md",
"B-spline basis function" => "math/bsplinebasis.md",
"B-spline manifold" => "math/bsplinemanifold.md",
"Rational B-spline manifold" => "math/rationalbsplinemanifold.md",
"Inclusive relationship" => "math/inclusive.md",
"Refinement" => "math/refinement.md",
"Derivative" => "math/derivative.md",
"Fitting" => "math/fitting.md",
],
# "Differentiation" => [
# "BSplineDerivativeSpace" => "bsplinederivativespace.md",
# "ForwardDiff" => "forwarddiff.md",
# "ChainRules" => "chainrules.md"
# ],
"Visualization" => [
"PlotlyJS.jl" => "visualization/plotlyjs.md",
"BasicBSplineExporter.jl" => "visualization/basicbsplineexporter.md",
],
"Interpolations" => "interpolations.md",
"API" => "api.md",
],
sitename = "BasicBSpline.jl",
authors = "hyrodium <[email protected]>",
warnonly = true,
)
deploydocs(
repo = "github.com/hyrodium/BasicBSpline.jl",
push_preview = true,
devbranch="main",
)
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 742 | # Run this script after running make.jl
dir_build = joinpath(@__DIR__, "build")
dir_img = joinpath(@__DIR__, "src", "img")
for filename in readdir(dir_build)
path_src = joinpath(dir_build, filename)
if startswith(filename, "readme-") && endswith(filename, ".html")
println(path_src)
path_png = joinpath(dir_img, chopsuffix(chopprefix(filename, "readme-"), ".html") * ".png")
cmd = `google-chrome-stable --headless --disable-gpu --screenshot=$path_png $path_src`
run(cmd)
end
if startswith(filename, "readme-") && endswith(filename, ".png")
println(path_src)
path_png = joinpath(dir_img, chopprefix(filename, "readme-"))
cp(path_src, path_png; force=true)
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 3352 | module BasicBSplineChainRulesCoreExt
using BasicBSpline
using ChainRulesCore
import BasicBSpline.AbstractFunctionSpace
import BasicBSpline.derivative
const BSPLINESPACE_INFO = """
derivatives of B-spline basis functions with respect to BSplineSpace not implemented currently.
"""
# bsplinebasis
function ChainRulesCore.frule((_, ΔP, Δi, Δt), ::typeof(bsplinebasis), P::AbstractFunctionSpace, i::Integer, t::Real)
B = bsplinebasis(P,i,t)
∂B_∂P = @not_implemented BSPLINESPACE_INFO
# ∂B_∂i = NoTangent()
∂B_∂t = bsplinebasis′(P,i,t)
return (B, ∂B_∂P*ΔP + ∂B_∂t*Δt)
end
function ChainRulesCore.rrule(::typeof(bsplinebasis), P::AbstractFunctionSpace, i::Integer, t::Real)
B = bsplinebasis(P,i,t)
# project_t = ProjectTo(t) # Not sure we need this ProjectTo.
function bsplinebasis_pullback(ΔB)
P̄ = @not_implemented BSPLINESPACE_INFO
ī = NoTangent()
t̄ = bsplinebasis′(P,i,t) * ΔB
return (NoTangent(), P̄, ī, t̄)
end
return (B, bsplinebasis_pullback)
end
# bsplinebasis₊₀
function ChainRulesCore.frule((_, ΔP, Δi, Δt), ::typeof(bsplinebasis₊₀), P::AbstractFunctionSpace, i::Integer, t::Real)
B = bsplinebasis₊₀(P,i,t)
∂B_∂P = @not_implemented BSPLINESPACE_INFO
# ∂B_∂i = NoTangent()
∂B_∂t = bsplinebasis′₊₀(P,i,t)
return (B, ∂B_∂P*ΔP + ∂B_∂t*Δt)
end
function ChainRulesCore.rrule(::typeof(bsplinebasis₊₀), P::AbstractFunctionSpace, i::Integer, t::Real)
B = bsplinebasis₊₀(P,i,t)
# project_t = ProjectTo(t) # Not sure we need this ProjectTo.
function bsplinebasis_pullback(ΔB)
P̄ = @not_implemented BSPLINESPACE_INFO
ī = NoTangent()
t̄ = bsplinebasis′₊₀(P,i,t) * ΔB
return (NoTangent(), P̄, ī, t̄)
end
return (B, bsplinebasis_pullback)
end
# bsplinebasis₋₀
function ChainRulesCore.frule((_, ΔP, Δi, Δt), ::typeof(bsplinebasis₋₀), P::AbstractFunctionSpace, i::Integer, t::Real)
B = bsplinebasis₋₀(P,i,t)
∂B_∂P = @not_implemented BSPLINESPACE_INFO
# ∂B_∂i = NoTangent()
∂B_∂t = bsplinebasis′₋₀(P,i,t)
return (B, ∂B_∂P*ΔP + ∂B_∂t*Δt)
end
function ChainRulesCore.rrule(::typeof(bsplinebasis₋₀), P::AbstractFunctionSpace, i::Integer, t::Real)
B = bsplinebasis₋₀(P,i,t)
# project_t = ProjectTo(t) # Not sure we need this ProjectTo.
function bsplinebasis_pullback(ΔB)
P̄ = @not_implemented BSPLINESPACE_INFO
ī = NoTangent()
t̄ = bsplinebasis′₋₀(P,i,t) * ΔB
return (NoTangent(), P̄, ī, t̄)
end
return (B, bsplinebasis_pullback)
end
# bsplinebasisall
function ChainRulesCore.frule((_, ΔP, Δi, Δt), ::typeof(bsplinebasisall), P::AbstractFunctionSpace, i::Integer, t::Real)
B = bsplinebasisall(P,i,t)
∂B_∂P = @not_implemented BSPLINESPACE_INFO
# ∂B_∂i = NoTangent()
∂B_∂t = bsplinebasisall(derivative(P),i,t)
return (B, ∂B_∂P*ΔP + ∂B_∂t*Δt)
end
function ChainRulesCore.rrule(::typeof(bsplinebasisall), P::AbstractFunctionSpace, i::Integer, t::Real)
B = bsplinebasisall(P,i,t)
# project_t = ProjectTo(t) # Not sure we need this ProjectTo.
function bsplinebasis_pullback(ΔB)
P̄ = @not_implemented BSPLINESPACE_INFO
ī = NoTangent()
t̄ = bsplinebasisall(derivative(P),i,t)' * ΔB
return (NoTangent(), P̄, ī, t̄)
end
return (B, bsplinebasis_pullback)
end
end # module
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 11785 | module BasicBSplineRecipesBaseExt
using BasicBSpline
using RecipesBase
import BasicBSpline.AbstractFunctionSpace
using StaticArrays
# B-spline space
@recipe function f(k::AbstractKnotVector; gap=0.02, offset=0.0, plane=:xy)
u = BasicBSpline._vec(k)
l = length(u)
v = fill(float(offset), l)
for i in 2:l
if u[i-1] == u[i]
v[i] = v[i-1] - gap
end
end
seriestype := :scatter
delete!(plotattributes, :gap)
delete!(plotattributes, :plane)
if plane === :xy
u, v
elseif plane === :xy
v, u
elseif plane === :xz
u, zero(u), v
elseif plane === :yz
zero(u), u, v
end
end
# B-spline space
@recipe function f(P::AbstractFunctionSpace; division_number=20, plane=:xy)
k = knotvector(P)
ts = Float64[]
for i in 1:length(k)-1
append!(ts, range(nextfloat(float(k[i])), prevfloat(float(k[i+1])), length=division_number+1))
end
pushfirst!(ts, k[begin])
push!(ts, k[end])
sort!(ts)
unique!(ts)
n = dim(P)
tt = repeat([ts;NaN],n)
bs = [bsplinebasis(P,i,t) for t in ts, i in 1:n]
bb = vec(vcat(bs,zeros(n)'))
delete!(plotattributes, :division_number)
delete!(plotattributes, :plane)
if plane === :xy
tt, bb
elseif plane === :xy
bb, tt
elseif plane === :xz
tt, zero(tt), bb
elseif plane === :yz
zero(tt), tt, bb
end
end
const _Manifold{Dim1, Dim2} = Union{BSplineManifold{Dim1,Deg,<:StaticVector{Dim2,<:Real}}, RationalBSplineManifold{Dim1,Deg,<:StaticVector{Dim2,<:Real}}} where Deg
Base.@kwdef struct PlotAttributesContolPoints
# https://docs.juliaplots.org/latest/generated/attributes_series/
line_z=nothing
linealpha=nothing
linecolor=:gray
linestyle=:solid
linewidth=:auto
marker_z=nothing
markeralpha=nothing
markercolor=:gray
markershape=:circle
markersize=4
markerstrokealpha=nothing
markerstrokecolor=:match
markerstrokestyle=:solid
markerstrokewidth=1
end
@recipe function f(M::_Manifold{1, 2}; controlpoints=(;), division_number=100)
attributes = PlotAttributesContolPoints(;controlpoints...)
t_min, t_max = extrema(domain(bsplinespaces(M)[1]))
ts = range(t_min, t_max, length=division_number+1)
@series begin
primary := false
line_z := attributes.line_z
linealpha := attributes.linealpha
linecolor := attributes.linecolor
linestyle := attributes.linestyle
linewidth := attributes.linewidth
marker_z := attributes.marker_z
markeralpha := attributes.markeralpha
markercolor := attributes.markercolor
markershape := attributes.markershape
markersize := attributes.markersize
markerstrokealpha := attributes.markerstrokealpha
markerstrokecolor := attributes.markerstrokecolor
markerstrokestyle := attributes.markerstrokestyle
markerstrokewidth := attributes.markerstrokewidth
a = BasicBSpline.controlpoints(M)
getindex.(a,1), getindex.(a,2)
end
p = M.(ts)
delete!(plotattributes, :controlpoints)
delete!(plotattributes, :division_number)
getindex.(p,1), getindex.(p,2)
end
@recipe function f(M::_Manifold{1, 3}; controlpoints=(;), division_number=100)
attributes = PlotAttributesContolPoints(;controlpoints...)
t_min, t_max = extrema(domain(bsplinespaces(M)[1]))
ts = range(t_min, t_max, length=division_number+1)
@series begin
primary := false
line_z := attributes.line_z
linealpha := attributes.linealpha
linecolor := attributes.linecolor
linestyle := attributes.linestyle
linewidth := attributes.linewidth
marker_z := attributes.marker_z
markeralpha := attributes.markeralpha
markercolor := attributes.markercolor
markershape := attributes.markershape
markersize := attributes.markersize
markerstrokealpha := attributes.markerstrokealpha
markerstrokecolor := attributes.markerstrokecolor
markerstrokestyle := attributes.markerstrokestyle
markerstrokewidth := attributes.markerstrokewidth
a = BasicBSpline.controlpoints(M)
getindex.(a,1), getindex.(a,2), getindex.(a,3)
end
p = M.(ts)
delete!(plotattributes, :controlpoints)
delete!(plotattributes, :division_number)
getindex.(p,1), getindex.(p,2), getindex.(p,3)
end
@recipe function f(M::_Manifold{2, 2}; controlpoints=(;), division_number=100)
attributes = PlotAttributesContolPoints(;controlpoints...)
a = BasicBSpline.controlpoints(M)
@series begin
primary := false
marker_z := attributes.marker_z
markeralpha := attributes.markeralpha
markercolor := attributes.markercolor
markershape := attributes.markershape
markersize := attributes.markersize
markerstrokealpha := attributes.markerstrokealpha
markerstrokecolor := attributes.markerstrokecolor
markerstrokestyle := attributes.markerstrokestyle
markerstrokewidth := attributes.markerstrokewidth
seriestype := :scatter
getindex.(a,1), getindex.(a,2)
end
@series begin
primary := false
line_z := attributes.line_z
linealpha := attributes.linealpha
linecolor := attributes.linecolor
linestyle := attributes.linestyle
linewidth := attributes.linewidth
seriestype := :path
getindex.(a,1), getindex.(a,2)
end
@series begin
primary := false
line_z := attributes.line_z
linealpha := attributes.linealpha
linecolor := attributes.linecolor
linestyle := attributes.linestyle
linewidth := attributes.linewidth
seriestype := :path
getindex.(a',1), getindex.(a',2)
end
I1, I2 = domain.(bsplinespaces(M))
a1, b1 = float.(extrema(I1))
a2, b2 = float.(extrema(I2))
ts_boundary = [
[(t1, a2) for t1 in view(range(I1, length=division_number+1), 1:division_number)];
[(b1, t2) for t2 in view(range(I2, length=division_number+1), 1:division_number)];
[(t1, b2) for t1 in view(range(I1, length=division_number+1), division_number+1:-1:2)];
[(a1, t2) for t2 in view(range(I2, length=division_number+1), division_number+1:-1:1)]
]
ps_boundary = [M(t...) for t in ts_boundary]
fill := true
fillalpha --> 0.5
delete!(plotattributes, :controlpoints)
delete!(plotattributes, :division_number)
getindex.(ps_boundary,1), getindex.(ps_boundary,2)
end
@recipe function f(M::_Manifold{2, 3}; controlpoints=(;), division_number=100)
attributes = PlotAttributesContolPoints(;controlpoints...)
t1_min, t1_max = extrema(domain(bsplinespaces(M)[1]))
t2_min, t2_max = extrema(domain(bsplinespaces(M)[2]))
t1s = range(t1_min, t1_max, length=division_number+1)
t2s = range(t2_min, t2_max, length=division_number+1)
a = BasicBSpline.controlpoints(M)
@series begin
primary := false
marker_z := attributes.marker_z
markeralpha := attributes.markeralpha
markercolor := attributes.markercolor
markershape := attributes.markershape
markersize := attributes.markersize
markerstrokealpha := attributes.markerstrokealpha
markerstrokecolor := attributes.markerstrokecolor
markerstrokestyle := attributes.markerstrokestyle
markerstrokewidth := attributes.markerstrokewidth
seriestype := :scatter
getindex.(a,1), getindex.(a,2), getindex.(a,3)
end
@series begin
primary := false
line_z := attributes.line_z
linealpha := attributes.linealpha
linecolor := attributes.linecolor
linestyle := attributes.linestyle
linewidth := attributes.linewidth
seriestype := :path
getindex.(a,1), getindex.(a,2), getindex.(a,3)
end
@series begin
primary := false
line_z := attributes.line_z
linealpha := attributes.linealpha
linecolor := attributes.linecolor
linestyle := attributes.linestyle
linewidth := attributes.linewidth
seriestype := :path
getindex.(a',1), getindex.(a',2), getindex.(a',3)
end
ps = M.(t1s,t2s')
xs = getindex.(ps,1)
ys = getindex.(ps,2)
zs = getindex.(ps,3)
seriestype := :surface
delete!(plotattributes, :controlpoints)
delete!(plotattributes, :division_number)
xs, ys, zs
end
@recipe function f(M::_Manifold{3, 3}; controlpoints=(;), division_number=100)
attributes = PlotAttributesContolPoints(;controlpoints...)
t1_min, t1_max = extrema(domain(bsplinespaces(M)[1]))
t2_min, t2_max = extrema(domain(bsplinespaces(M)[2]))
t3_min, t3_max = extrema(domain(bsplinespaces(M)[3]))
t1s = range(t1_min, t1_max, length=division_number+1)
t2s = range(t2_min, t2_max, length=division_number+1)
t3s = range(t3_min, t3_max, length=division_number+1)
a = BasicBSpline.controlpoints(M)
@series begin
primary := false
marker_z := attributes.marker_z
markeralpha := attributes.markeralpha
markercolor := attributes.markercolor
markershape := attributes.markershape
markersize := attributes.markersize
markerstrokealpha := attributes.markerstrokealpha
markerstrokecolor := attributes.markerstrokecolor
markerstrokestyle := attributes.markerstrokestyle
markerstrokewidth := attributes.markerstrokewidth
seriestype := :scatter
vec(getindex.(a,1)), vec(getindex.(a,2)), vec(getindex.(a,3))
end
@series begin
primary := false
line_z := attributes.line_z
linealpha := attributes.linealpha
linecolor := attributes.linecolor
linestyle := attributes.linestyle
linewidth := attributes.linewidth
seriestype := :path
n1, n2, n3 = dim.(bsplinespaces(M))
X = Float64[]
Y = Float64[]
Z = Float64[]
a1 = a
xs = [p[1] for p in a1]
ys = [p[2] for p in a1]
zs = [p[3] for p in a1]
append!(X, vec(cat(xs, fill(NaN,1,n2,n3), dims=1)))
append!(Y, vec(cat(ys, fill(NaN,1,n2,n3), dims=1)))
append!(Z, vec(cat(zs, fill(NaN,1,n2,n3), dims=1)))
a2 = permutedims(a,(2,3,1))
xs = [p[1] for p in a2]
ys = [p[2] for p in a2]
zs = [p[3] for p in a2]
append!(X, vec(cat(xs, fill(NaN,1,n3,n1), dims=1)))
append!(Y, vec(cat(ys, fill(NaN,1,n3,n1), dims=1)))
append!(Z, vec(cat(zs, fill(NaN,1,n3,n1), dims=1)))
a3 = permutedims(a,(3,1,2))
xs = [p[1] for p in a3]
ys = [p[2] for p in a3]
zs = [p[3] for p in a3]
append!(X, vec(cat(xs, fill(NaN,1,n1,n2), dims=1)))
append!(Y, vec(cat(ys, fill(NaN,1,n1,n2), dims=1)))
append!(Z, vec(cat(zs, fill(NaN,1,n1,n2), dims=1)))
X,Y,Z
end
nanvec = fill(SVector(NaN,NaN,NaN), 1, division_number+1)
qs1 = M.(t1s, t2s', t3_max)
qs2 = M.(t1s', t2s, t3_min)
qs3 = M.(t1_max, t2s, t3s')
qs4 = M.(t1_min, t2s', t3s)
qs5 = M.(t1s', t2_max, t3s)
qs6 = M.(t1s, t2_min, t3s')
ps = [
qs1;
qs1[end:end,:]; # Adhoc additional values for fixing boundary
nanvec;
qs2;
qs2[end:end,:];
nanvec;
qs3;
qs3[end:end,:];
nanvec;
qs4;
qs4[end:end,:];
nanvec;
qs5;
qs5[end:end,:];
nanvec;
qs6
]
xs = getindex.(ps,1)
ys = getindex.(ps,2)
zs = getindex.(ps,3)
seriestype := :surface
delete!(plotattributes, :controlpoints)
delete!(plotattributes, :division_number)
xs, ys, zs
end
end # module
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 1622 | module BasicBSpline
using LinearAlgebra
using SparseArrays
using IntervalSets
using StaticArrays
using PrecompileTools
# Types
export AbstractKnotVector, KnotVector, UniformKnotVector, EmptyKnotVector, SubKnotVector
export BSplineSpace, BSplineDerivativeSpace, UniformBSplineSpace
export BSplineManifold, RationalBSplineManifold
# B-spline basis functions
export bsplinebasis₊₀, bsplinebasis₋₀, bsplinebasis
export bsplinebasis′₊₀, bsplinebasis′₋₀, bsplinebasis′
export bsplinebasisall, intervalindex
# B-spline space
export issqsubset, ⊑, ⊒, ⋢, ⋣, ⋤, ⋥, ≃
export dim, exactdim, exactdim_R, exactdim_I
export domain
export changebasis, changebasis_R, changebasis_I
export bsplinesupport, bsplinesupport_R, bsplinesupport_I
export expandspace, expandspace_R, expandspace_I
export isdegenerate, isdegenerate_R, isdegenerate_I
export isnondegenerate, isnondegenerate_R, isnondegenerate_I
export countknots
export degree
export unbounded_mapping
# Getter methods
export bsplinespaces, controlpoints, weights
export knotvector
export bsplinespace
# Useful functions
export refinement, refinement_R, refinement_I
# Macros
export @knotvector_str
include("_util.jl")
include("_KnotVector.jl")
include("_BSplineSpace.jl")
include("_BSplineBasis.jl")
include("_DerivativeSpace.jl")
include("_DerivativeBasis.jl")
include("_ChangeBasis.jl")
include("_BSplineManifold.jl")
include("_RationalBSplineManifold.jl")
include("_Refinement.jl")
include("_precompile.jl")
if !isdefined(Base, :get_extension)
include("../ext/BasicBSplineChainRulesCoreExt.jl")
include("../ext/BasicBSplineRecipesBaseExt.jl")
end
end # module
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 12822 | #############################
#= B-Spline Basis Function =#
#############################
@doc raw"""
``i``-th B-spline basis function.
Right-sided limit version.
```math
\begin{aligned}
{B}_{(i,p,k)}(t)
&=
\frac{t-k_{i}}{k_{i+p}-k_{i}}{B}_{(i,p-1,k)}(t)
+\frac{k_{i+p+1}-t}{k_{i+p+1}-k_{i+1}}{B}_{(i+1,p-1,k)}(t) \\
{B}_{(i,0,k)}(t)
&=
\begin{cases}
&1\quad (k_{i}\le t< k_{i+1})\\
&0\quad (\text{otherwise})
\end{cases}
\end{aligned}
```
# Examples
```jldoctest
julia> P = BSplineSpace{0}(KnotVector(1:6))
BSplineSpace{0, Int64, KnotVector{Int64}}(KnotVector([1, 2, 3, 4, 5, 6]))
julia> bsplinebasis₊₀.(P,1:5,(1:6)')
5×6 Matrix{Float64}:
1.0 0.0 0.0 0.0 0.0 0.0
0.0 1.0 0.0 0.0 0.0 0.0
0.0 0.0 1.0 0.0 0.0 0.0
0.0 0.0 0.0 1.0 0.0 0.0
0.0 0.0 0.0 0.0 1.0 0.0
```
"""
@generated function bsplinebasis₊₀(P::BSplineSpace{p,T}, i::Integer, t::S) where {p, T, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
ks = [Symbol(:k,i) for i in 1:p+2]
Ks = [Symbol(:K,i) for i in 1:p+1]
Bs = [Symbol(:B,i) for i in 1:p+1]
k_l = Expr(:tuple, ks...)
k_r = Expr(:tuple, :(v[i]), (:(v[i+$j]) for j in 1:p+1)...)
K_l(n) = Expr(:tuple, Ks[1:n]...)
B_l(n) = Expr(:tuple, Bs[1:n]...)
A_r(n) = Expr(:tuple, [:($U($(ks[i])≤t<$(ks[i+1]))) for i in 1:n]...)
K_r(m,n) = Expr(:tuple, [:(_d(t-$(ks[i]),$(ks[i+m])-$(ks[i]))) for i in 1:n]...)
B_r(n) = Expr(:tuple, [:($(Ks[i])*$(Bs[i])+(1-$(Ks[i+1]))*$(Bs[i+1])) for i in 1:n]...)
exs = Expr[]
for i in 1:p
push!(exs, :($(K_l(p+2-i)) = $(K_r(i,p+2-i))))
push!(exs, :($(B_l(p+1-i)) = $(B_r(p+1-i))))
end
Expr(:block,
:(v = knotvector(P).vector),
:($k_l = $k_r),
:($(B_l(p+1)) = $(A_r(p+1))),
exs...,
:(return B1)
)
end
@doc raw"""
``i``-th B-spline basis function.
Left-sided limit version.
```math
\begin{aligned}
{B}_{(i,p,k)}(t)
&=
\frac{t-k_{i}}{k_{i+p}-k_{i}}{B}_{(i,p-1,k)}(t)
+\frac{k_{i+p+1}-t}{k_{i+p+1}-k_{i+1}}{B}_{(i+1,p-1,k)}(t) \\
{B}_{(i,0,k)}(t)
&=
\begin{cases}
&1\quad (k_{i}< t\le k_{i+1})\\
&0\quad (\text{otherwise})
\end{cases}
\end{aligned}
```
# Examples
```jldoctest
julia> P = BSplineSpace{0}(KnotVector(1:6))
BSplineSpace{0, Int64, KnotVector{Int64}}(KnotVector([1, 2, 3, 4, 5, 6]))
julia> bsplinebasis₋₀.(P,1:5,(1:6)')
5×6 Matrix{Float64}:
0.0 1.0 0.0 0.0 0.0 0.0
0.0 0.0 1.0 0.0 0.0 0.0
0.0 0.0 0.0 1.0 0.0 0.0
0.0 0.0 0.0 0.0 1.0 0.0
0.0 0.0 0.0 0.0 0.0 1.0
```
"""
@generated function bsplinebasis₋₀(P::BSplineSpace{p,T}, i::Integer, t::S) where {p, T, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
ks = [Symbol(:k,i) for i in 1:p+2]
Ks = [Symbol(:K,i) for i in 1:p+1]
Bs = [Symbol(:B,i) for i in 1:p+1]
k_l = Expr(:tuple, ks...)
k_r = Expr(:tuple, :(v[i]), (:(v[i+$j]) for j in 1:p+1)...)
K_l(n) = Expr(:tuple, Ks[1:n]...)
B_l(n) = Expr(:tuple, Bs[1:n]...)
A_r(n) = Expr(:tuple, [:($U($(ks[i])<t≤$(ks[i+1]))) for i in 1:n]...)
K_r(m,n) = Expr(:tuple, [:(_d(t-$(ks[i]),$(ks[i+m])-$(ks[i]))) for i in 1:n]...)
B_r(n) = Expr(:tuple, [:($(Ks[i])*$(Bs[i])+(1-$(Ks[i+1]))*$(Bs[i+1])) for i in 1:n]...)
exs = Expr[]
for i in 1:p
push!(exs, :($(K_l(p+2-i)) = $(K_r(i,p+2-i))))
push!(exs, :($(B_l(p+1-i)) = $(B_r(p+1-i))))
end
Expr(:block,
:(v = knotvector(P).vector),
:($k_l = $k_r),
:($(B_l(p+1)) = $(A_r(p+1))),
exs...,
:(return B1)
)
end
@doc raw"""
``i``-th B-spline basis function.
Modified version.
```math
\begin{aligned}
{B}_{(i,p,k)}(t)
&=
\frac{t-k_{i}}{k_{i+p}-k_{i}}{B}_{(i,p-1,k)}(t)
+\frac{k_{i+p+1}-t}{k_{i+p+1}-k_{i+1}}{B}_{(i+1,p-1,k)}(t) \\
{B}_{(i,0,k)}(t)
&=
\begin{cases}
&1\quad (k_{i} \le t < k_{i+1}) \\
&1\quad (k_{i} < t = k_{i+1}=k_{l}) \\
&0\quad (\text{otherwise})
\end{cases}
\end{aligned}
```
# Examples
```jldoctest
julia> P = BSplineSpace{0}(KnotVector(1:6))
BSplineSpace{0, Int64, KnotVector{Int64}}(KnotVector([1, 2, 3, 4, 5, 6]))
julia> bsplinebasis.(P,1:5,(1:6)')
5×6 Matrix{Float64}:
1.0 0.0 0.0 0.0 0.0 0.0
0.0 1.0 0.0 0.0 0.0 0.0
0.0 0.0 1.0 0.0 0.0 0.0
0.0 0.0 0.0 1.0 0.0 0.0
0.0 0.0 0.0 0.0 1.0 1.0
```
"""
@generated function bsplinebasis(P::BSplineSpace{p,T}, i::Integer, t::S) where {p, T, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
ks = [Symbol(:k,i) for i in 1:p+2]
Ks = [Symbol(:K,i) for i in 1:p+1]
Bs = [Symbol(:B,i) for i in 1:p+1]
k_l = Expr(:tuple, ks...)
k_r = Expr(:tuple, :(v[i]), (:(v[i+$j]) for j in 1:p+1)...)
K_l(n) = Expr(:tuple, Ks[1:n]...)
B_l(n) = Expr(:tuple, Bs[1:n]...)
A_r(n) = Expr(:tuple, [:($U(($(ks[i])≤t<$(ks[i+1])) || ($(ks[i])<t==$(ks[i+1])==v[end]))) for i in 1:n]...)
K_r(m,n) = Expr(:tuple, [:(_d(t-$(ks[i]),$(ks[i+m])-$(ks[i]))) for i in 1:n]...)
B_r(n) = Expr(:tuple, [:($(Ks[i])*$(Bs[i])+(1-$(Ks[i+1]))*$(Bs[i+1])) for i in 1:n]...)
exs = Expr[]
for i in 1:p
push!(exs, :($(K_l(p+2-i)) = $(K_r(i,p+2-i))))
push!(exs, :($(B_l(p+1-i)) = $(B_r(p+1-i))))
end
Expr(:block,
:(v = knotvector(P).vector),
:($k_l = $k_r),
:($(B_l(p+1)) = $(A_r(p+1))),
exs...,
:(return B1)
)
end
@doc raw"""
``i``-th B-spline basis function.
Modified version (2).
```math
\begin{aligned}
{B}_{(i,p,k)}(t)
&=
\frac{t-k_{i}}{k_{i+p}-k_{i}}{B}_{(i,p-1,k)}(t)
+\frac{k_{i+p+1}-t}{k_{i+p+1}-k_{i+1}}{B}_{(i+1,p-1,k)}(t) \\
{B}_{(i,0,k)}(t)
&=
\begin{cases}
&1\quad (k_{1+p} \le k_{i} < t \le k_{i+1}) \\
&1\quad (t = k_{1+p} = k_{i} < k_{i+1}) \\
&1\quad (k_{i} \le t < k_{i+1} \le k_{1+p}) \\
&0\quad (\text{otherwise})
\end{cases}
\end{aligned}
```
# Examples
```jldoctest
julia> P = BSplineSpace{0}(KnotVector(1:6))
BSplineSpace{0, Int64, KnotVector{Int64}}(KnotVector([1, 2, 3, 4, 5, 6]))
julia> BasicBSpline.bsplinebasis₋₀I.(P,1:5,(1:6)')
5×6 Matrix{Float64}:
1.0 1.0 0.0 0.0 0.0 0.0
0.0 0.0 1.0 0.0 0.0 0.0
0.0 0.0 0.0 1.0 0.0 0.0
0.0 0.0 0.0 0.0 1.0 0.0
0.0 0.0 0.0 0.0 0.0 1.0
```
"""
@generated function bsplinebasis₋₀I(P::BSplineSpace{p,T}, i::Integer, t::S) where {p, T, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
ks = [Symbol(:k,i) for i in 1:p+2]
Ks = [Symbol(:K,i) for i in 1:p+1]
Bs = [Symbol(:B,i) for i in 1:p+1]
k_l = Expr(:tuple, ks...)
k_r = Expr(:tuple, :(v[i]), (:(v[i+$j]) for j in 1:p+1)...)
K_l(n) = Expr(:tuple, Ks[1:n]...)
B_l(n) = Expr(:tuple, Bs[1:n]...)
A_r(n) = Expr(:tuple, [:($U((v[1+p]≤$(ks[i])<t≤$(ks[i+1])) || (t==v[1+p]==$(ks[i])<$(ks[i+1])) || ($(ks[i])≤t<$(ks[i+1])≤v[1+p]))) for i in 1:n]...)
K_r(m,n) = Expr(:tuple, [:(_d(t-$(ks[i]),$(ks[i+m])-$(ks[i]))) for i in 1:n]...)
B_r(n) = Expr(:tuple, [:($(Ks[i])*$(Bs[i])+(1-$(Ks[i+1]))*$(Bs[i+1])) for i in 1:n]...)
exs = Expr[]
for i in 1:p
push!(exs, :($(K_l(p+2-i)) = $(K_r(i,p+2-i))))
push!(exs, :($(B_l(p+1-i)) = $(B_r(p+1-i))))
end
Expr(:block,
:(v = knotvector(P).vector),
:($k_l = $k_r),
:($(B_l(p+1)) = $(A_r(p+1))),
exs...,
:(return B1)
)
end
# bsplinebasis with UniformKnotVector
@inline function bsplinebasis(P::UniformBSplineSpace{p,T,R},i::Integer,t::S) where {p, T, R<:AbstractUnitRange, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
k = knotvector(P)
@boundscheck (1 ≤ i ≤ dim(P)) || throw(DomainError(i, "index of B-spline basis function is out of range."))
return U(uniform_bsplinebasis_kernel(Val{p}(),t-i+1-k[1]))
end
@inline function bsplinebasis(P::UniformBSplineSpace{p,T},i::Integer,t::S) where {p, T, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
k = knotvector(P)
@boundscheck (1 ≤ i ≤ dim(P)) || throw(DomainError(i, "index of B-spline basis function is out of range."))
a = @inbounds k.vector[i]
b = @inbounds k.vector[i+p+1]
return U(uniform_bsplinebasis_kernel(Val{p}(),(p+1)*(t-a)/(b-a)))
end
@inline bsplinebasis₋₀(P::UniformBSplineSpace,i::Integer,t::Real) = bsplinebasis(P,i,t)
@inline bsplinebasis₊₀(P::UniformBSplineSpace,i::Integer,t::Real) = bsplinebasis(P,i,t)
@inline bsplinebasis₋₀I(P::UniformBSplineSpace,i::Integer,t::Real) = bsplinebasis(P,i,t)
################################################
#= B-Spline Basis Functions at specific point =#
################################################
"""
B-spline basis functions at point `t` on `i`-th interval.
# Examples
```jldoctest
julia> k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
julia> p = 2
2
julia> P = BSplineSpace{p}(k)
BSplineSpace{2, Float64, KnotVector{Float64}}(KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0]))
julia> t = 5.7
5.7
julia> i = intervalindex(P,t)
2
julia> bsplinebasisall(P,i,t)
3-element SVector{3, Float64} with indices SOneTo(3):
0.3847272727272727
0.6107012987012989
0.00457142857142858
julia> bsplinebasis.(P,i:i+p,t)
3-element Vector{Float64}:
0.38472727272727264
0.6107012987012989
0.00457142857142858
```
"""
bsplinebasisall
@inline function bsplinebasisall(P::BSplineSpace{0,T},i::Integer,t::S) where {T, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
SVector(one(U),)
end
@inline function bsplinebasisall(P::BSplineSpace{1}, i::Integer, t::Real)
k = knotvector(P)
B1 = (k[i+2]-t)/(k[i+2]-k[i+1])
B2 = (t-k[i+1])/(k[i+2]-k[i+1])
return SVector(B1, B2)
end
@generated function bsplinebasisall(P::BSplineSpace{p,T}, i::Integer, t::Real) where {p,T}
bs = [Symbol(:b,i) for i in 1:p]
Bs = [Symbol(:B,i) for i in 1:p+1]
K1s = [:((k[i+$(p+j)]-t)/(k[i+$(p+j)]-k[i+$(j)])) for j in 1:p]
K2s = [:((t-k[i+$(j)])/(k[i+$(p+j)]-k[i+$(j)])) for j in 1:p]
b = Expr(:tuple, bs...)
B = Expr(:tuple, Bs...)
exs = [:($(Bs[j+1]) = ($(K1s[j+1])*$(bs[j+1]) + $(K2s[j])*$(bs[j]))) for j in 1:p-1]
Expr(:block,
:($(Expr(:meta, :inline))),
:(k = knotvector(P)),
:($b = bsplinebasisall(_lower_R(P),i+1,t)),
:($(Bs[1]) = $(K1s[1])*$(bs[1])),
exs...,
:($(Bs[p+1]) = $(K2s[p])*$(bs[p])),
:(return SVector($(B)))
)
end
## bsplinebasisall with UniformKnotVector
@inline function bsplinebasisall(P::UniformBSplineSpace{p,T,R},i::Integer,t::S) where {p, T, R<:AbstractUnitRange, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
k = knotvector(P)
@boundscheck (0 ≤ i ≤ length(k)-2p) || throw(DomainError(i, "index of interval is out of range."))
return uniform_bsplinebasisall_kernel(Val{p}(),U(t-i+1-p-k[1]))
end
@inline function bsplinebasisall(P::UniformBSplineSpace{p,T},i::Integer,t::S) where {p, T, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
k = knotvector(P)
@boundscheck (0 ≤ i ≤ length(k)-2p) || throw(DomainError(i, "index of interval is out of range."))
a = @inbounds k.vector[i+p]
b = @inbounds k.vector[i+p+1]
return uniform_bsplinebasisall_kernel(Val{p}(),U((t-a)/(b-a)))
end
#########################################################
#= Kernel funcitons of uniform B-spline basis function =#
#########################################################
@inline function uniform_bsplinebasisall_kernel(::Val{0},t::T) where T<:Real
U = StaticArrays.arithmetic_closure(T)
SVector{1,U}(one(t))
end
@inline function uniform_bsplinebasisall_kernel(::Val{1},t::T) where T<:Real
U = StaticArrays.arithmetic_closure(T)
SVector{2,U}(1-t,t)
end
@generated function uniform_bsplinebasisall_kernel(::Val{p}, t::T) where {p, T<:Real}
bs = [Symbol(:b,i) for i in 1:p]
Bs = [Symbol(:B,i) for i in 1:p+1]
K1s = [:(($(j)-t)/$(p)) for j in 1:p]
K2s = [:((t-$(j-p))/$(p)) for j in 1:p]
b = Expr(:tuple, bs...)
B = Expr(:tuple, Bs...)
exs = [:($(Bs[j+1]) = ($(K1s[j+1])*$(bs[j+1]) + $(K2s[j])*$(bs[j]))) for j in 1:p-1]
Expr(
:block,
:($(Expr(:meta, :inline))),
:($b = uniform_bsplinebasisall_kernel(Val{$(p-1)}(),t)),
:($(Bs[1]) = $(K1s[1])*$(bs[1])),
exs...,
:($(Bs[p+1]) = $(K2s[p])*$(bs[p])),
:(return SVector($(B)))
)
end
@inline function uniform_bsplinebasis_kernel(::Val{0},t::T) where T<:Real
U = StaticArrays.arithmetic_closure(T)
return U(zero(t) ≤ t < one(t))
end
@inline function uniform_bsplinebasis_kernel(::Val{1},t::T) where T<:Real
U = StaticArrays.arithmetic_closure(T)
return U(max(1-abs(t-1), zero(t)))
end
@inline function uniform_bsplinebasis_kernel(::Val{p},t::T) where {p,T<:Real}
return (t*uniform_bsplinebasis_kernel(Val{p-1}(),t) + (p+1-t)*uniform_bsplinebasis_kernel(Val{p-1}(),t-1))/p
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 8521 | # B-spline manifold
abstract type AbstractManifold{Dim} end
# Broadcast like a scalar
Base.Broadcast.broadcastable(M::AbstractManifold) = Ref(M)
dim(::AbstractManifold{Dim}) where Dim = Dim
@doc raw"""
Construct B-spline manifold from given control points and B-spline spaces.
# Examples
```jldoctest
julia> using StaticArrays
julia> P = BSplineSpace{2}(KnotVector([0,0,0,1,1,1]))
BSplineSpace{2, Int64, KnotVector{Int64}}(KnotVector([0, 0, 0, 1, 1, 1]))
julia> a = [SVector(1,0), SVector(1,1), SVector(0,1)]
3-element Vector{SVector{2, Int64}}:
[1, 0]
[1, 1]
[0, 1]
julia> M = BSplineManifold(a, P);
julia> M(0.4)
2-element SVector{2, Float64} with indices SOneTo(2):
0.84
0.64
julia> M(1.2)
ERROR: DomainError with 1.2:
The input 1.2 is out of domain 0 .. 1.
[...]
```
"""
struct BSplineManifold{Dim,Deg,C,T,S<:NTuple{Dim, BSplineSpace{p,T} where p}} <: AbstractManifold{Dim}
controlpoints::Array{C,Dim}
bsplinespaces::S
function BSplineManifold{Dim,Deg,C,T,S}(a::Array{C,Dim},P::S) where {S<:NTuple{Dim, BSplineSpace{p,T} where p},C} where {Dim, Deg, T}
new{Dim,Deg,C,T,S}(a,P)
end
end
function BSplineManifold(a::Array{C,Dim},P::S) where {S<:Tuple{BSplineSpace{p,T} where p, Vararg{BSplineSpace{p,T} where p}}} where {Dim, T, C}
if size(a) != dim.(P)
msg = "The size of control points array $(size(a)) and dimensions of B-spline spaces $(dim.(P)) must be equal."
throw(DimensionMismatch(msg))
end
Deg = degree.(P)
return BSplineManifold{Dim,Deg,C,T,S}(a, P)
end
function BSplineManifold(a::Array{C,Dim},P::S) where {S<:NTuple{Dim, BSplineSpace{p,T} where {p,T}},C} where {Dim}
P′ = _promote_knottype(P)
return BSplineManifold(a, P′)
end
BSplineManifold(a::Array{C,Dim},Ps::Vararg{BSplineSpace, Dim}) where {C,Dim} = BSplineManifold(a,Ps)
Base.:(==)(M1::AbstractManifold, M2::AbstractManifold) = (bsplinespaces(M1)==bsplinespaces(M2)) & (controlpoints(M1)==controlpoints(M2))
bsplinespaces(M::BSplineManifold) = M.bsplinespaces
controlpoints(M::BSplineManifold) = M.controlpoints
function Base.hash(M::BSplineManifold{0}, h::UInt)
hash(BSplineManifold{0}, hash(controlpoints(M), h))
end
function Base.hash(M::BSplineManifold, h::UInt)
hash(xor(hash.(bsplinespaces(M), h)...), hash(controlpoints(M), h))
end
@doc raw"""
unbounded_mapping(M::BSplineManifold{Dim}, t::Vararg{Real,Dim})
# Examples
```jldoctest
julia> P = BSplineSpace{1}(KnotVector([0,0,1,1]))
BSplineSpace{1, Int64, KnotVector{Int64}}(KnotVector([0, 0, 1, 1]))
julia> domain(P)
0 .. 1
julia> M = BSplineManifold([0,1], P);
julia> unbounded_mapping(M, 0.1)
0.1
julia> M(0.1)
0.1
julia> unbounded_mapping(M, 1.2)
1.2
julia> M(1.2)
ERROR: DomainError with 1.2:
The input 1.2 is out of domain 0 .. 1.
[...]
```
"""
function unbounded_mapping end
@generated function unbounded_mapping(M::BSplineManifold{Dim,Deg}, t::Vararg{Real,Dim}) where {Dim,Deg}
# Use `UnitRange` to support Julia v1.6 (LTS)
# This can be replaced with `range` if we drop support for v1.6
iter = CartesianIndices(UnitRange.(1, Deg .+ 1))
exs = Expr[]
for ci in iter
ex = Expr(:call, [:getindex, :a, [:($(Symbol(:i,d))+$(ci[d]-1)) for d in 1:Dim]...]...)
ex = Expr(:call, [:*, [:($(Symbol(:b,d))[$(ci[d])]) for d in 1:Dim]..., ex]...)
ex = Expr(:+=, :v, ex)
push!(exs, ex)
end
exs[1].head = :(=)
Expr(
:block,
Expr(:(=), Expr(:tuple, [Symbol(:P, i) for i in 1:Dim]...), :(bsplinespaces(M))),
Expr(:(=), Expr(:tuple, [Symbol(:t, i) for i in 1:Dim]...), :t),
:(a = controlpoints(M)),
Expr(:(=), Expr(:tuple, [Symbol(:i, i) for i in 1:Dim]...), Expr(:tuple, [:(intervalindex($(Symbol(:P, i)), $(Symbol(:t, i)))) for i in 1:Dim]...)),
Expr(:(=), Expr(:tuple, [Symbol(:b, i) for i in 1:Dim]...), Expr(:tuple, [:(bsplinebasisall($(Symbol(:P, i)), $(Symbol(:i, i)), $(Symbol(:t, i)))) for i in 1:Dim]...)),
exs...,
:(return v)
)
end
@generated function (M::BSplineManifold{Dim})(t::Vararg{Real, Dim}) where Dim
Ps = [Symbol(:P,i) for i in 1:Dim]
P = Expr(:tuple, Ps...)
ts = [Symbol(:t,i) for i in 1:Dim]
T = Expr(:tuple, ts...)
exs = [:($(Symbol(:t,i)) in domain($(Symbol(:P,i))) || throw(DomainError($(Symbol(:t,i)), "The input "*string($(Symbol(:t,i)))*" is out of domain $(domain($(Symbol(:P,i))))."))) for i in 1:Dim]
ret = Expr(:call,:unbounded_mapping,:M,[Symbol(:t,i) for i in 1:Dim]...)
Expr(
:block,
:($(Expr(:meta, :inline))),
:($T = t),
:($P = bsplinespaces(M)),
exs...,
:(return $(ret))
)
end
## currying
# 2dim
@inline function (M::BSplineManifold{2,p})(t1::Real,::Colon) where p
p1, p2 = p
P1, P2 = bsplinespaces(M)
a = controlpoints(M)
j1 = intervalindex(P1,t1)
B1 = bsplinebasisall(P1,j1,t1)
b = sum(a[j1+i1,:]*B1[1+i1] for i1 in 0:p1)
return BSplineManifold(b,(P2,))
end
@inline function (M::BSplineManifold{2,p})(::Colon,t2::Real) where p
p1, p2 = p
P1, P2 = bsplinespaces(M)
a = controlpoints(M)
j2 = intervalindex(P2,t2)
B2 = bsplinebasisall(P2,j2,t2)
b = sum(a[:,j2+i2]*B2[1+i2] for i2 in 0:p2)
return BSplineManifold(b,(P1,))
end
# 3dim
@inline function (M::BSplineManifold{3,p})(t1::Real,::Colon,::Colon) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
j1 = intervalindex(P1,t1)
B1 = bsplinebasisall(P1,j1,t1)
b = sum(a[j1+i1,:,:]*B1[1+i1] for i1 in 0:p1)
return BSplineManifold(b,(P2,P3))
end
@inline function (M::BSplineManifold{3,p})(::Colon,t2::Real,::Colon) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
j2 = intervalindex(P2,t2)
B2 = bsplinebasisall(P2,j2,t2)
b = sum(a[:,j2+i2,:]*B2[1+i2] for i2 in 0:p2)
return BSplineManifold(b,(P1,P3))
end
@inline function (M::BSplineManifold{3,p})(::Colon,::Colon,t3::Real) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
j3 = intervalindex(P3,t3)
B3 = bsplinebasisall(P3,j3,t3)
b = sum(a[:,:,j3+i3]*B3[1+i3] for i3 in 0:p3)
return BSplineManifold(b,(P1,P2))
end
@inline function (M::BSplineManifold{3,p})(t1::Real,t2::Real,::Colon) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
j1 = intervalindex(P1,t1)
j2 = intervalindex(P2,t2)
B1 = bsplinebasisall(P1,j1,t1)
B2 = bsplinebasisall(P2,j2,t2)
b = sum(a[j1+i1,j2+i2,:]*B1[1+i1]*B2[1+i2] for i1 in 0:p1, i2 in 0:p2)
return BSplineManifold(b,(P3,))
end
@inline function (M::BSplineManifold{3,p})(t1::Real,::Colon,t3::Real) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
j1 = intervalindex(P1,t1)
j3 = intervalindex(P3,t3)
B1 = bsplinebasisall(P1,j1,t1)
B3 = bsplinebasisall(P3,j3,t3)
b = sum(a[j1+i1,:,j3+i3]*B1[1+i1]*B3[1+i3] for i1 in 0:p1, i3 in 0:p3)
return BSplineManifold(b,(P2,))
end
@inline function (M::BSplineManifold{3,p})(::Colon,t2::Real,t3::Real) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
j2 = intervalindex(P2,t2)
j3 = intervalindex(P3,t3)
B2 = bsplinebasisall(P2,j2,t2)
B3 = bsplinebasisall(P3,j3,t3)
b = sum(a[:,j2+i2,j3+i3]*B2[1+i2]*B3[1+i3] for i2 in 0:p2, i3 in 0:p3)
return BSplineManifold(b,(P1,))
end
# TODO: The performance of this method can be improved.
function (M::BSplineManifold{Dim,Deg})(t::Union{Real, Colon}...) where {Dim, Deg}
P = bsplinespaces(M)
a = controlpoints(M)
t_real = _remove_colon(t...)
P_real = _remove_colon(_get_on_real.(P, t)...)
P_colon = _remove_colon(_get_on_colon.(P, t)...)
j_real = intervalindex.(P_real, t_real)
B = bsplinebasisall.(P_real, j_real, t_real)
Deg_real = _remove_colon(_get_on_real.(Deg, t)...)
ci = CartesianIndices(UnitRange.(0, Deg_real))
next = _replace_noncolon((), j_real, t...)
a′ = view(a, next...) .* *(getindex.(B, 1)...)
l = length(ci)
for i in view(ci,2:l)
next = _replace_noncolon((), j_real .+ i.I, t...)
b = *(getindex.(B, i.I .+ 1)...)
a′ .+= view(a, next...) .* b
end
return BSplineManifold(a′, P_colon)
end
@inline function (M::BSplineManifold{Dim})(::Vararg{Colon, Dim}) where Dim
a = copy(controlpoints(M))
Ps = bsplinespaces(M)
return BSplineManifold(a,Ps)
end
@inline function (M::BSplineManifold{0})()
a = controlpoints(M)
return a[]
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 13725 | # B-spline space
abstract type AbstractFunctionSpace{T} end
@doc raw"""
Construct B-spline space from given polynominal degree and knot vector.
```math
\mathcal{P}[p,k]
```
# Examples
```jldoctest
julia> p = 2
2
julia> k = KnotVector([1,3,5,6,8,9])
KnotVector([1, 3, 5, 6, 8, 9])
julia> BSplineSpace{p}(k)
BSplineSpace{2, Int64, KnotVector{Int64}}(KnotVector([1, 3, 5, 6, 8, 9]))
```
"""
struct BSplineSpace{p, T<:Real, K<:AbstractKnotVector{T}} <: AbstractFunctionSpace{T}
knotvector::K
global unsafe_bsplinespace(::Val{p}, k::K) where {p, K<:AbstractKnotVector{T}} where {T<:Real} = new{p,T,K}(k)
end
function BSplineSpace{p}(k::AbstractKnotVector) where p
if p < 0
throw(DomainError(p, "degree of polynominal must be non-negative"))
end
return unsafe_bsplinespace(Val{p}(), k)
end
function BSplineSpace{p,T}(k::AbstractKnotVector{T}) where {p, T}
return BSplineSpace{p}(k)
end
function BSplineSpace{p,T1}(k::AbstractKnotVector{T2}) where {p, T1, T2}
return BSplineSpace{p,T1}(AbstractKnotVector{T1}(k))
end
const UniformBSplineSpace{p, T, R} = BSplineSpace{p, T, UniformKnotVector{T, R}}
"""
Convert BSplineSpace to BSplineSpace
"""
function BSplineSpace(P::BSplineSpace{p}) where p
return P
end
function BSplineSpace{p}(P::BSplineSpace{p}) where p
return P
end
function BSplineSpace{p,T}(P::BSplineSpace{p}) where {p,T}
return BSplineSpace{p}(AbstractKnotVector{T}(knotvector(P)))
end
function BSplineSpace{p,T,K}(P::BSplineSpace{p}) where {p,T,K}
return BSplineSpace{p,T}(K(knotvector(P)))
end
function BSplineSpace{p,T,K}(k::AbstractKnotVector) where {p,T,K}
return BSplineSpace{p,T}(K(k))
end
# Broadcast like a scalar
Base.Broadcast.broadcastable(P::BSplineSpace) = Ref(P)
Base.iterate(P::AbstractFunctionSpace) = (P, nothing)
Base.iterate(::AbstractFunctionSpace, ::Any) = nothing
# Equality
@inline Base.:(==)(P1::BSplineSpace{p}, P2::BSplineSpace{p}) where p = knotvector(P1) == knotvector(P2)
@inline Base.:(==)(P1::BSplineSpace{p1}, P2::BSplineSpace{p2}) where {p1, p2} = false
bsplinespace(P::BSplineSpace) = P
@inline function degree(::BSplineSpace{p}) where p
return p
end
@inline function knotvector(P::BSplineSpace)
return P.knotvector
end
@generated function _promote_knottype(P::NTuple{Dim,BSplineSpace}) where Dim
Expr(
:block,
Expr(:(=), Expr(:tuple, [Symbol(:P, i) for i in 1:Dim]...), :P),
Expr(:(=), Expr(:tuple, [Symbol(:k, i) for i in 1:Dim]...), Expr(:tuple, [:(knotvector($(Symbol(:P, i)))) for i in 1:Dim]...)),
Expr(:(=), :T, Expr(:call, :promote_type, [:(eltype($(Symbol(:k, i)))) for i in 1:Dim]...)),
Expr(:(=), Expr(:tuple, [Symbol(:k, i, :(var"′")) for i in 1:Dim]...), Expr(:tuple, [:(AbstractKnotVector{T}($(Symbol(:k, i)))) for i in 1:Dim]...)),
Expr(:(=), :P′, Expr(:tuple, [:(BSplineSpace{degree($(Symbol(:P, i)))}($(Symbol(:k, i, :(var"′"))))) for i in 1:Dim]...)),
:(return P′)
)
end
function domain(P::BSplineSpace)
p = degree(P)
k = knotvector(P)
return k[1+p]..k[end-p]
end
@doc raw"""
Return dimention of a B-spline space.
```math
\dim(\mathcal{P}[p,k])
=\# k - p -1
```
# Examples
```jldoctest
julia> dim(BSplineSpace{1}(KnotVector([1,2,3,4,5,6,7])))
5
julia> dim(BSplineSpace{1}(KnotVector([1,2,4,4,4,6,7])))
5
julia> dim(BSplineSpace{1}(KnotVector([1,2,3,5,5,5,7])))
5
```
"""
function dim(bsplinespace::BSplineSpace{p}) where p
k = knotvector(bsplinespace)
return length(k) - p - 1
end
@doc raw"""
Check inclusive relationship between B-spline spaces.
```math
\mathcal{P}[p,k]
\subseteq\mathcal{P}[p',k']
```
# Examples
```jldoctest
julia> P1 = BSplineSpace{1}(KnotVector([1,3,5,8]));
julia> P2 = BSplineSpace{1}(KnotVector([1,3,5,6,8,9]));
julia> P3 = BSplineSpace{2}(KnotVector([1,1,3,3,5,5,8,8]));
julia> P1 ⊆ P2
true
julia> P1 ⊆ P3
true
julia> P2 ⊆ P3
false
julia> P2 ⊈ P3
true
```
"""
function Base.issubset(P::BSplineSpace{p}, P′::BSplineSpace{p′}) where {p, p′}
p₊ = p′ - p
p₊ < 0 && return false
k = knotvector(P)
k′ = knotvector(P′)
l = length(k)
i = 1
c = 0
for j in 1:length(k′)
if l < i
return true
end
if k[i] < k′[j]
return false
end
if k[i] == k′[j]
c += 1
if c == p₊+1
i += 1
c = 0
elseif (i ≠ l) && (k[i] == k[i+1])
i += 1
c = 0
end
end
end
return l < i
# The above implementation is the same as `k + p₊ * unique(k) ⊆ k′`, but that's much faster.
end
@doc raw"""
Check inclusive relationship between B-spline spaces.
```math
\mathcal{P}[p,k]
\sqsubseteq\mathcal{P}[p',k']
\Leftrightarrow
\mathcal{P}[p,k]|_{[k_{p+1},k_{l-p}]}
\subseteq\mathcal{P}[p',k']|_{[k'_{p'+1},k'_{l'-p'}]}
```
"""
function issqsubset(P::BSplineSpace{p}, P′::BSplineSpace{p′}) where {p, p′}
p₊ = p′ - p
p₊ < 0 && return false
k = knotvector(P)
k′ = knotvector(P′)
!(k[1+p] == k′[1+p′] < k′[end-p′] == k[end-p]) && return false
l = length(k)
l′ = length(k′)
inner_knotvector = view(k, p+2:l-p-1)
inner_knotvector′ = view(k′, p′+2:l′-p′-1)
_P = BSplineSpace{p}(inner_knotvector)
_P′ = BSplineSpace{p′}(inner_knotvector′)
return _P ⊆ _P′
end
const ⊑ = issqsubset
⊒(l, r) = r ⊑ l
⋢(l, r) = !⊑(l, r)
⋣(l, r) = r ⋢ l
≃(P1::BSplineSpace, P2::BSplineSpace) = (P1 ⊑ P2) & (P2 ⊑ P1)
Base.:⊊(A::AbstractFunctionSpace, B::AbstractFunctionSpace) = (A ≠ B) & (A ⊆ B)
Base.:⊋(A::AbstractFunctionSpace, B::AbstractFunctionSpace) = (A ≠ B) & (A ⊇ B)
⋤(A::AbstractFunctionSpace, B::AbstractFunctionSpace) = (A ≠ B) & (A ⊑ B)
⋥(A::AbstractFunctionSpace, B::AbstractFunctionSpace) = (A ≠ B) & (A ⊒ B)
function isdegenerate_R(P::BSplineSpace{p}, i::Integer) where p
k = knotvector(P)
return k[i] == k[i+p+1]
end
function isdegenerate_I(P::BSplineSpace{p}, i::Integer) where p
return iszero(width(bsplinesupport(P,i) ∩ domain(P)))
end
function _iszeros_R(P::BSplineSpace{p}) where p
return [isdegenerate_R(P,i) for i in 1:dim(P)]
end
function _iszeros_I(P::BSplineSpace{p}) where p
return [isdegenerate_I(P,i) for i in 1:dim(P)]
end
@doc raw"""
Check if given B-spline space is non-degenerate.
# Examples
```jldoctest
julia> isnondegenerate(BSplineSpace{2}(KnotVector([1,3,5,6,8,9])))
true
julia> isnondegenerate(BSplineSpace{1}(KnotVector([1,3,3,3,8,9])))
false
```
"""
isnondegenerate(P::BSplineSpace)
@doc raw"""
Check if given B-spline space is degenerate.
# Examples
```jldoctest
julia> isdegenerate(BSplineSpace{2}(KnotVector([1,3,5,6,8,9])))
false
julia> isdegenerate(BSplineSpace{1}(KnotVector([1,3,3,3,8,9])))
true
```
"""
isdegenerate(P::BSplineSpace)
for (f, fnon) in ((:isdegenerate_R, :isnondegenerate_R), (:isdegenerate_I, :isnondegenerate_I))
@eval function $f(P::AbstractFunctionSpace)
for i in 1:dim(P)
$f(P,i) && return true
end
return false
end
@eval $fnon(P, i::Integer) = !$f(P, i)
@eval $fnon(P) = !$f(P)
end
const isdegenerate = isdegenerate_R
const isnondegenerate = isnondegenerate_R
function _nondegeneratize_R(P::BSplineSpace{p}) where p
k = copy(KnotVector(knotvector(P)))
I = Int[]
for i in 1:dim(P)
isdegenerate_R(P,i) && push!(I, i)
end
deleteat!(BasicBSpline._vec(k), I)
return BSplineSpace{p}(k)
end
function _nondegeneratize_I(P::BSplineSpace{p}) where p
k = copy(KnotVector(knotvector(P)))
l = length(k)
I = Int[]
for i in 1:dim(P)
if isdegenerate_I(P,i)
if k[l-p] < k[i+p+1]
push!(I, i+p+1)
else
push!(I, i)
end
end
end
deleteat!(BasicBSpline._vec(k), I)
return BSplineSpace{p}(k)
end
"""
Exact dimension of a B-spline space.
# Examples
```jldoctest
julia> exactdim_R(BSplineSpace{1}(KnotVector([1,2,3,4,5,6,7])))
5
julia> exactdim_R(BSplineSpace{1}(KnotVector([1,2,4,4,4,6,7])))
4
julia> exactdim_R(BSplineSpace{1}(KnotVector([1,2,3,5,5,5,7])))
4
```
"""
function exactdim_R(P::BSplineSpace)
n = dim(P)
for i in 1:dim(P)
n -= isdegenerate_R(P,i)
end
return n
# The above implementation is the same as `dim(P)-sum(_iszeros_R(P))`, but that's much faster.
end
"""
Exact dimension of a B-spline space.
# Examples
```jldoctest
julia> exactdim_I(BSplineSpace{1}(KnotVector([1,2,3,4,5,6,7])))
5
julia> exactdim_I(BSplineSpace{1}(KnotVector([1,2,4,4,4,6,7])))
4
julia> exactdim_I(BSplineSpace{1}(KnotVector([1,2,3,5,5,5,7])))
3
```
"""
function exactdim_I(P::BSplineSpace)
n = dim(P)
for i in 1:dim(P)
n -= isdegenerate_I(P,i)
end
return n
# The above implementation is the same as `dim(P)-sum(_iszeros_I(P))`, but that's much faster.
end
const exactdim = exactdim_R
@doc raw"""
Return the support of ``i``-th B-spline basis function.
```math
\operatorname{supp}(B_{(i,p,k)})=[k_{i},k_{i+p+1}]
```
# Examples
```jldoctest
julia> k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
julia> P = BSplineSpace{2}(k)
BSplineSpace{2, Float64, KnotVector{Float64}}(KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0]))
julia> bsplinesupport(P,1)
0.0 .. 5.5
julia> bsplinesupport(P,2)
1.5 .. 8.0
```
"""
bsplinesupport(P::BSplineSpace, i::Integer) = bsplinesupport_R(P,i)
function bsplinesupport_R(P::BSplineSpace{p}, i::Integer) where p
k = knotvector(P)
return k[i]..k[i+p+1]
end
function bsplinesupport_I(P::BSplineSpace{p}, i::Integer) where p
return bsplinesupport_R(P,i) ∩ domain(P)
end
@doc raw"""
Internal methods for obtaining a B-spline space with one degree lower.
```math
\begin{aligned}
\mathcal{P}[p,k] &\mapsto \mathcal{P}[p-1,k] \\
D^r\mathcal{P}[p,k] &\mapsto D^{r-1}\mathcal{P}[p-1,k]
\end{aligned}
```
"""
_lower_R
_lower_R(P::BSplineSpace{p,T}) where {p,T} = BSplineSpace{p-1}(knotvector(P))
function _lower_I(P::BSplineSpace{p,T}) where {p,T}
k = knotvector(P)
l = length(k)
return BSplineSpace{p-1}(view(k,2:l-1))
end
"""
Return an index of a interval in the domain of B-spline space
# Examples
```jldoctest
julia> k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0]);
julia> P = BSplineSpace{2}(k);
julia> domain(P)
2.5 .. 9.0
julia> intervalindex(P,2.6)
1
julia> intervalindex(P,5.6)
2
julia> intervalindex(P,8.5)
3
julia> intervalindex(P,9.5)
3
```
"""
function intervalindex(P::BSplineSpace{p},t::Real) where p
k = knotvector(P)
l = length(k)
v = view(_vec(k),2+p:l-p-1)
return searchsortedlast(v,t)+1
end
"""
Expand B-spline space with given additional degree and knotvector.
This function is compatible with `issqsubset` (`⊑`)
# Examples
```jldoctest
julia> k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0]);
julia> P = BSplineSpace{2}(k);
julia> P′ = expandspace_I(P, Val(1), KnotVector([6.0]))
BSplineSpace{3, Float64, KnotVector{Float64}}(KnotVector([0.0, 1.5, 2.5, 2.5, 5.5, 5.5, 6.0, 8.0, 8.0, 9.0, 9.0, 9.5, 10.0]))
julia> P ⊆ P′
false
julia> P ⊑ P′
true
julia> domain(P)
2.5 .. 9.0
julia> domain(P′)
2.5 .. 9.0
```
"""
function expandspace_I end
function expandspace_I(P::BSplineSpace{p,T}, ::Val{p₊}, k₊::AbstractKnotVector=EmptyKnotVector{T}()) where {p,p₊,T}
k = knotvector(P)
I = domain(P)
l = length(k)
l₊ = length(k₊)
if l₊ ≥ 1
k₊[1] ∉ I && throw(DomainError(k₊, "input knot vector is out of domain."))
end
if l₊ ≥ 2
k₊[end] ∉ I && throw(DomainError(k₊, "input knot vector is out of domain."))
end
k̂ = unique(view(k, 1+p:l-p))
p′ = p + p₊
k′ = k + p₊*k̂ + k₊
P′ = BSplineSpace{p′}(k′)
return P′
end
function expandspace_I(P::BSplineSpace{p,T}, k₊::AbstractKnotVector=EmptyKnotVector{T}()) where {p,T}
k = knotvector(P)
I = domain(P)
l₊ = length(k₊)
if l₊ ≥ 1
k₊[1] ∉ I && throw(DomainError(k₊, "input knot vector is out of domain."))
end
if l₊ ≥ 2
k₊[end] ∉ I && throw(DomainError(k₊, "input knot vector is out of domain."))
end
k′ = k + k₊
P′ = BSplineSpace{p}(k′)
return P′
end
"""
Expand B-spline space with given additional degree and knotvector.
This function is compatible with `issubset` (`⊆`).
# Examples
```jldoctest
julia> k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0]);
julia> P = BSplineSpace{2}(k);
julia> P′ = expandspace_R(P, Val(1), KnotVector([6.0]))
BSplineSpace{3, Float64, KnotVector{Float64}}(KnotVector([0.0, 0.0, 1.5, 1.5, 2.5, 2.5, 5.5, 5.5, 6.0, 8.0, 8.0, 9.0, 9.0, 9.5, 9.5, 10.0, 10.0]))
julia> P ⊆ P′
true
julia> P ⊑ P′
false
julia> domain(P)
2.5 .. 9.0
julia> domain(P′)
1.5 .. 9.5
```
"""
function expandspace_R end
function expandspace_R(P::BSplineSpace{p,T}, ::Val{p₊}, k₊::AbstractKnotVector=EmptyKnotVector{T}()) where {p,p₊,T}
k = knotvector(P)
p′ = p + p₊
k′ = k + p₊*k + k₊
P′ = BSplineSpace{p′}(k′)
return P′
end
function expandspace_R(P::BSplineSpace{p,T}, k₊::AbstractKnotVector=EmptyKnotVector{T}()) where {p,T}
k = knotvector(P)
k′ = k + k₊
P′ = BSplineSpace{p}(k′)
return P′
end
"""
Expand B-spline space with given additional degree and knotvector.
The behavior of `expandspace` is same as `expandspace_I`.
"""
function expandspace(P::BSplineSpace{p,T}, _p₊::Val{p₊}, k₊::AbstractKnotVector=EmptyKnotVector{T}()) where {p,p₊,T}
expandspace_I(P,_p₊,k₊)
end
function expandspace(P::BSplineSpace{p,T}, k₊::AbstractKnotVector=EmptyKnotVector{T}()) where {p,T}
expandspace_I(P,k₊)
end
function Base.hash(P::BSplineSpace{p}, h::UInt) where p
k = knotvector(P)
hash(BSplineSpace{p}, hash(_vec(k), h))
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 28044 | # Change Basis between B-Spline Spaces
# See https://hackmd.io/lpA0D0ySTQ6Hq1CdaaONxQ for more information.
@doc raw"""
changebasis_R(P::AbstractFunctionSpace, P′::AbstractFunctionSpace)
Return a coefficient matrix ``A`` which satisfy
```math
B_{(i,p,k)} = \sum_{j}A_{i,j}B_{(j,p',k')}
```
# Examples
```jldoctest
julia> P = BSplineSpace{2}(knotvector"3 13")
BSplineSpace{2, Int64, KnotVector{Int64}}(KnotVector([1, 1, 1, 3, 4, 4, 4]))
julia> P′ = BSplineSpace{3}(knotvector"4124")
BSplineSpace{3, Int64, KnotVector{Int64}}(KnotVector([1, 1, 1, 1, 2, 3, 3, 4, 4, 4, 4]))
julia> P ⊆ P′
true
julia> changebasis_R(P, P′)
4×7 SparseArrays.SparseMatrixCSC{Float64, Int32} with 13 stored entries:
1.0 0.666667 0.166667 ⋅ ⋅ ⋅ ⋅
⋅ 0.333333 0.722222 0.555556 0.111111 ⋅ ⋅
⋅ ⋅ 0.111111 0.444444 0.888889 0.666667 ⋅
⋅ ⋅ ⋅ ⋅ ⋅ 0.333333 1.0
```
"""
function changebasis_R(P::AbstractFunctionSpace, P′::AbstractFunctionSpace)
P ⊆ P′ || throw(DomainError((P,P′),"P ⊆ P′ should be hold."))
return _changebasis_R(P, P′)
end
"""
_changebasis_R(P::AbstractFunctionSpace, P′::AbstractFunctionSpace)
Internal function for [`changebasis_R`](@ref).
Implicit assumption:
- `P ⊆ P′`
"""
_changebasis_R
function _changebasis_R(P::BSplineSpace{p,T}, P′::BSplineSpace{p′,T′}) where {p,T,p′,T′}
_P = BSplineSpace{p,T,KnotVector{T}}(P)
_P′ = BSplineSpace{p′,T′,KnotVector{T′}}(P′)
return _changebasis_R(_P,_P′)
end
function _changebasis_R(P::BSplineSpace{0,T,KnotVector{T}}, P′::BSplineSpace{p′,T′,KnotVector{T′}}) where {p′,T,T′}
U = StaticArrays.arithmetic_closure(promote_type(T, T′))
n = dim(P)
n′ = dim(P′)
n′_exact = exactdim_R(P′)
k = knotvector(P)
k′ = knotvector(P′)
I = Vector{Int32}(undef, n′_exact)
J = Vector{Int32}(undef, n′_exact)
s = 1
local j_begin
j_end = 0
for i in 1:n
isdegenerate(P, i) && continue
for j in (j_end+1):n′
k′[j] == k[i] && (j_begin = j; break)
end
for j in j_begin:n′
k′[j+p′+1] == k[i+1] && (j_end = j + p′; break)
end
for j in j_begin:j_end
isdegenerate(P′, j) && continue
I[s] = i
J[s] = j
s += 1
end
end
A⁰ = sparse(view(I,1:s-1), view(J,1:s-1), fill(one(U), s-1), n, n′)
return A⁰
end
function _find_j_range_R(P::BSplineSpace{p}, P′::BSplineSpace{p′}, i, j_range) where {p, p′}
k = knotvector(P)
k′ = knotvector(P′)
n′ = dim(P′)
# Pi = BSplineSpace{p}(view(k, i:i+p+1))
j_begin, j_end = extrema(j_range)
# Find `j_end`. This is the same as:
# j_end::Int = findnext(j->Pi ⊆ BSplineSpace{p′}(view(k′, j_begin:j+p′+1)), 1:n′, j_end)
m = p′-p
t_end = k[i+p+1]
for ii in 0:(p+1)
if k[i+p+1-ii] == t_end
m += 1
else
break
end
end
for j in (j_end-p′-1):n′
if t_end == k′[j+p′+1] # can be ≤
m -= 1
end
if m == 0
j_end = j
break
end
end
# Find `j_begin`. This is the same as:
# j_begin::Int = findprev(j->Pi ⊆ BSplineSpace{p′}(view(k′, j:j_end+p′+1)), 1:n′, j_end)
m = p′-p
t_begin = k[i]
for ii in 0:(p+1)
if k[i+ii] == t_begin
m += 1
else
break
end
end
for j in reverse(1:(j_end+p′+1))
if k′[j] == t_begin # can be ≤
m -= 1
end
if m == 0
j_begin = j
break
end
end
return j_begin:j_end
end
function _ΔAᵖ_R(Aᵖ⁻¹::AbstractMatrix, K::AbstractVector, K′::AbstractVector, i::Integer, j::Integer)
return K′[j] * (K[i] * Aᵖ⁻¹[i, j] - K[i+1] * Aᵖ⁻¹[i+1, j])
end
function _changebasis_R(P::BSplineSpace{p,T,KnotVector{T}}, P′::BSplineSpace{p′,T′,KnotVector{T′}}) where {p,p′,T,T′}
#=
Example matrix: n=3, n′=4
Aᵖ⁻¹₁₁ Aᵖ⁻¹₁₂ Aᵖ⁻¹₁₃ Aᵖ⁻¹₁₄ Aᵖ⁻¹₁₅
├ Aᵖ₁₁ ┼ Aᵖ₁₂ ┼ Aᵖ₁₃ ┼ Aᵖ₁₄ ┤
Aᵖ⁻¹₂₁ Aᵖ⁻¹₂₂ Aᵖ⁻¹₂₃ Aᵖ⁻¹₂₄ Aᵖ⁻¹₂₅
├ Aᵖ₂₁ ┼ Aᵖ₂₂ ┼ Aᵖ₂₃ ┼ Aᵖ₂₄ ┤
Aᵖ⁻¹₃₁ Aᵖ⁻¹₃₂ Aᵖ⁻¹₃₃ Aᵖ⁻¹₃₄ Aᵖ⁻¹₃₅
├ Aᵖ₃₁ ┼ Aᵖ₃₂ ┼ Aᵖ₃₃ ┼ Aᵖ₃₄ ┤
Aᵖ⁻¹₄₁ Aᵖ⁻¹₄₂ Aᵖ⁻¹₄₃ Aᵖ⁻¹₄₄ Aᵖ⁻¹₄₅
=== i-rule ===
- isdegenerate_R(P, i) ⇒ Aᵖᵢⱼ = 0
=== j-rules for fixed i ===
- Rule-0: B₍ᵢ,ₚ,ₖ₎ ∈ span₍ᵤ₌ₛ…ₜ₎(B₍ᵤ,ₚ′,ₖ′₎), s≤j≤t ⇒ Aᵖᵢⱼ ≠ 0
supp(B₍ⱼ,ₚ′,ₖ′₎) ⊈ supp(B₍ᵢ,ₚ,ₖ₎) ⇒ Aᵖᵢⱼ = 0 is almost equivalent (if there are no duplicated knots).
- Rule-1: isdegenerate_R(P′, j) ⇒ Aᵖᵢⱼ = 0
Ideally this should be NaN, but we need to support `Rational` which does not include `NaN`.
- Rule-2: k′ⱼ = k′ⱼ₊ₚ′ ⇒ B₍ᵢ,ₚ,ₖ₎(t) = ∑ⱼAᵖᵢⱼB₍ⱼ,ₚ′,ₖ′₎(t) (t → k′ⱼ + 0)
- Rule-3: k′ⱼ₊₁ = k′ⱼ₊ₚ′ ⇒ B₍ᵢ,ₚ,ₖ₎(t) = ∑ⱼAᵖᵢⱼB₍ⱼ,ₚ′,ₖ′₎(t) (t → k′ⱼ₊₁ - 0)
- Rule-6: Aᵖᵢⱼ = Aᵖᵢⱼ₋₁ + (recursive formula based on Aᵖ⁻¹)
- Rule-7: Aᵖᵢⱼ = Aᵖᵢⱼ₊₁ - (recursive formula based on Aᵖ⁻¹)
=#
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
k = knotvector(P)
k′ = knotvector(P′)
n = dim(P)
n′ = dim(P′)
K′ = [k′[j+p′] - k′[j] for j in 1:n′+1]
K = U[ifelse(k[i+p] ≠ k[i], U(1 / (k[i+p] - k[i])), zero(U)) for i in 1:n+1]
Aᵖ⁻¹ = _changebasis_R(_lower_R(P), _lower_R(P′)) # (n+1) × (n′+1) matrix
n_nonzero = exactdim_R(P′)*(p+1) # This is a upper bound of the number of non-zero elements of Aᵖ (rough estimation).
I = Vector{Int32}(undef, n_nonzero)
J = Vector{Int32}(undef, n_nonzero)
V = Vector{U}(undef, n_nonzero)
s = 1
j_range = 1:1 # j_begin:j_end
for i in 1:n
# Skip for degenerated basis
isdegenerate_R(P,i) && continue
# The following indices `j*` have the following relationships.
#=
1 n′
|--*-----------------------------*-->|
j_begin j_end
|----*----------------*------>|
j_prev j_mid j_next
| | |
|--j₊->||<-j₋--|
266666666777777773
366666666777777773
1 n′
|--*-----------------------------*-->|
j_begin j_end
*|---------------*------------>|
j_prev j_mid j_next
| | |
|--j₊->||<-j₋--|
066666666777777773
1 n′
|--*-----------------------------*-->|
j_begin j_end
|-------------*-------------->|*
j_prev j_mid j_next
| | |
|--j₊->||<-j₋--|
266666666777777770
366666666777777770
1 n′
*-----------------------------*----->|
j_begin j_end
*----------------*----------->|
j_prev j_mid j_next
| | |
|--j₊->||<-j₋--|
066666666777777773
1 n′
|------*---------------------------->*
j_begin j_end
|-------------*--------------->*
j_prev j_mid j_next
| | |
|--j₊->||<-j₋--|
266666666777777770
366666666777777770
=#
# Precalculate the range of j
j_range = _find_j_range_R(P, P′, i, j_range)
j_begin, j_end = extrema(j_range)
# Rule-0: outside of j_range
j_prev = j_begin-1
Aᵖᵢⱼ_prev = zero(U)
for j_next in j_range
# Rule-1: zero
isdegenerate_R(P′,j_next) && continue
# Rule-2: right limit
if k′[j_next] == k′[j_next+p′]
I[s], J[s] = i, j_next
V[s] = Aᵖᵢⱼ_prev = bsplinebasis₊₀(P,i,k′[j_next+1])
s += 1
j_prev = j_next
# Rule-3: left limit (or both limit)
elseif k′[j_next+1] == k′[j_next+p′]
j_mid = (j_prev + j_next) ÷ 2
# Rule-6: right recursion
for j₊ in (j_prev+1):j_mid
I[s], J[s] = i, j₊
V[s] = Aᵖᵢⱼ_prev = Aᵖᵢⱼ_prev + p * _ΔAᵖ_R(Aᵖ⁻¹,K,K′,i,j₊) / p′
s += 1
end
I[s], J[s] = i, j_next
V[s] = Aᵖᵢⱼ_prev = Aᵖᵢⱼ_next = bsplinebasis₋₀(P,i,k′[j_next+1])
s += 1
# Rule-7: left recursion
for j₋ in reverse((j_mid+1):(j_next-1))
I[s], J[s] = i, j₋
V[s] = Aᵖᵢⱼ_next = Aᵖᵢⱼ_next - p * _ΔAᵖ_R(Aᵖ⁻¹,K,K′,i,j₋+1) / p′
s += 1
end
j_prev = j_next
end
end
# Rule-0: outside of j_range
j_next = j_end + 1
j_mid = (j_prev + j_next) ÷ 2
Aᵖᵢⱼ_next = zero(U)
# Rule-6: right recursion
for j₊ in (j_prev+1):j_mid
I[s], J[s] = i, j₊
V[s] = Aᵖᵢⱼ_prev = Aᵖᵢⱼ_prev + p * _ΔAᵖ_R(Aᵖ⁻¹,K,K′,i,j₊) / p′
s += 1
end
# Rule-7: left recursion
for j₋ in reverse((j_mid+1):(j_next-1))
I[s], J[s] = i, j₋
V[s] = Aᵖᵢⱼ_next = Aᵖᵢⱼ_next - p * _ΔAᵖ_R(Aᵖ⁻¹,K,K′,i,j₋+1) / p′
s += 1
end
end
Aᵖ = sparse(view(I,1:s-1), view(J,1:s-1), view(V,1:s-1), n, n′)
return Aᵖ
end
@doc raw"""
Return a coefficient matrix ``A`` which satisfy
```math
B_{(i,p_1,k_1)} = \sum_{j}A_{i,j}B_{(j,p_2,k_2)}
```
Assumption:
* ``P_1 ≃ P_2``
"""
function _changebasis_sim(P1::BSplineSpace{p,T1}, P2::BSplineSpace{p,T2}) where {p,T1,T2}
P1 ≃ P2 || throw(DomainError((P1,P2),"P1 ≃ P2 should be hold."))
U = StaticArrays.arithmetic_closure(promote_type(T1,T2))
k1 = knotvector(P1)
k2 = knotvector(P2)
n = dim(P1) # == dim(P2)
l = length(k1) # == length(k2)
A = SparseMatrixCSC{U,Int32}(I,n,n)
A1 = _derivatives_at_left(P1)
A2 = _derivatives_at_left(P2)
A12 = A1/A2
Δ = p
for i in reverse(1:p)
k1[i] ≠ k2[i] && break
Δ -= 1
end
# A12 must be lower-triangular
for i in 1:Δ, j in 1:i
A[i, j] = A12[i,j]
end
A1 = _derivatives_at_right(P1)
A2 = _derivatives_at_right(P2)
A12 = A1/A2
Δ = p
for i in l-p+1:l
k1[i] ≠ k2[i] && break
Δ -= 1
end
# A12 must be upper-triangular
for i in 1:Δ, j in i:Δ
A[n-Δ+i, n-Δ+j] = A12[i+p-Δ,j+p-Δ]
end
return A
end
@generated function _derivatives_at_left(P::BSplineSpace{p,T}) where {p, T}
args = [:(pop(bsplinebasisall(BSplineDerivativeSpace{$(r)}(P),1,a))) for r in 0:p-1]
quote
a, _ = extrema(domain(P))
$(Expr(:call, :hcat, args...))
end
end
function _derivatives_at_left(::BSplineSpace{0,T}) where {T}
U = StaticArrays.arithmetic_closure(T)
SMatrix{0,0,U}()
end
@generated function _derivatives_at_right(P::BSplineSpace{p,T}) where {p, T}
args = [:(popfirst(bsplinebasisall(BSplineDerivativeSpace{$(r)}(P),n-p,b))) for r in 0:p-1]
quote
n = dim(P)
_, b = extrema(domain(P))
$(Expr(:call, :hcat, args...))
end
end
function _derivatives_at_right(::BSplineSpace{0,T}) where {T}
U = StaticArrays.arithmetic_closure(T)
SMatrix{0,0,U}()
end
@doc raw"""
changebasis_I(P::AbstractFunctionSpace, P′::AbstractFunctionSpace)
Return a coefficient matrix ``A`` which satisfy
```math
B_{(i,p,k)} = \sum_{j}A_{i,j}B_{(j,p',k')}
```
# Examples
```jldoctest
julia> P = BSplineSpace{2}(knotvector"3 13")
BSplineSpace{2, Int64, KnotVector{Int64}}(KnotVector([1, 1, 1, 3, 4, 4, 4]))
julia> P′ = BSplineSpace{3}(knotvector"4124")
BSplineSpace{3, Int64, KnotVector{Int64}}(KnotVector([1, 1, 1, 1, 2, 3, 3, 4, 4, 4, 4]))
julia> P ⊑ P′
true
julia> changebasis_I(P, P′)
4×7 SparseArrays.SparseMatrixCSC{Float64, Int32} with 13 stored entries:
1.0 0.666667 0.166667 ⋅ ⋅ ⋅ ⋅
⋅ 0.333333 0.722222 0.555556 0.111111 ⋅ ⋅
⋅ ⋅ 0.111111 0.444444 0.888889 0.666667 ⋅
⋅ ⋅ ⋅ ⋅ ⋅ 0.333333 1.0
```
"""
function changebasis_I(P::AbstractFunctionSpace, P′::AbstractFunctionSpace)
P ⊑ P′ || throw(DomainError((P,P′),"P ⊑ P′ should be hold."))
return _changebasis_I(P, P′)
end
"""
_changebasis_I(P::AbstractFunctionSpace, P′::AbstractFunctionSpace)
Internal function for [`changebasis_I`](@ref).
Implicit assumption:
- `P ⊑ P′`
"""
_changebasis_I
function _changebasis_I(P::BSplineSpace, P′::BSplineSpace{p′}) where p′
k′ = knotvector(P′)
l′ = length(k′)
i = 1 + p′
v = k′[i]
i = i + 1
while true
k′[i] ≠ v && break
i = i + 1
end
degenerated_rank_on_left = i - p′ - 2
i = length(k′) - p′
v = k′[i]
i = i - 1
while true
k′[i] ≠ v && break
i = i - 1
end
degenerated_rank_on_right = l′ - p′ - i - 1
if degenerated_rank_on_left == degenerated_rank_on_right == 0
if P ⊆ P′
return _changebasis_R(P, P′)
else
return __changebasis_I(P, P′)
end
else
_k′ = view(k′, 1+degenerated_rank_on_left:l′-degenerated_rank_on_right)
_P′ = BSplineSpace{p′}(_k′)
_A = _changebasis_I(P, _P′)
m = _A.m
n = _A.n + degenerated_rank_on_left + degenerated_rank_on_right
colptr = _A.colptr
prepend!(colptr, fill(colptr[begin], degenerated_rank_on_left))
append!(colptr, fill(colptr[end], degenerated_rank_on_right))
rowval = _A.rowval
nzval = _A.nzval
return SparseMatrixCSC(m,n,colptr,rowval,nzval)
end
end
"""
__changebasis_I(P::AbstractFunctionSpace, P′::AbstractFunctionSpace)
Internal function for [`changebasis_I`](@ref).
Implicit assumption:
- `P ⊑ P′`
- `isnondegenerate_I(P′, 1)`
- `isnondegenerate_I(P′, dim(P′))`
"""
__changebasis_I
function __changebasis_I(P::BSplineSpace{0,T,<:AbstractKnotVector{T}}, P′::BSplineSpace{p′,T′,<:AbstractKnotVector{T′}}) where {p′,T,T′}
U = StaticArrays.arithmetic_closure(promote_type(T, T′))
n = dim(P)
n′ = dim(P′)
n′_exact = exactdim_R(P′)
k = knotvector(P)
k′ = knotvector(P′)
I = Vector{Int32}(undef, n′_exact)
J = Vector{Int32}(undef, n′_exact)
s = 1
local j_begin
j_end = 0
for i in 1:n
isdegenerate(P, i) && continue
for j in (j_end+1):n′
k′[j] ≤ k[i] && (j_begin = j; break)
end
for j in j_begin:n′
k′[j+p′+1] ≥ k[i+1] && (j_end = j + p′; break)
end
for j in j_begin:j_end
isdegenerate(P′, j) && continue
I[s] = i
J[s] = j
s += 1
end
end
A⁰ = sparse(view(I,1:s-1), view(J,1:s-1), fill(one(U), s-1), n, n′)
return A⁰
end
function _changebasis_I_old(P::BSplineSpace{p,T}, P′::BSplineSpace{p′,T′}) where {p,p′,T,T′}
k = knotvector(P)
k′ = knotvector(P′)
_P = BSplineSpace{p}(k[1+p:end-p] + p * KnotVector{T}([k[1+p], k[end-p]]))
_P′ = BSplineSpace{p′}(k′[1+p′:end-p′] + p′ * KnotVector{T′}([k′[1+p′], k′[end-p′]]))
_A = _changebasis_R(_P, _P′)
Asim = _changebasis_sim(P, _P)
Asim′ = _changebasis_sim(_P′, P′)
A = Asim * _A * Asim′
return A
end
function __changebasis_I_old(P1::BSplineSpace{p,T}, P2::BSplineSpace{p′,T′}) where {p,p′,T,T′}
U = StaticArrays.arithmetic_closure(promote_type(T, T′))
_P1 = _nondegeneratize_I(P1)
_P2 = _nondegeneratize_I(P2)
_A = sparse(Int32[], Int32[], U[], dim(P1), dim(P2))
_A[isnondegenerate_I.(P1,1:dim(P1)), isnondegenerate_I.(P2,1:dim(P2))] = _changebasis_I_old(_P1,_P2)
return _A
end
function _find_j_range_I(P::BSplineSpace{p}, P′::BSplineSpace{p′}, i, j_range, Aᵖ_old) where {p, p′}
# TODO: remove `Aᵖ_old` argument
# TODO: fix performance https://github.com/hyrodium/BasicBSpline.jl/pull/323#issuecomment-1723216566
# TODO: remove threshold such as 1e-14
Pi = BSplineSpace{p}(view(knotvector(P), i:i+p+1))
if Pi ⊆ P′
return _find_j_range_R(P, P′, i, j_range)
end
j_begin = findfirst(e->abs(e)>1e-14, view(Aᵖ_old, i, :))
j_end = findlast(e->abs(e)>1e-14, view(Aᵖ_old, i, :))
return j_begin:j_end
end
function _ΔAᵖ_I(Aᵖ⁻¹::AbstractMatrix, K::AbstractVector, K′::AbstractVector, i::Integer, j::Integer)
n = length(K)-1
if i == 1
return - K′[j] * K[i+1] * Aᵖ⁻¹[i, j-1]
elseif i == n
return K′[j] * K[i] * Aᵖ⁻¹[i-1, j-1]
else
return K′[j] * (K[i] * Aᵖ⁻¹[i-1, j-1] - K[i+1] * Aᵖ⁻¹[i, j-1])
end
end
function __changebasis_I(P::BSplineSpace{p,T,<:AbstractKnotVector{T}}, P′::BSplineSpace{p′,T′,<:AbstractKnotVector{T′}}) where {p,p′,T,T′}
#=
Example matrix: n=4, n′=5
Aᵖ₁₁ ┬ Aᵖ₁₂ ┬ Aᵖ₁₃ ┬ Aᵖ₁₄ ┬ Aᵖ₁₅
Aᵖ⁻¹₁₁ Aᵖ⁻¹₁₂ Aᵖ⁻¹₁₃ Aᵖ⁻¹₁₄
Aᵖ₂₁ ┼ Aᵖ₂₂ ┼ Aᵖ₂₃ ┼ Aᵖ₂₄ ┼ Aᵖ₂₅
Aᵖ⁻¹₂₁ Aᵖ⁻¹₂₂ Aᵖ⁻¹₂₃ Aᵖ⁻¹₂₄
Aᵖ₃₁ ┼ Aᵖ₃₂ ┼ Aᵖ₃₃ ┼ Aᵖ₃₄ ┼ Aᵖ₃₅
Aᵖ⁻¹₃₁ Aᵖ⁻¹₃₂ Aᵖ⁻¹₃₃ Aᵖ⁻¹₃₄
Aᵖ₄₁ ┴ Aᵖ₄₂ ┴ Aᵖ₄₃ ┴ Aᵖ₄₄ ┴ Aᵖ₄₅
=== i-rule ===
- isdegenerate_I(P, i) ⇒ Aᵖᵢⱼ = 0
=== j-rules for fixed i ===
- Rule-0: B₍ᵢ,ₚ,ₖ₎ ∈ span₍ᵤ₌ₛ…ₜ₎(B₍ᵤ,ₚ′,ₖ′₎), s≤j≤t ⇒ Aᵖᵢⱼ ≠ 0 (on B-spline space domain)
supp(B₍ⱼ,ₚ′,ₖ′₎) ⊈ supp(B₍ᵢ,ₚ,ₖ₎) ⇒ Aᵖᵢⱼ = 0 is almost equivalent (if there are no duplicated knots).
- Rule-1: isdegenerate_I(P′, j) ⇒ Aᵖᵢⱼ = 0
Ideally this should be NaN, but we need to support `Rational` which does not include `NaN`.
- Rule-2: k′ⱼ = k′ⱼ₊ₚ′ ⇒ B₍ᵢ,ₚ,ₖ₎(t) = ∑ⱼAᵖᵢⱼB₍ⱼ,ₚ′,ₖ′₎(t) (t → k′ⱼ + 0)
- Rule-3: k′ⱼ₊₁ = k′ⱼ₊ₚ′ ⇒ B₍ᵢ,ₚ,ₖ₎(t) = ∑ⱼAᵖᵢⱼB₍ⱼ,ₚ′,ₖ′₎(t) (t → k′ⱼ₊₁ - 0)
- Rule-6: Aᵖᵢⱼ = Aᵖᵢⱼ₋₁ + (recursive formula based on Aᵖ⁻¹)
- Rule-7: Aᵖᵢⱼ = Aᵖᵢⱼ₊₁ - (recursive formula based on Aᵖ⁻¹)
- Rule-8: Aᵖᵢⱼ = Aᵖᵢⱼ₋₁ + (recursive formula based on Aᵖ⁻¹) with postprocess Δ
=#
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
k = knotvector(P)
k′ = knotvector(P′)
n = dim(P)
n′ = dim(P′)
K′ = [k′[j+p′] - k′[j] for j in 1:n′+1]
K = U[ifelse(k[i+p] ≠ k[i], U(1 / (k[i+p] - k[i])), zero(U)) for i in 1:n+1]
Aᵖ⁻¹ = _changebasis_I(_lower_I(P), _lower_I(P′)) # (n-1) × (n′-1) matrix
n_nonzero = exactdim_I(P′)*(p+1) # This would be a upper bound of the number of non-zero elements of Aᵖ.
I = Vector{Int32}(undef, n_nonzero)
J = Vector{Int32}(undef, n_nonzero)
V = Vector{U}(undef, n_nonzero)
s = 1
j_range = 1:1 # j_begin:j_end
Aᵖ_old = __changebasis_I_old(P, P′)
for i in 1:n
# Skip for degenerated basis
isdegenerate_I(P,i) && continue
# The following indices `j*` have the following relationships.
#=
1 n′
|--*-----------------------------*-->|
j_begin j_end
|----*----------------*------>|
j_prev j_mid j_next
| | |
|--j₊->||<-j₋--|
266666666777777773
366666666777777773
1 n′
|--*-----------------------------*-->|
j_begin j_end
*|---------------*------------>|
j_prev j_mid j_next
| | |
|--j₊->||<-j₋--|
066666666777777773
177777777777777773
1 n′
|--*-----------------------------*-->|
j_begin j_end
|-------------*-------------->|*
j_prev j_mid j_next
| | |
|--j₊->||<-j₋--|
266666666777777770
366666666777777770
266666666666666661
366666666666666661
1 n′
*-----------------------------*----->|
j_begin j_end
*---------------*------------>|
j_prev=j_mid j_next
| |
|<-----j₋------|
077777777777777773
1 n′
|------*---------------------------->*
j_begin j_end
|-------------*--------------->*
j_prev j_mid+1=j_next
| |
|------j₊----->|
266666666666666660
366666666666666660
1 n′
*----------------------------------->*
j_begin j_end
*------------------------------------>*
j_prev j_next
| |
|-----------------j₊---------------->|
0888888888888888888888888888888888888880
=#
# Precalculate the range of j
j_range = _find_j_range_I(P, P′, i, j_range, Aᵖ_old)
j_begin, j_end = extrema(j_range)
# Rule-0: outside of j_range
j_prev = j_begin-1
Aᵖᵢⱼ_prev = zero(U)
for j_next in j_range
# Rule-1: zero
isdegenerate_I(P′,j_next) && continue
# Rule-2: right limit
if k′[j_next] == k′[j_next+p′]
I[s], J[s] = i, j_next
V[s] = Aᵖᵢⱼ_prev = bsplinebasis₊₀(P,i,k′[j_next+1])
s += 1
j_prev = j_next
# Rule-3: left limit (or both limit)
elseif k′[j_next+1] == k′[j_next+p′]
j_mid = (j_prev == 0 || isdegenerate_I(P′, j_prev) ? j_prev : (j_prev + j_next) ÷ 2)
# Rule-6: right recursion
for j₊ in (j_prev+1):j_mid
I[s], J[s] = i, j₊
V[s] = Aᵖᵢⱼ_prev = Aᵖᵢⱼ_prev + p * _ΔAᵖ_I(Aᵖ⁻¹,K,K′,i,j₊) / p′
s += 1
end
I[s], J[s] = i, j_next
V[s] = Aᵖᵢⱼ_prev = Aᵖᵢⱼ_next = bsplinebasis₋₀I(P,i,k′[j_next+1])
s += 1
# Rule-7: left recursion
for j₋ in reverse((j_mid+1):(j_next-1))
I[s], J[s] = i, j₋
V[s] = Aᵖᵢⱼ_next = Aᵖᵢⱼ_next - p * _ΔAᵖ_I(Aᵖ⁻¹,K,K′,i,j₋+1) / p′
s += 1
end
j_prev = j_next
end
end
# Rule-0: outside of j_range
j_next = j_end + 1
if j_next == n′+1
j_mid = j_next - 1
if j_prev == 0
# Rule-8: right recursion with postprocess
# We can't find Aᵖᵢ₁ or Aᵖᵢₙ′ directly (yet!), so we need Δ-shift.
# TODO: Find a way to avoid the Δ-shift.
I[s], J[s] = i, 1
V[s] = Aᵖᵢⱼ_prev = zero(U)
s += 1
for j₊ in 2:n′
I[s], J[s] = i, j₊
V[s] = Aᵖᵢⱼ_prev = Aᵖᵢⱼ_prev + p * _ΔAᵖ_I(Aᵖ⁻¹,K,K′,i,j₊) / p′
s += 1
end
t_mid = (maximum(domain(P))+minimum(domain(P))) / 2one(U)
Δ = bsplinebasis(P, i, t_mid) - dot(view(V, s-n′:s-1), bsplinebasis.(P′, 1:n′, t_mid))
V[s-n′:s-1] .+= Δ
continue
end
elseif j_prev == 0
j_mid = j_prev
else
j_mid = (j_prev + j_next) ÷ 2
end
Aᵖᵢⱼ_next = zero(U)
# Rule-6: right recursion
for j₊ in (j_prev+1):j_mid
I[s], J[s] = i, j₊
V[s] = Aᵖᵢⱼ_prev = Aᵖᵢⱼ_prev + p * _ΔAᵖ_I(Aᵖ⁻¹,K,K′,i,j₊) / p′
s += 1
end
# Rule-7: left recursion
for j₋ in reverse((j_mid+1):(j_next-1))
I[s], J[s] = i, j₋
V[s] = Aᵖᵢⱼ_next = Aᵖᵢⱼ_next - p * _ΔAᵖ_I(Aᵖ⁻¹,K,K′,i,j₋+1) / p′
s += 1
end
end
Aᵖ = sparse(view(I,1:s-1), view(J,1:s-1), view(V,1:s-1), n, n′)
return Aᵖ
end
## Uniform B-spline space
function _changebasis_R(P::UniformBSplineSpace{p,T}, P′::UniformBSplineSpace{p,T′}) where {p,T,T′}
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
k = knotvector(P)
k′ = knotvector(P′)
r = round(Int, step(k)/step(k′))
block = [r_nomial(p+1,i,r) for i in 0:(r-1)*(p+1)]/r^p
n = dim(P)
n′ = dim(P′)
j = findfirst(==(k[1]), _vec(k′))
A = spzeros(U, n, n′)
for i in 1:n
A[i, j+r*(i-1):j+(r-1)*(p+1)+r*(i-1)] = block
end
return A
end
function _changebasis_I(P::UniformBSplineSpace{0,T}, P′::UniformBSplineSpace{0,T′}) where {T,T′}
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
n = dim(P)
n′ = dim(P′)
A = spzeros(U, n, n′)
for i in 1:n
b = r*i
a = b-r+1
rr = a:b
if rr ⊆ 1:n′
A[i,rr] .= one(U)
else
A[i,max(a,1):min(b,n′)] .= one(U)
end
end
return A
end
function _changebasis_I(P::UniformBSplineSpace{p,T}, P′::UniformBSplineSpace{p,T′}) where {p,T,T′}
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
k = knotvector(P)
k′ = knotvector(P′)
r = round(Int, step(k)/step(k′))
block = [r_nomial(p+1,i,r) for i in 0:(r-1)*(p+1)]/r^p
n = dim(P)
n′ = dim(P′)
A = spzeros(U, n, n′)
for i in 1:n
a = r*i-(r-1)*(p+1)
b = r*i
rr = a:b
if rr ⊆ 1:n′
A[i,rr] = block
else
A[i,max(a,1):min(b,n′)] = block[max(a,1)-a+1:min(b,n′)-b+(r-1)*(p+1)+1]
end
end
return A
end
## BSplineDerivativeSpace
function _changebasis_R(dP::BSplineDerivativeSpace{r,<:BSplineSpace{p, T}}, P′::BSplineSpace{p′,T′}) where {r,p,p′,T,T′}
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
k = knotvector(dP)
n = dim(dP)
A = SparseMatrixCSC{U,Int32}(I,n,n)
for _r in 0:r-1
_p = p - _r
_A = spzeros(U, n+_r, n+1+_r)
for i in 1:n+_r
_A[i,i] = _p/(k[i+_p]-k[i])
_A[i,i+1] = -_p/(k[i+_p+1]-k[i+1])
end
A = A*_A
end
_P = BSplineSpace{degree(dP)}(k)
A = A*_changebasis_R(_P, P′)
return A
end
function _changebasis_R(dP::BSplineDerivativeSpace, dP′::BSplineDerivativeSpace{0})
P′ = bsplinespace(dP′)
return _changebasis_R(dP, P′)
end
function _changebasis_R(dP::BSplineDerivativeSpace{r}, dP′::BSplineDerivativeSpace{r′}) where {r,r′}
if r > r′
P = bsplinespace(dP)
P′ = bsplinespace(dP′)
_dP = BSplineDerivativeSpace{r-r′}(P)
return _changebasis_R(_dP, P′)
elseif r == r′
P = bsplinespace(dP)
P′ = bsplinespace(dP′)
return _changebasis_R(P, P′)
end
end
function _changebasis_R(P::BSplineSpace, dP′::BSplineDerivativeSpace{0})
P′ = bsplinespace(dP′)
return _changebasis_R(P, P′)
end
@doc raw"""
changebasis(P::AbstractFunctionSpace, P′::AbstractFunctionSpace)
Return `changebasis_R(P, P′)` if ``P ⊆ P′``, otherwise `changebasis_R(P, P′)` if ``P ⊑ P′``.
Throw an error if ``P ⊈ P′`` and ``P ⋢ P′``.
"""
function changebasis(P::AbstractFunctionSpace, P′::AbstractFunctionSpace)
P ⊆ P′ && return _changebasis_R(P, P′)
P ⊑ P′ && return _changebasis_I(P, P′)
throw(DomainError((P, P′),"P ⊆ P′ or P ⊑ P′ must hold."))
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 7616 | # Derivative of B-spline basis function
@generated function bsplinebasis₊₀(dP::BSplineDerivativeSpace{r,<:BSplineSpace{p,T}}, i::Integer, t::S) where {r, p, T, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
ks = [Symbol(:k,i) for i in 1:p+2]
Ks = [Symbol(:K,i) for i in 1:p+1]
Bs = [Symbol(:B,i) for i in 1:p+1]
k_l = Expr(:tuple, ks...)
k_r = Expr(:tuple, :(v[i]), (:(v[i+$j]) for j in 1:p+1)...)
K_l(n) = Expr(:tuple, Ks[1:n]...)
B_l(n) = Expr(:tuple, Bs[1:n]...)
A_r(n) = Expr(:tuple, [:($U($(ks[i])≤t<$(ks[i+1]))) for i in 1:n]...)
K_r(m,n) = Expr(:tuple, [:(_d(t-$(ks[i]),$(ks[i+m])-$(ks[i]))) for i in 1:n]...)
L_r(m,n) = Expr(:tuple, [:(_d(one($U),$(ks[i+m])-$(ks[i]))) for i in 1:n]...)
B_r(n) = Expr(:tuple, [:($(Ks[i])*$(Bs[i])+(1-$(Ks[i+1]))*$(Bs[i+1])) for i in 1:n]...)
C_r(n) = Expr(:tuple, [:($(Ks[i])*$(Bs[i])-$(Ks[i+1])*$(Bs[i+1])) for i in 1:n]...)
if r ≤ p
exs = Expr[]
for i in 1:p-r
push!(exs, :($(K_l(p+2-i)) = $(K_r(i,p+2-i))))
push!(exs, :($(B_l(p+1-i)) = $(B_r(p+1-i))))
end
for i in p-r+1:p
push!(exs, :($(K_l(p+2-i)) = $(L_r(i,p+2-i))))
push!(exs, :($(B_l(p+1-i)) = $(C_r(p+1-i))))
end
Expr(:block,
:(v = knotvector(dP).vector),
:($k_l = $k_r),
:($(B_l(p+1)) = $(A_r(p+1))),
exs...,
:(return $(prod(p-r+1:p))*B1)
)
else
:(return zero($U))
end
end
@generated function bsplinebasis₋₀(dP::BSplineDerivativeSpace{r,<:BSplineSpace{p,T}}, i::Integer, t::S) where {r, p, T, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
ks = [Symbol(:k,i) for i in 1:p+2]
Ks = [Symbol(:K,i) for i in 1:p+1]
Bs = [Symbol(:B,i) for i in 1:p+1]
k_l = Expr(:tuple, ks...)
k_r = Expr(:tuple, :(v[i]), (:(v[i+$j]) for j in 1:p+1)...)
K_l(n) = Expr(:tuple, Ks[1:n]...)
B_l(n) = Expr(:tuple, Bs[1:n]...)
A_r(n) = Expr(:tuple, [:($U($(ks[i])<t≤$(ks[i+1]))) for i in 1:n]...)
K_r(m,n) = Expr(:tuple, [:(_d(t-$(ks[i]),$(ks[i+m])-$(ks[i]))) for i in 1:n]...)
L_r(m,n) = Expr(:tuple, [:(_d(one($U),$(ks[i+m])-$(ks[i]))) for i in 1:n]...)
B_r(n) = Expr(:tuple, [:($(Ks[i])*$(Bs[i])+(1-$(Ks[i+1]))*$(Bs[i+1])) for i in 1:n]...)
C_r(n) = Expr(:tuple, [:($(Ks[i])*$(Bs[i])-$(Ks[i+1])*$(Bs[i+1])) for i in 1:n]...)
if r ≤ p
exs = Expr[]
for i in 1:p-r
push!(exs, :($(K_l(p+2-i)) = $(K_r(i,p+2-i))))
push!(exs, :($(B_l(p+1-i)) = $(B_r(p+1-i))))
end
for i in p-r+1:p
push!(exs, :($(K_l(p+2-i)) = $(L_r(i,p+2-i))))
push!(exs, :($(B_l(p+1-i)) = $(C_r(p+1-i))))
end
Expr(:block,
:(v = knotvector(dP).vector),
:($k_l = $k_r),
:($(B_l(p+1)) = $(A_r(p+1))),
exs...,
:(return $(prod(p-r+1:p))*B1)
)
else
:(return zero($U))
end
end
@generated function bsplinebasis(dP::BSplineDerivativeSpace{r,<:BSplineSpace{p,T}}, i::Integer, t::S) where {r, p, T, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
ks = [Symbol(:k,i) for i in 1:p+2]
Ks = [Symbol(:K,i) for i in 1:p+1]
Bs = [Symbol(:B,i) for i in 1:p+1]
k_l = Expr(:tuple, ks...)
k_r = Expr(:tuple, :(v[i]), (:(v[i+$j]) for j in 1:p+1)...)
K_l(n) = Expr(:tuple, Ks[1:n]...)
B_l(n) = Expr(:tuple, Bs[1:n]...)
A_r(n) = Expr(:tuple, [:($U(($(ks[i])≤t<$(ks[i+1])) || ($(ks[i])<t==$(ks[i+1])==v[end]))) for i in 1:n]...)
K_r(m,n) = Expr(:tuple, [:(_d(t-$(ks[i]),$(ks[i+m])-$(ks[i]))) for i in 1:n]...)
L_r(m,n) = Expr(:tuple, [:(_d(one($U),$(ks[i+m])-$(ks[i]))) for i in 1:n]...)
B_r(n) = Expr(:tuple, [:($(Ks[i])*$(Bs[i])+(1-$(Ks[i+1]))*$(Bs[i+1])) for i in 1:n]...)
C_r(n) = Expr(:tuple, [:($(Ks[i])*$(Bs[i])-$(Ks[i+1])*$(Bs[i+1])) for i in 1:n]...)
if r ≤ p
exs = Expr[]
for i in 1:p-r
push!(exs, :($(K_l(p+2-i)) = $(K_r(i,p+2-i))))
push!(exs, :($(B_l(p+1-i)) = $(B_r(p+1-i))))
end
for i in p-r+1:p
push!(exs, :($(K_l(p+2-i)) = $(L_r(i,p+2-i))))
push!(exs, :($(B_l(p+1-i)) = $(C_r(p+1-i))))
end
Expr(:block,
:(v = knotvector(dP).vector),
:($k_l = $k_r),
:($(B_l(p+1)) = $(A_r(p+1))),
exs...,
:(return $(prod(p-r+1:p))*B1)
)
else
:(return zero($U))
end
end
@doc raw"""
bsplinebasis′₊₀(::AbstractFunctionSpace, ::Integer, ::Real) -> Real
1st derivative of B-spline basis function.
Right-sided limit version.
```math
\dot{B}_{(i,p,k)}(t)
=p\left(\frac{1}{k_{i+p}-k_{i}}B_{(i,p-1,k)}(t)-\frac{1}{k_{i+p+1}-k_{i+1}}B_{(i+1,p-1,k)}(t)\right)
```
`bsplinebasis′₊₀(P, i, t)` is equivalent to `bsplinebasis₊₀(derivative(P), i, t)`.
"""
bsplinebasis′₊₀
@doc raw"""
bsplinebasis′₋₀(::AbstractFunctionSpace, ::Integer, ::Real) -> Real
1st derivative of B-spline basis function.
Left-sided limit version.
```math
\dot{B}_{(i,p,k)}(t)
=p\left(\frac{1}{k_{i+p}-k_{i}}B_{(i,p-1,k)}(t)-\frac{1}{k_{i+p+1}-k_{i+1}}B_{(i+1,p-1,k)}(t)\right)
```
`bsplinebasis′₋₀(P, i, t)` is equivalent to `bsplinebasis₋₀(derivative(P), i, t)`.
"""
bsplinebasis′₋₀
@doc raw"""
bsplinebasis′(::AbstractFunctionSpace, ::Integer, ::Real) -> Real
1st derivative of B-spline basis function.
Modified version.
```math
\dot{B}_{(i,p,k)}(t)
=p\left(\frac{1}{k_{i+p}-k_{i}}B_{(i,p-1,k)}(t)-\frac{1}{k_{i+p+1}-k_{i+1}}B_{(i+1,p-1,k)}(t)\right)
```
`bsplinebasis′(P, i, t)` is equivalent to `bsplinebasis(derivative(P), i, t)`.
"""
bsplinebasis′
for suffix in ("", "₋₀", "₊₀")
fname = Symbol(:bsplinebasis, suffix)
fname′ = Symbol(:bsplinebasis, "′" ,suffix)
@eval function $(fname′)(P::AbstractFunctionSpace, i::Integer, t::Real)
return $(fname)(derivative(P), i, t)
end
end
@generated function bsplinebasisall(dP::BSplineDerivativeSpace{r,<:BSplineSpace{p,T}}, i::Integer, t::S) where {r, p, T, S<:Real}
U = StaticArrays.arithmetic_closure(promote_type(T,S))
bs = [Symbol(:b,i) for i in 1:p]
Bs = [Symbol(:B,i) for i in 1:p+1]
K1s = [:($(p)/(k[i+$(j)]-k[i+$(p+j)])) for j in 1:p]
K2s = [:($(p)/(k[i+$(p+j)]-k[i+$(j)])) for j in 1:p]
b = Expr(:tuple, bs...)
B = Expr(:tuple, Bs...)
exs = [:($(Bs[j+1]) = ($(K1s[j+1])*$(bs[j+1]) + $(K2s[j])*$(bs[j]))) for j in 1:p-1]
if r ≤ p
Expr(:block,
:($(Expr(:meta, :inline))),
:(k = knotvector(dP)),
:($b = bsplinebasisall(_lower_R(dP),i+1,t)),
:($(Bs[1]) = $(K1s[1])*$(bs[1])),
exs...,
:($(Bs[p+1]) = $(K2s[p])*$(bs[p])),
:(return SVector($(B)))
)
else
Z = Expr(:tuple, [:(zero($U)) for i in 1:p+1]...)
:(return SVector($(Z)))
end
end
@inline function bsplinebasisall(dP::BSplineDerivativeSpace{0,<:BSplineSpace{p,T}}, i::Integer, t::Real) where {p, T}
P = bsplinespace(dP)
bsplinebasisall(P,i,t)
end
# TODO: add methods for UniformBSplineSpace (and OpenUniformBSplineSpace)
# function bsplinebasis(dP::BSplineDerivativeSpace{r,UniformBSplineSpace{p,T,R}}, i, t) where {r,p,T,R}
# end
# function bsplinebasis₊₀(dP::BSplineDerivativeSpace{r,UniformBSplineSpace{p,T,R}}, i, t) where {r,p,T,R}
# end
# function bsplinebasis₋₀(dP::BSplineDerivativeSpace{r,UniformBSplineSpace{p,T,R}}, i, t) where {r,p,T,R}
# end
# function bsplinebasisall(dP::BSplineDerivativeSpace{r,UniformBSplineSpace{p,T,R}}, i, t) where {r,p,T,R}
# end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 5195 | # Space of derivative of B-spline basis function
@doc raw"""
BSplineDerivativeSpace{r}(P::BSplineSpace)
Construct derivative of B-spline space from given differential order and B-spline space.
```math
D^{r}(\mathcal{P}[p,k])
=\left\{t \mapsto \left. \frac{d^r f}{dt^r}(t) \ \right| \ f \in \mathcal{P}[p,k] \right\}
```
# Examples
```jldoctest
julia> P = BSplineSpace{2}(KnotVector([1,2,3,4,5,6]))
BSplineSpace{2, Int64, KnotVector{Int64}}(KnotVector([1, 2, 3, 4, 5, 6]))
julia> dP = BSplineDerivativeSpace{1}(P)
BSplineDerivativeSpace{1, BSplineSpace{2, Int64, KnotVector{Int64}}, Int64}(BSplineSpace{2, Int64, KnotVector{Int64}}(KnotVector([1, 2, 3, 4, 5, 6])))
julia> degree(P), degree(dP)
(2, 1)
```
"""
struct BSplineDerivativeSpace{r, S<:BSplineSpace, T} <: AbstractFunctionSpace{T}
bsplinespace::S
function BSplineDerivativeSpace{r,S,T}(P::S) where {r, S<:BSplineSpace{p,T}} where {p,T}
new{r,S,T}(P)
end
end
function BSplineDerivativeSpace{r}(P::S) where {r, S<:BSplineSpace{p,T}} where {p,T}
BSplineDerivativeSpace{r,S,T}(P)
end
function BSplineDerivativeSpace{r,S}(P::S) where {r, S<:BSplineSpace{p,T}} where {p,T}
BSplineDerivativeSpace{r,S,T}(P)
end
function BSplineDerivativeSpace{r,S1}(P::S2) where {r, S1<:BSplineSpace{p,T1}, S2<:BSplineSpace{p,T2}} where {p,T1,T2}
BSplineDerivativeSpace{r}(S1(P))
end
function BSplineDerivativeSpace{r,S}(dP::BSplineDerivativeSpace{r,S}) where {r,S}
dP
end
function BSplineDerivativeSpace{r,S1}(dP::BSplineDerivativeSpace{r,S2}) where {r,S1,S2}
BSplineDerivativeSpace{r,S1}(S1(bsplinespace(dP)))
end
# Broadcast like a scalar
Base.Broadcast.broadcastable(dP::BSplineDerivativeSpace) = Ref(dP)
# Equality
@inline Base.:(==)(dP1::BSplineDerivativeSpace{r}, dP2::BSplineDerivativeSpace{r}) where r = bsplinespace(dP1) == bsplinespace(dP2)
@inline Base.:(==)(dP1::BSplineDerivativeSpace{r1}, dP2::BSplineDerivativeSpace{r2}) where {r1, r2} = false
bsplinespace(dP::BSplineDerivativeSpace) = dP.bsplinespace
knotvector(dP::BSplineDerivativeSpace) = knotvector(bsplinespace(dP))
degree(dP::BSplineDerivativeSpace{r,<:BSplineSpace{p}}) where {r,p} = p - r
dim(dP::BSplineDerivativeSpace{r,<:BSplineSpace{p}}) where {r,p} = dim(bsplinespace(dP))
exactdim_R(dP::BSplineDerivativeSpace{r,<:BSplineSpace{p}}) where {r,p} = exactdim_R(bsplinespace(dP)) - r
exactdim_I(dP::BSplineDerivativeSpace{r,<:BSplineSpace{p}}) where {r,p} = exactdim_I(bsplinespace(dP)) - r
intervalindex(dP::BSplineDerivativeSpace,t::Real) = intervalindex(bsplinespace(dP),t)
domain(dP::BSplineDerivativeSpace) = domain(bsplinespace(dP))
_lower_R(dP::BSplineDerivativeSpace{r}) where r = BSplineDerivativeSpace{r-1}(_lower_R(bsplinespace(dP)))
_lower_I(dP::BSplineDerivativeSpace{r}) where r = BSplineDerivativeSpace{r-1}(_lower_I(bsplinespace(dP)))
_iszeros_R(P::BSplineDerivativeSpace) = _iszeros_R(bsplinespace(P))
_iszeros_I(P::BSplineDerivativeSpace) = _iszeros_I(bsplinespace(P))
function isdegenerate_R(dP::BSplineDerivativeSpace, i::Integer)
return isdegenerate_R(bsplinespace(dP), i)
end
function isdegenerate_I(dP::BSplineDerivativeSpace, i::Integer)
return isdegenerate_I(bsplinespace(dP), i)
end
@doc raw"""
derivative(::BSplineDerivativeSpace{r}) -> BSplineDerivativeSpace{r+1}
derivative(::BSplineSpace) -> BSplineDerivativeSpace{1}
Derivative of B-spline related space.
# Examples
```jldoctest
julia> BSplineSpace{2}(KnotVector(0:5))
BSplineSpace{2, Int64, KnotVector{Int64}}(KnotVector([0, 1, 2, 3, 4, 5]))
julia> BasicBSpline.derivative(ans)
BSplineDerivativeSpace{1, BSplineSpace{2, Int64, KnotVector{Int64}}, Int64}(BSplineSpace{2, Int64, KnotVector{Int64}}(KnotVector([0, 1, 2, 3, 4, 5])))
julia> BasicBSpline.derivative(ans)
BSplineDerivativeSpace{2, BSplineSpace{2, Int64, KnotVector{Int64}}, Int64}(BSplineSpace{2, Int64, KnotVector{Int64}}(KnotVector([0, 1, 2, 3, 4, 5])))
```
"""
derivative(P::BSplineSpace) = BSplineDerivativeSpace{1}(P)
derivative(dP::BSplineDerivativeSpace{r}) where r = BSplineDerivativeSpace{r+1}(bsplinespace(dP))
function Base.issubset(dP::BSplineDerivativeSpace{r,<:BSplineSpace{p}}, P′::BSplineSpace) where {r,p}
k = knotvector(dP)
P = BSplineSpace{p-r}(k)
return P ⊆ P′
end
function Base.issubset(dP::BSplineDerivativeSpace, dP′::BSplineDerivativeSpace{0})
P′ = bsplinespace(dP′)
return dP ⊆ P′
end
function Base.issubset(dP::BSplineDerivativeSpace{r}, dP′::BSplineDerivativeSpace{r′}) where {r,r′}
if r > r′
P = bsplinespace(dP)
P′ = bsplinespace(dP′)
_dP = BSplineDerivativeSpace{r-r′}(P)
return _dP ⊆ P′
elseif r == r′
P = bsplinespace(dP)
P′ = bsplinespace(dP′)
return P ⊆ P′
else
return false
end
end
function Base.issubset(P::BSplineSpace, dP′::BSplineDerivativeSpace{0})
P′ = bsplinespace(dP′)
return P ⊆ P′
end
function Base.issubset(P::BSplineSpace, dP′::BSplineDerivativeSpace)
return false
end
# TODO: Add issqsubset
function Base.hash(dP::BSplineDerivativeSpace{r,<:BSplineSpace{p}}, h::UInt) where {r,p}
P = bsplinespace(dP)
k = knotvector(P)
hash(BSplineDerivativeSpace{r,<:BSplineSpace{p}}, hash(_vec(k), h))
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 12555 | ######################
#= Type definitions =#
######################
@doc raw"""
An abstract type for knot vector.
"""
abstract type AbstractKnotVector{T<:Real} end
@doc raw"""
Knot vector with zero-element.
```math
k=()
```
This struct is intended for internal use.
# Examples
```jldoctest
julia> EmptyKnotVector()
EmptyKnotVector{Bool}()
julia> EmptyKnotVector{Float64}()
EmptyKnotVector{Float64}()
```
"""
struct EmptyKnotVector{T} <: AbstractKnotVector{T} end
@doc raw"""
Construct knot vector from given array.
```math
k=(k_1,\dots,k_l)
```
# Examples
```jldoctest
julia> k = KnotVector([1,2,3])
KnotVector([1, 2, 3])
julia> k = KnotVector(1:3)
KnotVector([1, 2, 3])
```
"""
struct KnotVector{T} <: AbstractKnotVector{T}
vector::Vector{T}
global unsafe_knotvector(::Type{T}, v) where T = new{T}(v)
end
@doc raw"""
Construct uniform knot vector from given range.
```math
k=(k_1,\dots,k_l)
```
# Examples
```jldoctest
julia> k = UniformKnotVector(1:8)
UniformKnotVector(1:8)
julia> UniformKnotVector(8:-1:3)
UniformKnotVector(3:1:8)
```
"""
struct UniformKnotVector{T,R<:AbstractRange} <: AbstractKnotVector{T}
vector::R
global unsafe_uniformknotvector(::Type{T}, v::R) where R<:AbstractRange{T} where T = new{T,R}(v)
end
@doc raw"""
A type to represetnt sub knot vector.
```math
k=(k_1,\dots,k_l)
```
# Examples
```jldoctest
julia> k = knotvector"1 11 211"
KnotVector([1, 3, 4, 6, 6, 7, 8])
julia> view(k, 2:5)
SubKnotVector([3, 4, 6, 6])
```
"""
struct SubKnotVector{T,S<:SubArray{T,1}} <: AbstractKnotVector{T}
vector::S
global unsafe_subknotvector(v::S) where {T,S<:SubArray{T,1}} = new{T,S}(v)
end
##################
#= Constructors =#
##################
EmptyKnotVector() = EmptyKnotVector{Bool}()
KnotVector{T}(v::AbstractVector) where T = unsafe_knotvector(T,sort(v))
KnotVector(v::AbstractVector{T}) where T = unsafe_knotvector(T,sort(v))
AbstractKnotVector{S}(k::KnotVector{T}) where {S, T} = unsafe_knotvector(promote_type(S,T), _vec(k))
AbstractKnotVector{T}(k::AbstractKnotVector{T}) where {T} = k
UniformKnotVector(v::AbstractRange{T}) where T = unsafe_uniformknotvector(T,sort(v))
UniformKnotVector(k::UniformKnotVector) = k
UniformKnotVector{T}(k::UniformKnotVector) where T = unsafe_uniformknotvector(T, k.vector)
UniformKnotVector{T,R}(k::UniformKnotVector) where R<:AbstractRange{T} where T = unsafe_uniformknotvector(T, R(k.vector))
SubKnotVector(k::SubKnotVector) = k
SubKnotVector{T,S}(k::SubKnotVector{T,S}) where {T,S} = k
Base.copy(k::EmptyKnotVector{T}) where T = k
Base.copy(k::KnotVector{T}) where T = unsafe_knotvector(T,copy(_vec(k)))
Base.copy(k::UniformKnotVector{T}) where T = unsafe_uniformknotvector(T,copy(_vec(k)))
Base.copy(k::SubKnotVector{T}) where T = unsafe_knotvector(T,copy(_vec(k)))
KnotVector(k::KnotVector) = k
KnotVector(k::AbstractKnotVector{T}) where T = unsafe_knotvector(T,_vec(k))
KnotVector{T}(k::KnotVector{T}) where T = k
KnotVector{T}(k::AbstractKnotVector) where T = unsafe_knotvector(T,_vec(k))
######################################
#= Other methods for Base functions =#
######################################
Base.convert(T::Type{<:AbstractKnotVector}, k::AbstractKnotVector) = T(k)
function Base.convert(::Type{UniformKnotVector{T,R}},k::UniformKnotVector) where {T,R}
UniformKnotVector{T,R}(k)
end
function Base.promote_rule(::Type{KnotVector{T}}, ::Type{KnotVector{S}}) where {T,S}
KnotVector{promote_type(T,S)}
end
function Base.promote_rule(::Type{KnotVector{T}}, ::Type{UniformKnotVector{S,R}}) where {T,S,R}
KnotVector{promote_type(T,S)}
end
function Base.promote_rule(::Type{KnotVector{T1}}, ::Type{SubKnotVector{T2,S2}}) where {T1,T2,S2}
KnotVector{promote_type(T1,T2)}
end
function Base.show(io::IO, k::KnotVector)
print(io, "KnotVector($(k.vector))")
end
function Base.show(io::IO, k::T) where T<:AbstractKnotVector
print(io, "$(nameof(T))($(k.vector))")
end
function Base.show(io::IO, ::T) where T<:EmptyKnotVector
print(io, "$(T)()")
end
Base.zero(::Type{<:EmptyKnotVector{T}}) where T = EmptyKnotVector{T}()
Base.zero(::Type{EmptyKnotVector}) = EmptyKnotVector()
Base.zero(::T) where {T<:EmptyKnotVector} = zero(T)
Base.zero(::Type{<:AbstractKnotVector{T}}) where T = EmptyKnotVector{T}()
Base.zero(::Type{AbstractKnotVector}) = EmptyKnotVector()
Base.zero(::Type{KnotVector}) = zero(KnotVector{Float64})
Base.zero(::Type{KnotVector{T}}) where T = unsafe_knotvector(T, T[])
Base.zero(::KnotVector{T}) where T = unsafe_knotvector(T, T[])
Base.zero(::UniformKnotVector{T}) where T = EmptyKnotVector{T}()
# ==
Base.:(==)(k₁::AbstractKnotVector, k₂::AbstractKnotVector) = (_vec(k₁) == _vec(k₂))
Base.:(==)(k::AbstractKnotVector, ::EmptyKnotVector) = isempty(k)
Base.:(==)(k1::EmptyKnotVector, k2::AbstractKnotVector) = (k2 == k1)
Base.:(==)(k::EmptyKnotVector, ::EmptyKnotVector) = true
Base.eltype(::AbstractKnotVector{T}) where T = T
Base.collect(k::UniformKnotVector) = collect(k.vector)
Base.collect(k::KnotVector) = copy(k.vector)
Base.isempty(::EmptyKnotVector) = true
# + AbstractKnotVector
Base.:+(k::AbstractKnotVector{T}, ::EmptyKnotVector{T}) where T = k
function Base.:+(k::AbstractKnotVector{T1}, ::EmptyKnotVector{T2}) where {T1, T2}
T = promote_type(T1, T2)
if T == T1
return k
else
return AbstractKnotVector{T}(k)
end
end
# + EmptyKnotVector
Base.:+(::EmptyKnotVector{T}, ::EmptyKnotVector{T}) where T = EmptyKnotVector{T}()
Base.:+(::EmptyKnotVector{T1}, ::EmptyKnotVector{T2}) where {T1, T2} = EmptyKnotVector{promote_type(T1, T2)}()
# + swap
Base.:+(k1::EmptyKnotVector, k2::AbstractKnotVector) = k2 + k1
@doc raw"""
Sum of knot vectors
```math
\begin{aligned}
k^{(1)}+k^{(2)}
&=(k^{(1)}_1, \dots, k^{(1)}_{l^{(1)}}) + (k^{(2)}_1, \dots, k^{(2)}_{l^{(2)}}) \\
&=(\text{sort of union of} \ k^{(1)} \ \text{and} \ k^{(2)} \text{)}
\end{aligned}
```
For example, ``(1,2,3,5)+(4,5,8)=(1,2,3,4,5,5,8)``.
# Examples
```jldoctest
julia> k1 = KnotVector([1,2,3,5]);
julia> k2 = KnotVector([4,5,8]);
julia> k1 + k2
KnotVector([1, 2, 3, 4, 5, 5, 8])
```
"""
function Base.:+(k1::KnotVector{T}, k2::KnotVector{T}) where T
v1, v2 = k1.vector, k2.vector
n1, n2 = length(v1), length(v2)
iszero(n1) && return k2
iszero(n2) && return k1
n = n1 + n2
v = Vector{T}(undef, n)
i1 = i2 = 1
for i in 1:n
if isless(v1[i1], v2[i2])
v[i] = v1[i1]
i1 += 1
if i1 > n1
v[i+1:n] = view(v2, i2:n2)
break
end
else
v[i] = v2[i2]
i2 += 1
if i2 > n2
v[i+1:n] = view(v1, i1:n1)
break
end
end
end
return BasicBSpline.unsafe_knotvector(T,v)
end
Base.:+(k1::AbstractKnotVector{T1}, k2::AbstractKnotVector{T2}) where {T1, T2} = +(promote(k1,k2)...)
Base.:+(k1::UniformKnotVector{T1},k2::UniformKnotVector{T2}) where {T1,T2} = KnotVector{promote_type(T1,T2)}([k1.vector;k2.vector])
@doc raw"""
Product of integer and knot vector
```math
\begin{aligned}
m\cdot k&=\underbrace{k+\cdots+k}_{m}
\end{aligned}
```
For example, ``2\cdot (1,2,2,5)=(1,1,2,2,2,2,5,5)``.
# Examples
```jldoctest
julia> k = KnotVector([1,2,2,5]);
julia> 2 * k
KnotVector([1, 1, 2, 2, 2, 2, 5, 5])
```
"""
function Base.:*(m::Integer, k::AbstractKnotVector)
return m*KnotVector(k)
end
function Base.:*(m::Integer, k::KnotVector{T}) where T
if m == 0
return zero(k)
elseif m == 1
return k
elseif m > 1
l = length(k)
v = Vector{T}(undef, m*l)
for i in 1:m
v[i:m:m*(l-1)+i] .= k.vector
end
return BasicBSpline.unsafe_knotvector(T,v)
else
throw(DomainError(m, "The number to be multiplied must be non-negative."))
end
end
Base.:*(k::AbstractKnotVector, m::Integer) = m*k
function Base.:*(m::Integer, k::EmptyKnotVector)
m < 0 && throw(DomainError(m, "The number to be multiplied must be non-negative."))
return k
end
Base.in(r::Real, k::AbstractKnotVector) = in(r, _vec(k))
Base.getindex(k::AbstractKnotVector, i::Integer) = _vec(k)[i]
Base.getindex(k::AbstractKnotVector, v::AbstractVector{<:Integer}) = KnotVector(_vec(k)[v])
Base.getindex(k::UniformKnotVector, v::AbstractRange{<:Integer}) = UniformKnotVector(sort(k.vector[v]))
@doc raw"""
Length of knot vector
```math
\begin{aligned}
\#{k}
&=(\text{number of knot elements of} \ k) \\
\end{aligned}
```
For example, ``\#{(1,2,2,3)}=4``.
# Examples
```jldoctest
julia> k = KnotVector([1,2,2,3]);
julia> length(k)
4
```
"""
Base.length(k::AbstractKnotVector) = length(_vec(k))
Base.firstindex(k::AbstractKnotVector) = 1
Base.lastindex(k::AbstractKnotVector) = length(k)
Base.step(k::UniformKnotVector) = step(_vec(k))
@doc raw"""
Unique elements of knot vector.
```math
\begin{aligned}
\widehat{k}
&=(\text{unique knot elements of} \ k) \\
\end{aligned}
```
For example, ``\widehat{(1,2,2,3)}=(1,2,3)``.
# Examples
```jldoctest
julia> k = KnotVector([1,2,2,3]);
julia> unique(k)
KnotVector([1, 2, 3])
```
"""
Base.unique(k::AbstractKnotVector)
Base.unique(k::EmptyKnotVector) = k
Base.unique(k::KnotVector{T}) where T = unsafe_knotvector(T, unique(k.vector))
Base.unique!(k::KnotVector) = (unique!(k.vector); k)
Base.unique(k::UniformKnotVector) = UniformKnotVector(unique(k.vector))
Base.unique(k::SubKnotVector{T}) where T = unsafe_knotvector(T, unique(_vec(k)))
Base.iterate(k::AbstractKnotVector) = iterate(_vec(k))
Base.iterate(k::AbstractKnotVector, i) = iterate(_vec(k), i)
Base.searchsortedfirst(k::AbstractKnotVector,t) = searchsortedfirst(_vec(k),t)
Base.searchsortedlast(k::AbstractKnotVector,t) = searchsortedlast(_vec(k),t)
Base.searchsorted(k::AbstractKnotVector,t) = searchsorted(_vec(k),t)
@doc raw"""
Check a inclusive relationship ``k\subseteq k'``, for example:
```math
\begin{aligned}
(1,2) &\subseteq (1,2,3) \\
(1,2,2) &\not\subseteq (1,2,3) \\
(1,2,3) &\subseteq (1,2,3) \\
\end{aligned}
```
# Examples
```jldoctest
julia> KnotVector([1,2]) ⊆ KnotVector([1,2,3])
true
julia> KnotVector([1,2,2]) ⊆ KnotVector([1,2,3])
false
julia> KnotVector([1,2,3]) ⊆ KnotVector([1,2,3])
true
```
"""
function Base.issubset(k::KnotVector, k′::KnotVector)
i = 1
l = length(k)
for k′ⱼ in k′
l < i && (return true)
k[i] < k′ⱼ && (return false)
k[i] == k′ⱼ && (i += 1)
end
return l < i
end
function Base.issubset(k::AbstractKnotVector, k′::AbstractKnotVector)
issubset(KnotVector(k),KnotVector(k′))
end
Base.:⊊(A::AbstractKnotVector, B::AbstractKnotVector) = (A ≠ B) & (A ⊆ B)
Base.:⊋(A::AbstractKnotVector, B::AbstractKnotVector) = (A ≠ B) & (A ⊇ B)
function Base.float(k::KnotVector{T}) where T
KnotVector(float(_vec(k)))
end
function Base.float(k::UniformKnotVector)
UniformKnotVector(float(_vec(k)))
end
Base.view(k::UniformKnotVector{T},inds) where T = unsafe_uniformknotvector(T, view(_vec(k), inds))
Base.view(k::KnotVector,inds) = unsafe_subknotvector(view(_vec(k), inds))
Base.view(k::SubKnotVector,inds) = unsafe_subknotvector(view(_vec(k), inds))
"""
Convert `AbstractKnotVector` to `AbstractVector`
"""
_vec
_vec(::EmptyKnotVector{T}) where T = SVector{0,T}()
_vec(k::KnotVector) = k.vector
_vec(k::UniformKnotVector) = k.vector
_vec(k::SubKnotVector) = k.vector
@doc raw"""
For given knot vector ``k``, the following function ``\mathfrak{n}_k:\mathbb{R}\to\mathbb{Z}`` represents the number of knots that duplicate the knot vector ``k``.
```math
\mathfrak{n}_k(t) = \#\{i \mid k_i=t \}
```
For example, if ``k=(1,2,2,3)``, then ``\mathfrak{n}_k(0.3)=0``, ``\mathfrak{n}_k(1)=1``, ``\mathfrak{n}_k(2)=2``.
```jldoctest
julia> k = KnotVector([1,2,2,3]);
julia> countknots(k,0.3)
0
julia> countknots(k,1.0)
1
julia> countknots(k,2.0)
2
```
"""
function countknots(k::AbstractKnotVector, t::Real)
# for small case, this is faster
# return count(==(t), k.vector)
# for large case, this is faster
return length(searchsorted(_vec(k), t, lt=<))
end
"""
@knotvector_str -> KnotVector
Construct a knotvector by specifying the numbers of duplicates of knots.
# Examples
```jldoctest
julia> knotvector"11111"
KnotVector([1, 2, 3, 4, 5])
julia> knotvector"123"
KnotVector([1, 2, 2, 3, 3, 3])
julia> knotvector" 2 2 2"
KnotVector([2, 2, 4, 4, 6, 6])
julia> knotvector" 1"
KnotVector([6])
```
"""
macro knotvector_str(s)
return sum(KnotVector(findall(==('0'+i), s))*i for i in 1:9)
end
function Base.hash(k::AbstractKnotVector, h::UInt)
hash(AbstractKnotVector, hash(_vec(k), h))
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 10281 | # Rational B-spline manifold (NURBS)
"""
Construct Rational B-spline manifold from given control points, weights and B-spline spaces.
# Examples
```jldoctest
julia> using StaticArrays, LinearAlgebra
julia> P = BSplineSpace{2}(KnotVector([0,0,0,1,1,1]))
BSplineSpace{2, Int64, KnotVector{Int64}}(KnotVector([0, 0, 0, 1, 1, 1]))
julia> w = [1, 1/√2, 1]
3-element Vector{Float64}:
1.0
0.7071067811865475
1.0
julia> a = [SVector(1,0), SVector(1,1), SVector(0,1)]
3-element Vector{SVector{2, Int64}}:
[1, 0]
[1, 1]
[0, 1]
julia> M = RationalBSplineManifold(a,w,P); # 1/4 arc
julia> M(0.3)
2-element SVector{2, Float64} with indices SOneTo(2):
0.8973756499953727
0.4412674277525845
julia> norm(M(0.3))
1.0
```
"""
struct RationalBSplineManifold{Dim,Deg,C,W,T,S<:NTuple{Dim, BSplineSpace}} <: AbstractManifold{Dim}
controlpoints::Array{C,Dim}
weights::Array{W,Dim}
bsplinespaces::S
function RationalBSplineManifold{Dim,Deg,C,W,T,S}(a::Array{C,Dim},w::Array{W,Dim},P::S) where {S<:NTuple{Dim, BSplineSpace{p,T} where p},C,W} where {Dim, Deg, T}
new{Dim,Deg,C,W,T,S}(a,w,P)
end
end
function RationalBSplineManifold(a::Array{C,Dim},w::Array{W,Dim},P::S) where {S<:Tuple{BSplineSpace{p,T} where p, Vararg{BSplineSpace{p,T} where p}}} where {Dim, T, C, W}
if size(a) != dim.(P)
msg = "The size of control points array $(size(a)) and dimensions of B-spline spaces $(dim.(P)) must be equal."
throw(DimensionMismatch(msg))
end
if size(w) != dim.(P)
msg = "The size of weights array $(size(w)) and dimensions of B-spline spaces $(dim.(P)) must be equal."
throw(DimensionMismatch(msg))
end
Deg = degree.(P)
return RationalBSplineManifold{Dim,Deg,C,W,T,S}(a, w, P)
end
function RationalBSplineManifold(a::Array{C,Dim},w::Array{W,Dim},P::S) where {S<:NTuple{Dim, BSplineSpace{p,T} where {p,T}},C,W} where {Dim}
P′ = _promote_knottype(P)
return RationalBSplineManifold(a, w, P′)
end
RationalBSplineManifold(a::Array{C,Dim},w::Array{T,Dim},Ps::Vararg{BSplineSpace, Dim}) where {C,Dim,T<:Real} = RationalBSplineManifold(a,w,Ps)
Base.:(==)(M1::RationalBSplineManifold, M2::RationalBSplineManifold) = (bsplinespaces(M1)==bsplinespaces(M2)) & (controlpoints(M1)==controlpoints(M2)) & (weights(M1)==weights(M2))
function Base.hash(M::RationalBSplineManifold{0}, h::UInt)
hash(RationalBSplineManifold{0}, hash(weights(M), hash(controlpoints(M), h)))
end
function Base.hash(M::RationalBSplineManifold, h::UInt)
hash(xor(hash.(bsplinespaces(M), h)...), hash(weights(M), hash(controlpoints(M), h)))
end
controlpoints(M::RationalBSplineManifold) = M.controlpoints
weights(M::RationalBSplineManifold) = M.weights
bsplinespaces(M::RationalBSplineManifold) = M.bsplinespaces
@generated function unbounded_mapping(M::RationalBSplineManifold{Dim,Deg}, t::Vararg{Real,Dim}) where {Dim,Deg}
# Use `UnitRange` to support Julia v1.6 (LTS)
# This can be replaced with `range` if we drop support for v1.6
iter = CartesianIndices(UnitRange.(1, Deg .+ 1))
exs = Expr[]
for ci in iter
ex_w = Expr(:call, [:getindex, :w, [:($(Symbol(:i,d))+$(ci[d]-1)) for d in 1:Dim]...]...)
ex_a = Expr(:call, [:getindex, :a, [:($(Symbol(:i,d))+$(ci[d]-1)) for d in 1:Dim]...]...)
ex = Expr(:call, [:*, [:($(Symbol(:b,d))[$(ci[d])]) for d in 1:Dim]..., ex_w]...)
ex = Expr(:+=, :u, ex)
push!(exs, ex)
ex = Expr(:call, [:getindex, :a, [:($(Symbol(:i,d))+$(ci[d]-1)) for d in 1:Dim]...]...)
ex = Expr(:call, [:*, [:($(Symbol(:b,d))[$(ci[d])]) for d in 1:Dim]..., ex_w, ex_a]...)
ex = Expr(:+=, :v, ex)
push!(exs, ex)
end
exs[1].head = :(=)
exs[2].head = :(=)
Expr(
:block,
Expr(:(=), Expr(:tuple, [Symbol(:P, i) for i in 1:Dim]...), :(bsplinespaces(M))),
Expr(:(=), Expr(:tuple, [Symbol(:t, i) for i in 1:Dim]...), :t),
:(a = controlpoints(M)),
:(w = weights(M)),
Expr(:(=), Expr(:tuple, [Symbol(:i, i) for i in 1:Dim]...), Expr(:tuple, [:(intervalindex($(Symbol(:P, i)), $(Symbol(:t, i)))) for i in 1:Dim]...)),
Expr(:(=), Expr(:tuple, [Symbol(:b, i) for i in 1:Dim]...), Expr(:tuple, [:(bsplinebasisall($(Symbol(:P, i)), $(Symbol(:i, i)), $(Symbol(:t, i)))) for i in 1:Dim]...)),
exs...,
:(return v/u)
)
end
@generated function (M::RationalBSplineManifold{Dim})(t::Vararg{Real, Dim}) where Dim
Ps = [Symbol(:P,i) for i in 1:Dim]
P = Expr(:tuple, Ps...)
ts = [Symbol(:t,i) for i in 1:Dim]
T = Expr(:tuple, ts...)
exs = [:($(Symbol(:t,i)) in domain($(Symbol(:P,i))) || throw(DomainError($(Symbol(:t,i)), "The input "*string($(Symbol(:t,i)))*" is out of domain $(domain($(Symbol(:P,i))))."))) for i in 1:Dim]
ret = Expr(:call,:unbounded_mapping,:M,[Symbol(:t,i) for i in 1:Dim]...)
Expr(
:block,
:($(Expr(:meta, :inline))),
:($T = t),
:($P = bsplinespaces(M)),
exs...,
:(return $(ret))
)
end
## currying
# 2dim
@inline function (M::RationalBSplineManifold{2})(::Colon,::Colon)
a = copy(controlpoints(M))
w = copy(weights(M))
Ps = bsplinespaces(M)
return RationalBSplineManifold(a,w,Ps)
end
@inline function (M::RationalBSplineManifold{2,p})(t1::Real,::Colon) where p
p1, p2 = p
P1, P2 = bsplinespaces(M)
a = controlpoints(M)
w = weights(M)
j1 = intervalindex(P1,t1)
B1 = bsplinebasisall(P1,j1,t1)
w′ = sum(w[j1+i1,:]*B1[1+i1] for i1 in 0:p1)
a′ = sum(a[j1+i1,:].*w[j1+i1,:].*B1[1+i1] for i1 in 0:p1) ./ w′
return RationalBSplineManifold(a′,w′,(P2,))
end
@inline function (M::RationalBSplineManifold{2,p})(::Colon,t2::Real) where p
p1, p2 = p
P1, P2 = bsplinespaces(M)
a = controlpoints(M)
w = weights(M)
j2 = intervalindex(P2,t2)
B2 = bsplinebasisall(P2,j2,t2)
w′ = sum(w[:,j2+i2]*B2[1+i2] for i2 in 0:p2)
a′ = sum(a[:,j2+i2].*w[:,j2+i2].*B2[1+i2] for i2 in 0:p2) ./ w′
return RationalBSplineManifold(a′,w′,(P1,))
end
# 3dim
@inline function (M::RationalBSplineManifold{3,p})(t1::Real,::Colon,::Colon) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
w = weights(M)
j1 = intervalindex(P1,t1)
B1 = bsplinebasisall(P1,j1,t1)
w′ = sum(w[j1+i1,:,:]*B1[1+i1] for i1 in 0:p1)
a′ = sum(a[j1+i1,:,:].*w[j1+i1,:,:].*B1[1+i1] for i1 in 0:p1) ./ w′
return RationalBSplineManifold(a′,w′,(P2,P3))
end
@inline function (M::RationalBSplineManifold{3,p})(::Colon,t2::Real,::Colon) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
w = weights(M)
j2 = intervalindex(P2,t2)
B2 = bsplinebasisall(P2,j2,t2)
w′ = sum(w[:,j2+i2,:]*B2[1+i2] for i2 in 0:p2)
a′ = sum(a[:,j2+i2,:].*w[:,j2+i2,:].*B2[1+i2] for i2 in 0:p2) ./ w′
return RationalBSplineManifold(a′,w′,(P1,P3))
end
@inline function (M::RationalBSplineManifold{3,p})(::Colon,::Colon,t3::Real) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
w = weights(M)
j3 = intervalindex(P3,t3)
B3 = bsplinebasisall(P3,j3,t3)
w′ = sum(w[:,:,j3+i3]*B3[1+i3] for i3 in 0:p3)
a′ = sum(a[:,:,j3+i3].*w[:,:,j3+i3].*B3[1+i3] for i3 in 0:p3) ./ w′
return RationalBSplineManifold(a′,w′,(P1,P2))
end
@inline function (M::RationalBSplineManifold{3,p})(t1::Real,t2::Real,::Colon) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
w = weights(M)
j1 = intervalindex(P1,t1)
j2 = intervalindex(P2,t2)
B1 = bsplinebasisall(P1,j1,t1)
B2 = bsplinebasisall(P2,j2,t2)
w′ = sum(w[j1+i1,j2+i2,:]*B1[1+i1]*B2[1+i2] for i1 in 0:p1, i2 in 0:p2)
a′ = sum(a[j1+i1,j2+i2,:].*w[j1+i1,j2+i2,:].*B1[1+i1].*B2[1+i2] for i1 in 0:p1, i2 in 0:p2) ./ w′
return RationalBSplineManifold(a′,w′,(P3,))
end
@inline function (M::RationalBSplineManifold{3,p})(t1::Real,::Colon,t3::Real) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
w = weights(M)
j1 = intervalindex(P1,t1)
j3 = intervalindex(P3,t3)
B1 = bsplinebasisall(P1,j1,t1)
B3 = bsplinebasisall(P3,j3,t3)
w′ = sum(w[j1+i1,:,j3+i3]*B1[1+i1]*B3[1+i3] for i1 in 0:p1, i3 in 0:p3)
a′ = sum(a[j1+i1,:,j3+i3].*w[j1+i1,:,j3+i3].*B1[1+i1].*B3[1+i3] for i1 in 0:p1, i3 in 0:p3) ./ w′
return RationalBSplineManifold(a′,w′,(P2,))
end
@inline function (M::RationalBSplineManifold{3,p})(::Colon,t2::Real,t3::Real) where p
p1, p2, p3 = p
P1, P2, P3 = bsplinespaces(M)
a = controlpoints(M)
w = weights(M)
j2 = intervalindex(P2,t2)
j3 = intervalindex(P3,t3)
B2 = bsplinebasisall(P2,j2,t2)
B3 = bsplinebasisall(P3,j3,t3)
w′ = sum(w[:,j2+i2,j3+i3]*B2[1+i2]*B3[1+i3] for i2 in 0:p2, i3 in 0:p3)
a′ = sum(a[:,j2+i2,j3+i3].*w[:,j2+i2,j3+i3].*B2[1+i2].*B3[1+i3] for i2 in 0:p2, i3 in 0:p3) ./ w′
return RationalBSplineManifold(a′,w′,(P1,))
end
# TODO: The performance of this method can be improved.
function (M::RationalBSplineManifold{Dim,Deg})(t::Union{Real, Colon}...) where {Dim, Deg}
P = bsplinespaces(M)
a = controlpoints(M)
w = weights(M)
t_real = _remove_colon(t...)
P_real = _remove_colon(_get_on_real.(P, t)...)
P_colon = _remove_colon(_get_on_colon.(P, t)...)
j_real = intervalindex.(P_real, t_real)
B = bsplinebasisall.(P_real, j_real, t_real)
Deg_real = _remove_colon(_get_on_real.(Deg, t)...)
ci = CartesianIndices(UnitRange.(0, Deg_real))
next = _replace_noncolon((), j_real, t...)
w′ = view(w, next...) .* *(getindex.(B, 1)...)
a′ = view(a, next...) .* view(w, next...) .* *(getindex.(B, 1)...)
l = length(ci)
for i in view(ci,2:l)
next = _replace_noncolon((), j_real .+ i.I, t...)
b = *(getindex.(B, i.I .+ 1)...)
w′ .+= view(w, next...) .* b
a′ .+= view(a, next...) .* view(w, next...) .* b
end
return RationalBSplineManifold(a′ ./ w′, w′, P_colon)
end
@inline function (M::RationalBSplineManifold{Dim})(::Vararg{Colon, Dim}) where Dim
a = copy(controlpoints(M))
w = copy(weights(M))
Ps = bsplinespaces(M)
return RationalBSplineManifold(a,w,Ps)
end
@inline function (M::RationalBSplineManifold{0})()
a = controlpoints(M)
return a[]
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 17115 | # Refinement
# TODO: Update docstrings
@doc raw"""
Refinement of B-spline manifold with given B-spline spaces.
"""
refinement
function _i_ranges_R(A, P′)
n, n′ = size(A)
i_ranges = fill(1:0, n′)
i = 1
for j in 1:n′
isdegenerate_R(P′, j) && continue
iszero(view(A,:,j)) && continue
while true
if Base.isstored(A,i,j)
i_ranges[j] = i:n
break
end
i = i + 1
end
end
i = n
for j in reverse(1:n′)
isdegenerate_R(P′, j) && continue
iszero(view(A,:,j)) && continue
while true
if Base.isstored(A,i,j)
i_ranges[j] = first(i_ranges[j]):i
break
end
i = i - 1
end
end
return i_ranges
end
function _i_ranges_I(A, P′)
n, n′ = size(A)
i_ranges = fill(1:0, n′)
i = 1
for j in 1:n′
isdegenerate_I(P′, j) && continue
while true
if Base.isstored(A,i,j)
i_ranges[j] = i:n
break
end
i = i + 1
end
end
i = n
for j in reverse(1:n′)
isdegenerate_I(P′, j) && continue
while true
if Base.isstored(A,i,j)
i_ranges[j] = first(i_ranges[j]):i
break
end
i = i - 1
end
end
return i_ranges
end
const _i_ranges = _i_ranges_R
function __control_points(value::T, index::Integer, dims::NTuple{Dim, Integer}) where {T, Dim}
a = Array{T,Dim}(undef, dims)
i = prod(index)
for i in 1:(i-1)
@inbounds a[i] = zero(value)
end
@inbounds a[i] = value
return a
end
function _isempty(R::NTuple{1, Vector{UnitRange{Int}}}, J::CartesianIndex{1})
return isempty(R[1][J[1]])
end
function _isempty(R::NTuple{2, Vector{UnitRange{Int}}}, J::CartesianIndex{2})
return isempty(R[1][J[1]]) || isempty(R[2][J[2]])
end
function _isempty(R::NTuple{3, Vector{UnitRange{Int}}}, J::CartesianIndex{3})
return isempty(R[1][J[1]]) || isempty(R[2][J[2]]) || isempty(R[3][J[3]])
end
function _isempty(R::NTuple{Dim, Vector{UnitRange{Int}}}, J::CartesianIndex{Dim}) where Dim
return isempty(R[1][J[1]]) || _isempty(R[2:end], CartesianIndex(J.I[2:end]))
end
function refinement_R(M::BSplineManifold{Dim, Deg, C, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where p′}) where {Dim, Deg, C, T, T′}
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
A::NTuple{Dim, SparseMatrixCSC{U, Int32}} = changebasis_R.(bsplinespaces(M), P′)
R::NTuple{Dim, Vector{UnitRange{Int64}}} = _i_ranges_R.(A, P′)
a::Array{C, Dim} = controlpoints(M)
J::CartesianIndex{Dim} = CartesianIndex(findfirst.(!isempty, R))
D::CartesianIndices{Dim, NTuple{Dim, UnitRange{Int64}}} = CartesianIndices(getindex.(R, J.I))
value = sum(*(getindex.(A, I.I, J.I)...) * a[I] for I in D)
j = prod(J.I)
a′ = __control_points(value, j, dim.(P′))
for J in view(CartesianIndices(UnitRange.(1, dim.(P′))), (j+1):prod(dim.(P′)))
if _isempty(R, J)
@inbounds a′[J] = zero(value)
else
D = CartesianIndices(getindex.(R, J.I))
@inbounds a′[J] = sum(*(getindex.(A, I.I, J.I)...) * a[I] for I in D)
end
end
return BSplineManifold(a′, P′)
end
function refinement_I(M::BSplineManifold{Dim, Deg, C, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where p′}) where {Dim, Deg, C, T, T′}
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
A::NTuple{Dim, SparseMatrixCSC{U, Int32}} = changebasis_I.(bsplinespaces(M), P′)
R::NTuple{Dim, Vector{UnitRange{Int64}}} = _i_ranges_I.(A, P′)
a::Array{C, Dim} = controlpoints(M)
J::CartesianIndex{Dim} = CartesianIndex(findfirst.(!isempty, R))
D::CartesianIndices{Dim, NTuple{Dim, UnitRange{Int64}}} = CartesianIndices(getindex.(R, J.I))
value = sum(*(getindex.(A, I.I, J.I)...) * a[I] for I in D)
j = prod(J.I)
a′ = __control_points(value, j, dim.(P′))
for J in view(CartesianIndices(UnitRange.(1, dim.(P′))), (j+1):prod(dim.(P′)))
if _isempty(R, J)
@inbounds a′[J] = zero(value)
else
D = CartesianIndices(getindex.(R, J.I))
@inbounds a′[J] = sum(*(getindex.(A, I.I, J.I)...) * a[I] for I in D)
end
end
return BSplineManifold(a′, P′)
end
function refinement(M::BSplineManifold{Dim, Deg, C, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where p′}) where {Dim, Deg, C, T, T′}
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
A::NTuple{Dim, SparseMatrixCSC{U, Int32}} = changebasis.(bsplinespaces(M), P′)
R::NTuple{Dim, Vector{UnitRange{Int64}}} = _i_ranges.(A, P′)
a::Array{C, Dim} = controlpoints(M)
J::CartesianIndex{Dim} = CartesianIndex(findfirst.(!isempty, R))
D::CartesianIndices{Dim, NTuple{Dim, UnitRange{Int64}}} = CartesianIndices(getindex.(R, J.I))
value = sum(*(getindex.(A, I.I, J.I)...) * a[I] for I in D)
j = prod(J.I)
a′ = __control_points(value, j, dim.(P′))
for J in view(CartesianIndices(UnitRange.(1, dim.(P′))), (j+1):prod(dim.(P′)))
if _isempty(R, J)
@inbounds a′[J] = zero(value)
else
D = CartesianIndices(getindex.(R, J.I))
@inbounds a′[J] = sum(*(getindex.(A, I.I, J.I)...) * a[I] for I in D)
end
end
return BSplineManifold(a′, P′)
end
function refinement_R(M::RationalBSplineManifold{Dim, Deg, C, W, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where p′}) where {Dim, Deg, C, W, T, T′}
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
A::NTuple{Dim, SparseMatrixCSC{U, Int32}} = changebasis_R.(bsplinespaces(M), P′)
R::NTuple{Dim, Vector{UnitRange{Int64}}} = _i_ranges_R.(A, P′)
a::Array{C, Dim} = controlpoints(M)
w::Array{W, Dim} = weights(M)
J::CartesianIndex{Dim} = CartesianIndex(findfirst.(!isempty, R))
D::CartesianIndices{Dim, NTuple{Dim, UnitRange{Int64}}} = CartesianIndices(getindex.(R, J.I))
value_w = sum(*(getindex.(A, I.I, J.I)...) * w[I] for I in D)
value_a = sum(*(getindex.(A, I.I, J.I)...) * w[I] * a[I] for I in D)
j = prod(J.I)
w′ = __control_points(value_w, j, dim.(P′))
a′ = __control_points(value_a, j, dim.(P′))
for J in view(CartesianIndices(UnitRange.(1, dim.(P′))), (j+1):prod(dim.(P′)))
if _isempty(R, J)
@inbounds w′[J] = zero(value_w)
@inbounds a′[J] = zero(value_a)
else
D = CartesianIndices(getindex.(R, J.I))
@inbounds w′[J] = sum(*(getindex.(A, I.I, J.I)...) * w[I] for I in D)
@inbounds a′[J] = sum(*(getindex.(A, I.I, J.I)...) * w[I] * a[I] for I in D)
end
end
nans = .!(iszero.(a′) .& iszero.(w′))
a′ ./= w′
a′ .*= nans
return RationalBSplineManifold(a′, w′, P′)
end
function refinement_I(M::RationalBSplineManifold{Dim, Deg, C, W, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where p′}) where {Dim, Deg, C, W, T, T′}
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
A::NTuple{Dim, SparseMatrixCSC{U, Int32}} = changebasis_I.(bsplinespaces(M), P′)
R::NTuple{Dim, Vector{UnitRange{Int64}}} = _i_ranges_I.(A, P′)
a::Array{C, Dim} = controlpoints(M)
w::Array{W, Dim} = weights(M)
J::CartesianIndex{Dim} = CartesianIndex(findfirst.(!isempty, R))
D::CartesianIndices{Dim, NTuple{Dim, UnitRange{Int64}}} = CartesianIndices(getindex.(R, J.I))
value_w = sum(*(getindex.(A, I.I, J.I)...) * w[I] for I in D)
value_a = sum(*(getindex.(A, I.I, J.I)...) * w[I] * a[I] for I in D)
j = prod(J.I)
w′ = __control_points(value_w, j, dim.(P′))
a′ = __control_points(value_a, j, dim.(P′))
for J in view(CartesianIndices(UnitRange.(1, dim.(P′))), (j+1):prod(dim.(P′)))
if _isempty(R, J)
@inbounds w′[J] = zero(value_w)
@inbounds a′[J] = zero(value_a)
else
D = CartesianIndices(getindex.(R, J.I))
@inbounds w′[J] = sum(*(getindex.(A, I.I, J.I)...) * w[I] for I in D)
@inbounds a′[J] = sum(*(getindex.(A, I.I, J.I)...) * w[I] * a[I] for I in D)
end
end
nans = .!(iszero.(a′) .& iszero.(w′))
a′ ./= w′
a′ .*= nans
return RationalBSplineManifold(a′, w′, P′)
end
function refinement(M::RationalBSplineManifold{Dim, Deg, C, W, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where p′}) where {Dim, Deg, C, W, T, T′}
U = StaticArrays.arithmetic_closure(promote_type(T,T′))
A::NTuple{Dim, SparseMatrixCSC{U, Int32}} = changebasis.(bsplinespaces(M), P′)
R::NTuple{Dim, Vector{UnitRange{Int64}}} = _i_ranges.(A, P′)
a::Array{C, Dim} = controlpoints(M)
w::Array{W, Dim} = weights(M)
J::CartesianIndex{Dim} = CartesianIndex(findfirst.(!isempty, R))
D::CartesianIndices{Dim, NTuple{Dim, UnitRange{Int64}}} = CartesianIndices(getindex.(R, J.I))
value_w = sum(*(getindex.(A, I.I, J.I)...) * w[I] for I in D)
value_a = sum(*(getindex.(A, I.I, J.I)...) * w[I] * a[I] for I in D)
j = prod(J.I)
w′ = __control_points(value_w, j, dim.(P′))
a′ = __control_points(value_a, j, dim.(P′))
for J in view(CartesianIndices(UnitRange.(1, dim.(P′))), (j+1):prod(dim.(P′)))
if _isempty(R, J)
@inbounds w′[J] = zero(value_w)
@inbounds a′[J] = zero(value_a)
else
D = CartesianIndices(getindex.(R, J.I))
@inbounds w′[J] = sum(*(getindex.(A, I.I, J.I)...) * w[I] for I in D)
@inbounds a′[J] = sum(*(getindex.(A, I.I, J.I)...) * w[I] * a[I] for I in D)
end
end
nans = .!(iszero.(a′) .& iszero.(w′))
a′ ./= w′
a′ .*= nans
return RationalBSplineManifold(a′, w′, P′)
end
function refinement_R(M::BSplineManifold{Dim, Deg, C, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where {p′, T′}}) where {Dim, Deg, C, T}
_P′ = _promote_knottype(P′)
return refinement_R(M, _P′)
end
function refinement_R(M::BSplineManifold{Dim}, P′::Vararg{BSplineSpace, Dim}) where Dim
return refinement_R(M, P′)
end
function refinement_R(M::RationalBSplineManifold{Dim, Deg, C, W, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where {p′, T′}}) where {Dim, Deg, C, W, T}
_P′ = _promote_knottype(P′)
return refinement_R(M, _P′)
end
function refinement_R(M::RationalBSplineManifold{Dim}, P′::Vararg{BSplineSpace, Dim}) where Dim
return refinement_R(M, P′)
end
function refinement_I(M::BSplineManifold{Dim, Deg, C, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where {p′, T′}}) where {Dim, Deg, C, T}
_P′ = _promote_knottype(P′)
return refinement_I(M, _P′)
end
function refinement_I(M::BSplineManifold{Dim}, P′::Vararg{BSplineSpace, Dim}) where Dim
return refinement_I(M, P′)
end
function refinement_I(M::RationalBSplineManifold{Dim, Deg, C, W, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where {p′, T′}}) where {Dim, Deg, C, W, T}
_P′ = _promote_knottype(P′)
return refinement_I(M, _P′)
end
function refinement_I(M::RationalBSplineManifold{Dim}, P′::Vararg{BSplineSpace, Dim}) where Dim
return refinement_I(M, P′)
end
function refinement(M::BSplineManifold{Dim, Deg, C, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where {p′, T′}}) where {Dim, Deg, C, T}
_P′ = _promote_knottype(P′)
return refinement(M, _P′)
end
function refinement(M::BSplineManifold{Dim}, P′::Vararg{BSplineSpace, Dim}) where Dim
return refinement(M, P′)
end
function refinement(M::RationalBSplineManifold{Dim, Deg, C, W, T}, P′::NTuple{Dim, BSplineSpace{p′,T′} where {p′, T′}}) where {Dim, Deg, C, W, T}
_P′ = _promote_knottype(P′)
return refinement(M, _P′)
end
function refinement(M::RationalBSplineManifold{Dim}, P′::Vararg{BSplineSpace, Dim}) where Dim
return refinement(M, P′)
end
@doc raw"""
Refinement of B-spline manifold with additional degree and knotvector.
"""
@generated function refinement_R(M::AbstractManifold{Dim},
p₊::NTuple{Dim, Val},
k₊::NTuple{Dim, AbstractKnotVector}=ntuple(i->EmptyKnotVector(), Val(Dim))) where Dim
Ps = [Symbol(:P,i) for i in 1:Dim]
Ps′ = [Symbol(:P,i,"′") for i in 1:Dim]
ks = [Symbol(:k,i,:₊) for i in 1:Dim]
ps = [Symbol(:p,i,:₊) for i in 1:Dim]
exP = Expr(:tuple, Ps...)
exP′ = Expr(:tuple, Ps′...)
exk = Expr(:tuple, ks...)
exp = Expr(:tuple, ps...)
exs = [:($(Symbol(:P,i,"′")) = expandspace_R($(Symbol(:P,i)), $(Symbol(:p,i,:₊)), $(Symbol(:k,i,:₊)))) for i in 1:Dim]
Expr(
:block,
:($exP = bsplinespaces(M)),
:($exp = p₊),
:($exk = k₊),
exs...,
:(return refinement_R(M, $(exP′)))
)
end
@generated function refinement_R(M::AbstractManifold{Dim},
k₊::NTuple{Dim, AbstractKnotVector}=ntuple(i->EmptyKnotVector(), Val(Dim))) where Dim
Ps = [Symbol(:P,i) for i in 1:Dim]
Ps′ = [Symbol(:P,i,"′") for i in 1:Dim]
ks = [Symbol(:k,i,:₊) for i in 1:Dim]
exP = Expr(:tuple, Ps...)
exP′ = Expr(:tuple, Ps′...)
exk = Expr(:tuple, ks...)
exs = [:($(Symbol(:P,i,"′")) = expandspace_R($(Symbol(:P,i)), $(Symbol(:k,i,:₊)))) for i in 1:Dim]
Expr(
:block,
:($exP = bsplinespaces(M)),
:($exk = k₊),
exs...,
:(return refinement_R(M, $(exP′)))
)
end
@doc raw"""
Refinement of B-spline manifold with additional degree and knotvector.
"""
@generated function refinement_I(M::AbstractManifold{Dim},
p₊::NTuple{Dim, Val},
k₊::NTuple{Dim, AbstractKnotVector}=ntuple(i->EmptyKnotVector(), Val(Dim))) where Dim
Ps = [Symbol(:P,i) for i in 1:Dim]
Ps′ = [Symbol(:P,i,"′") for i in 1:Dim]
ks = [Symbol(:k,i,:₊) for i in 1:Dim]
ps = [Symbol(:p,i,:₊) for i in 1:Dim]
exP = Expr(:tuple, Ps...)
exP′ = Expr(:tuple, Ps′...)
exk = Expr(:tuple, ks...)
exp = Expr(:tuple, ps...)
exs = [:($(Symbol(:P,i,"′")) = expandspace_I($(Symbol(:P,i)), $(Symbol(:p,i,:₊)), $(Symbol(:k,i,:₊)))) for i in 1:Dim]
Expr(
:block,
:($exP = bsplinespaces(M)),
:($exp = p₊),
:($exk = k₊),
exs...,
:(return refinement_I(M, $(exP′)))
)
end
@generated function refinement_I(M::AbstractManifold{Dim},
k₊::NTuple{Dim, AbstractKnotVector}=ntuple(i->EmptyKnotVector(), Val(Dim))) where Dim
Ps = [Symbol(:P,i) for i in 1:Dim]
Ps′ = [Symbol(:P,i,"′") for i in 1:Dim]
ks = [Symbol(:k,i,:₊) for i in 1:Dim]
exP = Expr(:tuple, Ps...)
exP′ = Expr(:tuple, Ps′...)
exk = Expr(:tuple, ks...)
exs = [:($(Symbol(:P,i,"′")) = expandspace_I($(Symbol(:P,i)), $(Symbol(:k,i,:₊)))) for i in 1:Dim]
Expr(
:block,
:($exP = bsplinespaces(M)),
:($exk = k₊),
exs...,
:(return refinement_I(M, $(exP′)))
)
end
@doc raw"""
Refinement of B-spline manifold with additional degree and knotvector.
"""
@generated function refinement(M::AbstractManifold{Dim},
p₊::NTuple{Dim, Val},
k₊::NTuple{Dim, AbstractKnotVector}=ntuple(i->EmptyKnotVector(), Val(Dim))) where Dim
Ps = [Symbol(:P,i) for i in 1:Dim]
Ps′ = [Symbol(:P,i,"′") for i in 1:Dim]
ks = [Symbol(:k,i,:₊) for i in 1:Dim]
ps = [Symbol(:p,i,:₊) for i in 1:Dim]
exP = Expr(:tuple, Ps...)
exP′ = Expr(:tuple, Ps′...)
exk = Expr(:tuple, ks...)
exp = Expr(:tuple, ps...)
exs = [:($(Symbol(:P,i,"′")) = expandspace($(Symbol(:P,i)), $(Symbol(:p,i,:₊)), $(Symbol(:k,i,:₊)))) for i in 1:Dim]
Expr(
:block,
:($exP = bsplinespaces(M)),
:($exp = p₊),
:($exk = k₊),
exs...,
:(return refinement(M, $(exP′)))
)
end
@generated function refinement(M::AbstractManifold{Dim},
k₊::NTuple{Dim, AbstractKnotVector}=ntuple(i->EmptyKnotVector(), Val(Dim))) where Dim
Ps = [Symbol(:P,i) for i in 1:Dim]
Ps′ = [Symbol(:P,i,"′") for i in 1:Dim]
ks = [Symbol(:k,i,:₊) for i in 1:Dim]
exP = Expr(:tuple, Ps...)
exP′ = Expr(:tuple, Ps′...)
exk = Expr(:tuple, ks...)
exs = [:($(Symbol(:P,i,"′")) = expandspace($(Symbol(:P,i)), $(Symbol(:k,i,:₊)))) for i in 1:Dim]
Expr(
:block,
:($exP = bsplinespaces(M)),
:($exk = k₊),
exs...,
:(return refinement(M, $(exP′)))
)
end
# resolve ambiguities
refinement_R(M::AbstractManifold{0}, ::Tuple{}) = M
refinement_R(M::BSplineManifold{0, Deg, C, T, S} where {Deg, C, T, S<:Tuple{}}, ::Tuple{}) = M
refinement_R(M::RationalBSplineManifold{0, Deg, C, W, T, S} where {Deg, C, W, T, S<:Tuple{}}, ::Tuple{}) = M
refinement_I(M::AbstractManifold{0}, ::Tuple{}) = M
refinement_I(M::BSplineManifold{0, Deg, C, T, S} where {Deg, C, T, S<:Tuple{}}, ::Tuple{}) = M
refinement_I(M::RationalBSplineManifold{0, Deg, C, W, T, S} where {Deg, C, W, T, S<:Tuple{}}, ::Tuple{}) = M
refinement(M::AbstractManifold{0}, ::Tuple{}) = M
refinement(M::BSplineManifold{0, Deg, C, T, S} where {Deg, C, T, S<:Tuple{}}, ::Tuple{}) = M
refinement(M::RationalBSplineManifold{0, Deg, C, W, T, S} where {Deg, C, W, T, S<:Tuple{}}, ::Tuple{}) = M
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 357 | @setup_workload begin
k1 = KnotVector(1:8)
k2 = UniformKnotVector(1:8)
P1 = BSplineSpace{3}(k1)
P2 = BSplineSpace{3}(k2)
@compile_workload begin
changebasis_I(P1, P1)
changebasis_R(P1, P1)
changebasis_I(P1, P2)
changebasis_R(P1, P2)
changebasis_I(P2, P2)
changebasis_R(P2, P2)
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 1918 | # Division, devided by zero will be zero
@inline function _d(a::T,b::T) where T
U=StaticArrays.arithmetic_closure(T)
iszero(b) && return zero(U)
return U(a/b)
end
@inline _d(a,b) = _d(promote(a,b)...)
@doc raw"""
Calculate ``r``-nomial coefficient
r_nomial(n, k, r)
**This function is considered as internal.**
```math
(1+x+\cdots+x^r)^n = \sum_{k} a_{n,k,r} x^k
```
"""
function r_nomial(n::T,k::T,r::T) where T<:Integer
# n must be non-negative
# r must be larger or equal to one
if r == 1
return T(iszero(k))
elseif r == 2
return binomial(n,k)
elseif k < 0
return zero(T)
elseif k == 0
return one(T)
elseif k == 1
return n
elseif k == 2
return n*(n+1)÷2
elseif (r-1)*n < 2k
return r_nomial(n,(r-one(T))*n-k,r)
elseif n == 1
return one(T)
elseif n == 2
return k+one(T)
else
m = r_nomial(n-one(T),k,r)
for i in 1:r-1
m += r_nomial(n-one(T),k-i,r)
end
return m
end
end
@inline _remove_colon(::Colon) = ()
@inline _remove_colon(x::Any) = (x,)
@inline _remove_colon(x::Any, rest...) = (x, _remove_colon(rest...)...)
@inline _remove_colon(::Colon, rest...) = _remove_colon(rest...)
@inline _replace_noncolon(new::Tuple, vals::Tuple, ::Colon, sample...) = _replace_noncolon((new...,:),vals,sample...)
@inline _replace_noncolon(new::Tuple, vals::Tuple, ::Any, sample...) = _replace_noncolon((new...,vals[1]),vals[2:end],sample...)
@inline _replace_noncolon(new::Tuple, vals::Tuple{}, ::Colon) = (new...,:)
@inline _replace_noncolon(new::Tuple, vals::Tuple{Any}, ::Any) = (new...,vals[1])
@inline _replace_noncolon(new::Tuple, vals::Tuple{Any}, ::Colon) = error("invalid inputs")
@inline _get_on_real(x,::Real) = x
@inline _get_on_real(::Any,::Colon) = (:)
@inline _get_on_colon(x,::Colon) = x
@inline _get_on_colon(::Any,::Real) = (:)
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 950 | using BasicBSpline
using ChainRulesTestUtils
using ChainRulesCore
using IntervalSets
using LinearAlgebra
using SparseArrays
using Test
using Random
using StaticArrays
using GeometryBasics
using Plots
using Aqua
if VERSION ≥ v"1.9.0"
# Disable ambiguities tests for ChainRulesCore.frule
# TODO enable unbound_args again
Aqua.test_all(BasicBSpline; ambiguities=false, unbound_args=false)
Aqua.test_ambiguities(BasicBSpline; exclude=[ChainRulesCore.frule])
end
Random.seed!(42)
include("test_util.jl")
include("test_KnotVector.jl")
include("test_BSplineSpace.jl")
include("test_BSplineBasis.jl")
include("test_UniformKnotVector.jl")
include("test_UniformBSplineSpace.jl")
include("test_UniformBSplineBasis.jl")
include("test_Derivative.jl")
include("test_ChangeBasis.jl")
include("test_BSplineManifold.jl")
include("test_RationalBSplineManifold.jl")
include("test_Refinement.jl")
include("test_ChainRules.jl")
include("test_Plots.jl")
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 5078 | function ≒(a,b)
if a ≈ b
return true
elseif abs(a-b) < 1e-10
return true
else
return false
end
end
@testset "BSplineBasis" begin
Δt = 1.0e-8
ε = 1.0e-8
@testset "$(p)-th degree basis" for p in 0:4
v = rand(10)
k = KnotVector(v) + (p+1)*KnotVector([0, 1]) + KnotVector(v[2:3])
P = BSplineSpace{p}(k)
n = dim(P)
@test degree(P) == p
# Check the values of B-spline basis funcitons
for i in 1:n, t in rand(5)
for t in rand(5)
@test (bsplinebasis₊₀(P, i, t)
≈ bsplinebasis₋₀(P, i, t)
≈ bsplinebasis(P, i, t))
end
for t in k
t₊₀ = nextfloat(t)
t₋₀ = prevfloat(t)
@test bsplinebasis₊₀(P, i, t) ≒ bsplinebasis₊₀(P, i, t₊₀)
@test bsplinebasis₋₀(P, i, t) ≒ bsplinebasis₋₀(P, i, t₋₀)
end
end
# Check the values of the derivative of B-spline basis funcitons
for t in k
s = sum([bsplinebasis(P, i, t) for i in 1:n])
s₊₀ = sum([bsplinebasis₊₀(P, i, t) for i in 1:n])
s₋₀ = sum([bsplinebasis₋₀(P, i, t) for i in 1:n])
if t == k[1]
@test s ≈ 1
@test s₊₀ ≈ 1
@test s₋₀ == 0
elseif t == k[end]
@test s ≈ 1
@test s₊₀ == 0
@test s₋₀ ≈ 1
else
@test s ≈ 1
@test s₊₀ ≈ 1
@test s₋₀ ≈ 1
end
end
end
@testset "bsplinebasisall" begin
k = KnotVector(rand(10).-1) + KnotVector(rand(10)) + KnotVector(rand(10).+1)
ts = rand(10)
for p in 0:5
P = BSplineSpace{p}(k)
for t in ts
j = intervalindex(P,t)
B = collect(bsplinebasisall(P,j,t))
_B = bsplinebasis.(P,j:j+p,t)
@test _B ≈ B
_B = bsplinebasis₊₀.(P,j:j+p,t)
@test _B ≈ B
_B = bsplinebasis₋₀.(P,j:j+p,t)
@test _B ≈ B
end
end
end
@testset "Rational" begin
k = KnotVector{Int}(1:12)
P = BSplineSpace{3}(k)
@test k isa KnotVector{Int}
@test P isa BSplineSpace{3,Int}
bsplinebasis(P,1,11//5) isa Rational{Int}
bsplinebasis₊₀(P,1,11//5) isa Rational{Int}
bsplinebasis₋₀(P,1,11//5) isa Rational{Int}
@test bsplinebasis(P,1,11//5) ===
bsplinebasis₊₀(P,1,11//5) ===
bsplinebasis₋₀(P,1,11//5) === 106//375
end
@testset "Check type" begin
k = KnotVector{Int}(1:12)
P0 = BSplineSpace{0}(k)
P1 = BSplineSpace{1}(k)
P2 = BSplineSpace{2}(k)
@test bsplinebasis(P0,1,5) isa Float64
@test bsplinebasis(P1,1,5) isa Float64
@test bsplinebasis(P2,1,5) isa Float64
@test bsplinebasis₊₀(P0,1,5) isa Float64
@test bsplinebasis₊₀(P1,1,5) isa Float64
@test bsplinebasis₊₀(P2,1,5) isa Float64
@test bsplinebasis₋₀(P0,1,5) isa Float64
@test bsplinebasis₋₀(P1,1,5) isa Float64
@test bsplinebasis₋₀(P2,1,5) isa Float64
@test bsplinebasisall(P0,1,5) isa SVector{1,Float64}
@test bsplinebasisall(P1,1,5) isa SVector{2,Float64}
@test bsplinebasisall(P2,1,5) isa SVector{3,Float64}
end
@testset "Endpoints" begin
p = 2
k = KnotVector(1:2) + (p+1)*KnotVector([0,3])
P0 = BSplineSpace{0}(k)
P1 = BSplineSpace{1}(k)
P2 = BSplineSpace{2}(k)
@test isdegenerate(P0)
@test isdegenerate(P1)
@test isnondegenerate(P2)
n0 = dim(P0)
n1 = dim(P1)
n2 = dim(P2)
@test bsplinebasis.(P0,1:n0,0) == bsplinebasis₊₀.(P0,1:n0,0) == [0,0,1,0,0,0,0]
@test bsplinebasis.(P1,1:n1,0) == bsplinebasis₊₀.(P1,1:n1,0) == [0,1,0,0,0,0]
@test bsplinebasis.(P2,1:n2,0) == bsplinebasis₊₀.(P2,1:n2,0) == [1,0,0,0,0]
@test bsplinebasis.(P0,1:n0,3) == bsplinebasis₋₀.(P0,1:n0,3) == [0,0,0,0,1,0,0]
@test bsplinebasis.(P1,1:n1,3) == bsplinebasis₋₀.(P1,1:n1,3) == [0,0,0,0,1,0]
@test bsplinebasis.(P2,1:n2,3) == bsplinebasis₋₀.(P2,1:n2,3) == [0,0,0,0,1]
@test bsplinebasis₋₀.(P0,1:n0,0) == [0,0,0,0,0,0,0]
@test bsplinebasis₋₀.(P1,1:n1,0) == [0,0,0,0,0,0]
@test bsplinebasis₋₀.(P2,1:n2,0) == [0,0,0,0,0]
@test bsplinebasis₊₀.(P0,1:n0,3) == [0,0,0,0,0,0,0]
@test bsplinebasis₊₀.(P1,1:n1,3) == [0,0,0,0,0,0]
@test bsplinebasis₊₀.(P2,1:n2,3) == [0,0,0,0,0]
end
@testset "kernel" begin
for p in 0:4
P = BSplineSpace{p}(UniformKnotVector(0:10))
t = rand()
v1 = BasicBSpline.uniform_bsplinebasisall_kernel(Val(p), t)
v2 = BasicBSpline.uniform_bsplinebasis_kernel.(Val(p), t .+ (p:-1:0))
v3 = bsplinebasisall.(P, 1, t+p)
@test v1 ≈ v2 ≈ v3
end
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 7575 | @testset "BSplineManifold" begin
function arrayofvector2array(a::AbstractArray{<:AbstractVector{T},d})::Array{T,d+1} where {d, T<:Real}
d̂ = length(a[1])
s = size(a)
N = prod(s)
a_2dim = [a[i][j] for i in 1:N, j in 1:d̂]
a′ = reshape(a_2dim, s..., d̂)
return a′
end
function array2arrayofvector(a::AbstractArray{T,d})::Array{Vector{T},d-1} where {d, T<:Real}
s = size(a)
d̂ = s[end]
N = s[1:end-1]
a_flat = reshape(a,prod(N),d̂)
a_vec = [a_flat[i,:] for i in 1:prod(N)]
a′ = reshape(a_vec,N)
return a′
end
@testset "constructor" begin
k1 = KnotVector(Float64[0,0,1,1])
k2 = UniformKnotVector(1.0:8.0)
k3 = KnotVector(rand(8))
_k1 = KnotVector([0.0, 0.0, 1.0, 1.0])
_k2 = KnotVector(1.0:8.0)
_k3 = view(k3,:)
P1 = BSplineSpace{1}(k1)
P2 = BSplineSpace{3}(k2)
P3 = BSplineSpace{2}(k3)
_P1 = BSplineSpace{1}(_k1)
_P2 = BSplineSpace{3}(_k2)
_P3 = BSplineSpace{2}(_k3)
# 0-dim
a = fill(1.2)
M = BSplineManifold{0,(),Float64,Int,Tuple{}}(a, ())
N = BSplineManifold{0,(),Float64,Int,Tuple{}}(copy(a), ())
@test M == M
@test M == N
@test hash(M) == hash(M)
@test hash(M) == hash(N)
@test M() == 1.2
# 4-dim
a = rand(dim(P1), dim(P2), dim(P3), dim(P3))
@test BSplineManifold(a, P1, P2, P3, P3) == BSplineManifold(a, P1, P2, P3, P3)
@test hash(BSplineManifold(a, P1, P2, P3, P3)) == hash(BSplineManifold(a, P1, P2, P3, P3))
@test BSplineManifold(a, P1, P2, P3, P3) == BSplineManifold(a, _P1, _P2, _P3, _P3)
@test hash(BSplineManifold(a, P1, P2, P3, P3)) == hash(BSplineManifold(a, _P1, _P2, _P3, _P3))
@test BSplineManifold(a, P1, P2, P3, P3) == BSplineManifold(copy(a), _P1, _P2, _P3, _P3)
@test hash(BSplineManifold(a, P1, P2, P3, P3)) == hash(BSplineManifold(copy(a), _P1, _P2, _P3, _P3))
end
@testset "1dim" begin
@testset "BSplineManifold-1dim" begin
P1 = BSplineSpace{1}(KnotVector([0, 0, 1, 1]))
n1 = dim(P1) # 2
a = [Point(i, rand()) for i in 1:n1] # n1 × n2 array of d̂-dim vector.
M = BSplineManifold(a, (P1,))
@test dim(M) == 1
P1′ = BSplineSpace{2}(KnotVector([-2, 0, 0, 1, 1, 2]))
p₊ = (Val(1),)
k₊ = (KnotVector(Float64[]),)
@test P1 ⊑ P1′
M′ = refinement(M, P1′)
M′′ = refinement(M, p₊, k₊)
ts = [[rand()] for _ in 1:10]
for t in ts
@test M(t...) ≈ M′(t...)
@test M(t...) ≈ M′′(t...)
end
@test_throws DomainError M(-5)
@test map.(M,[0.2,0.5,0.6]) == M.([0.2,0.5,0.6])
@test M(:) == M
@test Base.mightalias(controlpoints(M), controlpoints(M))
@test !Base.mightalias(controlpoints(M), controlpoints(M(:)))
end
end
@testset "2dim" begin
@testset "BSplineManifold-2dim" begin
P1 = BSplineSpace{1}(KnotVector([0, 0, 1, 1]))
P2 = BSplineSpace{1}(KnotVector([1, 1, 2, 3, 3]))
n1 = dim(P1) # 2
n2 = dim(P2) # 3
a = [Point(i, j) for i in 1:n1, j in 1:n2] # n1 × n2 array of d̂-dim vector.
M = BSplineManifold(a, (P1, P2))
@test dim(M) == 2
P1′ = BSplineSpace{2}(KnotVector([0, 0, 0, 1, 1, 1]))
P2′ = BSplineSpace{1}(KnotVector([1, 1, 2, 1.45, 3, 3]))
p₊ = (Val(1), Val(0))
k₊ = (KnotVector(Float64[]), KnotVector([1.45]))
@test P1 ⊆ P1′
@test P2 ⊆ P2′
M′ = refinement(M, (P1′, P2′))
M′′ = refinement(M, p₊, k₊)
ts = [[rand(), 1 + 2 * rand()] for _ in 1:10]
for t in ts
t1, t2 = t
@test M(t1,t2) ≈ M′(t1,t2)
@test M(t1,t2) ≈ M′′(t1,t2)
@test M(t1,t2) ≈ M(t1,:)(t2)
@test M(t1,t2) ≈ M(:,t2)(t1)
end
@test_throws DomainError M(-5,-8)
@test M(:,:) == M
@test Base.mightalias(controlpoints(M), controlpoints(M))
@test !Base.mightalias(controlpoints(M), controlpoints(M(:,:)))
end
end
@testset "3dim" begin
@testset "BSplineManifold-3dim" begin
P1 = BSplineSpace{1}(KnotVector([0, 0, 1, 1]))
P2 = BSplineSpace{1}(KnotVector([1, 1, 2, 3, 3]))
P3 = BSplineSpace{2}(KnotVector(rand(16)))
n1 = dim(P1) # 2
n2 = dim(P2) # 3
n3 = dim(P3)
a = [Point(i1, i2, 3) for i1 in 1:n1, i2 in 1:n2, i3 in 1:n3]
M = BSplineManifold(a, (P1, P2, P3))
@test dim(M) == 3
p₊ = (Val(1), Val(0), Val(1))
k₊ = (KnotVector(Float64[]), KnotVector([1.45]), EmptyKnotVector())
M′′ = refinement(M, p₊, k₊)
ts = [[rand(), 1 + 2 * rand(), 0.5] for _ in 1:10]
for t in ts
t1, t2, t3 = t
@test M(t1,t2,t3) ≈ M′′(t1,t2,t3)
@test M(t1,t2,t3) ≈ M(t1,:,:)(t2,t3)
@test M(t1,t2,t3) ≈ M(:,t2,:)(t1,t3)
@test M(t1,t2,t3) ≈ M(:,:,t3)(t1,t2)
@test M(t1,t2,t3) ≈ M(t1,t2,:)(t3)
@test M(t1,t2,t3) ≈ M(t1,:,t3)(t2)
@test M(t1,t2,t3) ≈ M(:,t2,t3)(t1)
end
@test_throws DomainError M(-5,-8,-120)
@test M(:,:,:) == M
@test Base.mightalias(controlpoints(M), controlpoints(M))
@test !Base.mightalias(controlpoints(M), controlpoints(M(:,:,:)))
end
end
@testset "4dim" begin
@testset "BSplineManifold-4dim" begin
P1 = BSplineSpace{3}(knotvector"43211112112112")
P2 = BSplineSpace{4}(knotvector"3211 1 112112115")
P3 = BSplineSpace{5}(knotvector" 411 1 112112 11133")
P4 = BSplineSpace{4}(knotvector"4 1112113 11 13 3")
n1 = dim(P1)
n2 = dim(P2)
n3 = dim(P3)
n4 = dim(P4)
a = rand(n1, n2, n3, n4)
M = BSplineManifold(a, (P1, P2, P3, P4))
@test dim(M) == 4
ts = [(rand.(domain.((P1, P2, P3, P4)))) for _ in 1:10]
for (t1, t2, t3, t4) in ts
@test M(t1,t2,t3,t4) ≈ M(t1,:,:,:)( t2,t3,t4)
@test M(t1,t2,t3,t4) ≈ M(:,t2,:,:)(t1, t3,t4)
@test M(t1,t2,t3,t4) ≈ M(:,:,t3,:)(t1,t2, t4)
@test M(t1,t2,t3,t4) ≈ M(:,:,:,t4)(t1,t2,t3 )
@test M(t1,t2,t3,t4) ≈ M(t1,t2,:,:)(t3,t4)
@test M(t1,t2,t3,t4) ≈ M(t1,:,t3,:)(t2,t4)
@test M(t1,t2,t3,t4) ≈ M(t1,:,:,t4)(t2,t3)
@test M(t1,t2,t3,t4) ≈ M(:,t2,t3,:)(t1,t4)
@test M(t1,t2,t3,t4) ≈ M(:,t2,:,t4)(t1,t3)
@test M(t1,t2,t3,t4) ≈ M(:,:,t3,t4)(t1,t2)
@test M(t1,t2,t3,t4) ≈ M(:,t2,t3,t4)(t1)
@test M(t1,t2,t3,t4) ≈ M(t1,:,t3,t4)(t2)
@test M(t1,t2,t3,t4) ≈ M(t1,t2,:,t4)(t3)
@test M(t1,t2,t3,t4) ≈ M(t1,t2,t3,:)(t4)
end
@test_throws DomainError M(-5,-8,-120,1)
@test M(:,:,:,:) == M
@test Base.mightalias(controlpoints(M), controlpoints(M))
@test !Base.mightalias(controlpoints(M), controlpoints(M(:,:,:,:)))
end
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 8576 | @testset "BSplineSpace" begin
@testset "constructor" begin
P1 = BSplineSpace{2}(KnotVector(1:8))
P2 = BSplineSpace{2}(P1)
P3 = BSplineSpace{2,Int}(P1)
P4 = BSplineSpace{2,Real}(P1)
P5 = BSplineSpace{2,Float64}(P1)
P6 = BSplineSpace{2,Float64}(KnotVector(1:8))
P7 = BSplineSpace{2,Float64,KnotVector{Float64}}(KnotVector(1:8))
@test P1 == P2 == P3 == P4 == P5 == bsplinespace(P1) == bsplinespace(P2) == bsplinespace(P3) == bsplinespace(P4) == bsplinespace(P5)
@test P5 == P6 == P7
@test typeof(P5) === typeof(P6) === typeof(P7)
@test P1 isa BSplineSpace{2,Int}
@test P2 isa BSplineSpace{2,Int}
@test P3 isa BSplineSpace{2,Int}
@test P4 isa BSplineSpace{2,Real}
@test P5 isa BSplineSpace{2,Float64}
@test P1 === BSplineSpace(P1)
@test_throws MethodError BSplineSpace(KnotVector(1:8))
@test_throws MethodError BSplineSpace{3}(P1)
end
@testset "dimension, dengenerate" begin
P1 = BSplineSpace{2}(KnotVector([1, 3, 5, 6, 8, 9, 9]))
@test bsplinesupport(P1, 2) == 3..8
@test bsplinesupport_R(P1, 2) == 3..8
@test bsplinesupport_I(P1, 2) == 5..8
@test domain(P1) == 5..8
@test dim(P1) == 4
@test exactdim_R(P1) == 4
@test isnondegenerate(P1) == true
@test isdegenerate(P1) == false
P2 = BSplineSpace{1}(KnotVector([1, 3, 3, 3, 8, 9]))
@test isnondegenerate(P2) == false
@test isdegenerate(P2) == true
@test isdegenerate(P2,1) == false
@test isdegenerate(P2,2) == true
@test isdegenerate(P2,3) == false
@test isdegenerate(P2,4) == false
@test isnondegenerate(P2,1) == true
@test isnondegenerate(P2,2) == false
@test isnondegenerate(P2,3) == true
@test isnondegenerate(P2,4) == true
@test dim(P2) == 4
@test exactdim_R(P2) == 3
P3 = BSplineSpace{2}(KnotVector([0,0,0,1,1,1,2]))
@test domain(P3) == 0..1
@test dim(P3) == 4
@test exactdim_R(P3) == 4
@test isnondegenerate(P3) == true
@test isdegenerate(P3) == false
@test isdegenerate(P3,1) == false
@test isdegenerate(P3,2) == false
@test isdegenerate(P3,3) == false
@test isdegenerate(P3,4) == false
@test isnondegenerate(P3,1) == true
@test isnondegenerate(P3,2) == true
@test isnondegenerate(P3,3) == true
@test isnondegenerate(P3,4) == true
@test isnondegenerate_I(P3) == false
@test isdegenerate_I(P3) == true
@test isdegenerate_I(P3,1) == false
@test isdegenerate_I(P3,2) == false
@test isdegenerate_I(P3,3) == false
@test isdegenerate_I(P3,4) == true
@test isnondegenerate_I(P3,1) == true
@test isnondegenerate_I(P3,2) == true
@test isnondegenerate_I(P3,3) == true
@test isnondegenerate_I(P3,4) == false
end
@testset "denegeration with lower degree" begin
k = KnotVector([1, 3, 3, 3, 6, 8, 9])
@test isnondegenerate(BSplineSpace{2}(k))
@test isdegenerate(BSplineSpace{1}(k))
end
@testset "subset" begin
P1 = BSplineSpace{1}(KnotVector([1, 3, 5, 8]))
P2 = BSplineSpace{1}(KnotVector([1, 3, 5, 6, 8, 9]))
P3 = BSplineSpace{2}(KnotVector([1, 1, 3, 3, 5, 5, 8, 8]))
@test P1 ⊆ P1
@test P2 ⊆ P2
@test P3 ⊆ P3
@test P1 ⊆ P2
@test P1 ⋢ P2
@test P1 ⊆ P3
@test P2 ⊈ P3
@test !(P1 ⊊ P1)
@test !(P2 ⊊ P2)
@test !(P3 ⊊ P3)
@test P1 ⊊ P2
@test P1 ⊊ P3
@test !(P1 ⊋ P1)
@test !(P2 ⊋ P2)
@test !(P3 ⊋ P3)
@test P2 ⊋ P1
@test P3 ⊋ P1
end
@testset "sqsubset" begin
P1 = BSplineSpace{3}(KnotVector([2, 2, 2, 3, 3, 4, 4, 4]))
P2 = BSplineSpace{3}(KnotVector([1, 3, 3, 3, 4]))
P3 = BSplineSpace{2}(knotvector"3 3")
P4 = BSplineSpace{3}(knotvector"4 4")
P5 = BSplineSpace{3}(knotvector"414")
@test P1 ⋢ P2
@test P3 ⊑ P4 ⊑ P5
end
@testset "equality" begin
P1 = BSplineSpace{2}(KnotVector([1, 2, 3, 5, 8, 8, 9]))
P2 = BSplineSpace{2}(KnotVector([1, 2, 3, 5, 8, 8, 9]))
P3 = BSplineSpace{1}(KnotVector([1, 2, 3, 5, 8, 8, 9]))
P4 = BSplineSpace{1}(KnotVector([1, 2, 3, 5, 8, 8, 9]))
@test P1 ⊆ P2
@test P2 ⊆ P1
@test P1 == P2
@test hash(P1) == hash(P2)
@test P3 ⊆ P4
@test P4 ⊆ P3
@test P3 == P4
@test hash(P3) == hash(P4)
@test P1 != P3
@test hash(P1) != hash(P3)
end
@testset "expandspace" begin
P1 = BSplineSpace{1}(KnotVector([0,0,0,0,0]))
P2 = BSplineSpace{3}(KnotVector(1:8))
P3 = BSplineSpace{2}(KnotVector(1:8)+3*KnotVector([0]))
P4 = BSplineSpace{2}(KnotVector([0,0,0,1,1,1,2]))
@test P1 == expandspace_R(P1) == expandspace_I(P1) == expandspace(P1)
@test P2 == expandspace_R(P2) == expandspace_I(P2) == expandspace(P2)
@test P3 == expandspace_R(P3) == expandspace_I(P3) == expandspace(P3)
@test P4 == expandspace_R(P4) == expandspace_I(P4) == expandspace(P4)
@test P1 ⊆ @inferred expandspace_R(P1, Val(1))
@test P2 ⊆ @inferred expandspace_R(P2, Val(1))
@test P3 ⊆ @inferred expandspace_R(P3, Val(1))
@test P4 ⊆ @inferred expandspace_R(P4, Val(1))
@test P1 ⊆ expandspace_R(P1, KnotVector([1,2,3]))
@test P2 ⊆ expandspace_R(P2, KnotVector([1,2,3]))
@test P3 ⊆ expandspace_R(P3, KnotVector([1,2,3]))
@test P4 ⊆ expandspace_R(P4, KnotVector([1,2,3]))
@test knotvector(P1) + KnotVector([1,2,3]) ⊆ knotvector(expandspace_R(P1, KnotVector([1,2,3])))
@test knotvector(P2) + KnotVector([1,2,3]) ⊆ knotvector(expandspace_R(P2, KnotVector([1,2,3])))
@test knotvector(P3) + KnotVector([1,2,3]) ⊆ knotvector(expandspace_R(P3, KnotVector([1,2,3])))
@test knotvector(P4) + KnotVector([1,2,3]) ⊆ knotvector(expandspace_R(P4, KnotVector([1,2,3])))
# P1 and P4 is not subset of expandspace_I.
@test P1 ⋢ expandspace_I(P1, Val(1)) == expandspace(P1, Val(1))
@test P2 ⊑ expandspace_I(P2, Val(1)) == expandspace(P2, Val(1))
@test P3 ⊑ expandspace_I(P3, Val(1)) == expandspace(P3, Val(1))
@test P4 ⋢ expandspace_I(P4, Val(1)) == expandspace(P4, Val(1))
# That was because P1 and P4 is not nondegenerate.
@test isdegenerate_I(P1)
@test isdegenerate_I(P4)
# Additional knot vector should be inside the domain
k5 = KnotVector(1:8)
P5 = BSplineSpace{3}(k5)
@test_throws DomainError expandspace_I(P5, KnotVector([9,19]))
@test expandspace_R(P5, KnotVector([9,19])) == expandspace_R(P5, Val(0), KnotVector([9,19]))
end
@testset "sqsubset and lowered B-spline space" begin
P4 = BSplineSpace{1}(KnotVector([1, 2, 3, 4, 5]))
P5 = BSplineSpace{2}(KnotVector([-1, 0.3, 2, 3, 3, 4, 5.2, 6]))
_P4 = BSplineSpace{degree(P4)-1}(knotvector(P4)[2:end-1])
_P5 = BSplineSpace{degree(P5)-1}(knotvector(P5)[2:end-1])
@test P4 ⊑ P4
@test P4 ⊑ P5
@test P5 ⊒ P4
@test P5 ⋢ P4
@test P4 ⋣ P5
@test (P4 ⊑ P4) == (_P4 ⊑ _P4)
@test (P4 ⊑ P5) == (_P4 ⊑ _P5)
@test (P5 ⊑ P4) == (_P5 ⊑ _P4)
end
@testset "subset and sqsubset" begin
P6 = BSplineSpace{2}(knotvector"1111 111")
P7 = BSplineSpace{2}(knotvector"11121111")
@test P6 ⊆ P6
@test P6 ⊆ P7
@test P7 ⊆ P7
@test P6 ⊑ P6
@test P6 ⊑ P7
@test P7 ⊑ P7
@test domain(P6) == domain(P7)
end
@testset "subset but not sqsubset" begin
P6 = BSplineSpace{2}(knotvector"11111111")
P7 = BSplineSpace{2}(knotvector"1111111111")
@test P6 ⊆ P6
@test P7 ⊆ P7
@test P6 ⊆ P7
@test P7 ⊈ P6
@test P6 ⊆ P6
@test P7 ⊆ P7
@test P6 ⊆ P7
@test P7 ⊈ P6
@test domain(P6) ⊆ domain(P7)
end
@testset "sqsubset but not subset" begin
P6 = BSplineSpace{2}(knotvector" 1111111")
P7 = BSplineSpace{2}(knotvector"11 11111")
@test P6 ⊑ P7
@test P7 ⊑ P6
@test P6 ≃ P7
@test P6 ⊈ P7
@test P7 ⊈ P6
@test P6 ⋤ P7
@test P7 ⋤ P6
@test P6 ⋥ P7
@test P7 ⋥ P6
@test domain(P6) == domain(P7)
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 893 | @testset "ChainRules" begin
k = KnotVector(rand(20))
p = 3
P = BSplineSpace{p}(k)
dP0 = BSplineDerivativeSpace{0}(P)
dP1 = BSplineDerivativeSpace{1}(P)
dP2 = BSplineDerivativeSpace{2}(P)
@testset "bsplinebasis" begin
for _P in (P, dP0, dP1, dP2), i in 1:dim(_P)
t = rand(domain(P))
test_frule(bsplinebasis, _P, i, t)
test_rrule(bsplinebasis, _P, i, t)
test_frule(bsplinebasis₊₀, _P, i, t)
test_rrule(bsplinebasis₊₀, _P, i, t)
test_frule(bsplinebasis₋₀, _P, i, t)
test_rrule(bsplinebasis₋₀, _P, i, t)
end
end
@testset "bsplinebasisall" begin
for _P in (P, dP0, dP1, dP2), i in 1:length(k)-2p-1
t = rand(domain(P))
test_frule(bsplinebasisall, _P, i, t)
test_rrule(bsplinebasisall, _P, i, t)
end
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 10800 | @testset "ChangeBasis" begin
ε = 1e-13
function test_changebasis_R(P,P′)
# The test case must hold P ⊆ P′
@test P ⊆ P′
# Test type stability
A = @inferred changebasis_R(P,P′)
# Test output type
@test A isa SparseMatrixCSC
# Zeros must not be stored
@test !any(iszero.(A.nzval))
# Test the size of A
n = dim(P)
n′ = dim(P′)
@test size(A) == (n,n′)
# Elements must not be stored for degenerate row/col
for j in 1:n′
if isdegenerate_R(P′, j)
@test !any(Base.isstored.(Ref(A), 1:n, j))
end
end
for i in 1:n
if isdegenerate_R(P, i)
@test !any(Base.isstored.(Ref(A), i, 1:n′))
end
end
# B_{(i,p,k)} = ∑ⱼ A_{i,j} B_{(j,p′,k′)}
ts = range(extrema(knotvector(P)+knotvector(P′))..., length=20)
for t in ts
@test norm(bsplinebasis.(P,1:n,t) - A*bsplinebasis.(P′,1:n′,t), Inf) < ε
end
end
function test_changebasis_I(P, P′; check_zero=true)
# The test case must hold P ⊑ P′
@test P ⊑ P′
# Test type stability
A = @inferred changebasis_I(P,P′)
# Test output type
@test A isa SparseMatrixCSC
# Zeros must not be stored
check_zero && @test !any(iszero.(A.nzval))
# Test the size of A
n = dim(P)
n′ = dim(P′)
@test size(A) == (n,n′)
# Elements must not be stored for degenerate row/col
for j in 1:n′
if isdegenerate_I(P′, j)
@test !any(Base.isstored.(Ref(A), 1:n, j))
end
end
for i in 1:n
if isdegenerate_I(P, i)
@test !any(Base.isstored.(Ref(A), i, 1:n′))
end
end
# B_{(i,p,k)} = ∑ⱼ A_{i,j} B_{(j,p′,k′)}
d = domain(P)
ts = range(extrema(d)..., length=21)[2:end-1]
for t in ts
@test norm(bsplinebasis.(P,1:n,t) - A*bsplinebasis.(P′,1:n′,t), Inf) < ε
end
end
@testset "subseteq (R)" begin
P1 = BSplineSpace{1}(KnotVector([1, 3, 5, 8]))
P2 = BSplineSpace{1}(KnotVector([1, 3, 5, 6, 8, 9]))
P3 = BSplineSpace{2}(KnotVector([1, 1, 3, 3, 5, 5, 8, 8]))
P4 = BSplineSpace{1}(KnotVector([1, 3, 4, 4, 4, 4, 5, 8]))
P5 = expandspace_R(P3, Val(2))
P6 = expandspace_R(P3, KnotVector([1.2]))
P7 = expandspace_R(P3, KnotVector([1, 1.2]))
test_changebasis_R(P1, P2)
test_changebasis_R(P1, P3)
test_changebasis_R(P1, P4)
test_changebasis_R(P1, P1)
test_changebasis_R(P2, P2)
test_changebasis_R(P3, P3)
test_changebasis_R(P4, P4)
test_changebasis_R(P1, P3)
test_changebasis_R(P3, P5)
test_changebasis_R(P1, P5)
A13 = changebasis(P1, P3)
A35 = changebasis(P3, P5)
A15 = changebasis(P1, P5)
@test A15 ≈ A13 * A35
test_changebasis_R(P1, P3)
test_changebasis_R(P3, P6)
test_changebasis_R(P1, P6)
A13 = changebasis(P1, P3)
A36 = changebasis(P3, P6)
A16 = changebasis(P1, P6)
@test A16 ≈ A13 * A36
test_changebasis_R(P3, P6)
test_changebasis_R(P6, P7)
test_changebasis_R(P3, P7)
A36 = changebasis(P3, P6)
A67 = changebasis(P6, P7)
A37 = changebasis(P3, P7)
@test A37 ≈ A36 * A67
@test P2 ⊈ P3
@test isnondegenerate(P1)
@test isnondegenerate(P2)
@test isnondegenerate(P3)
@test isdegenerate(P4)
@test changebasis_R(P1, P1) == I
@test changebasis_R(P2, P2) == I
@test changebasis_R(P3, P3) == I
@test changebasis_R(P4, P4) ≠ I
end
@testset "sqsubseteq (I)" begin
p1 = 1
p2 = 2
P1 = BSplineSpace{p1}(KnotVector([1, 2, 3, 4, 5]))
P2 = BSplineSpace{p2}(KnotVector([-1, 0.3, 2, 3, 3, 4, 5.2, 6]))
@test P1 ⊑ P1
@test P1 ⊑ P2
@test P2 ⊒ P1
@test P2 ⋢ P1
@test P1 ⋣ P2
@test P1 ⊈ P2
test_changebasis_I(P1, P2)
test_changebasis_I(P1, P1)
test_changebasis_I(P2, P2)
P3 = BSplineSpace{p1-1}(knotvector(P1)[2:end-1])
P4 = BSplineSpace{p2-1}(knotvector(P2)[2:end-1])
@test P3 ⊑ P4
@test P3 ⊈ P4
test_changebasis_I(P3, P4)
# https://github.com/hyrodium/BasicBSpline.jl/issues/325
P5 = BSplineSpace{2}(knotvector" 21 3")
P6 = BSplineSpace{3}(knotvector"212 4")
test_changebasis_I(P5, P6)
P7 = BSplineSpace{3, Int64, KnotVector{Int64}}(KnotVector([1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 6]))
P8 = BSplineSpace{3, Int64, KnotVector{Int64}}(KnotVector([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 7, 7]))
test_changebasis_I(P7, P8)
_P7 = BSplineSpace{3, Int64, KnotVector{Int64}}(KnotVector(-[1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 6]))
_P8 = BSplineSpace{3, Int64, KnotVector{Int64}}(KnotVector(-[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 7, 7]))
test_changebasis_I(_P7, _P8)
# (2,2)-element is stored, but it is zero.
Q1 = BSplineSpace{1, Int64, KnotVector{Int64}}(KnotVector([2, 2, 4, 4, 6, 6]))
Q2 = BSplineSpace{3, Int64, KnotVector{Int64}}(KnotVector([1, 1, 1, 2, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7]))
test_changebasis_I(Q1, Q2; check_zero=false)
Q3 = BSplineSpace{4, Int64, KnotVector{Int64}}(KnotVector([1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 7]))
Q4 = BSplineSpace{5, Int64, KnotVector{Int64}}(KnotVector([1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 6]))
test_changebasis_I(Q3, Q4)
end
@testset "different changebasis_R and changebasis_I" begin
P1 = BSplineSpace{3}(knotvector"1111 132")
P2 = BSplineSpace{3}(knotvector"11121132")
@test isdegenerate_I(P1)
@test isdegenerate_I(P2)
@test isnondegenerate_R(P1)
@test isnondegenerate_R(P2)
@test P1 ⊆ P2
@test P1 ⊑ P2
test_changebasis_I(P1, P2)
test_changebasis_R(P1, P2)
A_R = changebasis_R(P1, P2)
A_I = changebasis_I(P1, P2)
@test A_R ≠ A_I
end
@testset "changebasis_sim" begin
for p in 1:3, L in 1:8
k1 = UniformKnotVector(1:L+2p+1)
k2 = UniformKnotVector(p+1:p+L+1) + p*KnotVector([p+1]) + KnotVector(p+L+1:2p+L)
P1 = BSplineSpace{p}(k1)
P2 = BSplineSpace{p}(k2)
@test P1 isa UniformBSplineSpace{p,T} where {p,T}
@test domain(P1) == domain(P2)
@test dim(P1) == dim(P2)
@test P1 ≃ P2
A = @inferred BasicBSpline._changebasis_sim(P1,P2)
D = domain(P1)
n = dim(P1)
for _ in 1:100
t = rand(D)
@test norm(bsplinebasis.(P1,1:n,t) - A*bsplinebasis.(P2,1:n,t), Inf) < ε
end
end
end
@testset "non-float" begin
k = UniformKnotVector(1:15)
P = BSplineSpace{3}(k)
@test changebasis(P,P) isa SparseMatrixCSC{Float64}
@test BasicBSpline._changebasis_R(P,P) isa SparseMatrixCSC{Float64}
@test BasicBSpline._changebasis_I(P,P) isa SparseMatrixCSC{Float64}
@test BasicBSpline._changebasis_sim(P,P) isa SparseMatrixCSC{Float64}
k = UniformKnotVector(1:15//1)
P = BSplineSpace{3}(k)
@test changebasis(P,P) isa SparseMatrixCSC{Rational{Int}}
@test BasicBSpline._changebasis_R(P,P) isa SparseMatrixCSC{Rational{Int}}
@test BasicBSpline._changebasis_I(P,P) isa SparseMatrixCSC{Rational{Int}}
@test BasicBSpline._changebasis_sim(P,P) isa SparseMatrixCSC{Rational{Int}}
k = UniformKnotVector(1:BigInt(15))
P = BSplineSpace{3}(k)
@test changebasis(P,P) isa SparseMatrixCSC{BigFloat}
@test BasicBSpline._changebasis_R(P,P) isa SparseMatrixCSC{BigFloat}
@test BasicBSpline._changebasis_I(P,P) isa SparseMatrixCSC{BigFloat}
@test BasicBSpline._changebasis_sim(P,P) isa SparseMatrixCSC{BigFloat}
end
@testset "uniform" begin
for r in 1:5
k = UniformKnotVector(0:r:50)
for p in 0:4
P = BSplineSpace{p}(k)
Q = BSplineSpace{p,Int,KnotVector{Int}}(P)
k′ = UniformKnotVector(0:50)
P′ = BSplineSpace{p}(k′)
Q′ = BSplineSpace{p,Int,KnotVector{Int}}(P′)
A1 = @inferred changebasis(P, P′)
A2 = @inferred changebasis(Q, Q′)
@test P ⊆ P′
@test P == Q
@test P′ == Q′
@test A1 ≈ A2
left = leftendpoint(domain(P))-p
right = rightendpoint(domain(P))+p
k′ = UniformKnotVector(left:right)
P′ = BSplineSpace{p}(k′)
Q′ = BSplineSpace{p,Int,KnotVector{Int}}(P′)
A3 = @inferred changebasis(P, P′)
A4 = @inferred changebasis(Q, Q′)
@test P ⊑ P′
@test P == Q
@test P′ == Q′
@test A3 ≈ A4
end
end
end
@testset "derivative" begin
k1 = KnotVector(5*rand(12))
k2 = k1 + KnotVector(rand(3)*3 .+ 1)
p = 5
dP1 = BSplineDerivativeSpace{1}(BSplineSpace{p}(k1))
dP2 = BSplineDerivativeSpace{0}(BSplineSpace{p-1}(k1))
P1 = BSplineSpace{p-1}(k1)
P2 = BSplineSpace{p-1}(k2)
test_changebasis_R(dP1, P1)
test_changebasis_R(dP1, P2)
test_changebasis_R(dP2, P1)
test_changebasis_R(dP2, P2)
test_changebasis_R(dP2, P1)
test_changebasis_R(dP2, P2)
test_changebasis_R(dP1, dP2)
test_changebasis_R(dP1, P2)
test_changebasis_R(dP2, dP2)
test_changebasis_R(dP2, P2)
test_changebasis_R(dP2, dP2)
test_changebasis_R(dP2, P2)
dP2 = BSplineDerivativeSpace{2}(BSplineSpace{p}(k1))
dP3 = BSplineDerivativeSpace{1}(BSplineSpace{p-1}(k1))
dP4 = BSplineDerivativeSpace{0}(BSplineSpace{p-2}(k1))
dP5 = BSplineDerivativeSpace{2}(BSplineSpace{p}(k2))
P3 = BSplineSpace{p-2}(k1)
P4 = BSplineSpace{p-2}(k2)
test_changebasis_R(dP2, dP3)
@test dP2 ⊉ dP3
test_changebasis_R(dP3, dP4)
@test dP3 ⊉ dP4
test_changebasis_R(dP4, P3)
test_changebasis_R(P3, dP4)
test_changebasis_R(dP2, dP5)
@test dP2 ⊉ dP5
test_changebasis_R(dP5, dP5)
test_changebasis_R(dP2, dP2)
test_changebasis_R(dP5, P4)
@test dP5 ⊉ P4
test_changebasis_R(dP3, P4)
@test dP3 ⊉ P4
@test_throws DomainError changebasis(P4, P3)
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 8645 | @testset "Derivative" begin
p_max = 4
ts = rand(10)
dt = 1e-8
@testset "constructor" begin
P1 = BSplineSpace{2}(KnotVector(1:8))
P2 = BSplineSpace{2}(UniformKnotVector(1:8))
P3 = BSplineSpace{2}(UniformKnotVector(1:1:8))
dP1 = BSplineDerivativeSpace{1}(P1)
dP2 = BSplineDerivativeSpace{1}(P2)
dP3 = BSplineDerivativeSpace{1}(P3)
dP4 = BSplineDerivativeSpace{2}(P3)
dP5 = BSplineDerivativeSpace{2,typeof(P2)}(P2)
dP6 = BSplineDerivativeSpace{2,typeof(P3)}(P2)
dP7 = BSplineDerivativeSpace{2,typeof(P3)}(dP6)
@test dP1 == dP2 == dP3 != dP4
@test dP1 !== dP2
@test hash(dP1) == hash(dP2) == hash(dP3) != hash(dP4)
@test_throws MethodError BSplineDerivativeSpace{1,typeof(P2)}(dP1)
@test_throws MethodError BSplineDerivativeSpace(dP1)
@test_throws MethodError BSplineDerivativeSpace{}(dP1)
@test dP3 === BSplineDerivativeSpace{1,typeof(P3)}(dP2)
@test dP2 !== BSplineDerivativeSpace{1,typeof(P3)}(dP2)
@test dP2 === BSplineDerivativeSpace{1,typeof(P2)}(dP2)
@test dP1 isa BSplineDerivativeSpace{1,<:BSplineSpace{p,T,KnotVector{T}} where {p,T}}
@test dP2 isa BSplineDerivativeSpace{1,<:UniformBSplineSpace{p,T} where {p,T}}
@test dP4 == dP5 == dP6 == dP7
@test hash(dP4) == hash(dP5) == hash(dP6) == hash(dP7)
@test dP2 == convert(BSplineDerivativeSpace,dP2)
@test dP2 == convert(BSplineDerivativeSpace{1},dP2)
@test_throws MethodError convert(BSplineDerivativeSpace{2},dP2)
end
@testset "degenerate" begin
P1 = BSplineSpace{2}(KnotVector(1:8))
P2 = BSplineSpace{2}(knotvector"111111151111")
dP1 = BSplineDerivativeSpace{1}(P1)
dP2 = BSplineDerivativeSpace{1}(P2)
@test isdegenerate_R(P1) == isdegenerate_R(dP1)
@test isdegenerate_R(P2) == isdegenerate_R(dP2)
@test isdegenerate_I(P1) == isdegenerate_I(dP1)
@test isdegenerate_I(P2) == isdegenerate_I(dP2)
for i in 1:dim(P1)
@test isdegenerate_R(P1, i) == isdegenerate_R(dP1, i)
@test isdegenerate_I(P1, i) == isdegenerate_I(dP1, i)
end
for i in 1:dim(P2)
@test isdegenerate_R(P2, i) == isdegenerate_R(dP2, i)
@test isdegenerate_I(P2, i) == isdegenerate_I(dP2, i)
end
end
# Not sure why this @testset doesn't work fine.
# @testset "$(p)-th degree basis" for p in 0:p_max
for p in 0:p_max
k = KnotVector(rand(20)) + (p+1)*KnotVector([0,1])
P = BSplineSpace{p}(k)
P0 = BSplineDerivativeSpace{0}(P)
for t in ts, i in 1:dim(P)
@test bsplinebasis(P,i,t) == bsplinebasis(P0,i,t)
@test bsplinebasis₋₀(P,i,t) == bsplinebasis₋₀(P0,i,t)
@test bsplinebasis₊₀(P,i,t) == bsplinebasis₊₀(P0,i,t)
end
@test dim(P) == dim(P0)
# Check the values of the derivative of B-spline basis funcitons
n = dim(P0)
for t in k
s = sum([bsplinebasis(P0, i, t) for i in 1:n])
s₊₀ = sum([bsplinebasis₊₀(P0, i, t) for i in 1:n])
s₋₀ = sum([bsplinebasis₋₀(P0, i, t) for i in 1:n])
if t == k[1]
@test s ≈ 1
@test s₊₀ ≈ 1
@test s₋₀ == 0
elseif t == k[end]
@test s ≈ 1
@test s₊₀ == 0
@test s₋₀ ≈ 1
else
@test s ≈ 1
@test s₊₀ ≈ 1
@test s₋₀ ≈ 1
end
end
P1 = BSplineDerivativeSpace{1}(P)
for t in ts, i in 1:dim(P)
@test bsplinebasis′(P,i,t) == bsplinebasis(P1,i,t)
end
for r in 1:p_max
Pa = BSplineDerivativeSpace{r}(P)
Pb = BSplineDerivativeSpace{r-1}(P)
@test degree(Pa) == p-r
@test dim(Pa) == dim(P)
@test exactdim_R(Pa) == exactdim_R(P)-r
@test domain(P) == domain(Pa) == domain(Pb)
for t in ts, i in 1:dim(P)
d1 = bsplinebasis(Pa,i,t)
d2 = (bsplinebasis(Pb,i,t+dt) - bsplinebasis(Pb,i,t-dt))/2dt
d3 = bsplinebasis′(Pb,i,t)
@test d1 ≈ d2 rtol=1e-7
@test d1 == d3
end
end
end
@testset "bsplinebasisall" begin
k = KnotVector(rand(10).-1) + KnotVector(rand(10)) + KnotVector(rand(10).+1)
ts = rand(10)
for p in 0:5
P = BSplineSpace{p}(k)
Q = P
for r in 0:5
dP = BSplineDerivativeSpace{r}(P)
@test (dP == Q) || (r == 0)
Q = BasicBSpline.derivative(Q)
for t in ts
j = intervalindex(dP,t)
B = collect(bsplinebasisall(dP,j,t))
@test bsplinebasis.(dP,j:j+p,t) ≈ B
@test bsplinebasis₊₀.(dP,j:j+p,t) ≈ B
@test bsplinebasis₋₀.(dP,j:j+p,t) ≈ B
end
end
end
end
@testset "bsplinebasisall (uniform)" begin
k = UniformKnotVector(1:20)
for p in 0:5
P = BSplineSpace{p}(k)
for r in 0:5
dP = BSplineDerivativeSpace{r}(P)
for _ in 1:10
t = rand(domain(dP))
j = intervalindex(dP,t)
B = collect(bsplinebasisall(dP,j,t))
@test bsplinebasis.(dP,j:j+p,t) ≈ B
@test bsplinebasis₊₀.(dP,j:j+p,t) ≈ B
@test bsplinebasis₋₀.(dP,j:j+p,t) ≈ B
end
end
end
end
@testset "Rational" begin
k = KnotVector{Int}(1:12)
P = BSplineSpace{3}(k)
dP = BSplineDerivativeSpace{1}(P)
k isa KnotVector{Int}
dP isa BSplineDerivativeSpace{1,BSplineSpace{3,Int}}
bsplinebasis(dP,1,11//5) isa Rational{Int}
bsplinebasis₊₀(dP,1,11//5) isa Rational{Int}
bsplinebasis₋₀(dP,1,11//5) isa Rational{Int}
@test bsplinebasis(dP,1,11//5) ===
bsplinebasis₊₀(dP,1,11//5) ===
bsplinebasis₋₀(dP,1,11//5) ===
bsplinebasis′(P,1,11//5) ===
bsplinebasis′₊₀(P,1,11//5) ===
bsplinebasis′₋₀(P,1,11//5) === 16//25
end
@testset "Check type" begin
k = KnotVector{Int}(1:12)
P0 = BSplineSpace{0}(k)
P1 = BSplineSpace{1}(k)
P2 = BSplineSpace{2}(k)
for r in 0:2
dP0 = BSplineDerivativeSpace{r}(P0)
dP1 = BSplineDerivativeSpace{r}(P1)
dP2 = BSplineDerivativeSpace{r}(P2)
@test bsplinebasis(dP0,1,5) isa Float64
@test bsplinebasis(dP1,1,5) isa Float64
@test bsplinebasis(dP2,1,5) isa Float64
@test bsplinebasis₊₀(dP0,1,5) isa Float64
@test bsplinebasis₊₀(dP1,1,5) isa Float64
@test bsplinebasis₊₀(dP2,1,5) isa Float64
@test bsplinebasis₋₀(dP0,1,5) isa Float64
@test bsplinebasis₋₀(dP1,1,5) isa Float64
@test bsplinebasis₋₀(dP2,1,5) isa Float64
@test bsplinebasisall(dP0,1,5) isa SVector{1,Float64}
@test bsplinebasisall(dP1,1,5) isa SVector{2,Float64}
@test bsplinebasisall(dP2,1,5) isa SVector{3,Float64}
end
end
@testset "Endpoints" begin
p = 2
k = KnotVector(1:2) + (p+1)*KnotVector([0,3])
P0 = BSplineSpace{0}(k)
P1 = BSplineSpace{1}(k)
P2 = BSplineSpace{2}(k)
@test isdegenerate(P0)
@test isdegenerate(P1)
@test isnondegenerate(P2)
n0 = dim(P0)
n1 = dim(P1)
n2 = dim(P2)
@test bsplinebasis′.(P0,1:n0,0) == bsplinebasis′₊₀.(P0,1:n0,0) == [0,0,0,0,0,0,0]
@test bsplinebasis′.(P1,1:n1,0) == bsplinebasis′₊₀.(P1,1:n1,0) == [0,-1,1,0,0,0]
@test bsplinebasis′.(P2,1:n2,0) == bsplinebasis′₊₀.(P2,1:n2,0) == [-2,2,0,0,0]
@test bsplinebasis′.(P0,1:n0,3) == bsplinebasis′₋₀.(P0,1:n0,3) == [0,0,0,0,0,0,0]
@test bsplinebasis′.(P1,1:n1,3) == bsplinebasis′₋₀.(P1,1:n1,3) == [0,0,0,-1,1,0]
@test bsplinebasis′.(P2,1:n2,3) == bsplinebasis′₋₀.(P2,1:n2,3) == [0,0,0,-2,2]
@test bsplinebasis′₋₀.(P0,1:n0,0) == [0,0,0,0,0,0,0]
@test bsplinebasis′₋₀.(P1,1:n1,0) == [0,0,0,0,0,0]
@test bsplinebasis′₋₀.(P2,1:n2,0) == [0,0,0,0,0]
@test bsplinebasis′₊₀.(P0,1:n0,3) == [0,0,0,0,0,0,0]
@test bsplinebasis′₊₀.(P1,1:n1,3) == [0,0,0,0,0,0]
@test bsplinebasis′₊₀.(P2,1:n2,3) == [0,0,0,0,0]
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 9538 | @testset "KnotVector" begin
@testset "constructor" begin
k1 = KnotVector([1,2,3])
k2 = KnotVector([1,2,2,3])
@test k1 isa KnotVector{Int64}
@test k1 == KnotVector(1:3)::KnotVector{Int}
@test k1 == KnotVector([1,3,2])::KnotVector{Int64}
@test k1 == KnotVector([1,2,3])::KnotVector{Int64}
@test k1 == KnotVector([1,3,2])::KnotVector{Int64}
@test k1 == KnotVector([1.,3,2])::KnotVector{Float64}
@test k1 == KnotVector{Int}([1,3,2])::KnotVector{Int}
@test k1 != k2
@test k1.vector !== copy(k1).vector
@test hash(k1) == hash(KnotVector(1:3)::KnotVector{Int})
@test hash(k1) == hash(KnotVector([1,3,2])::KnotVector{Int64})
@test hash(k1) == hash(KnotVector([1,2,3])::KnotVector{Int64})
@test hash(k1) == hash(KnotVector([1,3,2])::KnotVector{Int64})
@test hash(k1) == hash(KnotVector([1.,3,2])::KnotVector{Float64})
@test hash(k1) == hash(KnotVector{Int}([1,3,2])::KnotVector{Int})
@test hash(k1) != hash(k2)
@test KnotVector{Int}([1,2]) isa KnotVector{Int}
@test KnotVector{Int}([1,2]) isa KnotVector{Int}
@test KnotVector{Int}([1,2.]) isa KnotVector{Int}
@test KnotVector{Int}(k1) isa KnotVector{Int}
@test KnotVector(k1) isa KnotVector{Int}
@test AbstractKnotVector{Float64}(k1) isa KnotVector{Float64}
@test knotvector"11111" == KnotVector([1, 2, 3, 4, 5])
@test knotvector"123" == KnotVector([1, 2, 2, 3, 3, 3])
@test knotvector" 2 2 2" == KnotVector([2, 2, 4, 4, 6, 6])
@test knotvector"020202" == KnotVector([2, 2, 4, 4, 6, 6])
@test knotvector" 1" == KnotVector([6])
end
@testset "eltype" begin
@test eltype(KnotVector([1,2,3])) == Int
@test eltype(KnotVector{Int}([1,2,3])) == Int
@test eltype(KnotVector{Real}([1,2,3])) == Real
@test eltype(KnotVector{Float64}([1,2,3])) == Float64
@test eltype(KnotVector{BigInt}([1,2,3])) == BigInt
@test eltype(KnotVector{Rational{Int}}([1,2,3])) == Rational{Int}
end
@testset "_vec" begin
@test BasicBSpline._vec(KnotVector([1,2,3])) isa Vector{Int}
@test BasicBSpline._vec(EmptyKnotVector()) isa SVector{0,Bool}
end
@testset "EmptyKnotVector" begin
k = EmptyKnotVector()
@test k === copy(k)
end
@testset "SubKnotVector and view" begin
k1 = KnotVector(1:8)
k2 = UniformKnotVector(1:8)
@test view(k1, 1:3) isa SubKnotVector
@test view(k2, 1:3) isa UniformKnotVector
@test copy(view(k1, 1:3)) isa KnotVector
@test copy(view(k1, 1:3)) == view(k1, 1:3) == KnotVector(1:3) == k1[1:3]
end
@testset "zeros" begin
k1 = KnotVector([1,2,3])
@test KnotVector(Float64[]) == zero(KnotVector)
@test KnotVector(Float64[]) == 0*k1 == k1*0 == zero(k1)
@test KnotVector(Float64[]) == EmptyKnotVector()
@test KnotVector(Float64[]) |> isempty
@test KnotVector(Float64[]) |> iszero
@test hash(KnotVector(Float64[])) == hash(zero(KnotVector))
@test hash(KnotVector(Float64[])) == hash(0*k1) == hash(k1*0) == hash(zero(k1))
@test hash(KnotVector(Float64[])) == hash(EmptyKnotVector())
@test_throws MethodError KnotVector()
@test EmptyKnotVector() |> isempty
@test EmptyKnotVector() |> iszero
@test EmptyKnotVector() == KnotVector(Float64[])
@test KnotVector(Float64[]) == EmptyKnotVector()
@test EmptyKnotVector{Bool}() === EmptyKnotVector() === zero(EmptyKnotVector) === zero(EmptyKnotVector{Bool})
@test EmptyKnotVector{Int}() == EmptyKnotVector()
@test EmptyKnotVector{Int}() == EmptyKnotVector{Int}()
@test EmptyKnotVector{Int}() == EmptyKnotVector{Float64}()
@test EmptyKnotVector() == EmptyKnotVector{Int}()
@test EmptyKnotVector{Int}() == EmptyKnotVector{Int}()
@test EmptyKnotVector{Float64}() == EmptyKnotVector{Int}()
@test EmptyKnotVector{Int}() === zero(EmptyKnotVector{Int}())
@test EmptyKnotVector{Int}() === zero(AbstractKnotVector{Int})
@test EmptyKnotVector{Int}() !== zero(AbstractKnotVector)
@test EmptyKnotVector{Bool}() === zero(AbstractKnotVector)
end
@testset "length" begin
@test length(KnotVector(Float64[])) == 0
@test length(KnotVector([1,2,2,3])) == 4
end
@testset "iterator" begin
k1 = KnotVector([1,2,3])
k2 = KnotVector([1,2,2,3])
k3 = KnotVector([2,4,5])
for t in k1
@test t in k2
end
@test k1[1] == 1
@test k2[end] == 3
@test collect(k2) isa Vector{Int}
@test [k2...] isa Vector{Int}
@test collect(k2) == [k2...]
@test collect(k2) != k2
end
@testset "addition, multiply" begin
k1 = KnotVector([1,2,3])
k2 = KnotVector([1,2,2,3])
k3 = KnotVector([2,4,5])
@test KnotVector([-1,2,3]) + 2 * KnotVector([2,5]) == KnotVector([-1,2,2,2,3,5,5])
@test KnotVector([-1,2,3]) + KnotVector([2,5]) * 2 == KnotVector([-1,2,2,2,3,5,5])
@test k1 + k3 == KnotVector([1,2,2,3,4,5])
@test 2 * KnotVector([2,3]) == KnotVector([2,2,3,3])
# EmptyKnotVector
_k1 = k1 + EmptyKnotVector()
_k2 = k2 + EmptyKnotVector{Int}()
_k3 = k3 + EmptyKnotVector{Float64}()
@test _k1.vector === k1.vector
@test _k2.vector === k2.vector
@test _k3.vector !== k3.vector
_k1 = EmptyKnotVector() + k1
_k2 = EmptyKnotVector{Int}() + k2
_k3 = EmptyKnotVector{Float64}() + k3
@test _k1.vector === k1.vector
@test _k2.vector === k2.vector
@test _k3.vector !== k3.vector
@test EmptyKnotVector{Int}() + EmptyKnotVector{Bool}() isa EmptyKnotVector{Int}
@test EmptyKnotVector{Int}()*0 === EmptyKnotVector{Int}()
@test EmptyKnotVector{Float64}()*1 === EmptyKnotVector{Float64}()
@test EmptyKnotVector{BigFloat}()*2 === EmptyKnotVector{BigFloat}()
@test_throws DomainError EmptyKnotVector()*(-1)
@test (EmptyKnotVector()
=== EmptyKnotVector() + EmptyKnotVector()
=== EmptyKnotVector() * 2
=== 2 * EmptyKnotVector())
@test EmptyKnotVector() isa EmptyKnotVector{Bool}
# type promotion
@test KnotVector{Int}([1,2]) + KnotVector([3]) == KnotVector([1,2,3])
@test KnotVector{Int}([1,2]) + KnotVector([3]) isa KnotVector{Int}
@test KnotVector{Int}([1,2]) + KnotVector{Rational{Int}}([3]) == KnotVector([1,2,3])
@test KnotVector{Int}([1,2]) + KnotVector{Rational{Int}}([3]) isa KnotVector{Rational{Int}}
@test KnotVector{Int}([1,2]) * 0 == KnotVector(Float64[])
@test KnotVector{Int}([1,2]) * 0 isa KnotVector{Int}
@test KnotVector{Int}(Int[]) isa KnotVector{Int}
@test EmptyKnotVector{Irrational{:π}}() + EmptyKnotVector{Rational{Int}}() isa EmptyKnotVector{Float64}
end
@testset "unique" begin
k1 = KnotVector([1,2,3])
k2 = KnotVector([1,2,2,3])
@test unique(k1) == k1
@test unique(k2) == k1
@test unique(EmptyKnotVector()) === EmptyKnotVector()
end
@testset "inclusive relation" begin
k1 = knotvector"111"
k2 = knotvector"121"
k3 = knotvector"121 1"
k4 = knotvector"111 1"
k5 = knotvector"1111"
k6 = EmptyKnotVector()
k7 = EmptyKnotVector{Real}()
k8 = EmptyKnotVector{Float64}()
@test k1 ⊆ k1
@test k1 ⊇ k1
@test k2 ⊆ k3
@test k2 ⊈ k4
@test k3 ⊇ k2
@test k4 ⊉ k2
@test !(k5 ⊊ k1)
@test !(k1 ⊊ k1)
@test k1 ⊊ k5
@test !(k1 ⊋ k5)
@test !(k1 ⊋ k1)
@test k5 ⊋ k1
@test k6 ⊆ k7 ⊆ k8 ⊆ k1
@test k6 ⊆ k7 ⊆ k8 ⊆ k2
@test k6 ⊆ k7 ⊆ k8 ⊆ k3
@test k6 ⊆ k7 ⊆ k8 ⊆ k4
@test k6 ⊆ k7 ⊆ k8 ⊆ k5
end
@testset "string" begin
k = KnotVector([1,2,2,3])
@test string(k) == "KnotVector([1, 2, 2, 3])"
@test string(KnotVector(Float64[])) == "KnotVector(Float64[])"
@test string(KnotVector(Int[])) == "KnotVector(Int64[])"
k1 = UniformKnotVector(1:1:3)
k2 = UniformKnotVector(Base.OneTo(3))
k3 = UniformKnotVector(1:4)
@test string(k1) == "UniformKnotVector(1:1:3)"
@test string(k2) == "UniformKnotVector(Base.OneTo(3))"
@test string(k3) == "UniformKnotVector(1:4)"
@test string(EmptyKnotVector()) == "EmptyKnotVector{Bool}()"
@test string(EmptyKnotVector{Int}()) == "EmptyKnotVector{Int64}()"
end
@testset "float" begin
k = KnotVector([1,2,3])
@test float(k) isa KnotVector{Float64}
@test k == float(k)
k = KnotVector{Float32}([1,2,3])
@test float(k) isa KnotVector{Float32}
@test k == float(k)
k = KnotVector{Rational{Int}}([1,2,3])
@test float(k) isa KnotVector{Float64}
@test k == float(k)
end
@testset "other operators" begin
k = KnotVector([1,2,2,3])
@test countknots(k, 0.3) == 0
@test countknots(k, 1.0) == 1
@test countknots(k, 2.0) == 2
@test 1 ∈ k
@test 1.5 ∉ k
k = KnotVector([-2.0, -1.0, -0.0, -0.0, 0.0, 1.0, 3.0])
@test countknots(k,0) == 3
@test countknots(k,0.0) == 3
@test countknots(k,-0.0) == 3
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 7378 | @testset "Plots" begin
dir_out = joinpath(@__DIR__, "out_plot")
rm(dir_out; force=true, recursive=true)
mkpath(dir_out)
@testset "B-spline space" begin
p = 3
k = KnotVector(0:3)+p*KnotVector([0,3])
P = BSplineSpace{p}(k)
pl = plot(P)
path_img = joinpath(dir_out, "bspline_space.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "B-spline space with knotvector" begin
k = knotvector"112111113111111121114"
P = BSplineSpace{3}(k)
pl = plot(P; label="B-spline basis"); plot!(k; label="knot vector")
path_img = joinpath(dir_out, "bspline_space_with_knotvector.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "Uniform B-spline space" begin
p = 3
k = UniformKnotVector(0:8)
P = BSplineSpace{p}(k)
pl = plot(P)
path_img = joinpath(dir_out, "bspline_space_uniform.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "Derivative B-spline space" begin
p = 3
k = UniformKnotVector(0:8)
dP = BSplineDerivativeSpace{1}(BSplineSpace{p}(k))
pl = plot(dP)
path_img = joinpath(dir_out, "bspline_space_derivative.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "B-spline spaces with knotvectors" begin
k1 = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
P1 = BSplineSpace{3}(k1)
P2 = expandspace_R(P1, KnotVector([2.0, 3.0, 5.5]))
pl = plot(P1, label="P1", color=:red)
plot!(P2, label="P2", color=:green)
plot!(knotvector(P1), label="k1", gap=0.01, color=:red)
plot!(knotvector(P2); label="k2", gap=0.01, offset=-0.03, color=:green)
path_img = joinpath(dir_out, "bspline_spaces_and_their_knotvectors.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "Tensor product of B-spline spaces" begin
# Define piecewise polynomial spaces
k1 = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
k2 = knotvector"31 2 121"
P1 = BSplineSpace{3}(k1)
P2 = BSplineSpace{2}(k2)
# Choose indices
i1 = 3
i2 = 4
# Visualize basis functions
xs = range(0,10,length=100)
ys = range(1,9,length=100)
pl = surface(xs, ys, bsplinebasis.(P1,i1,xs') .* bsplinebasis.(P2,i2,ys))
plot!(P1; plane=:xz, label="P1", color=:red)
plot!(P2; plane=:yz, label="P2", color=:green)
plot!(k1; plane=:xz, label="k1", color=:red, markersize=2)
plot!(k2; plane=:yz, label="k2", color=:green, markersize=2)
path_img = joinpath(dir_out, "bspline_space_tensor_product.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "B-spline curve in 2d" begin
a = [SVector(0, 0), SVector(1, 1), SVector(2, -1), SVector(3, 0), SVector(4, -2), SVector(5, 1)]
p = 3
k = KnotVector(0:3)+p*KnotVector([0,3])
P = BSplineSpace{p}(k)
M = BSplineManifold(a, P)
pl = plot(M)
path_img = joinpath(dir_out, "bspline_curve_2d.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "B-spline curve in 3d" begin
a = [SVector(0, 0, 2), SVector(1, 1, 1), SVector(2, -1, 4), SVector(3, 0, 0), SVector(4, -2, 0), SVector(5, 1, 2)]
p = 3
k = KnotVector(0:3)+p*KnotVector([0,3])
P = BSplineSpace{p}(k)
M = BSplineManifold(a, P)
pl = plot(M)
path_img = joinpath(dir_out, "bspline_curve_3d.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "B-spline surface in 2d" begin
k1 = KnotVector(1:8)
k2 = KnotVector(1:10)
P1 = BSplineSpace{2}(k1)
P2 = BSplineSpace{2}(k2)
n1 = dim(P1)
n2 = dim(P2)
a = [SVector(i+j/2-cos(i-j)/5, j-i/2+sin(i+j)/5) for i in 1:n1, j in 1:n2]
M = BSplineManifold(a,(P1,P2))
pl = plot(M)
path_img = joinpath(dir_out, "bspline_surface_2d.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "B-spline surface in 3d" begin
k1 = KnotVector(1:8)
k2 = KnotVector(1:10)
P1 = BSplineSpace{2}(k1)
P2 = BSplineSpace{2}(k2)
n1 = dim(P1)
n2 = dim(P2)
a = [SVector(i,j,sin(i+j)) for i in 1:n1, j in 1:n2]
M = BSplineManifold(a,(P1,P2))
pl = plot(M)
path_img = joinpath(dir_out, "bspline_surface_3d.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "B-spline solid in 3d" begin
P1 = P2 = BSplineSpace{3}(KnotVector([0,0,0,0,1,1,1,1]))
P3 = BSplineSpace{3}(KnotVector([0,0,0,0,1,2,3,4,5,6,6,6,6]))
n1 = dim(P1)
n2 = dim(P2)
n3 = dim(P3)
a = [SVector(i+j/2-cos(i-j)/5+sin(k), j-i/2+sin(i+j)/5+cos(k), k) for i in 1:n1, j in 1:n2, k in 1:n3]
M = BSplineManifold(a, P1, P2, P3);
pl = plot(M; controlpoints=(;markersize=1))
path_img = joinpath(dir_out, "bspline_solid_3d.png")
@test !isfile(path_img)
# https://github.com/hyrodium/BasicBSpline.jl/pull/374#issuecomment-1927050884
# savefig(pl, path_img)
# @test isfile(path_img)
end
@testset "Rational B-spline curve in 2d" begin
a = [SVector(0, 0), SVector(1, 1), SVector(2, -1), SVector(3, 0), SVector(4, -2), SVector(5, 1)]
w = rand(6)
p = 3
k = KnotVector(0:3)+p*KnotVector([0,3])
P = BSplineSpace{p}(k)
M = RationalBSplineManifold(a, w, P)
pl = plot(M)
path_img = joinpath(dir_out, "rational_bspline_curve_2d.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "Rational B-spline curve in 3d" begin
a = [SVector(0, 0, 2), SVector(1, 1, 1), SVector(2, -1, 4), SVector(3, 0, 0), SVector(4, -2, 0), SVector(5, 1, 2)]
w = rand(6)
p = 3
k = KnotVector(0:3)+p*KnotVector([0,3])
P = BSplineSpace{p}(k)
M = RationalBSplineManifold(a, w, P)
pl = plot(M)
path_img = joinpath(dir_out, "rational_bspline_curve_3d.png")
@test !isfile(path_img)
savefig(pl, path_img)
@test isfile(path_img)
end
@testset "Rational B-spline surface in 3d" begin
k1 = KnotVector(1:8)
k2 = KnotVector(1:10)
P1 = BSplineSpace{2}(k1)
P2 = BSplineSpace{2}(k2)
n1 = dim(P1)
n2 = dim(P2)
a = [SVector(i,j,sin(i+j)) for i in 1:n1, j in 1:n2]
w = rand(n1,n2)
M = RationalBSplineManifold(a,w,(P1,P2))
pl = plot(M)
path_img = joinpath(dir_out, "rational_bspline_surface_3d.png")
@test !isfile(path_img)
# https://github.com/hyrodium/BasicBSpline.jl/pull/374#issuecomment-1927050884
# savefig(pl, path_img)
# @test isfile(path_img)
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 8978 | @testset "RationalBSplineManifold" begin
@testset "constructor" begin
k1 = KnotVector(Float64[0,0,1,1])
k2 = UniformKnotVector(1.0:8.0)
k3 = KnotVector(rand(8))
_k1 = KnotVector([0.0, 0.0, 1.0, 1.0])
_k2 = KnotVector(1.0:8.0)
_k3 = view(k3,:)
P1 = BSplineSpace{1}(k1)
P2 = BSplineSpace{3}(k2)
P3 = BSplineSpace{2}(k3)
_P1 = BSplineSpace{1}(_k1)
_P2 = BSplineSpace{3}(_k2)
_P3 = BSplineSpace{2}(_k3)
# 0-dim
a = fill(1.2)
w = fill(4.2)
M = RationalBSplineManifold{0,(),Float64,Float64,Int,Tuple{}}(a, w, ())
N = RationalBSplineManifold{0,(),Float64,Float64,Int,Tuple{}}(copy(a), copy(w), ())
@test M == M
@test M == N
@test hash(M) == hash(M)
@test hash(M) == hash(N)
@test M() == 1.2
# 4-dim
a = rand(dim(P1), dim(P2), dim(P3), dim(P3))
w = rand(dim(P1), dim(P2), dim(P3), dim(P3))
@test RationalBSplineManifold(a, w, P1, P2, P3, P3) == RationalBSplineManifold(a, w, P1, P2, P3, P3)
@test hash(RationalBSplineManifold(a, w, P1, P2, P3, P3)) == hash(RationalBSplineManifold(a, w, P1, P2, P3, P3))
@test RationalBSplineManifold(a, w, P1, P2, P3, P3) == RationalBSplineManifold(a, w, _P1, _P2, _P3, _P3)
@test hash(RationalBSplineManifold(a, w, P1, P2, P3, P3)) == hash(RationalBSplineManifold(a, w, _P1, _P2, _P3, _P3))
@test RationalBSplineManifold(a, w, P1, P2, P3, P3) == RationalBSplineManifold(copy(a), copy(w), _P1, _P2, _P3, _P3)
@test hash(RationalBSplineManifold(a, w, P1, P2, P3, P3)) == hash(RationalBSplineManifold(copy(a), copy(w), _P1, _P2, _P3, _P3))
end
@testset "1dim-arc" begin
a = [SVector(1,0), SVector(1,1), SVector(0,1), SVector(-1,1), SVector(-1,0)]
w = [1, 1/√2, 1, 1/√2, 1]
k = KnotVector([0,0,0,1,1,2,2,2])
p = 2
P = BSplineSpace{p}(k)
M = RationalBSplineManifold(a,w,P)
for _ in 1:100
t1 = 2rand()
@test norm(M(t1)) ≈ 1
end
@test_throws DomainError M(-0.1)
@test_throws DomainError M(2.1)
end
@testset "general cases" begin
p1 = 2
p2 = 3
p3 = 4
k1 = KnotVector(rand(30)) + (p1+1)*KnotVector([0,1])
k2 = KnotVector(rand(30)) + (p2+1)*KnotVector([0,1])
k3 = KnotVector(rand(30)) + (p3+1)*KnotVector([0,1])
P1 = BSplineSpace{p1}(k1)
P2 = BSplineSpace{p2}(k2)
P3 = BSplineSpace{p3}(k3)
n1 = dim(P1)
n2 = dim(P2)
n3 = dim(P3)
@testset "RationalBSpilneManifold definition" begin
@testset "1dim" begin
a = randn(ComplexF64,n1)
w = ones(n1)+rand(n1)
R = RationalBSplineManifold(a,w,(P1,))
A = BSplineManifold(a.*w,(P1,))
W = BSplineManifold(w,(P1,))
@test R(:) == R
@test Base.mightalias(controlpoints(R), controlpoints(R))
@test !Base.mightalias(controlpoints(R), controlpoints(R(:)))
ts = [(rand.(domain.(bsplinespaces(R)))) for _ in 1:10]
for (t1,) in ts
@test R(t1) ≈ A(t1)/W(t1)
end
end
@testset "2dim" begin
a = randn(ComplexF64,n1,n2)
w = ones(n1,n2)+rand(n1,n2)
R = RationalBSplineManifold(a,w,(P1,P2))
A = BSplineManifold(a.*w,(P1,P2))
W = BSplineManifold(w,(P1,P2))
@test R(:,:) == R
@test Base.mightalias(controlpoints(R), controlpoints(R))
@test !Base.mightalias(controlpoints(R), controlpoints(R(:,:)))
ts = [(rand.(domain.(bsplinespaces(R)))) for _ in 1:10]
for (t1, t2) in ts
@test R(t1,t2) ≈ A(t1,t2)/W(t1,t2)
@test R(t1,t2) ≈ R(t1,:)(t2)
@test R(t1,t2) ≈ R(:,t2)(t1)
end
end
@testset "3dim" begin
a = randn(ComplexF64,n1,n2,n3)
w = ones(n1,n2,n3)+rand(n1,n2,n3)
R = RationalBSplineManifold(a,w,(P1,P2,P3))
A = BSplineManifold(a.*w,(P1,P2,P3))
W = BSplineManifold(w,(P1,P2,P3))
@test R(:,:,:) == R
@test Base.mightalias(controlpoints(R), controlpoints(R))
@test !Base.mightalias(controlpoints(R), controlpoints(R(:,:,:)))
ts = [(rand.(domain.(bsplinespaces(R)))) for _ in 1:10]
for (t1, t2, t3) in ts
@test R(t1,t2,t3) ≈ A(t1,t2,t3)/W(t1,t2,t3)
@test R(t1,t2,t3) ≈ R(t1,:,:)(t2,t3)
@test R(t1,t2,t3) ≈ R(:,t2,:)(t1,t3)
@test R(t1,t2,t3) ≈ R(:,:,t3)(t1,t2)
@test R(t1,t2,t3) ≈ R(t1,t2,:)(t3)
@test R(t1,t2,t3) ≈ R(t1,:,t3)(t2)
@test R(t1,t2,t3) ≈ R(:,t2,t3)(t1)
end
end
@testset "4dim" begin
@testset "BSplineManifold-4dim" begin
P1 = BSplineSpace{3}(knotvector"43211112112112")
P2 = BSplineSpace{4}(knotvector"3211 1 112112115")
P3 = BSplineSpace{5}(knotvector" 411 1 112112 11133")
P4 = BSplineSpace{4}(knotvector"4 1112113 11 13 3")
n1 = dim(P1)
n2 = dim(P2)
n3 = dim(P3)
n4 = dim(P4)
a = rand(n1, n2, n3, n4)
w = rand(n1, n2, n3, n4) .+ 1
R = RationalBSplineManifold(a, w, (P1, P2, P3, P4))
@test dim(R) == 4
ts = [(rand.(domain.((P1, P2, P3, P4)))) for _ in 1:10]
for (t1, t2, t3, t4) in ts
@test R(t1,t2,t3,t4) ≈ R(t1,:,:,:)( t2,t3,t4)
@test R(t1,t2,t3,t4) ≈ R(:,t2,:,:)(t1, t3,t4)
@test R(t1,t2,t3,t4) ≈ R(:,:,t3,:)(t1,t2, t4)
@test R(t1,t2,t3,t4) ≈ R(:,:,:,t4)(t1,t2,t3 )
@test R(t1,t2,t3,t4) ≈ R(t1,t2,:,:)(t3,t4)
@test R(t1,t2,t3,t4) ≈ R(t1,:,t3,:)(t2,t4)
@test R(t1,t2,t3,t4) ≈ R(t1,:,:,t4)(t2,t3)
@test R(t1,t2,t3,t4) ≈ R(:,t2,t3,:)(t1,t4)
@test R(t1,t2,t3,t4) ≈ R(:,t2,:,t4)(t1,t3)
@test R(t1,t2,t3,t4) ≈ R(:,:,t3,t4)(t1,t2)
@test R(t1,t2,t3,t4) ≈ R(:,t2,t3,t4)(t1)
@test R(t1,t2,t3,t4) ≈ R(t1,:,t3,t4)(t2)
@test R(t1,t2,t3,t4) ≈ R(t1,t2,:,t4)(t3)
@test R(t1,t2,t3,t4) ≈ R(t1,t2,t3,:)(t4)
end
@test_throws DomainError R(-5,-8,-120,1)
@test R(:,:,:,:) == R
@test Base.mightalias(controlpoints(R), controlpoints(R))
@test !Base.mightalias(controlpoints(R), controlpoints(R(:,:,:,:)))
end
end
end
@testset "compatibility with BSplineManifold" begin
@testset "1dim" begin
a = randn(n1)
w1 = ones(n1)
w2 = 2ones(n1)
M = BSplineManifold(a,P1)
M1 = RationalBSplineManifold(a,w1,P1)
M2 = RationalBSplineManifold(a,w2,P1)
ts = [(rand.(domain.(bsplinespaces(M)))) for _ in 1:10]
for (t1,) in ts
@test M(t1) ≈ M1(t1) atol=1e-14
@test M(t1) ≈ M2(t1) atol=1e-14
end
end
@testset "2dim" begin
a = randn(n1,n2)
w1 = ones(n1,n2)
w2 = 2ones(n1,n2)
M = BSplineManifold(a,P1,P2)
M1 = RationalBSplineManifold(a,w1,P1,P2)
M2 = RationalBSplineManifold(a,w2,P1,P2)
ts = [(rand.(domain.(bsplinespaces(M)))) for _ in 1:10]
for (t1, t2) in ts
@test M(t1,t2) ≈ M1(t1,t2) atol=1e-14
@test M(t1,t2) ≈ M2(t1,t2) atol=1e-14
end
end
@testset "3dim" begin
a = randn(n1,n2,n3)
w1 = ones(n1,n2,n3)
w2 = 2ones(n1,n2,n3)
M = BSplineManifold(a,P1,P2,P3)
M1 = RationalBSplineManifold(a,w1,P1,P2,P3)
M2 = RationalBSplineManifold(a,w2,P1,P2,P3)
ts = [(rand.(domain.(bsplinespaces(M)))) for _ in 1:10]
for (t1, t2, t3) in ts
@test M(t1,t2,t3) ≈ M1(t1,t2,t3) atol=1e-14
@test M(t1,t2,t3) ≈ M2(t1,t2,t3) atol=1e-14
end
end
end
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 13306 | @testset "Refinement" begin
p1,p2,p3 = 3,2,4
k1 = KnotVector(1:8)
k2 = KnotVector([1,4]) + p2*KnotVector([1,4])
k3 = KnotVector([0,2]) + p3*KnotVector([1,2])
P1 = BSplineSpace{p1}(k1)
P2 = BSplineSpace{p2}(k2)
P3 = BSplineSpace{p3}(k3)
P1′ = BSplineSpace{3}(k1+KnotVector([1.2,5.5,7.2,8.5]))
P2′ = expandspace(P2, Val(1), KnotVector([2,2,2,2,2]))
P3′ = BSplineSpace{4}(UniformKnotVector(-3.0:6.0))
n1,n2,n3 = dim(P1),dim(P2),dim(P3)
D1,D2,D3 = domain(P1),domain(P2),domain(P3)
@test P1 ⊆ P1′
@test P2 ⊆ P2′
@test !(P3 ⊆ P3′)
@test !(P1 ⊑ P1′)
@test P2 ⊑ P2′
@test P3 ⊑ P3′
@test P3 ≃ P3′
@testset "_I and _R" begin
@testset "1dim" begin
a1 = rand(SVector{3, Float64}, n1)
a2 = rand(SVector{3, Float64}, n2)
a3 = rand(SVector{3, Float64}, n3)
w1 = rand(n1) .+ 1
w2 = rand(n2) .+ 1
w3 = rand(n3) .+ 1
M1 = BSplineManifold(a1, P1)
M2 = BSplineManifold(a2, P2)
M3 = BSplineManifold(a3, P3)
R1 = RationalBSplineManifold(a1, w1, P1)
R2 = RationalBSplineManifold(a2, w2, P2)
R3 = RationalBSplineManifold(a3, w3, P3)
@test refinement_R(M1, P1′) == refinement(M1, P1′)
@test refinement_R(R1, P1′) == refinement(R1, P1′)
@test refinement_R(M2, P2′) == refinement(M2, P2′)
@test refinement_R(R2, P2′) == refinement(R2, P2′)
@test_throws DomainError refinement_R(M3, P3′)
@test_throws DomainError refinement_R(R3, P3′)
@test_throws DomainError refinement_I(M1, P1′)
@test_throws DomainError refinement_I(R1, P1′)
@test refinement_I(M2, P2′) == refinement(M2, P2′)
@test refinement_I(R2, P2′) == refinement(R2, P2′)
@test refinement_I(M3, P3′) == refinement(M3, P3′)
@test refinement_I(R3, P3′) == refinement(R3, P3′)
@test refinement_R(M1) == refinement_I(M1) == refinement(M1)
@test refinement_R(R1) == refinement_I(R1) == refinement(R1)
@test refinement_R(M2) == refinement_I(M2) == refinement(M2)
@test refinement_R(R2) == refinement_I(R2) == refinement(R2)
@test refinement_R(M3) == refinement_I(M3) == refinement(M3)
@test refinement_R(R3) == refinement_I(R3) == refinement(R3)
# P1 ⊆ P1′ but not P1 ⊑ P1′
M1a_R = refinement_R(refinement_R(M1, (Val(0),)), (KnotVector([1.2,5.5,7.2,8.5]),))
M1b_R = refinement_R(M1, (Val(0),), (KnotVector([1.2,5.5,7.2,8.5]),))
M1c_R = refinement_R(M1, P1′)
@test controlpoints(M1a_R) ≈ controlpoints(M1b_R) == controlpoints(M1c_R)
@test_throws DomainError refinement_I(refinement_I(M1, (Val(0),)), (KnotVector([1.2,5.5,7.2,8.5]),))
@test_throws DomainError refinement_I(M1, (Val(0),), (KnotVector([1.2,5.5,7.2,8.5]),))
@test_throws DomainError refinement_I(M1, P1′)
@test_throws DomainError refinement(refinement(M1, (Val(1),)), (KnotVector([1.2,5.5,7.2,8.5]),))
@test_throws DomainError refinement(M1, (Val(1),), (KnotVector([1.2,5.5,7.2,8.5]),))
M1c = refinement(M1, P1′)
# P2 ⊆ P2′ and P2 ⊑ P2′
M2a_R = refinement_R(refinement_R(M2, (Val(1),)), (KnotVector([2,2,2,2,2]),))
M2b_R = refinement_R(M2, (Val(1),), (KnotVector([2,2,2,2,2]),))
M2c_R = refinement_R(M2, P2′)
@test controlpoints(M2a_R) ≈ controlpoints(M2b_R) ≠ controlpoints(M2c_R)
M2a_I = refinement_I(refinement_I(M2, (Val(1),)), (KnotVector([2,2,2,2,2]),))
M2b_I = refinement_I(M2, (Val(1),), (KnotVector([2,2,2,2,2]),))
M2c_I = refinement_I(M2, P2′)
@test controlpoints(M2a_I) ≈ controlpoints(M2b_I) == controlpoints(M2c_I)
M2a = refinement(refinement(M2, (Val(1),)), (KnotVector([2,2,2,2,2]),))
M2b = refinement(M2, (Val(1),), (KnotVector([2,2,2,2,2]),))
M2c = refinement(M2, P2′)
@test controlpoints(M2a) ≈ controlpoints(M2b) == controlpoints(M2c)
# P3 ⊑ P3′ but not P3 ⊆ P3′
M3a_R = refinement_R(refinement_R(M3, (Val(0),)), (EmptyKnotVector(),))
M3b_R = refinement_R(M3, (Val(0),), (EmptyKnotVector(),))
@test_throws DomainError refinement_R(M3, P3′)
@test controlpoints(M3a_R) ≈ controlpoints(M3b_R)
M3a_I = refinement_I(refinement_I(M3, (Val(0),)), (EmptyKnotVector(),))
M3b_I = refinement_I(M3, (Val(0),), (EmptyKnotVector(),))
M3c_I = refinement_I(M3, P3′)
@test controlpoints(M3a_I) ≈ controlpoints(M3b_I) ≉ controlpoints(M3c_I)
M3a = refinement(refinement(M3, (Val(0),)), (EmptyKnotVector(),))
M3b = refinement(M3, (Val(0),), (EmptyKnotVector(),))
M3c = refinement(M3, P3′)
@test controlpoints(M3a) ≈ controlpoints(M3b) ≉ controlpoints(M3c)
end
@testset "2dim" begin
a12 = rand(SVector{3, Float64}, n1, n2)
a23 = rand(SVector{3, Float64}, n2, n3)
w12 = rand(n1, n2) .+ 1
w23 = rand(n2, n3) .+ 1
M12 = BSplineManifold(a12, P1, P2)
M23 = BSplineManifold(a23, P2, P3)
R12 = RationalBSplineManifold(a12, w12, P1, P2)
R23 = RationalBSplineManifold(a23, w23, P2, P3)
@test refinement_R(M12, P1′, P2′) == refinement(M12, P1′, P2′)
@test refinement_R(R12, P1′, P2′) == refinement(R12, P1′, P2′)
@test_throws DomainError refinement_R(M23, P2′, P3′) == refinement(M23, P2′, P3′)
@test_throws DomainError refinement_R(R23, P2′, P3′) == refinement(R23, P2′, P3′)
@test_throws DomainError refinement_I(M12, P1′, P2′) == refinement(M12, P1′, P2′)
@test_throws DomainError refinement_I(R12, P1′, P2′) == refinement(R12, P1′, P2′)
@test refinement_I(M23, P2′, P3′) == refinement(M23, P2′, P3′)
@test refinement_I(R23, P2′, P3′) == refinement(R23, P2′, P3′)
@test refinement_R(M12) == refinement_I(M12) == refinement(M12)
@test refinement_R(R12) == refinement_I(R12) == refinement(R12)
@test refinement_R(M23) == refinement_I(M23) == refinement(M23)
@test refinement_R(R23) == refinement_I(R23) == refinement(R23)
end
@testset "4dim" begin
a1122 = rand(SVector{3, Float64}, n1, n1, n2, n2)
a2233 = rand(SVector{3, Float64}, n2, n2, n3, n3)
w1122 = rand(n1, n1, n2, n2) .+ 1
w2233 = rand(n2, n2, n3, n3) .+ 1
M1122 = BSplineManifold(a1122, P1, P1, P2, P2)
M2233 = BSplineManifold(a2233, P2, P2, P3, P3)
R1122 = RationalBSplineManifold(a1122, w1122, P1, P1, P2, P2)
R2233 = RationalBSplineManifold(a2233, w2233, P2, P2, P3, P3)
@test refinement_R(M1122, P1′, P1′, P2′, P2′) == refinement(M1122, P1′, P1′, P2′, P2′)
@test refinement_R(R1122, P1′, P1′, P2′, P2′) == refinement(R1122, P1′, P1′, P2′, P2′)
@test_throws DomainError refinement_R(M2233, P2′, P2′, P3′, P3′) == refinement(M2233, P2′, P2′, P3′, P3′)
@test_throws DomainError refinement_R(R2233, P2′, P2′, P3′, P3′) == refinement(R2233, P2′, P2′, P3′, P3′)
@test_throws DomainError refinement_I(M1122, P1′, P1′, P2′, P2′) == refinement(M12, P1′, P1′, P2′, P2′)
@test_throws DomainError refinement_I(R1122, P1′, P1′, P2′, P2′) == refinement(R12, P1′, P1′, P2′, P2′)
@test refinement_I(M2233, P2′, P2′, P3′, P3′) == refinement(M2233, P2′, P2′, P3′, P3′)
@test refinement_I(R2233, P2′, P2′, P3′, P3′) == refinement(R2233, P2′, P2′, P3′, P3′)
@test refinement_R(M1122) == refinement_I(M1122) == refinement(M1122)
@test refinement_R(R1122) == refinement_I(R1122) == refinement(R1122)
@test refinement_R(M2233) == refinement_I(M2233) == refinement(M2233)
@test refinement_R(R2233) == refinement_I(R2233) == refinement(R2233)
end
end
@testset "1dim" begin
a = [Point(i, rand()) for i in 1:n1]
p₊ = (Val(1),)
k₊ = (KnotVector([4.5]),)
# k₊ = (KnotVector([4.5,4.95]),)
@testset "BSplineManifold" begin
M = BSplineManifold(a, (P1,))
M0 = @inferred refinement(M)
M1 = @inferred refinement(M, k₊)
M2 = @inferred refinement(M, p₊)
M3 = @inferred refinement(M, p₊, k₊)
M4 = @inferred refinement(M, (P1′,))
for _ in 1:100
t1 = rand(D1)
@test M(t1) ≈ M1(t1)
@test M(t1) ≈ M2(t1)
@test M(t1) ≈ M3(t1)
@test M(t1) ≈ M4(t1)
end
end
@testset "RationalBSplineManifold" begin
w = rand(n1) .+ 1
R = RationalBSplineManifold(a, w, (P1,))
R0 = @inferred refinement(R)
R1 = @inferred refinement(R, k₊)
R2 = @inferred refinement(R, p₊)
R3 = @inferred refinement(R, p₊, k₊)
R4 = @inferred refinement(R, (P1′,))
for _ in 1:100
t1 = rand(D1)
@test R(t1) ≈ R1(t1)
@test R(t1) ≈ R2(t1)
@test R(t1) ≈ R3(t1)
@test R(t1) ≈ R4(t1)
end
end
end
@testset "2dim" begin
a = [Point(i, rand()) for i in 1:n1, j in 1:n2]
p₊ = (Val(1), Val(2))
k₊ = (KnotVector([4.5,4.7]),KnotVector(Float64[]))
@testset "BSplineManifold" begin
M = BSplineManifold(a, (P1,P2))
M0 = @inferred refinement(M)
M1 = @inferred refinement(M, k₊)
M2 = @inferred refinement(M, p₊)
M3 = @inferred refinement(M, p₊, k₊)
M4 = @inferred refinement(M, (P1′,P2′))
for _ in 1:100
t1 = rand(D1)
t2 = rand(D2)
@test M(t1,t2) ≈ M1(t1,t2)
@test M(t1,t2) ≈ M2(t1,t2)
@test M(t1,t2) ≈ M3(t1,t2)
@test M(t1,t2) ≈ M4(t1,t2)
end
end
@testset "RationalBSplineManifold" begin
w = rand(n1,n2) .+ 1
R = RationalBSplineManifold(a, w, (P1,P2))
R0 = @inferred refinement(R)
R1 = @inferred refinement(R, k₊)
R2 = @inferred refinement(R, p₊)
R3 = @inferred refinement(R, p₊, k₊)
R4 = @inferred refinement(R, (P1′,P2′))
for _ in 1:100
t1 = rand(D1)
t2 = rand(D2)
@test R(t1,t2) ≈ R1(t1,t2)
@test R(t1,t2) ≈ R2(t1,t2)
@test R(t1,t2) ≈ R3(t1,t2)
@test R(t1,t2) ≈ R4(t1,t2)
end
end
end
@testset "3dim" begin
a = [Point(i, rand()) for i in 1:n1, j in 1:n2, k in 1:n3]
p₊ = (Val(1), Val(2), Val(0))
k₊ = (KnotVector([4.4,4.7]),KnotVector(Float64[]),KnotVector([1.8]))
@testset "BSplineManifold" begin
M = BSplineManifold(a, (P1,P2,P3))
# On Julia v1.6, the following script seems not type-stable.
if VERSION ≥ v"1.8"
M0 = @inferred refinement(M)
M1 = @inferred refinement(M, k₊)
M2 = @inferred refinement(M, p₊)
M3 = @inferred refinement(M, p₊, k₊)
M4 = @inferred refinement(M, (P1′,P2′,P3′))
else
M0 = refinement(M)
M1 = refinement(M, k₊)
M2 = refinement(M, p₊)
M3 = refinement(M, p₊, k₊)
M4 = refinement(M, (P1′,P2′,P3′))
end
for _ in 1:100
t1 = rand(D1)
t2 = rand(D2)
t3 = rand(D3)
@test M(t1,t2,t3) ≈ M1(t1,t2,t3)
@test M(t1,t2,t3) ≈ M2(t1,t2,t3)
@test M(t1,t2,t3) ≈ M3(t1,t2,t3)
@test M(t1,t2,t3) ≈ M4(t1,t2,t3)
end
end
@testset "RationalBSplineManifold" begin
w = rand(n1,n2,n3) .+ 1
R = RationalBSplineManifold(a, w, (P1,P2,P3))
# On Julia v1.6, the following script seems not type-stable.
if VERSION ≥ v"1.8"
R0 = @inferred refinement(R)
R1 = @inferred refinement(R, k₊)
R2 = @inferred refinement(R, p₊)
R3 = @inferred refinement(R, p₊, k₊)
R4 = @inferred refinement(R, (P1′,P2′,P3′))
else
R0 = refinement(R)
R1 = refinement(R, k₊)
R2 = refinement(R, p₊)
R3 = refinement(R, p₊, k₊)
R4 = refinement(R, (P1′,P2′,P3′))
end
for _ in 1:100
t1 = rand(D1)
t2 = rand(D2)
t3 = rand(D3)
@test R(t1,t2,t3) ≈ R1(t1,t2,t3)
@test R(t1,t2,t3) ≈ R2(t1,t2,t3)
@test R(t1,t2,t3) ≈ R3(t1,t2,t3)
@test R(t1,t2,t3) ≈ R4(t1,t2,t3)
end
end
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 3179 | @testset "UniformBSplineBasis" begin
@testset "bsplinebasis" begin
v = 2:10
k = KnotVector(v)
k1 = UniformKnotVector(v)
k2 = UniformKnotVector(v/2)
k3 = UniformKnotVector(v*2)
@test eltype(k1) == Int
@test eltype(k2) == Float64
@test eltype(k3) == Int
for p in 0:3
P = BSplineSpace{p}(k)
P1 = BSplineSpace{p}(k1)
P2 = BSplineSpace{p}(k2)
P3 = BSplineSpace{p}(k3)
@test dim(P) == dim(P1)
@test dim(P) == dim(P2)
@test dim(P) == dim(P3)
n = dim(P)
@test bsplinebasis(P1,n÷2,6//1) isa Rational{Int}
@test bsplinebasis(P2,n÷2,6//1) isa Float64
@test bsplinebasis(P3,n÷2,6//1) isa Rational{Int}
for _ in 1:20
t = 10*rand()
for i in 1:n
@test bsplinebasis(P1,i,t) ≈ bsplinebasis(P,i,t)
@test bsplinebasis(P2,i,t/2) ≈ bsplinebasis(P,i,t)
@test bsplinebasis(P3,i,t*2) ≈ bsplinebasis(P,i,t)
@test (t ∈ bsplinesupport(P1,i)) == (bsplinebasis(P1,i,t) != 0)
@test (t/2 ∈ bsplinesupport(P2,i)) == (bsplinebasis(P2,i,t/2) != 0)
@test (t*2 ∈ bsplinesupport(P3,i)) == (bsplinebasis(P3,i,t*2) != 0)
@test bsplinebasis(P1,i,t) isa Float64
@test bsplinebasis(P2,i,t) isa Float64
@test bsplinebasis(P3,i,t) isa Float64
@test bsplinebasis(P1,i,t) == bsplinebasis₊₀(P1,i,t) == bsplinebasis₋₀(P1,i,t)
@test bsplinebasis(P2,i,t) == bsplinebasis₊₀(P2,i,t) == bsplinebasis₋₀(P2,i,t)
@test bsplinebasis(P3,i,t) == bsplinebasis₊₀(P3,i,t) == bsplinebasis₋₀(P3,i,t)
end
end
end
end
@testset "bsplinebasisall" begin
v = 2:10
k = KnotVector(v)
l = length(k)
k1 = UniformKnotVector(v)
k2 = UniformKnotVector(v/2)
k3 = UniformKnotVector(v*2)
for p in 0:3
P = BSplineSpace{p}(k)
P1 = BSplineSpace{p}(k1)
P2 = BSplineSpace{p}(k2)
P3 = BSplineSpace{p}(k3)
@test bsplinebasisall(P1,(l-2p)÷2,6//1) isa SVector{p+1,Rational{Int}}
@test bsplinebasisall(P2,(l-2p)÷2,6//1) isa SVector{p+1,Float64}
@test bsplinebasisall(P3,(l-2p)÷2,6//1) isa SVector{p+1,Rational{Int}}
for _ in 1:20
t = 10*rand()
for i in 1:l-2p-1 # FIXME: This can be 0:l-2p, but don't know why the test doesn't pass.
@test bsplinebasisall(P1,i,t) ≈ bsplinebasisall(P,i,t)
@test bsplinebasisall(P2,i,t/2) ≈ bsplinebasisall(P,i,t)
@test bsplinebasisall(P3,i,t*2) ≈ bsplinebasisall(P,i,t)
@test bsplinebasisall(P1,i,t) isa SVector{p+1,Float64}
@test bsplinebasisall(P2,i,t) isa SVector{p+1,Float64}
@test bsplinebasisall(P3,i,t) isa SVector{p+1,Float64}
end
end
end
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 3736 | @testset "BSplineSpace with uniform knot vector" begin
@testset "constructor, subset" begin
k1 = UniformKnotVector(1:8)
P1 = BSplineSpace{2}(KnotVector(k1))
P1′ = BSplineSpace{2}(k1)
# @test P1 === BSplineSpace{2}(P1)
# @test P1 === BSplineSpace{2,Int}(P1)
@test P1 === BSplineSpace{2,Int}(P1)
@test bsplinesupport(P1, 2) == bsplinesupport(P1′, 2) == 2..5
@test dim(P1) == dim(P1′) == 5
@test exactdim_R(P1) == exactdim_R(P1′) == 5
@test isnondegenerate(P1) == true
@test isdegenerate(P1) == false
@test P1 == P1′
k2 = UniformKnotVector(range(1,1,length=8))
P2 = BSplineSpace{2}(k2)
P2′ = BSplineSpace{2}(k2)
@test bsplinesupport(P2, 2) == bsplinesupport(P2′, 2) == 1..1
@test dim(P2) == dim(P2′) == 5
@test exactdim_R(P2) == exactdim_R(P2′) == 0
@test isnondegenerate(P2) == false
@test isdegenerate(P2) == true
@test P2 === P2′
k3 = UniformKnotVector(1.0:0.5:12.0)
P3 = BSplineSpace{2}(k3)
@test P1 ⊆ P3
@test P2 ⋢ P3
@test P1 ⋢ P3
@test P2 ⋢ P3
k4 = UniformKnotVector(1.0:0.5:12.0)
P3 = BSplineSpace{2}(k3)
@test P1 ⊆ P3
@test P2 ⋢ P3
@test P1 ⋢ P3
@test P2 ⋢ P3
end
@testset "dimension, dengenerate" begin
P1 = BSplineSpace{2}(UniformKnotVector(1:8))
@test bsplinesupport(P1, 2) == 2..5
@test dim(P1) == 5
@test exactdim_R(P1) == 5
@test isnondegenerate(P1) == true
@test isdegenerate(P1) == false
P2 = BSplineSpace{2}(UniformKnotVector(range(1,1,length=8)))
@test isnondegenerate(P2) == false
@test isdegenerate(P2) == true
@test isdegenerate(P2,1) == true
@test isdegenerate(P2,2) == true
@test isdegenerate(P2,3) == true
@test isdegenerate(P2,4) == true
@test isnondegenerate(P2,1) == false
@test isnondegenerate(P2,2) == false
@test isnondegenerate(P2,3) == false
@test isnondegenerate(P2,4) == false
@test dim(P2) == 5
@test exactdim_R(P2) == 0
end
@testset "support" begin
k = UniformKnotVector(0:9)
P = BSplineSpace{2}(k)
@test bsplinesupport(P,1) == 0..3
@test bsplinesupport(P,2) == 1..4
end
@testset "equality" begin
P1 = BSplineSpace{2}(UniformKnotVector(Base.OneTo(8)))
P2 = BSplineSpace{2}(UniformKnotVector(1:8))
P3 = BSplineSpace{2}(UniformKnotVector(1:1:8))
P4 = BSplineSpace{2}(UniformKnotVector(1.0:1.0:8.0))
P5 = BSplineSpace{1}(UniformKnotVector(1.0:1.0:8.0))
P6 = BSplineSpace{2}(UniformKnotVector(1.0:2.0:8.0))
@test P1 == P2 == P3 == P4
@test P1 != P5
@test P1 != P6
@test hash(P1) == hash(P2) == hash(P3) == hash(P4)
@test hash(P1) != hash(P5)
@test hash(P1) != hash(P6)
end
@testset "subset but not sqsubset" begin
P1 = BSplineSpace{2}(UniformKnotVector(0:1:8))
P2 = BSplineSpace{2}(UniformKnotVector(0.0:0.5:12.0))
@test P1 ⊆ P1
@test P2 ⊆ P2
@test P1 ⊆ P2
@test P2 ⊈ P1
@test P1 ⊑ P1
@test P2 ⊑ P2
@test P1 ⋢ P2
@test P2 ⋢ P1
end
@testset "sqsubset but not subset" begin
P1 = BSplineSpace{2}(UniformKnotVector(0:1:8))
P2 = BSplineSpace{2}(UniformKnotVector(1.0:0.5:7.0))
@test domain(P1) == domain(P2)
@test P1 ⊆ P1
@test P2 ⊆ P2
@test P1 ⊈ P2
@test P2 ⊈ P1
@test P1 ⊑ P1
@test P2 ⊑ P2
@test P1 ⊑ P2
@test P2 ⋢ P1
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 4617 | @testset "UniformKnotVector" begin
k1 = UniformKnotVector(1:1:3)
k2 = UniformKnotVector(Base.OneTo(3))
k3 = UniformKnotVector(1:4)
k4 = UniformKnotVector(2:4)
k5 = UniformKnotVector(2.0:4.0)
k6 = UniformKnotVector(2.0:2.0:12.0)
@testset "equality" begin
@test k1 == k1
@test k1 == k2
@test k2 != k3
@test k4 != k3
@test k4 != k2
@test k2 == KnotVector(1:3)
@test k2 != 1:3
@test k1.vector === copy(k1).vector
@test k1 === copy(k1)
@test hash(k1) == hash(k1)
@test hash(k1) == hash(k2)
@test hash(k2) != hash(k3)
@test hash(k4) != hash(k3)
@test hash(k4) != hash(k2)
@test hash(k2) == hash(KnotVector(1:3))
@test hash(k2) != hash(1:3)
end
@testset "constructor, conversion" begin
@test k1 isa UniformKnotVector{Int,StepRange{Int,Int}}
@test k2 isa UniformKnotVector{Int,Base.OneTo{Int}}
@test k3 isa UniformKnotVector{Int,UnitRange{Int}}
@test UniformKnotVector(k2) isa UniformKnotVector{Int,Base.OneTo{Int}}
@test_throws MethodError UniformKnotVector{Float64}(k3)
T1 = UniformKnotVector{Float64,typeof(1.0:1.0)}
T2 = UniformKnotVector{Int,typeof(1:1:1)}
T3 = UniformKnotVector{Float64,typeof(1:1:1)}
@test T1 != T2
@test T1(k3) isa T1
@test T2(k3) isa T2
@test_throws MethodError T3(k3)
@test convert(T1,k3) isa T1
@test convert(T2,k3) isa T2
@test_throws MethodError convert(T3,k3)
@test KnotVector(k1) isa KnotVector{Int}
@test KnotVector(k2) isa KnotVector{Int}
@test KnotVector(k5) isa KnotVector{Float64}
end
@testset "eltype" begin
@test eltype(UniformKnotVector(1:3)) == Int
@test eltype(UniformKnotVector(1:1:3)) == Int
@test eltype(UniformKnotVector(1:1:BigInt(3))) == BigInt
@test eltype(UniformKnotVector(1.0:1.0:3.0)) == Float64
@test eltype(UniformKnotVector(1//1:1//5:3//1)) == Rational{Int}
end
@testset "length" begin
@test length(k2) == 3
@test length(k3) == 4
@test length(k4) == 3
end
@testset "step" begin
step(k1) == 1
step(k2) == 1
step(k3) == 1
step(k4) == 1
step(k5) == 1
step(k6) == 2
end
@testset "iterator, getindex" begin
for t in k2
@test t in k3
end
@test k1[1] == 1
@test k2[end] == 3
@test k4[2] == 3
@test k4[[1,2]] == KnotVector([2,3])
@test k3[2:4] == k4
@test collect(k2) isa Vector{Int}
@test [k2...] isa Vector{Int}
@test collect(k5) isa Vector{Float64}
@test [k5...] isa Vector{Float64}
@test collect(k2) == [k2...]
@test collect(k2) != k2
end
@testset "addition, multiply" begin
@test k2 + k3 == KnotVector(k2) + KnotVector(k3)
@test k2 + k4 == KnotVector(k2) + KnotVector(k4)
@test 2 * k2 == k2 * 2 == k2 + k2
end
@testset "zeros" begin
@test_throws MethodError zero(UniformKnotVector)
@test_throws MethodError zeros(UniformKnotVector,3)
@test zero(k1) isa EmptyKnotVector{Int}
@test zero(k5) isa EmptyKnotVector{Float64}
@test k1 * 0 == zero(k1)
@test k1 + zero(k1) == k1
@test zero(k1) |> isempty
@test zero(k1) |> iszero
end
@testset "unique" begin
@test unique(k2) == k2
@test unique(k3) == k3
@test unique(k4) == k4
end
@testset "inclusive relation" begin
@test k1 == k2
@test k1 ⊆ k2
@test k2 ⊆ k1
@test k2 ⊆ k3
@test k4 ⊆ k3
@test k2 ⊈ k4
@test KnotVector(k2) ⊆ k3
@test KnotVector(k4) ⊆ k3
@test KnotVector(k2) ⊈ k4
@test k2 ⊆ KnotVector(k3)
@test k4 ⊆ KnotVector(k3)
@test k2 ⊈ KnotVector(k4)
end
@testset "float" begin
k = UniformKnotVector(1:3)
@test float(k) isa UniformKnotVector{Float64}
@test k == float(k)
k = UniformKnotVector(1f0:3f0)
@test float(k) isa UniformKnotVector{Float32}
@test k == float(k)
k = UniformKnotVector(1//1:3//1)
@test float(k) isa UniformKnotVector{Float64}
@test k == float(k)
end
@testset "other operators" begin
@test countknots(k2, 0.3) == 0
@test countknots(k2, 1) == 1
@test countknots(k2, 1.0) == 1
@test countknots(k2, 2.0) == 1
@test 1 ∈ k2
@test 1.5 ∉ k2
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | code | 3166 | @testset "util" begin
@testset "r-nomial" begin
A1 = [BasicBSpline.r_nomial(n,k,1) for n in 0:5, k in -1:10]
A2 = [BasicBSpline.r_nomial(n,k,2) for n in 0:5, k in -1:10]
A3 = [BasicBSpline.r_nomial(n,k,3) for n in 0:5, k in -1:10]
A4 = [BasicBSpline.r_nomial(n,k,4) for n in 0:5, k in -1:10]
A5 = [BasicBSpline.r_nomial(n,k,5) for n in 0:5, k in -1:10]
A6 = [BasicBSpline.r_nomial(n,k,6) for n in 0:5, k in -1:10]
A7 = [BasicBSpline.r_nomial(n,k,7) for n in 0:5, k in -1:10]
@test A1 == [
0 1 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0
]
@test A2 == [
0 1 0 0 0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0 0 0
0 1 2 1 0 0 0 0 0 0 0 0
0 1 3 3 1 0 0 0 0 0 0 0
0 1 4 6 4 1 0 0 0 0 0 0
0 1 5 10 10 5 1 0 0 0 0 0
]
@test A3 == [
0 1 0 0 0 0 0 0 0 0 0 0
0 1 1 1 0 0 0 0 0 0 0 0
0 1 2 3 2 1 0 0 0 0 0 0
0 1 3 6 7 6 3 1 0 0 0 0
0 1 4 10 16 19 16 10 4 1 0 0
0 1 5 15 30 45 51 45 30 15 5 1
]
@test A4 == [
0 1 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 0 0 0 0 0 0 0
0 1 2 3 4 3 2 1 0 0 0 0
0 1 3 6 10 12 12 10 6 3 1 0
0 1 4 10 20 31 40 44 40 31 20 10
0 1 5 15 35 65 101 135 155 155 135 101
]
@test A5 == [
0 1 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0 0 0
0 1 2 3 4 5 4 3 2 1 0 0
0 1 3 6 10 15 18 19 18 15 10 6
0 1 4 10 20 35 52 68 80 85 80 68
0 1 5 15 35 70 121 185 255 320 365 381
]
@test A6 == [
0 1 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 0 0 0 0 0
0 1 2 3 4 5 6 5 4 3 2 1
0 1 3 6 10 15 21 25 27 27 25 21
0 1 4 10 20 35 56 80 104 125 140 146
0 1 5 15 35 70 126 205 305 420 540 651
]
@test A7 == [
0 1 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 0 0 0 0
0 1 2 3 4 5 6 7 6 5 4 3
0 1 3 6 10 15 21 28 33 36 37 36
0 1 4 10 20 35 56 84 116 149 180 206
0 1 5 15 35 70 126 210 325 470 640 826
]
end
end
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 7980 | # BasicBSpline.jl
Basic (mathematical) operations for B-spline functions and related things with Julia.
[](https://hyrodium.github.io/BasicBSpline.jl/stable)
[](https://hyrodium.github.io/BasicBSpline.jl/dev)
[](https://github.com/hyrodium/BasicBSpline.jl/actions)
[](https://codecov.io/gh/hyrodium/BasicBSpline.jl)
[](https://github.com/JuliaTesting/Aqua.jl)
[](https://zenodo.org/badge/latestdoi/258791290)
[](https://pkgs.genieframework.com?packages=BasicBSpline)

## Summary
This package provides basic mathematical operations for [B-spline](https://en.wikipedia.org/wiki/B-spline).
* B-spline basis function
* Some operations for knot vector
* Some operations for B-spline space (piecewise polynomial space)
* B-spline manifold (includes curve, surface and solid)
* Refinement algorithm for B-spline manifold
* Fitting control points for a given function
## Comparison to other B-spline packages
There are several Julia packages for B-spline, and this package distinguishes itself with the following key benefits:
* Supports all degrees of polynomials.
* Includes a refinement algorithm for B-spline manifolds.
* Delivers high-speed performance.
* Is mathematically oriented.
* Provides a fitting algorithm using least squares. (via [BasicBSplineFitting.jl](https://github.com/hyrodium/BasicBSplineFitting.jl))
* Offers exact SVG export feature. (via [BasicBSplineExporter.jl](https://github.com/hyrodium/BasicBSplineExporter.jl))
If you have any thoughts, please comment in:
* [Discourse post about BasicBSpline.jl](https://discourse.julialang.org/t//96323)
* [JuliaPackageComparisons](https://juliapackagecomparisons.github.io/pages/bspline/)
## Installation
Install this package via Julia REPL's package mode.
```
]add BasicBSpline
```
## Quick start
### B-spline basis function
The value of B-spline basis function $B_{(i,p,k)}$ can be obtained with `bsplinebasis₊₀`.
$$
\begin{aligned}
{B}_{(i,p,k)}(t)
&=
\frac{t-k_{i}}{k_{i+p}-k_{i}}{B}_{(i,p-1,k)}(t)
+\frac{k_{i+p+1}-t}{k_{i+p+1}-k_{i+1}}{B}_{(i+1,p-1,k)}(t) \\
{B}_{(i,0,k)}(t)
&=
\begin{cases}
&1\quad (k_{i}\le t< k_{i+1})\\
&0\quad (\text{otherwise})
\end{cases}
\end{aligned}
$$
```julia
julia> using BasicBSpline
julia> P3 = BSplineSpace{3}(KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0]))
BSplineSpace{3, Float64, KnotVector{Float64}}(KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0]))
julia> bsplinebasis₊₀(P3, 2, 7.5)
0.13786213786213783
```
BasicBSpline.jl has many recipes based on [RecipesBase.jl](https://docs.juliaplots.org/dev/RecipesBase/), and `BSplineSpace` object can be visualized with its basis functions.
([Try B-spline basis functions in Desmos](https://www.desmos.com/calculator/ql6jqgdabs))
```julia
using BasicBSpline
using Plots
k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
P0 = BSplineSpace{0}(k) # 0th degree piecewise polynomial space
P1 = BSplineSpace{1}(k) # 1st degree piecewise polynomial space
P2 = BSplineSpace{2}(k) # 2nd degree piecewise polynomial space
P3 = BSplineSpace{3}(k) # 3rd degree piecewise polynomial space
gr()
plot(
plot(P0; ylims=(0,1), label="P0"),
plot(P1; ylims=(0,1), label="P1"),
plot(P2; ylims=(0,1), label="P2"),
plot(P3; ylims=(0,1), label="P3"),
layout=(2,2),
)
```

You can visualize the differentiability of B-spline basis function. See [Differentiability and knot duplications](https://hyrodium.github.io/BasicBSpline.jl/dev/math/bsplinebasis/#Differentiability-and-knot-duplications) for details.
https://github.com/hyrodium/BasicBSpline.jl/assets/7488140/034cf6d0-62ea-44e0-a00f-d307e6aad0fe
### B-spline manifold
```julia
using BasicBSpline
using StaticArrays
using Plots
## 1-dim B-spline manifold
p = 2 # degree of polynomial
k = KnotVector(1:12) # knot vector
P = BSplineSpace{p}(k) # B-spline space
a = [SVector(i-5, 3*sin(i^2)) for i in 1:dim(P)] # control points
M = BSplineManifold(a, P) # Define B-spline manifold
gr(); plot(M)
```

### Rational B-spline manifold (NURBS)
```julia
using BasicBSpline
using LinearAlgebra
using StaticArrays
using Plots
plotly()
R1 = 3 # major radius of torus
R2 = 1 # minor radius of torus
p = 2
k = KnotVector([0,0,0,1,1,2,2,3,3,4,4,4])
P = BSplineSpace{p}(k)
a = [normalize(SVector(cosd(t), sind(t)), Inf) for t in 0:45:360]
w = [ifelse(isodd(i), √2, 1) for i in 1:9]
a0 = push.(a, 0)
a1 = (R1+R2)*a0
a5 = (R1-R2)*a0
a2 = [p+R2*SVector(0,0,1) for p in a1]
a3 = [p+R2*SVector(0,0,1) for p in R1*a0]
a4 = [p+R2*SVector(0,0,1) for p in a5]
a6 = [p-R2*SVector(0,0,1) for p in a5]
a7 = [p-R2*SVector(0,0,1) for p in R1*a0]
a8 = [p-R2*SVector(0,0,1) for p in a1]
M = RationalBSplineManifold(hcat(a1,a2,a3,a4,a5,a6,a7,a8,a1), w*w', P, P)
plot(M; controlpoints=(markersize=2,))
```

### Refinement
#### h-refinement
```julia
k₊ = (KnotVector([3.1, 3.2, 3.3]), KnotVector([0.5, 0.8, 0.9])) # additional knot vectors
M_h = refinement(M, k₊) # refinement of B-spline manifold
plot(M_h; controlpoints=(markersize=2,))
```

Note that this shape and the last shape are equivalent.
#### p-refinement
```julia
p₊ = (Val(1), Val(2)) # additional degrees
M_p = refinement(M, p₊) # refinement of B-spline manifold
plot(M_p; controlpoints=(markersize=2,))
```

Note that this shape and the last shape are equivalent.
### Fitting B-spline manifold
The next example shows the fitting for [the following graph on Desmos graphing calculator](https://www.desmos.com/calculator/2hm3b1fbdf)!

```julia
using BasicBSplineFitting
p1 = 2
p2 = 2
k1 = KnotVector(-10:10)+p1*KnotVector([-10,10])
k2 = KnotVector(-10:10)+p2*KnotVector([-10,10])
P1 = BSplineSpace{p1}(k1)
P2 = BSplineSpace{p2}(k2)
f(u1, u2) = SVector(2u1 + sin(u1) + cos(u2) + u2 / 2, 3u2 + sin(u2) + sin(u1) / 2 + u1^2 / 6) / 5
a = fittingcontrolpoints(f, (P1, P2))
M = BSplineManifold(a, (P1, P2))
gr()
plot(M; aspectratio=1)
```

If the knot vector span is too coarse, the approximation will be coarse.
```julia
p1 = 2
p2 = 2
k1 = KnotVector(-10:5:10)+p1*KnotVector([-10,10])
k2 = KnotVector(-10:5:10)+p2*KnotVector([-10,10])
P1 = BSplineSpace{p1}(k1)
P2 = BSplineSpace{p2}(k2)
f(u1, u2) = SVector(2u1 + sin(u1) + cos(u2) + u2 / 2, 3u2 + sin(u2) + sin(u1) / 2 + u1^2 / 6) / 5
a = fittingcontrolpoints(f, (P1, P2))
M = BSplineManifold(a, (P1, P2))
plot(M; aspectratio=1)
```

### Draw smooth vector graphics
```julia
using BasicBSpline
using BasicBSplineFitting
using BasicBSplineExporter
p = 3
k = KnotVector(range(-2π,2π,length=8))+p*KnotVector([-2π,2π])
P = BSplineSpace{p}(k)
f(u) = SVector(u,sin(u))
a = fittingcontrolpoints(f, P)
M = BSplineManifold(a, P)
save_svg("sine-curve.svg", M, unitlength=50, xlims=(-8,8), ylims=(-2,2))
save_svg("sine-curve_no-points.svg", M, unitlength=50, xlims=(-8,8), ylims=(-2,2), points=false)
```


This is useful when you edit graphs (or curves) with your favorite vector graphics editor.

See [Plotting smooth graphs with Julia](https://forem.julialang.org/hyrodium/plotting-smooth-graphs-with-julia-6mj) for more tutorials.
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 218 | # API
## BasicBSpline.jl
```@autodocs
Modules = [BasicBSpline]
Order = [:type, :function, :macro]
```
## BasicBSplineFitting.jl
```@autodocs
Modules = [BasicBSplineFitting]
Order = [:type, :function, :macro]
```
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 4094 | # Interpolations
Currently, BasicBSpline.jl doesn't have APIs for interpolations, but it is not hard to implement some basic interpolation algorithms with this package.
## Setup
```@example interpolation
using BasicBSpline
using IntervalSets
using Random; Random.seed!(42)
using Plots
```
## Interpolation with cubic B-spline
```@example interpolation
function interpolate(xs::AbstractVector, fs::AbstractVector{T}) where T
# Cubic open B-spline space
p = 3
k = KnotVector(xs) + KnotVector([xs[1],xs[end]]) * p
P = BSplineSpace{p}(k)
# dimensions
m = length(xs)
n = dim(P)
# The interpolant function has a f''=0 property at bounds.
ddP = BSplineDerivativeSpace{2}(P)
dda = [bsplinebasis(ddP,j,xs[1]) for j in 1:n]
ddb = [bsplinebasis(ddP,j,xs[m]) for j in 1:n]
# Compute the interpolant function (1-dim B-spline manifold)
M = [bsplinebasis(P,j,xs[i]) for i in 1:m, j in 1:n]
M = vcat(dda', M, ddb')
y = vcat(zero(T), fs, zero(T))
return BSplineManifold(M\y, P)
end
# Example inputs
xs = [1, 2, 3, 4, 6, 7]
fs = [1.3, 1.5, 2, 2.1, 1.9, 1.3]
f = interpolate(xs,fs)
# Plot
plotly()
scatter(xs, fs)
plot!(t->f(t))
savefig("interpolation_cubic.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../interpolation_cubic.html" style="width:100%;height:420px;"></object>
```
## Interpolation with linear B-spline
```@example interpolation
function interpolate_linear(xs::AbstractVector, fs::AbstractVector{T}) where T
# Linear open B-spline space
p = 1
k = KnotVector(xs) + KnotVector([xs[1],xs[end]])
P = BSplineSpace{p}(k)
# dimensions
m = length(xs)
n = dim(P)
# Compute the interpolant function (1-dim B-spline manifold)
return BSplineManifold(fs, P)
end
# Example inputs
xs = [1, 2, 3, 4, 6, 7]
fs = [1.3, 1.5, 2, 2.1, 1.9, 1.3]
f = interpolate_linear(xs,fs)
# Plot
scatter(xs, fs)
plot!(t->f(t))
savefig("interpolation_linear.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../interpolation_linear.html" style="width:100%;height:420px;"></object>
```
## Interpolation with periodic B-spline
```@example interpolation
function interpolate_periodic(xs::AbstractVector, fs::AbstractVector, ::Val{p}) where p
# Closed B-spline space, any polynomial degrees can be accepted
n = length(xs) - 1
period = xs[end]-xs[begin]
k = KnotVector(vcat(
xs[end-p:end-1] .- period,
xs,
xs[begin+1:begin+p] .+ period
))
P = BSplineSpace{p}(k)
A = [bsplinebasis(P,j,xs[i]) for i in 1:n, j in 1:n]
for i in 1:p-1, j in 1:i
A[n+i-p+1,j] += bsplinebasis(P,j+n,xs[i+n-p+1])
end
b = A \ fs[begin:end-1]
# Compute the interpolant function (1-dim B-spline manifold)
return BSplineManifold(vcat(b,b[1:p]), P)
end
# Example inputs
xs = [1, 2, 3, 4, 6, 7]
fs = [1.3, 1.5, 2, 2.1, 1.9, 1.3] # fs[1] == fs[end]
f = interpolate_periodic(xs,fs,Val(2))
# Plot
scatter(xs, fs)
plot!(t->f(mod(t-1,6)+1),1,14)
plot!(t->f(t))
savefig("interpolation_periodic.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../interpolation_periodic.html" style="width:100%;height:420px;"></object>
```
Note that the periodic interpolation supports any degree of polynomial.
```@example interpolation
xs = 2π*rand(10)
sort!(push!(xs, 0, 2π))
fs = sin.(xs)
f1 = interpolate_periodic(xs,fs,Val(1))
f2 = interpolate_periodic(xs,fs,Val(2))
f3 = interpolate_periodic(xs,fs,Val(3))
f4 = interpolate_periodic(xs,fs,Val(4))
f5 = interpolate_periodic(xs,fs,Val(5))
scatter(xs, fs, label="sampling points")
plot!(sin, label="sine curve", color=:black)
plot!(t->f1(t), label="polynomial degree 1")
plot!(t->f2(t), label="polynomial degree 2")
plot!(t->f3(t), label="polynomial degree 3")
plot!(t->f4(t), label="polynomial degree 4")
plot!(t->f5(t), label="polynomial degree 5")
savefig("interpolation_periodic_sin.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../interpolation_periodic_sin.html" style="width:100%;height:420px;"></object>
```
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 9819 | # B-spline basis function
## Setup
```@example math_bsplinebasis
using BasicBSpline
using Random
using Plots
```
## Basic properties of B-spline basis function
!!! tip "Def. B-spline space"
B-spline basis function is defined by [Cox–de Boor recursion formula](https://en.wikipedia.org/wiki/De_Boor%27s_algorithm).
```math
\begin{aligned}
{B}_{(i,p,k)}(t)
&=
\frac{t-k_{i}}{k_{i+p}-k_{i}}{B}_{(i,p-1,k)}(t)
+\frac{k_{i+p+1}-t}{k_{i+p+1}-k_{i+1}}{B}_{(i+1,p-1,k)}(t) \\
{B}_{(i,0,k)}(t)
&=
\begin{cases}
&1\quad (k_{i}\le t< k_{i+1})\\
&0\quad (\text{otherwise})
\end{cases}
\end{aligned}
```
If the denominator is zero, then the term is assumed to be zero.
The next figure shows the plot of B-spline basis functions.
You can manipulate these plots on [desmos graphing calculator](https://www.desmos.com/calculator/ql6jqgdabs)!

!!! info "Thm. Basis of B-spline space"
The set of functions ``\{B_{(i,p,k)}\}_i`` is a basis of B-spline space ``\mathcal{P}[p,k]``.
These B-spline basis functions can be calculated with [`bsplinebasis₊₀`](@ref).
```@example math_bsplinebasis
p = 2
k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
P = BSplineSpace{p}(k)
gr()
plot([t->bsplinebasis₊₀(P,i,t) for i in 1:dim(P)], 0, 10, ylims=(0,1), label=false)
savefig("bsplinebasisplot.png") # hide
nothing # hide
```

The first terms can be defined in different ways ([`bsplinebasis₋₀`](@ref)).
```math
\begin{aligned}
{B}_{(i,0,k)}(t)
&=
\begin{cases}
&1\quad (k_{i} < t \le k_{i+1}) \\
&0\quad (\text{otherwise})
\end{cases}
\end{aligned}
```
```@example math_bsplinebasis
p = 2
k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
P = BSplineSpace{p}(k)
plot([t->bsplinebasis₋₀(P,i,t) for i in 1:dim(P)], 0, 10, ylims=(0,1), label=false)
savefig("bsplinebasisplot2.png") # hide
nothing # hide
```

In these cases, each B-spline basis function ``B_{(i,2,k)}`` is coninuous, so [`bsplinebasis₊₀`](@ref) and [`bsplinebasis₋₀`](@ref) are equal.
## Support of B-spline basis function
!!! info "Thm. Support of B-spline basis function"
If a B-spline space``\mathcal{P}[p,k]`` is non-degenerate, the support of its basis function is calculated as follows:
```math
\operatorname{supp}(B_{(i,p,k)})=[k_{i},k_{i+p+1}]
```
[TODO: fig]
## Partition of unity
!!! info "Thm. Partition of unity"
Let ``B_{(i,p,k)}`` be a B-spline basis function, then the following equation is satisfied.
```math
\begin{aligned}
\sum_{i}B_{(i,p,k)}(t) &= 1 & (k_{p+1} \le t < k_{l-p}) \\
0 \le B_{(i,p,k)}(t) &\le 1
\end{aligned}
```
```@example math_bsplinebasis
p = 2
k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
P = BSplineSpace{p}(k)
plot(t->sum(bsplinebasis₊₀(P,i,t) for i in 1:dim(P)), 0, 10, ylims=(-0.1, 1.1), label="sum of bspline basis functions")
plot!(k, label="knot vector", legend=:inside)
savefig("sumofbsplineplot.png") # hide
nothing # hide
```

To satisfy the partition of unity on whole interval ``[0,10]``, sometimes more knots will be inserted to the endpoints of the interval.
```@example math_bsplinebasis
p = 2
k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0]) + p * KnotVector([0,10])
P = BSplineSpace{p}(k)
plot(t->sum(bsplinebasis₊₀(P,i,t) for i in 1:dim(P)), 0, 10, ylims=(-0.1, 1.1), label="sum of bspline basis functions")
plot!(k, label="knot vector", legend=:inside)
savefig("sumofbsplineplot2.png") # hide
nothing # hide
```

But, the sum ``\sum_{i} B_{(i,p,k)}(t)`` is not equal to ``1`` at ``t=8``.
Therefore, to satisfy partition of unity on closed interval ``[k_{p+1}, k_{l-p}]``, the definition of first terms of B-spline basis functions are sometimes replaced:
```math
\begin{aligned}
{B}_{(i,0,k)}(t)
&=
\begin{cases}
&1\quad (k_{i} \le t<k_{i+1})\\
&1\quad (k_{i} < t = k_{i+1}=k_{l})\\
&0\quad (\text{otherwise})
\end{cases}
\end{aligned}
```
```@example math_bsplinebasis
p = 2
k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0]) + p * KnotVector([0,10])
P = BSplineSpace{p}(k)
plot(t->sum(bsplinebasis(P,i,t) for i in 1:dim(P)), 0, 10, ylims=(-0.1, 1.1), label="sum of bspline basis functions")
plot!(k, label="knot vector", legend=:inside)
savefig("sumofbsplineplot3.png") # hide
nothing # hide
```

Here are all of valiations of the B-spline basis function.
* [`bsplinebasis₊₀`](@ref)
* [`bsplinebasis₋₀`](@ref)
* [`bsplinebasis`](@ref)
* [`BasicBSpline.bsplinebasis₋₀I`](@ref)
## [Differentiability and knot duplications](@id differentiability-and-knot-duplications)
The differentiability of the B-spline basis function depends on the duplications on the knot vector.
The following animation shows this property.
```@example math_bsplinebasis
# Initialize
gr()
Random.seed!(42)
N = 10
# Easing functions
c=2/√3
f(t) = ifelse(t>0, exp(-1/t), 0.0)
g(t) = 1 - f(c*t) / (f(c*t) + f(c-c*t))
h(t) = clamp(1 - f((1-t)/2) / f(1/2), 0, 1)
# Default knot vector
v = 10*(1:N-1)/N + randn(N-1)*0.5
pushfirst!(v, 0)
push!(v, 10)
# Generate animation
anim = @animate for t in 0:0.05:5
w = copy(v)
w[5] = v[4] + (g(t-0.0) + h(t-3.9)) * (v[5]-v[4])
w[6] = v[4] + (g(t-1.0) + h(t-3.6)) * (v[6]-v[4])
w[7] = v[4] + (g(t-2.0) + h(t-3.3)) * (v[7]-v[4])
k = KnotVector(w)
P0 = BSplineSpace{0}(k)
P1 = BSplineSpace{1}(k)
P2 = BSplineSpace{2}(k)
P3 = BSplineSpace{3}(k)
plot(
plot(P0; label="P0", ylims=(0,1), color=palette(:cool,4)[1]),
plot(P1; label="P1", ylims=(0,1), color=palette(:cool,4)[2]),
plot(P2; label="P2", ylims=(0,1), color=palette(:cool,4)[3]),
plot(P3; label="P3", ylims=(0,1), color=palette(:cool,4)[4]),
plot(k; label="knot vector", ylims=(-0.1,0.02), color=:white, yticks=nothing);
layout=grid(5, 1, heights=[0.23 ,0.23, 0.23, 0.23, 0.08]),
size=(501,800)
)
end
# Run ffmepg to generate mp4 file
# cmd = `ffmpeg -y -framerate 24 -i $(anim.dir)/%06d.png -c:v libx264 -pix_fmt yuv420p differentiability.mp4`
cmd = `ffmpeg -y -framerate 24 -i $(anim.dir)/%06d.png -c:v libx264 -pix_fmt yuv420p differentiability.mp4` # hide
out = Pipe() # hide
err = Pipe() # hide
run(pipeline(ignorestatus(cmd), stdout=out, stderr=err)) # hide
nothing # hide
```

## B-spline basis functions at specific point
Sometimes, you may need the non-zero values of B-spline basis functions at specific point.
The [`bsplinebasisall`](@ref) function is much more efficient than evaluating B-spline functions one by one with [`bsplinebasis`](@ref) function.
```@example math_bsplinebasis
P = BSplineSpace{2}(KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0]))
t = 6.3
plot(P; label="P", ylims=(0,1))
scatter!(fill(t,3), [bsplinebasis(P,2,t), bsplinebasis(P,3,t), bsplinebasis(P,4,t)]; markershape=:circle, markersize=10, label="bsplinebasis")
scatter!(fill(t,3), bsplinebasisall(P, 2, t); markershape=:star7, markersize=10, label="bsplinebasisall")
savefig("bsplinebasis_vs_bsplinebasisall.png") # hide
nothing # hide
```

Benchmark:
```@repl
using BenchmarkTools, BasicBSpline
P = BSplineSpace{2}(KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0]))
t = 6.3
(bsplinebasis(P, 2, t), bsplinebasis(P, 3, t), bsplinebasis(P, 4, t))
bsplinebasisall(P, 2, t)
@benchmark (bsplinebasis($P, 2, $t), bsplinebasis($P, 3, $t), bsplinebasis($P, 4, $t))
@benchmark bsplinebasisall($P, 2, $t)
```
The next figures illustlates the relation between `domain(P)`, `intervalindex(P,t)` and `bsplinebasisall(P,i,t)`.
```@example math_bsplinebasis
plotly()
k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
for p in 1:3
local P
P = BSplineSpace{p}(k)
plot(P, legend=:topleft, label="B-spline basis (p=1)")
plot!(t->intervalindex(P,t),0,10, label="Interval index")
plot!(t->sum(bsplinebasis(P,i,t) for i in 1:dim(P)),0,10, label="Sum of B-spline basis")
plot!(k, label="knot vector")
plot!([t->bsplinebasisall(P,1,t)[i] for i in 1:p+1],0,10, color=:black, label="bsplinebasisall (i=1)", ylim=(-1,8-2p))
savefig("bsplinebasisall-$(p).html") # hide
nothing # hide
end
```
```@raw html
<object type="text/html" data="../bsplinebasisall-1.html" style="width:100%;height:420px;"></object>
```
```@raw html
<object type="text/html" data="../bsplinebasisall-2.html" style="width:100%;height:420px;"></object>
```
```@raw html
<object type="text/html" data="../bsplinebasisall-3.html" style="width:100%;height:420px;"></object>
```
## Uniform B-spline basis and uniform distribution
Let ``X_1, \dots, X_n`` be i.i.d. random variables with ``X_i \sim U(0,1)``, then the probability density function of ``X_1+\cdots+X_n`` can be obtained via `BasicBSpline.uniform_bsplinebasis_kernel(Val(n-1),t)`.
```@example math_bsplinebasis
gr()
N = 100000
# polynomial degree 0
plot1 = histogram([rand() for _ in 1:N], normalize=true, label=false)
plot!(t->BasicBSpline.uniform_bsplinebasis_kernel(Val(0),t), label=false)
# polynomial degree 1
plot2 = histogram([rand()+rand() for _ in 1:N], normalize=true, label=false)
plot!(t->BasicBSpline.uniform_bsplinebasis_kernel(Val(1),t), label=false)
# polynomial degree 2
plot3 = histogram([rand()+rand()+rand() for _ in 1:N], normalize=true, label=false)
plot!(t->BasicBSpline.uniform_bsplinebasis_kernel(Val(2),t), label=false)
# polynomial degree 3
plot4 = histogram([rand()+rand()+rand()+rand() for _ in 1:N], normalize=true, label=false)
plot!(t->BasicBSpline.uniform_bsplinebasis_kernel(Val(3),t), label=false)
# plot all
plot(plot1,plot2,plot3,plot4)
savefig("histogram-uniform.png") # hide
nothing # hide
```

| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 6659 | # B-spline manifold
## Setup
```@example math_bsplinemanifold
using BasicBSpline
using StaticArrays
using StaticArrays
using Plots
```
## Multi-dimensional B-spline
!!! info "Thm. Basis of tensor product of B-spline spaces"
The tensor product of B-spline spaces ``\mathcal{P}[p^1,k^1]\otimes\mathcal{P}[p^2,k^2]`` is a linear space with the following basis.
```math
\mathcal{P}[p^1,k^1]\otimes\mathcal{P}[p^2,k^2]
= \operatorname*{span}_{i,j} (B_{(i,p^1,k^1)} \otimes B_{(j,p^2,k^2)})
```
where the basis are defined as
```math
(B_{(i,p^1,k^1)} \otimes B_{(j,p^2,k^2)})(t^1, t^2)
= B_{(i,p^1,k^1)}(t^1) \cdot B_{(j,p^2,k^2)}(t^2)
```
The next plot shows ``B_{(3,p^1,k^1)} \otimes B_{(4,p^2,k^2)}`` basis function.
```@example math_bsplinemanifold
# Define shape
k1 = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
k2 = knotvector"31 2 121"
P1 = BSplineSpace{3}(k1)
P2 = BSplineSpace{2}(k2)
# Choose indices
i1 = 3
i2 = 4
# Visualize basis functions
plotly()
plot(P1; plane=:xz, label="P1", color=:red)
plot!(P2; plane=:yz, label="P2", color=:green)
plot!(k1; plane=:xz, label="k1", color=:red, markersize=2)
plot!(k2; plane=:yz, label="k2", color=:green, markersize=2)
xs = range(0,10,length=100)
ys = range(1,9,length=100)
surface!(xs, ys, bsplinebasis.(P1,i1,xs') .* bsplinebasis.(P2,i2,ys))
savefig("2dim-tensor-product-bspline.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../2dim-tensor-product-bspline.html" style="width:100%;height:420px;"></object>
```
Higher dimensional tensor products ``\mathcal{P}[p^1,k^1]\otimes\cdots\otimes\mathcal{P}[p^d,k^d]`` are defined similarly.
## Definition
B-spline manifold is a parametric representation of a shape.
!!! tip "Def. B-spline manifold"
For given ``d``-dimensional B-spline basis functions ``B_{(i^1,p^1,k^1)} \otimes \cdots \otimes B_{(i^d,p^d,k^d)}`` and given points ``\bm{a}_{i^1 \dots i^d} \in V``, B-spline manifold is defined by the following parametrization:
```math
\bm{p}(t^1,\dots,t^d;\bm{a}_{i^1 \dots i^d})
=\sum_{i^1,\dots,i^d}(B_{(i^1,p^1,k^1)} \otimes \cdots \otimes B_{(i^d,p^d,k^d)})(t^1,\dots,t^d) \bm{a}_{i^1 \dots i^d}
```
Where ``\bm{a}_{i^1 \dots i^d}`` are called **control points**.
We will also write ``\bm{p}(t^1,\dots,t^d; \bm{a})``, ``\bm{p}(t^1,\dots,t^d)``, ``\bm{p}(t; \bm{a})`` or ``\bm{p}(t)`` for simplicity.
Note that the [`BSplineManifold`](@ref) objects are callable, and the arguments will be checked if it fits in the domain of [`BSplineSpace`](@ref).
```@example math_bsplinemanifold
P = BSplineSpace{2}(KnotVector([0,0,0,1,1,1]))
a = [SVector(1,0), SVector(1,1), SVector(0,1)] # `length(a) == dim(P)`
M = BSplineManifold(a, P)
M(0.4) # Calculate `sum(a[i]*bsplinebasis(P, i, 0.4) for i in 1:dim(P))`
```
If you need extension of [`BSplineManifold`](@ref) or don't need the arguments check, you can call [`unbounded_mapping`](@ref).
```@repl math_bsplinemanifold
M(0.4)
unbounded_mapping(M, 0.4)
M(1.2)
unbounded_mapping(M, 1.2)
```
`unbounded_mapping(M,t...)` is a little bit faster than `M(t...)` because it does not check the domain.
## B-spline curve
```@example math_bsplinemanifold
## 1-dim B-spline manifold
p = 2 # degree of polynomial
k = KnotVector(1:12) # knot vector
P = BSplineSpace{p}(k) # B-spline space
a = [SVector(i-5, 3*sin(i^2)) for i in 1:dim(P)] # control points
M = BSplineManifold(a, P) # Define B-spline manifold
plot(M)
savefig("1dim-manifold.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../1dim-manifold.html" style="width:100%;height:420px;"></object>
```
## B-spline surface
```@example math_bsplinemanifold
## 2-dim B-spline manifold
p = 2 # degree of polynomial
k = KnotVector(1:8) # knot vector
P = BSplineSpace{p}(k) # B-spline space
rand_a = [SVector(rand(), rand(), rand()) for i in 1:dim(P), j in 1:dim(P)]
a = [SVector(2*i-6.5, 2*j-6.5, 0) for i in 1:dim(P), j in 1:dim(P)] + rand_a # random generated control points
M = BSplineManifold(a,(P,P)) # Define B-spline manifold
plot(M)
savefig("2dim-manifold.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../2dim-manifold.html" style="width:100%;height:420px;"></object>
```
**Paraboloid**
```@example math_bsplinemanifold
plotly()
p = 2
k = KnotVector([-1,-1,-1,1,1,1])
P = BSplineSpace{p}(k)
a = [SVector(i,j,2i^2+2j^2-2) for i in -1:1, j in -1:1]
M = BSplineManifold(a,P,P)
plot(M)
savefig("paraboloid.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../paraboloid.html" style="width:100%;height:420px;"></object>
```
**Hyperbolic paraboloid**
```@example math_bsplinemanifold
plotly()
a = [SVector(i,j,2i^2-2j^2) for i in -1:1, j in -1:1]
M = BSplineManifold(a,P,P)
plot(M)
savefig("hyperbolicparaboloid.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../hyperbolicparaboloid.html" style="width:100%;height:420px;"></object>
```
## B-spline solid
```@example math_bsplinemanifold
k1 = k2 = KnotVector([0,0,1,1])
k3 = UniformKnotVector(-6:6)
P1 = BSplineSpace{1}(k1)
P2 = BSplineSpace{1}(k2)
P3 = BSplineSpace{3}(k3)
e₁(t) = SVector(cos(t),sin(t),0)
e₂(t) = SVector(-sin(t),cos(t),0)
a = cat([[e₁(t)*i+e₂(t)*j+SVector(0,0,t) for i in 0:1, j in 0:1] for t in -2:0.5:2]..., dims=3)
M = BSplineManifold(a,(P1,P2,P3))
plot(M; colorbar=false)
savefig("bsplinesolid.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../bsplinesolid.html" style="width:100%;height:420px;"></object>
```
## Affine commutativity
!!! info "Thm. Affine commutativity"
Let ``T`` be a affine transform ``V \to W``, then the following equality holds.
```math
T(\bm{p}(t; \bm{a}))
=\bm{p}(t; T(\bm{a}))
```
## Fixing arguments (currying)
Just like fixing first index such as `A[3,:]::Array{1}` for matrix `A::Array{2}`, fixing first argument `M(4.3,:)` will create `BSplineManifold{1}` for B-spline surface `M::BSplineManifold{2}`.
```@repl math_bsplinemanifold
p = 2;
k = KnotVector(1:8);
P = BSplineSpace{p}(k);
a = [SVector(5i+5j+rand(), 5i-5j+rand(), rand()) for i in 1:dim(P), j in 1:dim(P)];
M = BSplineManifold(a,(P,P));
M isa BSplineManifold{2}
M(:,:) isa BSplineManifold{2}
M(4.3,:) isa BSplineManifold{1} # Fix first argument
```
```@example math_bsplinemanifold
plot(M)
plot!(M(4.3,:), linewidth = 5, color=:cyan)
plot!(M(4.4,:), linewidth = 5, color=:red)
plot!(M(:,5.2), linewidth = 5, color=:green)
savefig("2dim-manifold-currying.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../2dim-manifold-currying.html" style="width:100%;height:420px;"></object>
```
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 2923 | # B-spline space
## Setup
```@example math_bsplinespace
using BasicBSpline
using StaticArrays
using Plots
```
## Defnition
Before defining B-spline space, we'll define polynomial space with degree ``p``.
!!! tip "Def. Polynomial space"
Polynomial space with degree ``p``.
```math
\mathcal{P}[p]
=\left\{f:\mathbb{R}\to\mathbb{R}\ ;\ t\mapsto a_0+a_1t^1+\cdots+a_pt^p \ \left| \ %
a_i\in \mathbb{R}
\right.
\right\}
```
This space ``\mathcal{P}[p]`` is a ``(p+1)``-dimensional linear space.
Note that ``\{t\mapsto t^i\}_{0 \le i \le p}`` is a basis of ``\mathcal{P}[p]``, and also the set of [Bernstein polynomial](https://en.wikipedia.org/wiki/Bernstein_polynomial) ``\{B_{(i,p)}\}_i`` is a basis of ``\mathcal{P}[p]``.
```math
\begin{aligned}
B_{(i,p)}(t)
&=\binom{p}{i-1}t^{i-1}(1-t)^{p-i+1}
&(i=1, \dots, p+1)
\end{aligned}
```
Where ``\binom{p}{i-1}`` is a [binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient).
You can try Bernstein polynomial on [desmos graphing calculator](https://www.desmos.com/calculator/yc2qe6j6re)!
!!! tip "Def. B-spline space"
For given polynomial degree ``p\ge 0`` and knot vector ``k=(k_1,\dots,k_l)``, B-spline space ``\mathcal{P}[p,k]`` is defined as follows:
```math
\mathcal{P}[p,k]
=\left\{f:\mathbb{R}\to\mathbb{R} \ \left| \ %
\begin{gathered}
\operatorname{supp}(f)\subseteq [k_1, k_l] \\
\exists \tilde{f}\in\mathcal{P}[p], f|_{[k_{i}, k_{i+1})} = \tilde{f}|_{[k_{i}, k_{i+1})} \\
\forall t \in \mathbb{R}, \exists \delta > 0, f|_{(t-\delta,t+\delta)}\in C^{p-\mathfrak{n}_k(t)}
\end{gathered} \right.
\right\}
```
Note that each element of the space ``\mathcal{P}[p,k]`` is a piecewise polynomial.
[TODO: fig]
## Degeneration
!!! tip "Def. Degeneration"
A B-spline space **non-degenerate** if its degree and knot vector satisfies following property:
```math
\begin{aligned}
k_{i}&<k_{i+p+1} & (1 \le i \le l-p-1)
\end{aligned}
```
## Dimensions
!!! info "Thm. Dimension of B-spline space"
The B-spline space is a linear space, and if a B-spline space is non-degenerate, its dimension is calculated by:
```math
\dim(\mathcal{P}[p,k])=\# k - p -1
```
```@repl math_bsplinespace
P1 = BSplineSpace{1}(KnotVector([1,2,3,4,5,6,7]))
P2 = BSplineSpace{1}(KnotVector([1,2,4,4,4,6,7]))
P3 = BSplineSpace{1}(KnotVector([1,2,3,5,5,5,7]))
dim(P1), exactdim_R(P1), exactdim_I(P1)
dim(P2), exactdim_R(P2), exactdim_I(P2)
dim(P3), exactdim_R(P3), exactdim_I(P3)
```
Visualization:
```@example math_bsplinespace
gr()
pl1 = plot(P1); plot!(pl1, knotvector(P1))
pl2 = plot(P2); plot!(pl2, knotvector(P2))
pl3 = plot(P3); plot!(pl3, knotvector(P3))
plot(pl1, pl2, pl3; layout=(1,3), legend=false)
savefig("dimension-degeneration.png") # hide
nothing # hide
```

| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 1155 | # Derivative of B-spline
```@example math_derivative
using BasicBSpline
using StaticArrays
using Plots
```
!!! info "Thm. Derivative of B-spline basis function"
The derivative of B-spline basis function can be expressed as follows:
```math
\begin{aligned}
\dot{B}_{(i,p,k)}(t)
&=\frac{d}{dt}B_{(i,p,k)}(t) \\
&=p\left(\frac{1}{k_{i+p}-k_{i}}B_{(i,p-1,k)}(t)-\frac{1}{k_{i+p+1}-k_{i+1}}B_{(i+1,p-1,k)}(t)\right)
\end{aligned}
```
Note that ``\dot{B}_{(i,p,k)}\in\mathcal{P}[p-1,k]``.
```@example math_derivative
k = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
P = BSplineSpace{3}(k)
plotly()
plot(
plot(BSplineDerivativeSpace{0}(P), label="0th derivative", color=:black),
plot(BSplineDerivativeSpace{1}(P), label="1st derivative", color=:red),
plot(BSplineDerivativeSpace{2}(P), label="2nd derivative", color=:green),
plot(BSplineDerivativeSpace{3}(P), label="3rd derivative", color=:blue),
)
savefig("bsplinebasisderivativeplot.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../bsplinebasisderivativeplot.html" style="width:100%;height:420px;"></object>
```
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 1713 | # Fitting with B-spline manifold
## Setup
```@example math_fitting
using BasicBSpline
using BasicBSplineFitting
using StaticArrays
using Plots
```
## Fitting with least squares
[`fittingcontrolpoints`](@ref) function
```@example math_fitting
p1 = 2
p2 = 2
k1 = KnotVector(-10:10)+p1*KnotVector([-10,10])
k2 = KnotVector(-10:10)+p2*KnotVector([-10,10])
P1 = BSplineSpace{p1}(k1)
P2 = BSplineSpace{p2}(k2)
f(u1, u2) = SVector(2u1 + sin(u1) + cos(u2) + u2 / 2, 3u2 + sin(u2) + sin(u1) / 2 + u1^2 / 6) / 5
a = fittingcontrolpoints(f, (P1, P2))
M = BSplineManifold(a, (P1, P2))
gr()
plot(M; xlims=(-10,10), ylims=(-10,10), aspectratio=1)
savefig("fitting.png") # hide
nothing # hide
```

[Try on Desmos graphing graphing calculator!](https://www.desmos.com/calculator/2hm3b1fbdf)

### Cardioid (planar curve)
```@example math_fitting
f(t) = SVector((1+cos(t))*cos(t),(1+cos(t))*sin(t))
p = 3
k = KnotVector(range(0,2π,15)) + p * KnotVector([0,2π]) + 2 * KnotVector([π])
P = BSplineSpace{p}(k)
a = fittingcontrolpoints(f, P)
M = BSplineManifold(a, P)
gr()
plot(M; aspectratio=1)
savefig("plots-cardioid.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../plots-cardioid.html" style="width:100%;height:550px;"></object>
```
### Helix (spatial curve)
```@example math_fitting
f(t) = SVector(cos(t),sin(t),t)
p = 3
k = KnotVector(range(0,6π,15)) + p * KnotVector([0,6π])
P = BSplineSpace{p}(k)
a = fittingcontrolpoints(f, P)
M = BSplineManifold(a, P)
plotly()
plot(M)
savefig("plots-helix.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../plots-helix.html" style="width:100%;height:550px;"></object>
```
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 4499 | # Inclusive relation between B-spline spaces
## Setup
```@example math_inclusive
using BasicBSpline
using StaticArrays
using Plots
```
## Theorem on [`issubset`](@ref)
!!! info "Thm. Inclusive relation between B-spline spaces"
For non-degenerate B-spline spaces, the following relationship holds.
```math
\mathcal{P}[p,k]
\subseteq \mathcal{P}[p',k']
\Leftrightarrow (m=p'-p \ge 0 \ \text{and} \ k+m\widehat{k}\subseteq k')
```
### Examples
Here are plots of the B-spline basis functions of the spaces `P1`, `P2`, `P3`.
```@example math_inclusive
P1 = BSplineSpace{1}(KnotVector([1,3,6,6]))
P2 = BSplineSpace{1}(KnotVector([1,3,5,6,6,8,9]))
P3 = BSplineSpace{2}(KnotVector([1,1,3,3,6,6,6,8,9]))
gr()
plot(
plot(P1; ylims=(0,1), label="P1"),
plot(P2; ylims=(0,1), label="P2"),
plot(P3; ylims=(0,1), label="P3"),
layout=(3,1),
link=:x
)
savefig("inclusive-issubset.png") # hide
nothing # hide
```

These spaces have the folllowing incusive relationships.
```@repl math_inclusive
P1 ⊆ P2
P1 ⊆ P3
P2 ⊆ P3, P3 ⊆ P2, P2 ⊆ P1, P3 ⊆ P1
```
## Definition on [`issqsubset`](@ref)
!!! tip "Def. Inclusive relation between B-spline spaces"
For non-degenerate B-spline spaces, the following relationship holds.
```math
\mathcal{P}[p,k]
\sqsubseteq\mathcal{P}[p',k']
\Leftrightarrow
\mathcal{P}[p,k]|_{[k_{p+1},k_{l-p}]}
\subseteq\mathcal{P}[p',k']|_{[k'_{p'+1},k'_{l'-p'}]}
```
### Examples
Here are plots of the B-spline basis functions of the spaces `P1`, `P2`, `P3`.
```@example math_inclusive
P1 = BSplineSpace{1}(KnotVector([1,3,6,6])) # Save definition as above
P4 = BSplineSpace{1}(KnotVector([1,3,5,6,8]))
P5 = BSplineSpace{2}(KnotVector([1,1,3,3,6,6,7,9]))
gr()
plot(
plot(P1; ylims=(0,1), label="P1"),
plot(P4; ylims=(0,1), label="P4"),
plot(P5; ylims=(0,1), label="P5"),
layout=(3,1),
link=:x
)
savefig("inclusive-issqsubset.png") # hide
nothing # hide
```

These spaces have the folllowing incusive relationships.
```@repl math_inclusive
P1 ⊑ P4
P1 ⊑ P5
P4 ⊑ P5, P5 ⊑ P4, P4 ⊑ P1, P5 ⊑ P1
```
## Change basis with a matrix
If ``\mathcal{P}[p,k] \subseteq \mathcal{P}[p',k']`` (or ``\mathcal{P}[p,k] \sqsubseteq \mathcal{P}[p',k']``), there exists a ``n \times n'`` matrix ``A`` which holds:
```math
\begin{aligned}
B_{(i,p,k)}
&=\sum_{j}A_{ij} B_{(j,p',k')} \\
n&=\dim(\mathcal{P}[p,k]) \\
n'&=\dim(\mathcal{P}[p',k'])
\end{aligned}
```
You can calculate the change of basis matrix ``A`` with [`changebasis`](@ref).
```@repl math_inclusive
A12 = changebasis(P1,P2)
A13 = changebasis(P1,P3)
```
```@example math_inclusive
plot(
plot([t->bsplinebasis₊₀(P1,i,t) for i in 1:dim(P1)], 1, 9, ylims=(0,1), legend=false),
plot([t->sum(A12[i,j]*bsplinebasis₊₀(P2,j,t) for j in 1:dim(P2)) for i in 1:dim(P1)], 1, 9, ylims=(0,1), legend=false),
plot([t->sum(A13[i,j]*bsplinebasis₊₀(P3,j,t) for j in 1:dim(P3)) for i in 1:dim(P1)], 1, 9, ylims=(0,1), legend=false),
layout=(3,1),
link=:x
)
savefig("inclusive-issubset-matrix.png") # hide
nothing # hide
```

```@repl math_inclusive
A14 = changebasis(P1,P4)
A15 = changebasis(P1,P5)
```
```@example math_inclusive
plot(
plot([t->bsplinebasis₊₀(P1,i,t) for i in 1:dim(P1)], 1, 9, ylims=(0,1), legend=false),
plot([t->sum(A14[i,j]*bsplinebasis₊₀(P4,j,t) for j in 1:dim(P4)) for i in 1:dim(P1)], 1, 9, ylims=(0,1), legend=false),
plot([t->sum(A15[i,j]*bsplinebasis₊₀(P5,j,t) for j in 1:dim(P5)) for i in 1:dim(P1)], 1, 9, ylims=(0,1), legend=false),
layout=(3,1),
link=:x
)
savefig("inclusive-issqsubset-matrix.png") # hide
nothing # hide
```

* [`changebasis_R`](@ref)
* Calculate the matrix based on ``P \subseteq P'``
* [`changebasis_I`](@ref)
* Calculate the matrix based on ``P \sqsubseteq P'``
* [`changebasis`](@ref)
* Return `changebasis_R` if ``P \subseteq P'``, otherwise return `changebasis_I` if ``P \sqsubseteq P'``.
## Expand spaces with additional knots or polynomial degree
There are some functions to expand spaces with additional knots or polynomial degree.
* [`expandspace_R`](@ref)
* [`expandspace_I`](@ref)
* [`expandspace`](@ref)
```@repl math_inclusive
P = BSplineSpace{2}(knotvector"21 113")
P_R = expandspace_R(P, Val(1), KnotVector([3.4, 4.2]))
P_I = expandspace_I(P, Val(1), KnotVector([3.4, 4.2]))
P ⊆ P_R
P ⊆ P_I
P ⊑ P_R
P ⊑ P_I
```
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 1450 | # Mathematical properties of B-spline
## Introduction
[B-spline](https://en.wikipedia.org/wiki/B-spline) is a mathematical object, and it has a lot of application. (e.g. Geometric representation: [NURBS](https://en.wikipedia.org/wiki/Non-uniform_rational_B-spline), Interpolation, Numerical analysis: [IGA](https://en.wikipedia.org/wiki/Isogeometric_analysis))
We will explain the mathematical definitions and properties of B-spline with Julia code in the following pages.
## Notice
Some of notations in this page are our original, but these are well-considered results.
## References
Most of this documentation around B-spline is self-contained.
If you want to learn more, the following resources are recommended.
* ["Geometric Modeling with Splines" by Elaine Cohen, Richard F. Riesenfeld, Gershon Elber](https://www.routledge.com/p/book/9780367447243)
* ["Spline Functions: Basic Theory" by Larry Schumaker](https://www.cambridge.org/core/books/spline-functions-basic-theory/843475201223F90091FFBDDCBF210BFB)
日本語の文献では以下がおすすめです。
* [スプライン関数とその応用 by 市田浩三, 吉本富士市](https://www.kyoiku-shuppan.co.jp/book/book/cate5/cate524/sho-463.html)
* [NURBS多様体による形状表現](https://hyrodium.github.io/ja/pdf/#NURBS%E5%A4%9A%E6%A7%98%E4%BD%93%E3%81%AB%E3%82%88%E3%82%8B%E5%BD%A2%E7%8A%B6%E8%A1%A8%E7%8F%BE)
* [BasicBSpline.jlを作ったので宣伝です!](https://zenn.dev/hyrodium/articles/5fb08f98d4a918)
* [B-spline入門(線形代数がすこし分かる人向け)](https://www.youtube.com/watch?v=GOdY02PA_WI)
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 3219 | # Knot vector
## Setup
```@example math_knotvector
using BasicBSpline
using Plots
using InteractiveUtils # hide
```
## Definition
!!! tip "Def. Knot vector"
A finite sequence
```math
k = (k_1, \dots, k_l)
```
is called **knot vector** if the sequence is broad monotonic increase, i.e. ``k_{i} \le k_{i+1}``.
There are four sutypes of [`AbstractKnotVector`](@ref); [`KnotVector`](@ref), [`UniformKnotVector`](@ref), [`SubKnotVector`](@ref), and [`EmptyKnotVector`](@ref).
```@repl math_knotvector
subtypes(AbstractKnotVector)
```
They can be constructed like this.
```@repl math_knotvector
KnotVector([1,2,3]) # `KnotVector` stores a vector with `Vector{<:Real}`
KnotVector(1:3)
UniformKnotVector(1:8) # `UniformKnotVector` stores a vector with `<:AbstractRange`
UniformKnotVector(8:-1:3)
view(KnotVector([1,2,3]), 2:3) # Efficient and lazy knot vector with `view`
EmptyKnotVector() # Sometimes `EmptyKnotVector` is useful.
EmptyKnotVector{Float64}()
```
There is a useful string macro [`@knotvector_str`](@ref) that generates a `KnotVector` instance.
```@repl math_knotvector
knotvector"1231123"
```
A knot vector can be visualized with `Plots.plot`.
```@repl math_knotvector
k1 = KnotVector([0.0, 1.5, 2.5, 5.5, 8.0, 9.0, 9.5, 10.0])
k2 = knotvector"1231123"
gr()
plot(k1; label="k1")
plot!(k2; label="k2", offset=0.5, ylims=(-0.1,1), xticks=0:10)
savefig("knotvector.png") # hide
nothing # hide
```

## Operations for knot vectors
### Setup and visualization
```@example math_knotvector
k1 = knotvector"1 2 1 11 2 31"
k2 = knotvector"113 1 12 2 32 1 1"
plot(k1; offset=-0.0, label="k1", xticks=1:18, yticks=nothing, legend=:right)
plot!(k2; offset=-0.2, label="k2")
plot!(k1+k2; offset=-0.4, label="k1+k2")
plot!(2k1; offset=-0.6, label="2k1")
plot!(unique(k1); offset=-0.8, label="unique(k1)")
plot!(unique(k2); offset=-1.0, label="unique(k2)")
plot!(unique(k1+k2); offset=-1.2, label="unique(k1+k2)")
savefig("knotvector_operations.png") # hide
nothing # hide
```

### Length of a knot vector
[`length(k::AbstractKnotVector)`](@ref)
```@repl math_knotvector
length(k1)
length(k2)
```
### Addition of knot vectors
Although a knot vector is **not** a vector in linear algebra, but we introduce **additional operator** ``+``.
[`Base.:+(k1::KnotVector{T}, k2::KnotVector{T}) where T`](@ref)
```@repl math_knotvector
k1 + k2
```
Note that the operator `+(::KnotVector, ::KnotVector)` is commutative.
This is why we choose the ``+`` sign.
We also introduce **product operator** ``\cdot`` for knot vector.
### Multiplication of knot vectors
[`*(m::Integer, k::AbstractKnotVector)`](@ref)
```@repl math_knotvector
2*k1
2*k2
```
### Generate a knot vector with unique elements
[`unique(k::AbstractKnotVector)`](@ref)
```@repl math_knotvector
unique(k1)
unique(k2)
```
### Inclusive relationship between knot vectors
[`Base.issubset(k::KnotVector, k′::KnotVector)`](@ref)
```@repl math_knotvector
unique(k1) ⊆ k1 ⊆ k2
k1 ⊆ k1
k2 ⊆ k1
```
### Count knots in a knot vector
[`countknots(k::AbstractKnotVector, t::Real)`](@ref)
```@repl math_knotvector
countknots(k1, 0.5)
countknots(k1, 1.0)
countknots(k1, 3.0)
```
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 4656 | # Rational B-spline manifold
## Setup
```@example math_rationalbsplinemanifold
using BasicBSpline
using StaticArrays
using LinearAlgebra
using Plots
```
[Non-uniform rational basis spline (NURBS)](https://en.wikipedia.org/wiki/Non-uniform_rational_B-spline) is also supported in BasicBSpline.jl package.
## Definition
Rational B-spline manifold is a parametric representation of a shape.
!!! tip "Def. Rational B-spline manifold"
For given ``d``-dimensional B-spline basis functions ``B_{(i^1,p^1,k^1)} \otimes \cdots \otimes B_{(i^d,p^d,k^d)}``, given points ``\bm{a}_{i^1 \dots i^d} \in V`` and real numbers ``w_{i^1 \dots i^d} > 0``, rational B-spline manifold is defined by the following equality:
```math
\bm{p}(t^1,\dots,t^d; \bm{a}_{i^1 \dots i^d}, w_{i^1 \dots i^d})
=\sum_{i^1,\dots,i^d}
\frac{(B_{(i^1,p^1,k^1)} \otimes \cdots \otimes B_{(i^d,p^d,k^d)})(t^1,\dots,t^d) w_{i^1 \dots i^d}}
{\sum\limits_{j^1,\dots,j^d}(B_{(j^1,p^1,k^1)} \otimes \cdots \otimes B_{(j^d,p^d,k^d)})(t^1,\dots,t^d) w_{j^1 \dots j^d}}
\bm{a}_{i^1 \dots i^d}
```
Where ``\bm{a}_{i^1,\dots,i^d}`` are called **control points**, and ``w_{i^1 \dots i^d}`` are called **weights**.
## Visualization with projection
A rational B-spline manifold in ``\mathbb{R}^d`` can be understanded as a projected B-spline manifold in ``\mathbb{R}^{d+1}``.
The next visuallzation this projection.
```@example math_rationalbsplinemanifold
# Define B-spline space
k = KnotVector([0.0, 1.5, 2.5, 5.0, 5.5, 8.0, 9.0, 9.5, 10.0])
P = BSplineSpace{3}(k)
# Define geometric parameters
a2 = [
SVector(-0.65, -0.20),
SVector(-0.20, +0.65),
SVector(-0.05, -0.10),
SVector(+0.75, +0.20),
SVector(+0.45, -0.65),
]
a3 = [SVector(p...,1) for p in a2]
w = [2.2, 1.3, 1.9, 2.1, 1.5]
# Define (rational) B-spline manifolds
R2 = RationalBSplineManifold(a2,w,(P,))
M3 = BSplineManifold(a3.*w,(P))
R3 = RationalBSplineManifold(a3,w,(P,))
# Plot
plotly()
pl2 = plot(R2, xlims=(-1,1), ylims=(-1,1); color=:blue, linewidth=3, aspectratio=1, label=false)
pl3 = plot(R3; color=:blue, linewidth=3, controlpoints=(markersize=2,), label="Rational B-spline curve")
plot!(pl3, M3; color=:red, linewidth=3, controlpoints=(markersize=2,), label="B-spline curve")
for p in a3.*w
plot!(pl3, [0,p[1]], [0,p[2]], [0,p[3]], color=:black, linestyle=:dash, label=false)
end
for t in range(domain(P), length=51)
p = M3(t)
plot!(pl3, [0,p[1]], [0,p[2]], [0,p[3]], color=:red, linestyle=:dash, label=false)
end
surface!(pl3, [-1,1], [-1,1], ones(2,2); color=:green, colorbar=false, alpha=0.5)
plot(pl2, pl3; layout=grid(1,2, widths=[0.35, 0.65]), size=(780,500))
savefig("rational_bspline_manifold_projection.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../rational_bspline_manifold_projection.html" style="width:100%;height:520px;"></object>
```
## Conic sections
One of the great aspect of rational B-spline manifolds is exact shape representation of circles.
This is achieved as conic sections.
### Arc
```@example math_rationalbsplinemanifold
gr()
p = 2
k = KnotVector([0,0,0,1,1,1])
P = BSplineSpace{p}(k)
t = 1 # angle in radians
a = [SVector(1,0), SVector(1,tan(t/2)), SVector(cos(t),sin(t))]
w = [1,cos(t/2),1]
M = RationalBSplineManifold(a,w,P)
plot([cosd(t) for t in 0:360], [sind(t) for t in 0:360]; xlims=(-1.1,1.1), ylims=(-1.1,1.1), aspectratio=1, label="circle", color=:gray, linestyle=:dash)
plot!(M; label="Rational B-spline curve")
savefig("geometricmodeling-arc.png") # hide
nothing # hide
```

### Circle
```@example math_rationalbsplinemanifold
gr()
p = 2
k = KnotVector([0,0,0,1,1,2,2,3,3,4,4,4])
P = BSplineSpace{p}(k)
a = [normalize(SVector(cosd(t), sind(t)), Inf) for t in 0:45:360]
w = [ifelse(isodd(i), √2, 1) for i in 1:9]
M = RationalBSplineManifold(a,w,P)
plot(M, xlims=(-1.2,1.2), ylims=(-1.2,1.2), aspectratio=1)
savefig("geometricmodeling-circle.png") # hide
nothing # hide
```

### Torus
```@example math_rationalbsplinemanifold
plotly()
R1 = 3
R2 = 1
A = push.(a, 0)
a1 = (R1+R2)*A
a5 = (R1-R2)*A
a2 = [p+R2*SVector(0,0,1) for p in a1]
a3 = [p+R2*SVector(0,0,1) for p in R1*A]
a4 = [p+R2*SVector(0,0,1) for p in a5]
a6 = [p-R2*SVector(0,0,1) for p in a5]
a7 = [p-R2*SVector(0,0,1) for p in R1*A]
a8 = [p-R2*SVector(0,0,1) for p in a1]
a = hcat(a1,a2,a3,a4,a5,a6,a7,a8,a1)
M = RationalBSplineManifold(a,w*w',P,P)
plot(M)
savefig("geometricmodeling-torus.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../geometricmodeling-torus.html" style="width:100%;height:420px;"></object>
```
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 1298 | # Refinement
## Setup
```@example math_refinement
using BasicBSpline
using BasicBSplineExporter
using StaticArrays
using Plots
```
## Example
### Define original manifold
```@example math_refinement
p = 2 # degree of polynomial
k = KnotVector(1:8) # knot vector
P = BSplineSpace{p}(k) # B-spline space
rand_a = [SVector(rand(), rand()) for i in 1:dim(P), j in 1:dim(P)]
a = [SVector(2*i-6.5, 2*j-6.5) for i in 1:dim(P), j in 1:dim(P)] + rand_a # random
M = BSplineManifold(a,(P,P)) # Define B-spline manifold
gr()
plot(M)
savefig("refinement_2dim_original.png") # hide
nothing # hide
```

### h-refinement
Insert additional knots to knot vector without changing the shape.
```@repl math_refinement
k₊ = (KnotVector([3.3,4.2]), KnotVector([3.8,3.2,5.3])) # additional knot vectors
M_h = refinement(M, k₊) # refinement of B-spline manifold
plot(M_h)
savefig("refinement_2dim_h.png") # hide
nothing # hide
```

### p-refinement
Increase the polynomial degree of B-spline manifold without changing the shape.
```@repl math_refinement
p₊ = (Val(1), Val(2)) # additional degrees
M_p = refinement(M, p₊) # refinement of B-spline manifold
plot(M_p)
savefig("refinement_2dim_p.png") # hide
nothing # hide
```

| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 1168 | # BasicBSplineExporter.jl
[BasicBSplineExporter.jl](https://github.com/hyrodium/BasicBSplineExporter.jl) supports export `BasicBSpline.BSplineManifold{Dim,Deg,<:StaticVector}` to:
* PNG image (`.png`)
* SVG image (`.png`)
* POV-Ray mesh (`.inc`)
## Installation
```julia
] add BasicBSplineExporter
```
## First example
```@example
using BasicBSpline
using BasicBSplineExporter
using StaticArrays
p = 2 # degree of polynomial
k1 = KnotVector(1:8) # knot vector
k2 = KnotVector(rand(7))+(p+1)*KnotVector([1])
P1 = BSplineSpace{p}(k1) # B-spline space
P2 = BSplineSpace{p}(k2)
n1 = dim(P1) # dimension of B-spline space
n2 = dim(P2)
a = [SVector(2i-6.5+rand(),1.5j-6.5+rand()) for i in 1:dim(P1), j in 1:dim(P2)] # random generated control points
M = BSplineManifold(a,(P1,P2)) # Define B-spline manifold
save_png("BasicBSplineExporter_2dim.png", M) # save image
```

## Other examples
Here are some images rendared with POV-Ray.



See [`BasicBSplineExporter.jl/test`](https://github.com/hyrodium/BasicBSplineExporter.jl/tree/main/test) for more examples.
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"MIT"
] | 0.11.2 | f579babb93fee8d881afbd998daf2291fda45c63 | docs | 1699 | # PlotlyJS.jl
## Cardioid
```@example
using BasicBSpline
using BasicBSplineFitting
using StaticArrays
using PlotlyJS
f(t) = SVector((1+cos(t))*cos(t),(1+cos(t))*sin(t))
p = 3
k = KnotVector(range(0,2π,15)) + p * KnotVector([0,2π]) + 2 * KnotVector([π])
P = BSplineSpace{p}(k)
a = fittingcontrolpoints(f, P)
M = BSplineManifold(a, P)
ts = range(0,2π,250)
xs_a = getindex.(a,1)
ys_a = getindex.(a,2)
xs_f = getindex.(M.(ts),1)
ys_f = getindex.(M.(ts),2)
fig = Plot(scatter(x=xs_a, y=ys_a, name="control points", line_color="blue", marker_size=8))
addtraces!(fig, scatter(x=xs_f, y=ys_f, name="B-spline curve", mode="lines", line_color="red"))
relayout!(fig, width=500, height=500)
savefig(fig,"cardioid.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../cardioid.html" style="width:100%;height:550px;"></object>
```
## Helix
```@example
using BasicBSpline
using BasicBSplineFitting
using StaticArrays
using PlotlyJS
f(t) = SVector(cos(t),sin(t),t)
p = 3
k = KnotVector(range(0,6π,15)) + p * KnotVector([0,6π])
P = BSplineSpace{p}(k)
a = fittingcontrolpoints(f, P)
M = BSplineManifold(a, P)
ts = range(0,6π,250)
xs_a = getindex.(a,1)
ys_a = getindex.(a,2)
zs_a = getindex.(a,3)
xs_f = getindex.(M.(ts),1)
ys_f = getindex.(M.(ts),2)
zs_f = getindex.(M.(ts),3)
fig = Plot(scatter3d(x=xs_a, y=ys_a, z=zs_a, name="control points", line_color="blue", marker_size=8))
addtraces!(fig, scatter3d(x=xs_f, y=ys_f, z=zs_f, name="B-spline curve", mode="lines", line_color="red"))
relayout!(fig, width=500, height=500)
savefig(fig,"helix.html") # hide
nothing # hide
```
```@raw html
<object type="text/html" data="../helix.html" style="width:100%;height:550px;"></object>
```
| BasicBSpline | https://github.com/hyrodium/BasicBSpline.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 14023 | using Test, AdmittanceModels
using ProgressMeter: @showprogress
using LinearAlgebra: norm, normalize
# set to false to create the figures in the paper, though it will take longer
run_fast = true
# to save data so figures in the paper can be created, set to true
write_data = false
# to make plots and print information set to true
show_results = false
if write_data
using DataFrames, CSV, NPZ
output_folder = joinpath(@__DIR__, "hybridization_results")
try
mkdir(output_folder)
catch SystemError
end
end
if show_results
using PlotlyJS
end
#######################################################
# Parameters
#######################################################
begin
ν = 1.2e8 # propagation_speed
Z0 = 50.0 # characteristic_impedance
δ = 50e-6 # discretization length
pfilter_num = 202
pfilter_len = pfilter_num * δ # purcell filter length
pfilter_res_0_coupler_num = floor(Int, pfilter_num/2) - 5
pfilter_res_coupler_0_len = pfilter_res_0_coupler_num * δ # position of res 0 coupler on filter
pfilter_res_1_coupler_num = floor(Int, pfilter_num/2) + 5
pfilter_res_coupler_1_len = pfilter_res_1_coupler_num * δ # position of res 1 coupler on filter
res_0_num = 102
res_0_len = res_0_num * δ
res_1_num = 101
res_1_len = res_1_num * δ
res_coupler_num = 16
res_coupler_len = res_coupler_num * δ # res coupler length from open
capacitance_0 = 12e-15 # res 0 - purcell filter capacitance
capacitance_1 = 12e-15 # res 1 - purcell filter capacitance
end
#######################################################
# Two resonators and Purcell filter
# Circuit version
#######################################################
begin
pfilter_circ = Circuit(TransmissionLine(["p/short_0", "p/short_1"], ν, Z0, pfilter_len, δ=δ),
"p/", [pfilter_num])
res_0_circ = Circuit(TransmissionLine(["r0/open", "r0/short"], ν, Z0, res_0_len, δ=δ),
"r0/", [res_0_num])
res_1_circ = Circuit(TransmissionLine(["r1/open", "r1/short"], ν, Z0, res_1_len, δ=δ),
"r1/", [res_1_num])
pfilter_res_0_coupler_name = "p/$(1+pfilter_res_0_coupler_num)"
res_0_coupler_name = "r0/$(1+res_coupler_num)"
pfilter_res_1_coupler_name = "p/$(1+pfilter_res_1_coupler_num)"
res_1_coupler_name = "r1/$(1+res_coupler_num)"
capacitor_0 = Circuit(SeriesComponent(pfilter_res_0_coupler_name, res_0_coupler_name, 0, 0, capacitance_0))
capacitor_1 = Circuit(SeriesComponent(pfilter_res_1_coupler_name, res_1_coupler_name, 0, 0, capacitance_1))
circ = cascade_and_unite(pfilter_circ, res_0_circ, res_1_circ, capacitor_0, capacitor_1)
ground = AdmittanceModels.ground
circ = unite_vertices(circ, ground, "p/short_0", "p/short_1", "r0/short", "r1/short")
input_output(stub_num) = ("p/$(1+stub_num)", "p/$(pfilter_num-stub_num+1)")
end
function bbox_from_circ(stub_num::Int, ω::Vector{<:Real})
input, output = input_output(stub_num)
pso = PSOModel(circ, [(input, ground), (output, ground)], ["in", "out"])
return Blackbox(ω, pso) |> canonical_gauge
end
#######################################################
# Two resonators and Purcell filter
# Admittance model version
#######################################################
function casc_from_model(stub_num::Int, discretization::Real=δ)
pfilter = TransmissionLine(["p/short_0", "in", "p/res_0_coupler", "p/middle",
"p/res_1_coupler", "out", "p/short_1"],
ν, Z0, pfilter_len, locations=[stub_num * δ, pfilter_res_coupler_0_len,
.5 * pfilter_len, pfilter_res_coupler_1_len,
pfilter_len - stub_num * δ], δ=discretization)
res_0 = TransmissionLine(["r0/open", "r0/pfilter_coupler", "r0/short"],
ν, Z0, res_0_len, locations=[res_coupler_len], δ=discretization)
res_1 = TransmissionLine(["r1/open", "r1/pfilter_coupler", "r1/short"],
ν, Z0, res_1_len, locations=[res_coupler_len], δ=discretization)
capacitor_0 = SeriesComponent("p/res_0_coupler", "r0/pfilter_coupler", 0, 0, capacitance_0)
capacitor_1 = SeriesComponent("p/res_1_coupler", "r1/pfilter_coupler", 0, 0, capacitance_1)
components = [pfilter, res_0, res_1, capacitor_0, capacitor_1]
operations = [short_ports => ["p/short_0", "p/short_1", "r0/short", "r1/short"]]
return Cascade(components, operations)
end
function bbox_from_pso(stub_num::Int, ω::Vector{<:Real}, discretization::Real=δ)
casc = casc_from_model(stub_num, discretization)
push!(casc.operations, open_ports_except => ["in", "out"])
return Blackbox(ω, PSOModel(casc)) |> canonical_gauge
end
function bbox_from_bbox(stub_num::Int, ω::Vector{<:Real})
casc = casc_from_model(stub_num)
push!(casc.operations, open_ports_except => ["in", "out"])
return Blackbox(ω, casc) |> canonical_gauge
end
#######################################################
# Compare them
#######################################################
begin
ω_circ = collect(range(5.4, stop=6.4, length=run_fast ? 100 : 2000)) * 2π * 1e9
bbox_circ_10 = bbox_from_circ(10, ω_circ)
bbox_circ_30 = bbox_from_circ(30, ω_circ)
bbox_pso_10 = bbox_from_pso(10, ω_circ)
bbox_pso_30 = bbox_from_pso(30, ω_circ)
bbox_bbox_10 = bbox_from_bbox(10, ω_circ)
bbox_bbox_30 = bbox_from_bbox(30, ω_circ)
end
s21(bbox) = [x[1,2] for x in scattering_matrices(bbox, [Z0, Z0])]
freqs = ω_circ/(2π)
if write_data
df = DataFrame(freqs = freqs,
circ_S_p5 = s21(bbox_circ_10),
circ_S_1p5 = s21(bbox_circ_30),
pso_S_p5 = s21(bbox_pso_10),
pso_S_1p5 = s21(bbox_pso_30),
bbox_S_p5 = s21(bbox_bbox_10),
bbox_S_1p5 = s21(bbox_bbox_30))
CSV.write(joinpath(output_folder, "S12.csv"), df)
end
if show_results
plot([scatter(x=freqs/1e6, y=abs.(s21(bbox_circ_10)), name="0.5mm circ"),
scatter(x=freqs/1e6, y=abs.(s21(bbox_circ_30)), name="1.5mm circ"),
scatter(x=freqs/1e6, y=abs.(s21(bbox_pso_10)), name="0.5mm pso"),
scatter(x=freqs/1e6, y=abs.(s21(bbox_pso_30)), name="1.5mm pso"),
scatter(x=freqs/1e6, y=abs.(s21(bbox_bbox_10)), name="0.5mm bbox", line_dash="dash"),
scatter(x=freqs/1e6, y=abs.(s21(bbox_bbox_30)), name="1.5mm bbox", line_dash="dash")],
Layout(xaxis_title="frequency", yaxis_title="|S21|"))
end
if show_results
abs_diff_10 = abs.(s21(bbox_circ_10) .- s21(bbox_bbox_10))
abs_diff_30 = abs.(s21(bbox_circ_30) .- s21(bbox_bbox_30))
plot([scatter(x=ω_circ/(2π*1e6), y=abs_diff_10, name="0.5mm error"),
scatter(x=ω_circ/(2π*1e6), y=abs_diff_30, name="1.5mm error")],
Layout(xaxis_title="frequency", yaxis_title="|S21_circ - S21_bbox|"))
end
if show_results
density(m) = count(!iszero, m)/(size(m,1) * size(m,2))
casc = casc_from_model(10, δ)
push!(casc.operations, open_ports_except => ["in", "out"])
println("pso matrix densities: $(map(density, get_Y(PSOModel(casc))))")
end
#######################################################
# All three models now match so we can use the circuit
# one for making mode plots
#######################################################
function resistor_circ(stub_num::Int)
input, output = input_output(stub_num)
resistor_0 = Circuit(ParallelComponent(input, 0, 1/Z0, 0))
resistor_1 = Circuit(ParallelComponent(output, 0, 1/Z0, 0))
return cascade_and_unite(circ, resistor_0, resistor_1)
end
begin
pfilter_vertices = pfilter_circ.vertices[3:end-1]
res_0_vertices = res_0_circ.vertices[2:end-1]
res_1_vertices = res_1_circ.vertices[2:end-1]
vertices = [pfilter_vertices; res_0_vertices; res_1_vertices]
tree = SpanningTree(ground, [(v, ground) for v in vertices])
port_edges = [("p/$(floor(Int, (2+pfilter_num)/2))", ground),
("r0/open", ground),
("r1/open", ground)]
ports = ["pfilter_max", "res_0_max", "res_1_max"]
mode_names = ["purcell filter", "resonator 0", "resonator 1"]
end
function resistor_pso(stub_num::Int)
return PSOModel(resistor_circ(stub_num), port_edges, ports, tree)
end
function eigenmodes(stub_num::Int)
pso = resistor_pso(stub_num)
eigenvalues, eigenvectors = lossy_modes_dense(pso, min_freq=4e9, max_freq=8e9)
port_inds = ports_to_indices(pso, ports)
mode_inds = AdmittanceModels.match_vectors(get_P(pso)[:, port_inds], eigenvectors)
return eigenvalues[mode_inds], eigenvectors[:,mode_inds]
end
begin
stub_nums = run_fast ? (1:10:60) : (1:60)
eigenmodes_arr = @showprogress [eigenmodes(i) for i in stub_nums]
complex_freqs_arr = hcat([p[1] for p in eigenmodes_arr]...)
eigenvectors = [p[2] for p in eigenmodes_arr]
end
if write_data
df = DataFrame(Dict(Symbol(mode_names[i]) => complex_freqs_arr[i,:] for i in 1:3))
df[:stub_len] = stub_nums * δ
CSV.write(joinpath(output_folder, "complex_frequencies.csv"), df)
df = DataFrame(transpose(hcat(eigenvectors...)))
labels = vcat([[(i, m) for m in mode_names] for i in stub_nums]...)
df[:stub_len] = [l[1] * δ for l in labels]
df[:mode_name] = [l[2] for l in labels]
CSV.write(joinpath(output_folder, "eigenvectors.csv"), df)
end
freq_func(s) = imag(s)/(2π)
decay_func(s) = -2 * real(s)/(2π)
T1_func(s) = 1/(-2 * real(s))
if show_results
frequency_plots = [scatter(x=stub_nums * δ * 1e3, y=freq_func.(complex_freqs_arr[i, :])/1e9,
name="$(mode_names[i])", mode="lines+markers") for i in 1:3]
plot(frequency_plots, Layout(xaxis_title="stub length [mm]", yaxis_title="frequency [GHz]",
title="Frequencies"))
end
if show_results
decay_plots = [scatter(x=stub_nums * δ * 1e3, y=decay_func.(complex_freqs_arr[i, :]),
name="$(mode_names[i])", mode="lines+markers") for i in 1:3]
plot(decay_plots, Layout(xaxis_title="stub length [mm]", yaxis_title="decay rate [Hz]",
yaxis_type="log", title="Decay rates"))
end
function spatial_profile(v)
w = [0; v[1:length(pfilter_vertices)]; 0;
v[length(pfilter_vertices)+1:length(pfilter_vertices)+length(res_0_vertices)]; 0;
v[length(pfilter_vertices)+length(res_0_vertices)+1:end]; 0]
return normalize(abs.(w))
end
mode_1 = run_fast ? 2 : 10
mode_2 = run_fast ? 4 : 30
function spatial_plot(mode_num::Int)
plot([scatter(y=spatial_profile(eigenvectors[mode_1][:, mode_num]), name= "mode 1"),
scatter(y=spatial_profile(eigenvectors[mode_2][:, mode_num]), name= "mode 2")],
Layout(title=mode_names[mode_num]))
end
if show_results
spatial_plot(1)
end
if show_results
spatial_plot(2)
end
if show_results
spatial_plot(3)
end
if write_data
df = DataFrame(Dict(Symbol(mode_names[mode_num]) => spatial_profile(eigenvectors[mode_1][:, mode_num])
for mode_num in 1:3))
CSV.write(joinpath(output_folder, "mode_profile_p5.csv"), df)
df = DataFrame(Dict(Symbol(mode_names[mode_num]) => spatial_profile(eigenvectors[mode_2][:, mode_num])
for mode_num in 1:3))
CSV.write(joinpath(output_folder, "mode_profile_1p5.csv"), df)
end
function regional_support(v)
x = norm(v[1:length(pfilter_vertices)])
y = norm(v[length(pfilter_vertices)+1:length(pfilter_vertices)+length(res_0_vertices)])
z = norm(v[length(pfilter_vertices)+length(res_0_vertices)+1:end])
return normalize([x, y, z]).^2
end
begin
support_vects = [[regional_support(vects[:, i]) for vects in eigenvectors] for i in 1:3]
standard_basis = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
hybridizations = [[norm(v - standard_basis[i],2) for v in support_vects[i]] for i in 1:3]
get_x(v) = v[2] + v[3]/2
get_y(v) = v[3] * sqrt(3)/2
xs = [get_x.(support_vects[i]) for i in 1:3]
ys = [get_y.(support_vects[i]) for i in 1:3]
end
if show_results
plot([scatter(x=stub_nums * δ * 1e3, y=hybridizations[i], name=mode_names[i], mode="lines+markers") for i in 1:3],
Layout(xaxis_title="stub length [mm]", yaxis_title="Distance"))
end
if show_results
plot([scatter(x=xs[i], y=ys[i], name=mode_names[i]) for i in 1:3],
Layout(xaxis_range=[0,1], yaxis_range=[0,sqrt(3)/2]))
end
if write_data
df = DataFrame(Dict(Symbol(mode_names[i]) => hybridizations[i] for i in 1:3))
df[:stub_len] = stub_nums * δ
CSV.write(joinpath(output_folder, "hybridization_curves.csv"), df)
df = DataFrame(Dict(Symbol(mode_names[i]) => xs[i] for i in 1:3))
CSV.write(joinpath(output_folder, "hybridization_scatter_x.csv"), df)
df = DataFrame(Dict(Symbol(mode_names[i]) => ys[i] for i in 1:3))
CSV.write(joinpath(output_folder, "hybridization_scatter_y.csv"), df)
end
#######################################################
# Convergence
#######################################################
function eigenvals(stub_num::Int, discretization::Real)
casc = casc_from_model(stub_num, discretization)
push!(casc.components, ParallelComponent("in", 0, 1/Z0, 0))
push!(casc.components, ParallelComponent("out", 0, 1/Z0, 0))
pso = PSOModel(casc)
eigenvalues, eigenvectors = lossy_modes_dense(pso, min_freq=4e9, max_freq=8e9)
port_inds = ports_to_indices(pso, "p/middle", "r0/open", "r1/open")
mode_inds = AdmittanceModels.match_vectors(get_P(pso)[:, port_inds], eigenvectors)
return eigenvalues[mode_inds]
end
if !run_fast
discretizations = [60e-6, 50e-6, 40e-6]
eigenvals_arr = [@showprogress [eigenvals(i, d) for i in stub_nums] for d in discretizations]
if write_data
npzwrite(joinpath(output_folder, "convergence_eigenvalues.npy"),
cat([hcat(eigenvals_arr[i]...) for i in 1:length(eigenvals_arr)]..., dims=3))
end
end
#######################################################
# Declare victory
#######################################################
@testset "hybridization" begin
@test true
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 13269 | using Test, AdmittanceModels
using ProgressMeter: @showprogress
# set to false to create the figures in the paper, though it will take longer
run_fast = true
# to save data so figures in the paper can be created, set to true
write_data = false
# to make plots and print information set to true
show_results = false
if write_data
using DataFrames, CSV, NPZ
output_folder = joinpath(@__DIR__, "radiative_loss_results")
try
mkdir(output_folder)
catch SystemError
end
end
if show_results
using PlotlyJS
end
#######################################################
# Shared parameters
#######################################################
begin
ν = 1.2e8 # propagation_speed
Z0 = 50.0 # characteristic_impedance
δ = run_fast ? 200e-6 : 50e-6 # discretization length
cg = 7e-15 # qubit - resonator coupling capacitance
cj = 100e-15 # qubit capacitance
lj = 10e-9 # qubit inductance
x0 = 800e-6 # coupler location on resonator
end
#######################################################
# Transmission line model
#######################################################
begin
L = .00499171 # resonator length
F = 2e-3 # length of tline
y0 = F/2 # coupler location on tline
cc = 10e-15 # resonator - tline coupling capacitance
tline_params = (L=L, x0=x0, F=F, y0=y0, cc=cc)
end
function create_tline_cascade(δ::Real)
resonator = TransmissionLine(["qr_coupler", "er_coupler_0", "mode_2_max", "short"],
ν, Z0, L, locations=[x0, 2*L/3], δ=δ)
environment = TransmissionLine(["in", "er_coupler_1", "out"],
ν, Z0, F, locations=[y0], δ=δ)
er_coupler = SeriesComponent("er_coupler_0", "er_coupler_1", 0, 0, cc)
qr_coupler = SeriesComponent("qubit", "qr_coupler", 0, 0, cg)
components = [resonator, environment, er_coupler, qr_coupler]
return Cascade(components, [short_ports => ["short"]])
end
tline_cascade = create_tline_cascade(δ)
#######################################################
# Purcell filter model
#######################################################
begin
L = .00503299# resonator length
F = .0102522 # length of pfilter
y0 = 5e-3 # coupler location on pfilter
cc = 2.6e-15 # resonator - pfilter coupling capacitance
st = 880e-6 # pfilter stub length
pfilter_params = (L=L, x0=x0, F=F, y0=y0, cc=cc, st=st)
end
function create_pfilter_cascade(δ::Real)
resonator = TransmissionLine(["qr_coupler", "er_coupler_0", "mode_2_max", "short 1"],
ν, Z0, L, locations=[x0, 2*L/3], δ=δ)
environment = TransmissionLine(["short 2", "in", "er_coupler_1", "out", "short 3"],
ν, Z0, F, locations=[st, y0, F-st], δ=δ)
er_coupler = SeriesComponent("er_coupler_0", "er_coupler_1", 0, 0, cc)
qr_coupler = SeriesComponent("qubit", "qr_coupler", 0, 0, cg)
components = [resonator, environment, er_coupler, qr_coupler]
return Cascade(components, [short_ports => ["short 1", "short 2", "short 3"]])
end
pfilter_cascade = create_pfilter_cascade(δ)
#######################################################
# Scattering parameters with qubit
#######################################################
begin
factor = run_fast ? 2 : 10
ω = [range(1.5, stop=5.89, length=10 * factor);
range(5.89, stop=5.92, length=60 * factor); # first mode for both
range(5.92, stop=17.69, length=10 * factor);
range(17.69, stop=17.72, length=100 * factor); # 2nd mode pfilter
range(17.72, stop=17.76, length=10 * factor);
range(17.76, stop=17.85, length=100 * factor); # 2nd mode tline
range(17.85, stop=25, length=10 * factor)] * 2π * 1e9
qubit = ParallelComponent("qubit", 1/lj, 0, cj)
components = [tline_cascade.components; qubit]
operations = [tline_cascade.operations; open_ports_except => ["in", "out"]]
tline_casc = Cascade(components, operations)
tline_pso_bbox = Blackbox(ω, PSOModel(tline_casc))
tline_pso_bbox_s = [x[1,2] for x in scattering_matrices(tline_pso_bbox, [Z0, Z0])]
tline_bbox = Blackbox(ω, tline_casc)
tline_bbox_s = [x[1,2] for x in scattering_matrices(tline_bbox, [Z0, Z0])]
components = [pfilter_cascade.components; qubit]
operations = [pfilter_cascade.operations; open_ports_except => ["in", "out"]]
pfilter_casc = Cascade(components, operations)
pfilter_pso_bbox = Blackbox(ω, PSOModel(pfilter_casc))
pfilter_pso_bbox_s = [x[1,2] for x in scattering_matrices(pfilter_pso_bbox, [Z0, Z0])]
pfilter_bbox = Blackbox(ω, pfilter_casc)
pfilter_bbox_s = [x[1,2] for x in scattering_matrices(pfilter_bbox, [Z0, Z0])]
end
if write_data
CSV.write(joinpath(output_folder, "S12.csv"), DataFrame(
freqs = ω/(2π),
tline_S = tline_pso_bbox_s,
pfilter_S = pfilter_pso_bbox_s))
end
if show_results
plot([scatter(x=ω/(2π*1e9), y=abs.(tline_pso_bbox_s), name="tline pso"),
scatter(x=ω/(2π*1e9), y=abs.(tline_bbox_s), name="tline bbox"),
scatter(x=ω/(2π*1e9), y=abs.(pfilter_pso_bbox_s), name="pfilter pso", line_dash="dash"),
scatter(x=ω/(2π*1e9), y=abs.(pfilter_bbox_s), name="pfilter bbox", line_dash="dash")],
Layout(xaxis_title="frequency", yaxis_title="|S21|"))
end
#######################################################
# Find effective capacitance
#######################################################
resistors = [ParallelComponent(name, 0, 1/Z0, 0) for name in ["in", "out"]]
function model_and_admittances(ω::Vector{<:Real}, casc::Cascade)
components = [casc.components; resistors]
operations = [casc.operations; [open_ports_except => ["qubit"]]]
bbox = Blackbox(ω, Cascade(components, operations)) |> canonical_gauge
Y = [x[1,1] for x in admittance_matrices(bbox)]
pso = PSOModel(Cascade(components, casc.operations))
return pso, Y
end
begin
fit_ω = collect(range(0.1e9, stop=2.5e9, length=run_fast ? 100 : 1000)) * 2π
plot_ω = collect(range(0.01e9, stop=10e9, length=run_fast ? 100 : 1000)) * 2π
linreg(x, y) = hcat(fill!(similar(x), 1), x) \ y
tline_pso, Y = model_and_admittances(fit_ω, tline_cascade)
_, tline_slope = linreg(fit_ω, imag.(Y))
_, tline_Y = model_and_admittances(plot_ω, tline_cascade)
_, Y = model_and_admittances(fit_ω, pfilter_cascade)
_, pfilter_slope = linreg(fit_ω, imag.(Y))
pfilter_pso, pfilter_Y = model_and_admittances(plot_ω, tline_cascade)
tline_eff_capacitance = tline_slope + cj
pfilter_eff_capacitance = pfilter_slope + cj
end
if show_results
println("tline_slope: $tline_slope, pfilter_slope: $pfilter_slope, cg: $cg")
println("tline_eff_capacitance: $tline_eff_capacitance, pfilter_eff_capacitance: $pfilter_eff_capacitance")
density(m) = count(!iszero, m)/(size(m,1) * size(m,2))
println("tline matrix densities: $(map(density, get_Y(tline_pso)))")
println("pfilter matrix densities: $(map(density, get_Y(tline_pso)))")
end
if write_data
CSV.write(joinpath(output_folder, "Y.csv"), DataFrame(
freqs = plot_ω/(2π),
tline_Y = tline_Y,
pfilter_Y = pfilter_Y))
end
if show_results
plot([scatter(x=plot_ω/(2π), y=imag.(tline_Y), name="imag(tline_Y)"),
scatter(x=plot_ω/(2π), y=imag.(pfilter_Y), name="imag(pfilter_Y)", line_dash="dash"),
scatter(x=plot_ω/(2π), y=cg * plot_ω, name="cg * ω")],
Layout(xaxis_title="frequency", yaxis_title="imag(Y)", yaxis_range=[-.001, .002]))
end
#######################################################
# Eigenmodes
#######################################################
function get_bare_qubit_freqs(num_points)
f0 = ν/(4 * tline_params.L)
f1 = ν/(2 * (tline_params.L - tline_params.x0))
f2 = 3 * f0
_eps = f0/10
freqs_0 = range(1.5e9, stop=f0-_eps, length=num_points)
freqs_1 = range(f0-_eps, stop=f0+_eps, length=num_points)
freqs_2 = range(f0+_eps, stop=f1-_eps, length=num_points)
freqs_3 = range(f1-_eps, stop=f1+_eps, length=num_points)
freqs_4 = range(f1+_eps, stop=f2-_eps, length=num_points)
freqs_5 = range(f2-_eps, stop=f2+_eps, length=num_points)
freqs_6 = range(f2+_eps, stop=25e9, length=num_points)
return [freqs_0; freqs_1; freqs_2; freqs_3; freqs_4; freqs_5; freqs_6]
end
function eigenmodes(lj::Real, pso::PSOModel)
qubit = ParallelComponent("qubit", 1/lj, 0, cj)
pso_full = cascade_and_unite(pso, PSOModel(qubit))
eigenvalues, eigenvectors = lossy_modes_dense(pso_full, min_freq=1e9, max_freq=25e9)
port_inds = ports_to_indices(pso_full, "qubit", "qr_coupler", "mode_2_max")
mode_inds = AdmittanceModels.match_vectors(get_P(pso_full)[:, port_inds], eigenvectors)
return eigenvalues[mode_inds]
end
function eigenmodes(casc::Cascade, eff_capacitance::Real, ω::Vector{<:Real})
pso, Y = model_and_admittances(ω, casc)
T1_Y = eff_capacitance ./ real.(Y)
ljs = (1 ./ (ω .^2 * eff_capacitance))
if show_results
println("dimension: $(size(pso.K,1)), num_ljs: $(length(ljs))")
end
λ_lists = @showprogress [eigenmodes(lj, pso) for lj in ljs]
λs = cat(λ_lists..., dims=2)
return λs, T1_Y
end
ω = 2π * get_bare_qubit_freqs(run_fast ? 10 : 120)
tline_λs, tline_T1_Y = eigenmodes(tline_cascade, tline_eff_capacitance, ω)
if show_results
plot([scatter(x=ω/(2π*1e9), y=imag.(tline_λs[i,:])/(2π*1e9), name="$i",
mode="lines+markers") for i in 1:size(tline_λs,1)],
Layout(xaxis_title="bare qubit freq", yaxis_title="mode freq", title="tline freqs"))
end
if show_results
traces = [scatter(x=ω/(2π*1e9), y=-.5 ./ real.(tline_λs[i,:]), name="$i",
mode="lines+markers") for i in 1:size(tline_λs,1)]
push!(traces, scatter(x=ω/(2π*1e9), y=tline_T1_Y, name="C/Re[Y]", mode="lines+markers"))
plot(traces, Layout(xaxis_title="bare qubit freq", yaxis_title="T1", yaxis_type="log", title="tline T1s"))
end
if write_data
df = DataFrame(transpose(tline_λs))
df[:freqs] = ω/(2π)
df[:T1_Y] = tline_T1_Y
CSV.write(joinpath(output_folder, "tline_eigenmodes.csv"), df)
end
pfilter_λs, pfilter_T1_Y = eigenmodes(pfilter_cascade, pfilter_eff_capacitance, ω)
if show_results
plot([scatter(x=ω/(2π*1e9), y=imag.(pfilter_λs[i,:])/(2π*1e9), name="$i",
mode="lines+markers") for i in 1:size(pfilter_λs,1)],
Layout(xaxis_title="bare qubit freq", yaxis_title="mode freq", title="pfilter freqs"))
end
if show_results
traces = [scatter(x=ω/(2π*1e9), y=-.5 ./ real.(pfilter_λs[i,:]), name="$i",
mode="lines+markers") for i in 1:size(pfilter_λs,1)]
push!(traces, scatter(x=ω/(2π*1e9), y=pfilter_T1_Y, name="C/Re[Y]", mode="lines+markers"))
plot(traces, Layout(xaxis_title="bare qubit freq", yaxis_title="T1", yaxis_type="log", title="pfilter T1s"))
end
if write_data
df = DataFrame(transpose(pfilter_λs))
df[:freqs] = ω/(2π)
df[:T1_Y] = pfilter_T1_Y
CSV.write(joinpath(output_folder, "pfilter_eigenmodes.csv"), df)
end
#######################################################
# Convergence
#######################################################
freqs_func(vects, mode_ind, δ_ind) = imag.(vects[δ_ind][mode_ind,:])/(2π*1e9)
T1_func(vects, mode_ind, δ_ind) = -.5 ./ real.(vects[δ_ind][mode_ind,:])
function diff(vects, func, mode_ind, δ_ind_bad, δ_ind_good)
f_bad = func(vects, mode_ind, δ_ind_bad)
f_good = func(vects, mode_ind, δ_ind_good)
return abs.((f_bad - f_good) ./ f_good) * 100
end
if !run_fast
δs = [60, 50, 40] * 1e-6
tline_λ_vects = [eigenmodes(create_tline_cascade(δ), tline_eff_capacitance, ω)[1] for δ in δs]
if write_data
npzwrite(joinpath(output_folder, "tline_eigenvalues.npy"), cat(tline_λ_vects..., dims=3))
end
if show_results
plot([scatter(x=ω/(2π*1e9), y=diff(tline_λ_vects, freqs_func, i, 1, 3), name="$i", mode="markers") for i in 1:3],
Layout(xaxis_title="bare qubit freq", yaxis_title="% error", yaxis_type="log", title="tline freqs"))
end
if show_results
plot([scatter(x=ω/(2π*1e9), y=diff(tline_λ_vects, T1_func, i, 2, 3), name="$i", mode="markers") for i in 1:3],
Layout(xaxis_title="bare qubit freq", yaxis_title="% error", yaxis_type="log", title="tline freqs"))
end
pfilter_λ_vects = [eigenmodes(create_pfilter_cascade(δ), pfilter_eff_capacitance, ω)[1] for δ in δs]
if write_data
npzwrite(joinpath(output_folder, "pfilter_eigenvalues.npy"), cat(pfilter_λ_vects..., dims=3))
end
if show_results
plot([scatter(x=ω/(2π*1e9), y=diff(pfilter_λ_vects, freqs_func, i, 2, 3), name="$i", mode="markers") for i in 1:3],
Layout(xaxis_title="bare qubit freq", yaxis_title="% error", yaxis_type="log", title="tline freqs"))
end
if show_results
plot([scatter(x=ω/(2π*1e9), y=diff(pfilter_λ_vects, T1_func, i, 2, 3), name="$i", mode="markers") for i in 1:3],
Layout(xaxis_title="bare qubit freq", yaxis_title="% error", yaxis_type="log", title="tline freqs"))
end
end
#######################################################
# Declare victory
#######################################################
@testset "radiative loss" begin
@test true
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 212 | module AdmittanceModels
include("linear_algebra.jl")
include("admittance_model.jl")
include("circuit.jl")
include("pso_model.jl")
include("blackbox.jl")
include("circuit_components.jl")
include("ansys.jl")
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 9151 | export AdmittanceModel
export get_Y, get_P, get_Q, get_ports, partial_copy, compatible, canonical_gauge
export apply_transform, cascade, cascade_and_unite, ports_to_indices
export unite_ports, open_ports, open_ports_except, short_ports, short_ports_except
"""
An abstract representation of a linear mapping from inputs `x` to outputs `y` of the form
`YΦ = Px`, `y = QᵀΦ`. Subtypes U <: AdmittanceModel are expected to implement:
get_Y(am::U)
get_P(am::U)
get_Q(am::U)
get_ports(am::U)
partial_copy(am::U; Y, P, ports)
compatible(AbstractVector{U})
"""
abstract type AdmittanceModel{T} end
"""
get_Y(pso::PSOModel)
get_Y(bbox::Blackbox)
Return a vector of admittance matrices.
"""
function get_Y end
"""
get_P(pso::PSOModel)
get_P(bbox::Blackbox)
Return an input port matrix.
"""
function get_P end
"""
get_Q(pso::PSOModel)
get_Q(bbox::Blackbox)
Return an output port matrix.
"""
function get_Q end
"""
get_ports(pso::PSOModel)
get_ports(bbox::Blackbox)
Return a vector of port identifiers.
"""
function get_ports end
"""
partial_copy(pso::PSOModel{T, U};
Y::Union{Vector{V}, Nothing}=nothing,
P::Union{V, Nothing}=nothing,
Q::Union{V, Nothing}=nothing,
ports::Union{AbstractVector{W}, Nothing}=nothing) where {T, U, V, W}
partial_copy(bbox::Blackbox{T, U};
Y::Union{Vector{V}, Nothing}=nothing,
P::Union{V, Nothing}=nothing,
Q::Union{V, Nothing}=nothing,
ports::Union{AbstractVector{W}, Nothing}=nothing) where {T, U, V, W}
Create a new model with the same fields except those given as keyword arguments.
"""
function partial_copy end
"""
compatible(psos::AbstractVector{PSOModel{T, U}}) where {T, U}
compatible(bboxes::AbstractVector{Blackbox{T, U}}) where {T, U}
Check if the models can be cascaded. Always true for PSOModels and true for Blackboxes
that share the same value of `ω`.
"""
function compatible end
"""
canonical_gauge(pso::PSOModel)
canonical_gauge(bbox::Blackbox)
Apply an invertible transformation that takes the model to coordinates in which
`P` is `[I ; 0]` (up to floating point errors). Note this will create a dense model.
"""
function canonical_gauge end
# don't remove space between Base. and ==
function Base. ==(am1::AdmittanceModel, am2::AdmittanceModel)
t = typeof(am1)
if typeof(am2) != t
return false
end
return all([getfield(am1, name) == getfield(am2, name) for name in fieldnames(t)])
end
function Base.isapprox(am1::AdmittanceModel, am2::AdmittanceModel)
t = typeof(am1)
if typeof(am2) != t
return false
end
return all([getfield(am1, name) ≈ getfield(am2, name) for name in fieldnames(t)])
end
"""
apply_transform(am::AdmittanceModel, transform::AbstractMatrix{<:Number})
Apply a linear transformation `transform` to the coordinates of the model.
"""
function apply_transform(am::AdmittanceModel, transform::AbstractMatrix{<:Number})
Y = [transpose(transform) * m * transform for m in get_Y(am)]
P = eltype(Y)(transpose(transform) * get_P(am))
Q = eltype(Y)(transpose(transform) * get_Q(am))
return partial_copy(am, Y=Y, P=P, Q=Q)
end
"""
cascade(ams::AbstractVector{U}) where {T, U <: AdmittanceModel{T}}
cascade(ams::Vararg{U}) where {T, U <: AdmittanceModel{T}}
Cascade the models into one larger block diagonal model.
"""
function cascade(ams::AbstractVector{U}) where {T, U <: AdmittanceModel{T}}
@assert length(ams) >= 1
if length(ams) == 1
return ams[1]
end
@assert compatible(ams)
Y = [cat(m..., dims=(1,2)) for m in zip([get_Y(am) for am in ams]...)]
P = cat([get_P(am) for am in ams]..., dims=(1,2))
Q = cat([get_Q(am) for am in ams]..., dims=(1,2))
ports = vcat([get_ports(am) for am in ams]...)
return partial_copy(ams[1], Y=Y, P=P, Q=Q, ports=ports)
end
cascade(ams::Vararg{U}) where {T, U <: AdmittanceModel{T}} = cascade(collect(ams))
"""
ports_to_indices(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
ports_to_indices(am::AdmittanceModel{T}, ports::Vararg{T}) where T
Find the indices corresponding to given ports.
"""
function ports_to_indices(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
am_ports = get_ports(am)
return [findfirst(isequal(p), am_ports) for p in ports]
end
ports_to_indices(am::AdmittanceModel{T}, ports::Vararg{T}) where T =
ports_to_indices(am, collect(ports))
"""
unite_ports(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
unite_ports(am::AdmittanceModel{T}, ports::Vararg{T}) where T
Unite the given ports into one port.
"""
function unite_ports(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
if length(ports) <= 1
return am
end
port_inds = ports_to_indices(am, ports)
keep_inds = filter(x -> !(x in port_inds[2:end]),
1:length(get_ports(am))) # keep the first port
P = get_P(am)
first_vector = P[:, port_inds[1]]
constraint_mat = transpose(hcat([first_vector - P[:, i] for i in port_inds[2:end]]...))
constrained_am = apply_transform(am, nullbasis(constraint_mat))
return partial_copy(constrained_am, P=get_P(constrained_am)[:, keep_inds],
Q=get_Q(constrained_am)[:, keep_inds], ports=get_ports(constrained_am)[keep_inds])
end
unite_ports(am::AdmittanceModel{T}, ports::Vararg{T}) where T =
unite_ports(am, collect(ports))
"""
open_ports(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
open_ports(am::AdmittanceModel{T}, ports::Vararg{T}) where T
Remove the given ports.
"""
function open_ports(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
if length(ports) == 0
return am
end
port_inds = ports_to_indices(am, ports)
keep_inds = filter(x -> !(x in port_inds), 1:length(get_ports(am)))
return partial_copy(am, P=get_P(am)[:, keep_inds],
Q=get_Q(am)[:, keep_inds], ports=get_ports(am)[keep_inds])
end
open_ports(am::AdmittanceModel{T}, ports::Vararg{T}) where T =
open_ports(am, collect(ports))
"""
open_ports_except(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
open_ports_except(am::AdmittanceModel{T}, ports::Vararg{T}) where T
Remove all ports except those specified.
"""
function open_ports_except(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
return open_ports(am, filter(x -> !(x in ports), get_ports(am)))
end
open_ports_except(am::AdmittanceModel{T}, ports::Vararg{T}) where T =
open_ports_except(am, collect(ports))
"""
short_ports(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
short_ports(am::AdmittanceModel{T}, ports::Vararg{T}) where T
Replace the given ports by short circuits.
"""
function short_ports(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
if length(ports) == 0
return am
end
port_inds = ports_to_indices(am, ports)
keep_inds = filter(x -> !(x in port_inds), 1:length(get_ports(am)))
constraint_mat = transpose(hcat([get_P(am)[:, i] for i in port_inds]...))
constrained_am = apply_transform(am, nullbasis(constraint_mat))
return partial_copy(constrained_am, P=get_P(constrained_am)[:, keep_inds],
Q=get_Q(constrained_am)[:, keep_inds], ports=get_ports(constrained_am)[keep_inds])
end
short_ports(am::AdmittanceModel{T}, ports::Vararg{T}) where T =
short_ports(am, collect(ports))
"""
short_ports_except(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
short_ports_except(am::AdmittanceModel{T}, ports::Vararg{T}) where T
Replace all ports with short circuits, except those specified.
"""
function short_ports_except(am::AdmittanceModel{T}, ports::AbstractVector{T}) where T
return short_ports(am, filter(x -> !(x in ports), get_ports(am)))
end
short_ports_except(am::AdmittanceModel{T}, ports::Vararg{T}) where T =
short_ports_except(am, collect(ports))
"""
cascade_and_unite(models::AbstractVector{U}) where {T, U <: AdmittanceModel{T}}
cascade_and_unite(models::Vararg{U}) where {T, U <: AdmittanceModel{T}}
Cascade all models and unite ports with the same name.
"""
function cascade_and_unite(models::AbstractVector{U}) where {T, U <: AdmittanceModel{T}}
@assert length(models) >= 1
if length(models) == 1
return models[1]
end
# number the ports so that the names are all distinct and then cascade
port_number = 1
function rename(model::U)
ports = [(port_number + i - 1, port) for (i, port) in enumerate(get_ports(model))]
port_number += length(ports)
return partial_copy(model, ports=ports)
end
model = cascade(map(rename, models))
# merge all ports with the same name
original_ports = vcat([get_ports(m) for m in models]...)
for port in unique(original_ports)
inds = findall([p[2] == port for p in get_ports(model)])
model = unite_ports(model, get_ports(model)[inds])
end
# remove numbering
return partial_copy(model, ports=[p[2] for p in get_ports(model)])
end
cascade_and_unite(models::Vararg{U}) where {T, U <: AdmittanceModel{T}} =
cascade_and_unite(collect(models))
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 7516 | #=
The functions here are intended to generate AdmittanceModels.Circuit objects
from ANSYS Q3D plain text output files containing RLGC parameters.
Here's a small example of the expected Q3D file format, valid for ANSYS Electronics Desktop 2016:
################################################################################################################
DesignVariation:\$DummyParam1='1' \$DummyParam2='1mm' \$dummy_param3='100e19pF' \$dummy_param4='1.2eUnits'
Setup1:LastAdaptive
Problem Type:C
C Units:farad, G Units:sie
Reduce Matrix:Original
Frequency: 4E+09 Hz
Capacitance Matrix
net_name_1 net_name_2
net_name_1 1.1924E-13 -1.3563E-16
net_name_2 -1.3563E-16 3.7607E-13
Conductance Matrix
net_name_1 net_name_2
net_name_1 2.4489E-09 -2.3722E-12
net_name_2 -2.3722E-12 7.7123E-09
Capacitance Matrix Coupling Coefficient
net_name_1 net_name_2
net_name_1 1 0.00064047 0.00018631
net_name_2 0.00064047 1 0.00010129
Conductance Matrix Coupling Coefficient
net_name_1 net_name_2
net_name_1 1 0.00054586 0.00017696
net_name_2 0.00054586 1 9.2987E-05
################################################################################################################
Each data block like \"Capacitance Matrix\" must start with a line enumerating
the N net names. These are the column labels for the given matrix. The matrix
rows are specified directly below this line. Each of the N row lines start with
a net name to label the row, followed by N space-separated float values for the
matrix elements. We expect these to be strings `parse(Float64, _)` can handle.
=#
using LinearAlgebra: diagind
using Compat
"""
parse_value_and_unit(s::AbstractString)
Parse strings like "9.9e-9mm" => (9.9e-9, "mm").
"""
function parse_value_and_unit(s::AbstractString)
# Three capture groups in the regex intended to match
# (±X.X)(e-X)(unit)
m = match(r"(\-?[\d|\.]+)(e-?[\d]+)?(\D*)", s)
exp_str = m[2] == nothing ? "" : m[2]
num_str = m[1] * exp_str
num = parse(Float64, num_str)
unit_str = String(m[3])
(num, unit_str)
end
const matrix_types = Dict(
:capacitance => "Capacitance Matrix",
:conductance => "Conductance Matrix",
# :dc_inductance => "DC Inductance Matrix",
# :dc_resistance => "DC Resistance Matrix",
# :ac_inductance => "AC Inductance Matrix",
# :ac_resistance => "AC Resistance Matrix",
# :dc_plus_ac_resistance => "DCPlusAC Resistance Matrix",
)
const unit_names = Dict(
:capacitance => "C Units",
:conductance => "G Units"
)
const units_to_multipliers = Dict(
"fF" => 1e-15,
"pF" => 1e-12,
"nF" => 1e-9,
"uF" => 1e-6,
"mF" => 1e-3,
"farad" => 1.0,
"mSie" => 1e-3,
"sie" => 1.0
)
"""
parse_q3d_txt(filepath, matrix_type::Symbol)
Parses a plain text file generated by ANSYS Q3D containing RLGC simulation output.
# Args
- `q3d_file`: the path to the text file.
- `matrix_type`: A `Symbol` indicating the type of data to read. Currently,
symbols in $(collect(keys(matrix_types))) are the only available choices,
and only the units in $(collect(keys(units_to_multipliers))) are handled.
# Returns
- A tuple `(design_variation, net_names, matrix)`, where:
- `design_variation` is a `Dict` of design variables
- `net_names` is a `Vector` of net names (strings)
- `matrix` is the requested matrix
"""
function parse_q3d_txt(q3d_file, matrix_type::Symbol)
!haskey(matrix_types, matrix_type) && error("matrix type not implemented.")
matrix_name = matrix_types[matrix_type]
unit_name = unit_names[matrix_type]
# Windows uses \r\n for newlines, where Linux just uses \n.
# We work around that difference here by deleting all carriage return (\r)
# characters from the file.
linesep = "\n"
file_text = replace(read(q3d_file, String), "\r" => "")
file_chunks = split(file_text, linesep * linesep)
@assert length(file_chunks) > 1 "expected more than one block in Q3D plain text file."
is_chunk(header) = chunk -> startswith(chunk, header)
function get_chunk(header)
# the chunk may be missing, guard against errors
idx = findfirst(is_chunk(header), file_chunks)
!isnothing(idx) && return file_chunks[idx]
return nothing
end
get_chunk_line(chunk, line_num) = split(chunk, linesep)[line_num]
# The following parses lines like:
# DesignVariation:var1='12' var2='1e-05' var3='123um'
# into Dict("var1" => (12, ""),
# "var2" => (1e-5, ""),
# "var3" => (123, "um"))
design_variation_chunk = get_chunk("DesignVariation")
design_variation = if !isnothing(design_variation_chunk)
_, design_variation_data_str = split(get_chunk_line(design_variation_chunk, 1), ":")
design_strings = split(design_variation_data_str)
parse_design_kv((k, v)) = String(k) => parse_value_and_unit(strip(v, ['\'']))
Dict(parse_design_kv.(split.(design_strings, ['='])))
else
Dict{String, Tuple{Float64, String}}()
end
local unit_multiplier
for l in split(file_chunks[1], linesep)
if occursin("Units", l)
unit = Dict(split.(split(l, ", "), ':'))[unit_name]
!haskey(units_to_multipliers, unit) && error("unit $unit not implemented.")
unit_multiplier = units_to_multipliers[unit]
break
end
end
(@isdefined unit_multiplier) || error("units not given in Q3D plain text file.")
# Don't forget to include the line separator here.
# We typically have matrix_name = "Capacitance Matrix"
# But, these files can have a heading like "Capacitance Matrix Coupling Coefficient"
matrix_chunk = get_chunk(matrix_name * linesep)
net_names = String.(split(get_chunk_line(matrix_chunk, 2)))
get_matrix_row(row_idx) = parse.(Float64,
split(get_chunk_line(matrix_chunk, 2 + row_idx))[2:end]) .* unit_multiplier
matrix = reduce(hcat, get_matrix_row.(1:length(net_names)))
(design_variation, net_names, matrix)
end
"""
Circuit(q3d_file; matrix_types = [:capacitance])
Return an `AdmittanceModels.Circuit` from a plain text file generated by
ANSYS Q3D containing RLGC simulation output.
# Args
- `q3d_file`: the path to the text file.
- `matrix_type`: A list of symbols indicating which type of matrix data to read.
Currently, symbols in $(collect(keys(matrix_types))) are the only available
choices, and only the units in $(collect(keys(units_to_multipliers))) are handled.
"""
function Circuit(q3d_file; matrix_types = [:capacitance])
parse_dict = Dict(t => parse_q3d_txt(q3d_file, t) for t ∈ matrix_types)
# Check that all matrix types are defined over the same set of nets
# `take_only` asserts the iterator it's passed has only one element
nets = take_only(collect(Set(map(t -> t[2], values(parse_dict)))))
matrix_dict = Dict(t => parse_dict[t][3] for t ∈ matrix_types)
zero_mat() = zeros(length(nets), length(nets))
# The C and G matrices expected in AdmittanceModels.Circuit are the same
# as those parsed from Q3D, except with all diagonal entries set to 0 and
# all values made positive.
function prep_matrix(matrix_type)
x = get(matrix_dict, matrix_type, zero_mat())
x[diagind(x)] .= 0.
abs.(x)
end
k = zero_mat()
g = prep_matrix(:conductance)
c = prep_matrix(:capacitance)
return Circuit(k, g, c, nets)
end
function take_only(xs)
@assert length(xs) == 1 "Expected $xs to have one element."
return xs[1]
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 4349 | using UniqueVectors: UniqueVector
export Blackbox
export impedance_matrices, admittance_matrices, scattering_matrices
"""
Blackbox{T, U}(ω::Vector{Float64}, Y::Vector{U}, P::U, Q::U,
ports::UniqueVector{T}) where {T, U}
Blackbox(ω::Vector{<:Real}, Y::Vector{U}, P::U, Q::U,
ports::AbstractVector{T}) where {T, U}
An admittance model with constant `P` and `Q` but with varying `Y`, indexed by a real
variable `ω`.
"""
struct Blackbox{T, U<:AbstractMatrix{<:Number}} <: AdmittanceModel{T}
ω::Vector{Float64}
Y::Vector{U}
P::U
Q::U
ports::UniqueVector{T}
function Blackbox{T, U}(ω::Vector{Float64}, Y::Vector{U}, P::U, Q::U,
ports::UniqueVector{T}) where {T, U}
if length(Y) > 0
l = size(Y[1], 1)
@assert size(P) == (l, length(ports))
@assert size(Q) == (l, length(ports))
@assert all([size(y) == (l, l) for y in Y])
end
@assert length(ω) == length(Y)
return new{T, U}(ω, Y, P, Q, ports)
end
end
Blackbox(ω::Vector{<:Real}, Y::Vector{U}, P::U, Q::U,
ports::AbstractVector{T}) where {T, U} = Blackbox{T, U}(ω, Y, P, Q, UniqueVector(ports))
get_Y(bbox::Blackbox) = bbox.Y
get_P(bbox::Blackbox) = bbox.P
get_Q(bbox::Blackbox) = bbox.Q
get_ports(bbox::Blackbox) = bbox.ports
function partial_copy(bbox::Blackbox{T, U};
Y::Union{Vector{V}, Nothing}=nothing,
P::Union{V, Nothing}=nothing,
Q::Union{V, Nothing}=nothing,
ports::Union{AbstractVector{W}, Nothing}=nothing) where {T, U, V, W}
Y = Y == nothing ? get_Y(bbox) : Y
P = P == nothing ? get_P(bbox) : P
Q = Q == nothing ? get_Q(bbox) : Q
ports = ports == nothing ? get_ports(bbox) : ports
return Blackbox(bbox.ω, Y, P, Q, ports)
end
function compatible(bboxes::AbstractVector{Blackbox{T, U}}) where {T, U}
if length(bboxes) == 0
return true
end
ω = bboxes[1].ω
return all([ω == bbox.ω for bbox in bboxes[2:end]])
end
# TODO for sparse matrices use sparse linear solver instead of \ and /
function impedance_to_scattering(Z::AbstractMatrix{<:Number}, Z0::AbstractVector{<:Real})
U = diagm(0 => Z0)
return (Z + U) \ (Z - U)
end
function scattering_to_impedance(S::AbstractMatrix{<:Number}, Z0::AbstractVector{<:Real})
U = diagm(0 => Z0)
return U * (I + S) / (I - S)
end
function admittance_to_scattering(Y::AbstractMatrix{<:Number}, Z0::AbstractVector{<:Real})
U = diagm(0 => Z0)
return (I + Y * U) \ (I - Y * U)
end
function scattering_to_admittance(S::AbstractMatrix{<:Number}, Z0::AbstractVector{<:Real})
V = diagm(0 => 1 ./ Z0)
return (I - S) * ((I + S) \ V)
end
"""
impedance_matrices(bbox::Blackbox)
Find the impedance matrices `Z` with `y = Zx` for each `ω`.
"""
impedance_matrices(bbox::Blackbox) = [transpose(bbox.Q) * (Y \ collect(bbox.P))
for Y in bbox.Y]
"""
admittance_matrices(bbox::Blackbox)
Find the admittance matrices `Y` with `Yy = x` for each `ω`.
"""
function admittance_matrices(bbox::Blackbox)
if bbox.P == I # avoid unnecessary matrix inversion
return map(collect, bbox.Y)
else
return [inv(Z) for Z in impedance_matrices(bbox)]
end
end
"""
scattering_matrices(bbox::Blackbox, Z0::AbstractVector{<:Real})
Find the scattering matrices that map incoming waves to outgoing waves on transmission
lines with characteristic impedance `Z0` for each `ω`.
"""
function scattering_matrices(bbox::Blackbox, Z0::AbstractVector{<:Real})
if bbox.P == I # avoid unnecessary matrix inversion
return [admittance_to_scattering(Y, Z0) for Y in admittance_matrices(bbox)]
else
return [impedance_to_scattering(Z, Z0) for Z in impedance_matrices(bbox)]
end
end
function canonical_gauge(bbox::Blackbox)
n = length(bbox.ports)
Y = admittance_matrices(bbox)
P = Matrix{eltype(eltype(Y))}(I, n, n)
Q = Matrix{eltype(eltype(Y))}(I, n, n)
return Blackbox(bbox.ω, Y, P, Q, bbox.ports)
end
"""
Blackbox(ω::Vector{<:Real}, pso::PSOModel)
Create a Blackbox for a PSOModel where `ω` represents angular frequency.
"""
function Blackbox(ω::Vector{<:Real}, pso::PSOModel)
K, G, C = get_Y(pso)
Y = [K ./ s + G + C .* s for s in 1im * ω]
P = get_P(pso) * (1.0 + 0im)
Q = get_Q(pso) * (1.0 + 0im)
return Blackbox(ω, Y, P, Q, get_ports(pso))
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 8429 | using UniqueVectors: UniqueVector
using LinearAlgebra: issymmetric, diag, I
using SparseArrays: spzeros
export Circuit
export partial_copy, matrices
export get_inv_inductance, get_inductance
export get_conductance, get_resistance
export get_elastance, get_capacitance
export set_inv_inductance!, set_inductance!
export set_conductance!, set_resistance!
export set_capacitance!, set_elastance!
export SpanningTree, coordinate_matrix
export cascade, unite_vertices, cascade_and_unite
SparseMat = SparseMatrixCSC{Float64,Int}
struct Circuit{T}
k::SparseMat # inverse inductances
g::SparseMat # conductances
c::SparseMat # capacitances
vertices::UniqueVector{T}
function Circuit{T}(k::SparseMat, g::SparseMat, c::SparseMat,
vertices::UniqueVector{T}) where T
for m in [k, g, c]
@assert issymmetric(m)
@assert size(m) == (length(vertices), length(vertices))
@assert all(diag(m) .== 0)
@assert all(m .>= 0)
end
return new{T}(k, g, c, vertices)
end
end
Circuit(k::SparseMat, g::SparseMat, c::SparseMat, vertices::AbstractVector{T}) where T =
Circuit{T}(k, g, c, UniqueVector(vertices))
Circuit(k::AbstractMatrix{<:Real}, g::AbstractMatrix{<:Real}, c::AbstractMatrix{<:Real},
vertices::AbstractVector) = Circuit(sparse(1.0 * k), sparse(1.0 * g), sparse(1.0 * c),
vertices)
function Circuit(vertices::AbstractVector{T}) where T
z() = spzeros(length(vertices), length(vertices))
return Circuit(z(), z(), z(), vertices)
end
function partial_copy(circ::Circuit{T};
k::Union{SparseMat, Nothing}=nothing,
g::Union{SparseMat, Nothing}=nothing,
c::Union{SparseMat, Nothing}=nothing,
vertices::Union{AbstractVector{U}, Nothing}=nothing) where {T, U}
k = k == nothing ? circ.k : k
g = g == nothing ? circ.g : g
c = c == nothing ? circ.c : c
vertices = vertices == nothing ? circ.vertices : vertices
return Circuit(k, g, c, vertices)
end
# don't remove space between Base. and ==
function Base. ==(circ1::Circuit, circ2::Circuit)
if typeof(circ1) != typeof(circ2)
return false
end
return all([getfield(circ1, name) == getfield(circ2, name)
for name in fieldnames(Circuit)])
end
function Base.isapprox(circ1::Circuit, circ2::Circuit)
if typeof(circ1) != typeof(circ2)
return false
end
return all([getfield(circ1, name) ≈ getfield(circ2, name)
for name in fieldnames(Circuit)[1:end-1]])
end
matrices(c::Circuit) = [c.k, c.g, c.c]
function get_matrix_element(c::Circuit, matrix_name::Symbol, v0, v1)
i0 = findfirst(isequal(v0), c.vertices)
i1 = findfirst(isequal(v1), c.vertices)
return getfield(c, matrix_name)[i0, i1]
end
get_inv_inductance(c::Circuit, v0, v1) = get_matrix_element(c, :k, v0, v1)
get_inductance(c::Circuit, v0, v1) = inv(get_inv_inductance(c, v0, v1))
get_conductance(c::Circuit, v0, v1) = get_matrix_element(c, :g, v0, v1)
get_resistance(c::Circuit, v0, v1) = inv(get_conductance(c, v0, v1))
get_capacitance(c::Circuit, v0, v1) = get_matrix_element(c, :c, v0, v1)
get_elastance(c::Circuit, v0, v1) = inv(get_capacitance(c, v0, v1))
function set_matrix_element!(c::Circuit, matrix_name::Symbol, v0, v1, value)
@assert value >= zero(value)
@assert !isinf(value)
i0 = findfirst(isequal(v0), c.vertices)
i1 = findfirst(isequal(v1), c.vertices)
@assert i0 != i1
matrix = getfield(c, matrix_name)
matrix[i0, i1] = value
matrix[i1, i0] = value
return c
end
set_inv_inductance!(c::Circuit, v0, v1, value) =
set_matrix_element!(c, :k, v0, v1, value)
set_inductance!(c::Circuit, v0, v1, value) =
set_inv_inductance!(c, v0, v1, inv(value))
set_conductance!(c::Circuit, v0, v1, value) =
set_matrix_element!(c, :g, v0, v1, value)
set_resistance!(c::Circuit, v0, v1, value) =
set_conductance!(c, v0, v1, inv(value))
set_capacitance!(c::Circuit, v0, v1, value) =
set_matrix_element!(c, :c, v0, v1, value)
set_elastance!(c::Circuit, v0, v1, value) =
set_capacitance!(c, v0, v1, inv(value))
#######################################################
# spanning trees
#######################################################
struct SpanningTree{T}
root::T
edges::Vector{Tuple{T, T}}
end
# depth-1 spanning tree
function SpanningTree(vertices::AbstractVector{T}) where T
@assert length(vertices) > 0
root = vertices[1]
edges = [(v, root) for v in vertices[2:end]]
return SpanningTree{T}(root, edges)
end
# T matrix in section IIC with a given spanning tree.
# The direction of the edges passed in is ignored and enforced as being outwards
# from the root
function coordinate_matrix(c::Circuit{T}, tree::SpanningTree{T}) where T
V = length(c.vertices)
@assert tree.root in c.vertices
@assert length(tree.edges) == V-1 # the correct number of edges for a spanning tree
mapping = Dict(tree.root => spzeros(V-1)) # the function l in equation 2
edge_set = Set(enumerate(tree.edges))
while !isempty(edge_set)
for e in edge_set
(index, (v0, v1)) = e
@assert !(v0 in keys(mapping) && v1 in keys(mapping)) # edges contains a loop
if v0 in keys(mapping) || v1 in keys(mapping)
delete!(edge_set, e)
if v0 in keys(mapping) # enforces all edges are oriented away from the root
mapping[v1] = 1.0 * mapping[v0]
mapping[v1][index] += 1
else
mapping[v0] = 1.0 * mapping[v1]
mapping[v0][index] += 1
end
end
end
end
@assert length(mapping) == V # all vertices have been assigned a coordinate
return hcat([mapping[v] for v in c.vertices]...)
end
# T matrix in section IIC for depth-1 spanning tree
coordinate_matrix(num_vertices::Int) = transpose([spzeros(1, num_vertices-1); I])
coordinate_matrix(c::Circuit) = coordinate_matrix(length(c.vertices))
#######################################################
# cascade and unite
#######################################################
function cascade(circs::AbstractVector{Circuit{T}}) where T
circuit_matrices = [cat(m..., dims=(1,2))
for m in zip([matrices(circ) for circ in circs]...)]
vertices = vcat([circ.vertices for circ in circs]...)
return Circuit(circuit_matrices..., vertices)
end
cascade(circs::Vararg{Circuit{T}}) where T = cascade(collect(circs))
function unite_vertices(circ::Circuit{T}, vertices::AbstractVector{T}) where T
if length(vertices) <= 1
return circ
end
n = length(circ.vertices)
vertex_inds = [findfirst(isequal(v), circ.vertices) for v in vertices]
keep_inds = filter(x -> !(x in vertex_inds[2:end]), 1:n)
function unite_indices(mat::AbstractMatrix)
m = copy(mat)
ind1 = vertex_inds[1]
for ind2 in vertex_inds[2:end]
m[ind1, :] += mat[ind2, :]
m[:, ind1] += mat[:, ind2]
end
m = m[keep_inds, keep_inds]
for i in 1:size(m, 1)
m[i, i] = 0
end
return m
end
circuit_matrices = [unite_indices(mat) for mat in matrices(circ)]
return Circuit(circuit_matrices..., circ.vertices[keep_inds])
end
unite_vertices(circ::Circuit{T}, vertices::Vararg{T}) where T =
unite_vertices(circ, collect(vertices))
# cascade all circuits and unite vertices with the same name
function cascade_and_unite(circs::AbstractVector{Circuit{T}}) where T
@assert length(circs) >= 1
if length(circs) == 1
return circs[1]
end
# number the vertices so that the names are all distinct and then cascade
vertex_number = 1
function rename(circ)
vertices = [(vertex_number + i - 1, vertex)
for (i, vertex) in enumerate(circ.vertices)]
vertex_number += length(vertices)
return Circuit(matrices(circ)..., vertices)
end
circ = cascade(map(rename, circs))
# merge all vertices with the same name
original_vertices = vcat([c.vertices for c in circs]...)
for vertex in unique(original_vertices)
inds = findall([v[2] == vertex for v in circ.vertices])
circ = unite_vertices(circ, circ.vertices[inds])
end
# remove numbering
return Circuit(matrices(circ)..., [v[2] for v in circ.vertices])
end
cascade_and_unite(circs::Vararg{Circuit{T}}) where T = cascade_and_unite(collect(circs))
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 9442 | export CircuitComponent, SeriesComponent, ParallelComponent, TransmissionLine
export Cascade, PortOperation
"""
An abstract representation of a circuit component e.g. a capacitor, inductor, or
transmission line.
"""
abstract type CircuitComponent end
# the empty string is used for the ground net
ground = ""
"""
Blackbox(ω::Vector{<:Real}, comp::CircuitComponent)
Blackbox(ω::Vector{<:Real}, comp::TransmissionLine)
Blackbox(ω::Vector{<:Real}, comp::Cascade)
Create a Blackbox model for a CircuitComponent.
"""
function Blackbox(ω::Vector{<:Real}, comp::CircuitComponent)
return canonical_gauge(Blackbox(ω, PSOModel(comp)))
end
"""
SeriesComponent(p1::String, p2::String, inv_inductance::Float64, conductance::Float64,
capacitance::Float64)
SeriesComponent(p1::String, p2::String, k::Real, g::Real, c::Real)
A parallel inductor, capacitor, and resistor between two ports.
"""
struct SeriesComponent <: CircuitComponent
p1::String
p2::String
inv_inductance::Float64
conductance::Float64
capacitance::Float64
function SeriesComponent(p1::String, p2::String, inv_inductance::Float64,
conductance::Float64, capacitance::Float64)
@assert p1 != ground
@assert p2 != ground
return new(p1, p2, inv_inductance, conductance, capacitance)
end
end
SeriesComponent(p1::String, p2::String, k::Real, g::Real, c::Real) =
SeriesComponent(p1, p2, 1.0 * k, 1.0 * g, 1.0 * c)
"""
Circuit(comp::SeriesComponent)
Circuit(comp::ParallelComponent)
Circuit(comp::TransmissionLine, vertex_prefix::AbstractString,
stages_per_segment::Union{Nothing, AbstractVector{Int}}=nothing)
Create a Circuit for a CircuitComponent.
"""
function Circuit(comp::SeriesComponent)
c = Circuit([ground, comp.p1, comp.p2])
set_inv_inductance!(c, comp.p1, comp.p2, comp.inv_inductance)
set_conductance!(c, comp.p1, comp.p2, comp.conductance)
set_capacitance!(c, comp.p1, comp.p2, comp.capacitance)
return c
end
"""
PSOModel(comp::SeriesComponent)
PSOModel(comp::ParallelComponent)
PSOModel(comp::TransmissionLine)
PSOModel(comp::Cascade)
Create a PSOModel for a CircuitComponent.
"""
function PSOModel(comp::SeriesComponent)
return PSOModel(Circuit(comp), [(comp.p1, ground), (comp.p2, ground)], [comp.p1, comp.p2])
end
"""
ParallelComponent(p::String, inv_inductance::Float64,
conductance::Float64, capacitance::Float64)
ParallelComponent(p::String, k::Real, g::Real, c::Real)
A parallel inductor, capacitor, and resistor with one port.
"""
struct ParallelComponent <: CircuitComponent
p::String
inv_inductance::Float64
conductance::Float64
capacitance::Float64
function ParallelComponent(p::String, inv_inductance::Float64,
conductance::Float64, capacitance::Float64)
@assert p != ground
return new(p, inv_inductance, conductance, capacitance)
end
end
ParallelComponent(p::String, k::Real, g::Real, c::Real) =
ParallelComponent(p, 1.0 * k, 1.0 * g, 1.0 * c)
function Circuit(comp::ParallelComponent)
c = Circuit([ground, comp.p])
set_inv_inductance!(c, comp.p, ground, comp.inv_inductance)
set_conductance!(c, comp.p, ground, comp.conductance)
set_capacitance!(c, comp.p, ground, comp.capacitance)
return c
end
PSOModel(comp::ParallelComponent) = PSOModel(Circuit(comp), [(comp.p, ground)], [comp.p])
"""
TransmissionLine(ports::Vector{String}, propagation_speed::Float64,
characteristic_impedance::Float64, len::Float64,
locations::AbstractVector{Float64}, δ::Float64)
TransmissionLine(ports::Vector{String}, propagation_speed::Real,
characteristic_impedance::Real, len::Real; locations::Vector{<:Real}=Float64[],
δ::Real=len/100)
A transmission line with given propagation speed and characteristic impedance. Ports will
be present at the two ends of the transmission line in addition to the `locations`. `δ` is
the maximum length of an LC stage in the circuit approximation to a transmission line. It
is ignored when constructing a Blackbox from a TransmissionLine.
"""
struct TransmissionLine <: CircuitComponent
ports::Vector{String}
propagation_speed::Float64
characteristic_impedance::Float64
len::Float64 # length, but that's the name of a built in function
port_locations::UniqueVector{Float64}
δ::Float64 # ignored when converted directly to Blackbox
function TransmissionLine(ports::Vector{String}, propagation_speed::Float64,
characteristic_impedance::Float64, len::Float64, locations::AbstractVector{Float64},
δ::Float64)
@assert !(ground in ports)
@assert propagation_speed > 0
@assert characteristic_impedance > 0
@assert len > 0
@assert all(locations .> 0)
@assert all(locations .< len)
port_locations = UniqueVector([0; locations; len])
@assert length(ports) == length(port_locations)
@assert δ >= 0
return new(ports, propagation_speed, characteristic_impedance,
len, port_locations, δ)
end
end
TransmissionLine(ports::Vector{String}, propagation_speed::Real,
characteristic_impedance::Real, len::Real; locations::Vector{<:Real}=Float64[],
δ::Real=len/100) = TransmissionLine(ports, propagation_speed,
characteristic_impedance, len, locations, δ)
function Circuit_and_ports(comp::TransmissionLine,
stages_per_segment::Union{Nothing, AbstractVector{Int}}=nothing)
sort_inds = sortperm(comp.port_locations)
port_locations, ports = comp.port_locations[sort_inds], comp.ports[sort_inds]
ν, Z0, δ = comp.propagation_speed, comp.characteristic_impedance, comp.δ
segment_lengths = port_locations[2:end] - port_locations[1:end-1]
if stages_per_segment == nothing
stages_per_segment = [ceil(Int, len / δ) for len in segment_lengths]
end
num_vertices = sum(stages_per_segment) + 2 # ground is 0
c = Circuit(0:(num_vertices-1))
v0 = 0
port_edges = Tuple{Int, Int}[]
for (segment_length, num_stages) in zip(segment_lengths, stages_per_segment)
stage_length = 1.0 * segment_length / num_stages
inductance = stage_length * Z0 / ν
capacitance = stage_length / (Z0 * ν)
for v in (v0 + 1):(v0 + num_stages)
set_inductance!(c, v, v + 1, inductance)
end
for v in [v0 + 1, v0 + num_stages + 1]
set_capacitance!(c, v, 0, 0.5 * capacitance + get_capacitance(c, v, 0))
end
for v in (v0 + 2):(v0 + num_stages)
set_capacitance!(c, v, 0, capacitance)
end
push!(port_edges, (v0 + 1, 0))
v0 += num_stages
end
@assert v0 + 1 == num_vertices-1
push!(port_edges, (num_vertices-1, 0))
return c, port_edges, ports
end
function Circuit(comp::TransmissionLine, vertex_prefix::AbstractString,
stages_per_segment::Union{Nothing, AbstractVector{Int}}=nothing)
c, port_edges, ports = Circuit_and_ports(comp, stages_per_segment)
vertices = [ground; ["$(vertex_prefix)$v" for v in c.vertices[2:end]]]
for (e, p) in zip(port_edges, ports)
vertices[e[1]+1] = p
end
return Circuit(matrices(c)..., vertices)
end
PSOModel(comp::TransmissionLine) = PSOModel(Circuit_and_ports(comp)...)
function Blackbox(ω::Vector{<:Real}, comp::TransmissionLine)
ν = comp.propagation_speed
Z0 = comp.characteristic_impedance
function Blackbox_from_params(ports::Vector, len::Real)
u = exp.(-1im * ω * len/ν)
# S matrix is [[0, u] [u, 0]]
# turn this into Y matrix using closed form expression
denom = (1 .- u.^2) * Z0
Y11_Y22 = (1 .+ u.^2) ./ denom
Y12_Y21 = -2 * u ./ denom
Y = [[[a, b] [b, a]] for (a, b) in zip(Y11_Y22, Y12_Y21)]
U = eltype(eltype(Y))
P = Matrix{U}(I, 2, 2)
return Blackbox(ω, Y, P, P, ports)
end
sort_inds = sortperm(comp.port_locations)
sort_port_locations = comp.port_locations[sort_inds]
sort_ports = comp.ports[sort_inds]
params = [(ports = [sort_ports[i], sort_ports[i + 1]],
len = sort_port_locations[i+1] - sort_port_locations[i])
for i in 1:(length(comp.ports)-1)]
return cascade_and_unite([Blackbox_from_params(p...) for p in params])
end
"""
The functions allowed in a Cascade.
"""
PortOperation = Union{typeof(short_ports),
typeof(short_ports_except),
typeof(open_ports),
typeof(open_ports_except),
typeof(unite_ports),
typeof(canonical_gauge)}
"""
Cascade(components::Vector{CircuitComponent},
operations::Vector{Pair{PortOperation, Vector{String}}})
A system created by cascading and uniting several CircuitComponents and then applying
PortOperations to the ports.
"""
struct Cascade <: CircuitComponent
components::Vector{CircuitComponent}
operations::Vector{Pair{PortOperation, Vector{String}}}
end
function PSOModel(comp::Cascade)
model = cascade_and_unite([PSOModel(m) for m in comp.components])
for (op, args) in comp.operations
model = op(model, args...)
end
return model
end
function Blackbox(ω::Vector{<:Real}, comp::Cascade)
model = cascade_and_unite([Blackbox(ω, m) for m in comp.components])
for (op, args) in comp.operations
model = op(model, args...)
end
return model
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 12758 | using LinearAlgebra: lu, I, ldiv!, rmul!, norm, qr, rank, nullspace
using SparseArrays: sparse, spzeros, SparseMatrixCSC, findnz
using Combinatorics: combinations
using MatrixNetworks: bfs, scomponents
export sparse_nullbasis, nullbasis
"""
closest_permutation(mat::AbstractMatrix{<:Real})
Given an `m × n` matrix `mat` where `m ≥ n`, find an assignment of rows to columns such
that each column is assigned a distinct row and the absolute values of the entries
corresponding to the assignment is as large as possible under lexicographical ordering.
Return a matrix of Bools where each column has a single true in it corresponding to its
assignment.
"""
function closest_permutation(mat::AbstractMatrix)
nrows, ncols = size(mat)
@assert nrows >= ncols
ans = similar(BitArray, axes(mat)) # initialize answer as all false
fill!(ans, false)
ax2 = axes(mat, 2)
# Do a first pass, ignoring collisions.
colidxs = similar(ax2)
for col in ax2
@inbounds begin
_, i = findmax(mat[:, col])
ans[i, col] = true
colidxs[col] = i
end
end
# Prepare a BitArray `collisions` and mark collided columns in it.
sp = sortperm(colidxs)
sortedidxs = colidxs[sp]
collisions = similar(BitArray, ax2)
fill!(collisions, false)
previndex = firstindex(sortedidxs)
@inbounds for i in eachindex(sortedidxs)
isequal(i, firstindex(sortedidxs)) && continue
if isequal(sortedidxs[i], sortedidxs[previndex])
collisions[sp[i]] = true
collisions[sp[previndex]] = true
end
previndex = i
end
@inbounds stack = sp[collisions]
isempty(stack) && return ans
# reset columns in `ans` where collisions happened
for col in stack
@inbounds ans[:, col] .= false
end
# fall-back to single-threaded collision resolution on collided columns
return _closest_permutation(mat, ans, stack)
end
function _closest_permutation(mat::AbstractMatrix, ans, stack)
ax1 = axes(mat, 1)
ax1l = length(ax1)
possible_assignments = Vector{eltype(ax1)}() # row indices
@inbounds while length(stack) > 0
col = pop!(stack)
resize!(possible_assignments, ax1l)
possible_assignments .= axes(mat, 1)
assigned = false
while !assigned
value, i = findmax(mat[possible_assignments, col])
assignment = possible_assignments[i]
collision = findfirst(ans[assignment, :])
if collision == nothing
ans[assignment, col] = true
assigned = true
elseif mat[assignment, collision] < value
ans[assignment, col] = true
assigned = true
ans[assignment, collision] = false
push!(stack, collision) # need to reassign collision
else
deleteat!(possible_assignments, i) # try somewhere else
end
end
end
return ans
end
"""
match_vectors(port_vectors::AbstractMatrix{<:Number},
eigenvectors::AbstractMatrix{<:Number})
For each column of `port_vectors` find a corresponding column of `eigenvectors` that has a
similar "shape". Match each `port_vector` to a different `eigenvector`.
"""
function match_vectors(port_vectors::AbstractMatrix{<:Number},
eigenvectors::AbstractMatrix{<:Number})
@assert size(port_vectors, 1) == size(eigenvectors, 1)
@assert size(port_vectors, 2) <= size(eigenvectors, 2)
mat = abs2.(eigenvectors' * port_vectors) # tall skinny matrix
_, indices = findmax(closest_permutation(mat), dims=1)
return [index[1] for index in vcat(indices...)]
end
"""
inv_power_eigen(M::AbstractMatrix{<:Number};
v0::AbstractVector{<:Number}=rand(Complex{real(eltype(M))}, size(M, 1)),
λ0::Union{Number, Nothing}=nothing,
pred::Function=(x,y) -> norm(x-y) < eps())
Use the inverse power method to find an eigenvalue and eigenvector.
# Arguments
- `v0::AbstractVector{<:Number}`: an initial value for the eigenvector. A random vector is
used if `v0` is not given.
- `λ0::Union{Number, Nothing}`: an initial value for the eigenvalue. `v' * M * v` is used
if `λ0` is not given.
- `pred::Function`: a function taking two successive eigenvalue estimates. The algorithm
halts when `pred` returns true.
"""
function inv_power_eigen(M::AbstractMatrix{<:Number};
v0::AbstractVector{<:Number}=rand(Complex{real(eltype(M))}, size(M, 1)),
λ0::Union{Number, Nothing}=nothing,
pred::Function=(x,y) -> norm(x-y) < eps())
v = v0/norm(v0)
l = length(v)
@assert size(M) == (l, l)
λ = (λ0 == nothing) ? v' * M * v : λ0
done = false
μ = λ
A = lu(M - λ * I)
while !done
ldiv!(A, v)
rmul!(v, 1/norm(v))
μ = v' * M * v
done = pred(λ, μ)::Bool
λ = μ
end
return μ, v
end
#######################################################
# sparse nullbases
#######################################################
"""
row_column_graph(mat::SparseMatrixCSC{<:Number, Int})
Let `mat` be a matrix with the following properties
- for any two rows of `mat` there is at most one column on which both rows are nonzero
- any column of `mat` has at most 2 nonzero values
The rows of `mat` form a simple graph where two rows have an edge if and only if they share
a nonzero column in `mat`. We add one additional vertex to this graph and for each column
with exactly one nonzero value, we add an edge between its nonzero row and the additional
vertex. In this graph every column with at least one nonzero value is represented by an
edge. Produce a matrix `A` where `A[i,j]` is the column shared by rows `i` and `j` if such a
column exists, and `0` otherwise. If `i == size(mat, 1) + 1`, then `A[i,j]` is chosen
arbitrarily from the columns whose unique nonzero value is in row `j`, or 0 if no such
columns exist. The case where `j == size(mat, 1) + 1` is analogous. `A` is an adjacency
matrix for the graph with extra information relating the graph to `mat`.
"""
function row_column_graph(mat::SparseMatrixCSC{<:Number, Int})
num_vertices = size(mat, 1) + 1
row_inds, col_inds, vals = Int[], Int[], Int[]
matT = sparse(transpose(mat)) # SparseMatrixCSC row access is slow
for (r1, r2) in combinations(1:(num_vertices-1), 2)
inds = findall((matT[:, r1] .!= 0) .& (matT[:, r2] .!= 0))
@assert length(inds) <= 1 # any two rows share at most 1 common nonzero column
if length(inds) == 1
c = inds[1]
push!(row_inds, r1); push!(col_inds, r2); push!(vals, c)
push!(row_inds, r2); push!(col_inds, r1); push!(vals, c)
end
end
root = num_vertices
connected_to_root = Set{Int}()
for c in 1:size(mat, 2)
inds = findall(mat[:, c] .!= 0)
@assert length(inds) <= 2 # any column has at most 2 nonzero values
if length(inds) == 1
r = inds[1]
if !(r in connected_to_root)
push!(connected_to_root, r)
push!(row_inds, root); push!(col_inds, r); push!(vals, c)
push!(row_inds, r); push!(col_inds, root); push!(vals, c)
end
end
end
adj = sparse(row_inds, col_inds, vals, num_vertices, num_vertices)
return adj
end
"""
connected_row_column_graph(mat::SparseMatrixCSC{<:Number, Int})
Let `mat` be a matrix with the following properties
- for any two rows of `mat` there is at most one column on which both rows are nonzero
- any column of `mat` has at most 2 nonzero values
Produce a matrix `mat_connected` with the same nullspace as `mat` such that
`row_column_graph(mat_connected)` encodes a connected graph. Return `mat_connected` and
`row_column_graph(mat_connected)`.
"""
function connected_row_column_graph(mat::SparseMatrixCSC{<:Number, Int})
adj = row_column_graph(mat)
components = scomponents(adj)
if components.number > 1 # adj is not connected
root_component = components.map[end]
remove_rows = Int[]
zero_columns = Set{Int}()
matT = sparse(transpose(mat)) # SparseMatrixCSC row access is slow
for component in 1:components.number
if component != root_component
inds = findall(components.map .== component)
num_dependent_rows = length(inds) - find_rank(matT[:, inds])
if num_dependent_rows > 0 # some rows are redundant, remove them
append!(remove_rows, inds[1:num_dependent_rows])
else # submat has full rank and trivial nullspace
append!(remove_rows, inds) # remove these rows
for i in inds # set columns in these rows to 0
push!(zero_columns, findall(matT[:, i] .!= 0)...)
end
end
end
end
num_zeros = length(zero_columns)
zero_rows = sparse(1:num_zeros, collect(zero_columns), ones(num_zeros),
num_zeros, size(mat, 2))
remaining_inds = setdiff(1:size(mat, 1), remove_rows)
mat = vcat(transpose(matT[:, remaining_inds]), zero_rows)
adj = row_column_graph(mat) # adj is now connected
end
return mat, adj
end
find_rank(m::Matrix) = rank(m)
find_rank(m::SparseMatrixCSC) = rank(qr(1.0 * m))
"""
bfs_tree(adj::AbstractMatrix{Int}, root::Int)
Produce the vertices and edges of the tree found by performing breadth first on the graph
with adjacency matrix `adj` starting from the vertex `root`. The vertices includes all
vertices of the tree besides the root.
"""
function bfs_tree(adj::AbstractMatrix{Int}, root::Int)
dists, _, predecessors = bfs(adj, root)
tree_vertices, tree_edges = Int[], Tuple{Int, Int}[]
for i1 in reverse(sortperm(dists))
i2 = predecessors[i1]
if dists[i1] > 0 # exclude unreachables and the root
push!(tree_vertices, i1)
push!(tree_edges, tuple(sort([i1, i2])...))
end
end
return tree_vertices, tree_edges
end
# Find the nullspace of mat by solving the equations corresponding to each of its rows. We
# solve row `tree_rows[i]`` by eliminating variable `tree_columns[i]`.
function sparse_nullbasis(mat::SparseMatrixCSC{<:Number, Int},
tree_rows::AbstractVector{Int}, tree_columns::AbstractVector{Int})
@assert length(tree_rows) == length(tree_columns) == size(mat, 1)
non_tree_columns = setdiff(1:size(mat, 2), tree_columns)
# first create mapping that preserves the non_tree_columns
row_inds, col_inds, vals = Int[], Int[], Float64[]
for (col_ind, row_ind) in enumerate(non_tree_columns)
push!(row_inds, row_ind); push!(col_inds, col_ind); push!(vals, 1)
end
# work with transposes because SparseMatrixCSC row access is slow
nullbasisT = sparse(col_inds, row_inds, vals, length(non_tree_columns), size(mat, 2))
matT = sparse(transpose(mat))
# now solve row constraints by walking the tree from the leaves to the root
for (mat_row, mat_col) in zip(tree_rows, tree_columns)
null_row = spzeros(size(nullbasisT, 1))
for other_mat_col in findall(matT[:, mat_row] .!= 0)
if other_mat_col != mat_col
null_row += (-mat[mat_row, other_mat_col]/mat[mat_row, mat_col]) *
nullbasisT[:, other_mat_col]
end
end
nullbasisT[:, mat_col] = null_row
end
return sparse(transpose(nullbasisT))
end
"""
sparse_nullbasis(mat::SparseMatrixCSC{<:Number, Int})
Let `mat` be a matrix with the following properties
- for any two rows of `mat` there is at most one column on which both rows are nonzero
- any column of `mat` has at most 2 nonzero values
Produce a sparse matrix whose columns form a basis for the nullspace of `mat`.
"""
function sparse_nullbasis(mat::SparseMatrixCSC{<:Number, Int})
mat, adj = connected_row_column_graph(mat)
tree_rows, tree_edges = bfs_tree(adj, size(adj, 1))
tree_columns = [adj[r1, r2] for (r1, r2) in tree_edges]
return sparse_nullbasis(mat, tree_rows, tree_columns)
end
"""
nullbasis(mat::AbstractMatrix{<:Number}; warn::Bool=true)
Return a `SparseMatrixCSC` whose columns form a basis for the null space of mat. If `mat`
satisfies the conditions of `sparse_nullbasis`, a sparse matrix is returned. Otherwise a
warning is issued and the `LinearAlgebra.nullspace` function is used.
"""
function nullbasis(mat::AbstractMatrix{<:Number}; warn::Bool=true)
try
return sparse_nullbasis(sparse(mat))
catch AssertionError
if warn
@warn "sparse nullbasis not found"
end
return sparse(nullspace(collect(mat)))
end
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 8059 | using UniqueVectors: UniqueVector
using SparseArrays: spzeros, spdiagm
using LinearAlgebra: I, eigen, svd, diagm
using IterativeSolvers: lobpcg
export PSOModel
export lossless_modes_dense, lossy_modes_dense, lossless_modes_sparse
"""
PSOModel{T, U}(K::U, G::U, C::U, P::U, Q::U, ports::UniqueVector{T}) where {T, U}
PSOModel(K::U, G::U, C::U, P::U, Q::U, ports::AbstractVector{T}) where {T, U}
A Positive Second Order model, representing the equations `(K + G∂ₜ + C∂²ₜ)Φ = Px`,
`y = Qᵀ∂ₜΦ`.
"""
struct PSOModel{T, U<:AbstractMatrix{Float64}} <: AdmittanceModel{T}
K::U
G::U
C::U
P::U
Q::U
ports::UniqueVector{T}
function PSOModel{T, U}(K::U, G::U, C::U, P::U, Q::U,
ports::UniqueVector{T}) where {T, U}
l = size(K, 1)
@assert size(P) == (l, length(ports))
@assert size(Q) == (l, length(ports))
@assert all([size(y) == (l, l) for y in [K, G, C]])
return new{T, U}(K, G, C, P, Q, ports)
end
end
PSOModel(K::U, G::U, C::U, P::U, Q::U, ports::AbstractVector{T}) where {T, U} =
PSOModel{T, U}(K, G, C, P, Q, UniqueVector(ports))
get_Y(pso::PSOModel) = [pso.K, pso.G, pso.C]
get_P(pso::PSOModel) = pso.P
get_Q(pso::PSOModel) = pso.Q
get_ports(pso::PSOModel) = pso.ports
function partial_copy(pso::PSOModel{T, U};
Y::Union{Vector{V}, Nothing}=nothing,
P::Union{V, Nothing}=nothing,
Q::Union{V, Nothing}=nothing,
ports::Union{AbstractVector{W}, Nothing}=nothing) where {T, U, V, W}
Y = Y == nothing ? get_Y(pso) : Y
P = P == nothing ? get_P(pso) : P
Q = Q == nothing ? get_Q(pso) : Q
ports = ports == nothing ? get_ports(pso) : ports
return PSOModel(Y..., P, Q, ports)
end
compatible(psos::AbstractVector{PSOModel{T, U}}) where {T, U} = true
function canonical_gauge(pso::PSOModel)
fullP = collect(pso.P)
F = qr(fullP)
(m, n) = size(fullP)
transform = (F.Q * Matrix(I,m,m)) * [transpose(inv(F.R)) zeros(n, m-n);
zeros(m-n, n) Matrix(I, m-n, m-n)]
return apply_transform(pso, transform)
end
# NOTE we cannot write lossy_modes_sparse because KrylovKit.geneigsolve
# solves Av = λBv but requires that B is positive semidefinite and A is
# symmetric or Hermitian. For lossy modes, we can make B positive semidefinite
# and A nonsymmetric or A symmetric and B not positive semidefinite. If
# KrylovKit gains the ability to solve either type of eigenproblem we can
# write lossy_modes_sparse.
"""
lossy_modes_dense(pso::PSOModel; min_freq::Real=0,
max_freq::Union{Real, Nothing}=nothing, real_tol::Real=Inf, imag_tol::Real=Inf)
Use a dense eigenvalue solver to find the decaying modes of the PSOModel. Each mode consists
of an eigenvalue `λ` and a spatial distribution vector `v`. The frequency of the mode is
`imag(λ)/(2π)` and the decay rate is `-2*real(λ)/(2π)`. `min_freq` and `max_freq` give the
frequency range in which to find eigenvalues. Passivity is enforced using an inverse power
method solver, and `real_tol` and `imag_tol` are the tolerances used in that method to
determine convergence of the real and imaginary parts of the eigenvalue.
"""
function lossy_modes_dense(pso::PSOModel; min_freq::Real=0,
max_freq::Union{Real, Nothing}=nothing, real_tol::Real=Inf, imag_tol::Real=Inf)
K, G, C = get_Y(pso)
Z = zero(K)
M = collect([C Z; Z I]) \ collect([-G -K; I Z])
M_scale = maximum(abs.(M))
# for some reason eigen(Y \ X) seems to perform better than eigen(X, Y)
values, vectors = eigen(M/M_scale)
values *= M_scale
freqs = imag.(values)/(2π)
if max_freq == nothing
max_freq = maximum(freqs)
end
inds = findall(max_freq .>= freqs .>= min_freq)
values, vectors = values[inds], vectors[:, inds]
# enforce passivity using inverse power method
pred(x, y) = ((real(y) <= 0) && (abs(real(x-y)) < real_tol) &&
(abs(imag(x-y)) < imag_tol))
for i in 1:length(values)
if real(values[i]) > 0
λ, v = inv_power_eigen(M, v0=vectors[:, i], λ0=values[i], pred=pred)
values[i] = λ
vectors[:, i] = v
end
end
# the second half of the eigenvector is the spatial part
vectors = vectors[size(K, 1)+1:end, :]
# normalize the columns
return values, vectors./sqrt.(sum(abs2.(vectors), dims=1))
end
"""
lossless_modes_dense(pso::PSOModel; min_freq::Real=0,
max_freq::Union{Real, Nothing}=nothing)
Use a dense svd solver to find the modes of the PSOModel neglecting loss. Each mode consists
of an eigenvalue `λ` and an eigenvector `v`. The frequency of the mode is `imag(λ)/(2π)`
and the decay rate is `-2*real(λ)/(2π)`. `min_freq` and `max_freq` give the
frequency range in which to find eigenvalues.
"""
function lossless_modes_dense(pso::PSOModel; min_freq::Real=0,
max_freq::Union{Real, Nothing}=nothing)
K, _, C = get_Y(pso)
K = .5 * (transpose(K) + K)
C = .5 * (transpose(C) + C)
sqrt_C, sqrt_K = sqrt(collect(C)), sqrt(collect(K))
M = sqrt_C \ sqrt_K
scale = maximum(abs.(M))
U, S, Vt = svd(M/scale)
freqs = S * scale/(2π)
vectors = real.(sqrt_C \ U)
if max_freq == nothing
max_freq = maximum(freqs)
end
inds = findall(max_freq .>= freqs .>= min_freq)
freqs, vectors = freqs[inds], vectors[:, inds]
inds = sortperm(freqs)
return freqs[inds] * 2π * 1im, vectors[:, inds]
end
"""
lossless_modes_sparse(pso::PSOModel; num_modes=1, maxiter=200)
Use a sparse generalized eigenvalue solver to find the `num_modes` lowest frequency modes
of the PSOModel neglecting loss. Each mode consists of an eigenvalue `λ` and an eigenvector
`v`. The frequency of the mode is `imag(λ)/(2π)` and the decay rate is `-2*real(λ)/(2π)`.
"""
function lossless_modes_sparse(pso::PSOModel; num_modes=1, maxiter=200)
K, _, C = get_Y(pso)
K = (K + transpose(K))/2
C = (C + transpose(C))/2
K_scale, C_scale = maximum(abs.(K)), maximum(abs.(C))
result = lobpcg(K/K_scale, C/C_scale, false, num_modes, maxiter=maxiter)
values = result.λ * (K_scale/C_scale)
vectors = result.X
return real.(sqrt.(values)) * 1im, vectors
end
function port_matrix(circuit::Circuit, port_edges::Vector{<:Tuple})
coord_matrix = coordinate_matrix(circuit)
if length(port_edges) > 0
port_indices = [(findfirst(isequal(p[1]), circuit.vertices),
findfirst(isequal(p[2]), circuit.vertices)) for p in port_edges]
return hcat([coord_matrix[:, i1] - coord_matrix[:, i2]
for (i1, i2) in port_indices]...)
else
return spzeros(size(coord_matrix, 1), 0)
end
end
circuit_to_pso_matrix(m::AbstractMatrix{<:Real}) =
(-m + spdiagm(0=>sum(m, dims=2)[:,1]))[2:end, 2:end]
"""
PSOModel(circuit::Circuit, port_edges::Vector{<:Tuple},
port_names::AbstractVector)
Create a PSOModel for a circuit with ports on given edges. The spanning tree where the
first vertex is chosen as ground and all other vertices are neighbors of ground is used.
"""
function PSOModel(circuit::Circuit, port_edges::Vector{<:Tuple},
port_names::AbstractVector)
Y = [circuit_to_pso_matrix(m) for m in matrices(circuit)]
P = port_matrix(circuit, port_edges)
return PSOModel(Y..., P, P, port_names)
end
coordinate_transform(m::AbstractMatrix{<:Real}) = m[:,2:end] .- m[:,1]
function coordinate_transform(coord_matrix_from::AbstractMatrix{<:Real},
coord_matrix_to::AbstractMatrix{<:Real})
return coordinate_transform(coord_matrix_to)/coordinate_transform(coord_matrix_from)
end
"""
PSOModel(circuit::Circuit, port_edges::Vector{<:Tuple},
port_names::AbstractVector, tree::SpanningTree)
Create a PSOModel for a circuit with ports on given edges and using the given spanning tree.
"""
function PSOModel(circuit::Circuit, port_edges::Vector{<:Tuple},
port_names::AbstractVector, tree::SpanningTree)
pso = PSOModel(circuit, port_edges, port_names)
transform = transpose(coordinate_transform(coordinate_matrix(circuit, tree)))
return apply_transform(pso, transform)
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 3247 | module CircuitExample
using AdmittanceModels
Q0_SIGNAL = "q0_signal"
Q0_GROUND = "q0_ground"
Q1_SIGNAL = "q1_signal"
Q1_GROUND = "q1_ground"
GROUND = AdmittanceModels.ground
circuit = Circuit([Q0_SIGNAL, Q0_GROUND, Q1_SIGNAL, Q1_GROUND, GROUND])
set_capacitance!(circuit, Q0_SIGNAL, Q0_GROUND, 100.0)
set_capacitance!(circuit, Q1_SIGNAL, Q1_GROUND, 100.0)
set_capacitance!(circuit, Q0_SIGNAL, Q1_SIGNAL, 10.0)
set_capacitance!(circuit, Q0_GROUND, Q1_GROUND, 10.0)
set_capacitance!(circuit, Q0_GROUND, GROUND, 1.0)
set_capacitance!(circuit, Q1_GROUND, GROUND, 1.0)
set_inv_inductance!(circuit, Q0_SIGNAL, Q0_GROUND, .1)
set_inv_inductance!(circuit, Q1_SIGNAL, Q1_GROUND, .1)
root = GROUND
edges = [(Q0_SIGNAL, Q0_GROUND),
(Q0_GROUND, GROUND),
(Q1_SIGNAL, Q1_GROUND),
(Q1_GROUND, GROUND)]
tree = SpanningTree(root, edges)
end
module CircuitCascadeExample
using LinearAlgebra: I
using AdmittanceModels
circuit0 = Circuit([0,1,2,3])
set_capacitance!(circuit0, 0, 1, 1.0)
set_capacitance!(circuit0, 0, 2, 2.0)
set_capacitance!(circuit0, 0, 3, 1.0)
set_capacitance!(circuit0, 1, 2, 10.0)
set_capacitance!(circuit0, 1, 3, 20.0)
set_capacitance!(circuit0, 2, 3, 30.0)
c = circuit0.c
i = ones(size(c)...) - I
k = 2*c + i
g = 3*c + 2 * i
circuit0 = Circuit(k, g, c, circuit0.vertices)
circuit1 = Circuit(2*k+3*i, 3*g+5*i, 8*c+2*i, [4,5,6,7])
circuit2 = Circuit(12*k+4*i, 11*g+2*i, 9*c+i, [8,9,10,11])
end
module PSOModelExample
using AdmittanceModels
using SparseArrays: sparse, spzeros
K = sparse(hcat([[0.1, 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0.1, 0.],
[0., 0., 0., 0.]]...))
G = spzeros(size(K)...)
C = sparse(hcat([[110., 10., -10., -10.],
[10., 21., -10., -20.],
[-10., -10., 110., 10.],
[-10., -20., 10., 21.]]...))
PORT_0 = "port_0"
PORT_1 = "port_1"
ports = [PORT_0, PORT_1]
P = 1.0 * sparse([[1, 0, 0, 0] [0, 0, 1, 0]])
pso = PSOModel(K, G, C, P, P, ports)
end
module LRCExample
using AdmittanceModels
circuit = Circuit([0, 1])
l, r, c = 1.0, 100.0, 3.0
ω = sqrt(1/(l * c) - 1/(2 * r * c)^2)
κ = 1/(r * c)
set_inv_inductance!(circuit, 0, 1, 1/l)
set_conductance!(circuit, 0, 1, 1/r)
set_capacitance!(circuit, 0, 1, c)
pso = PSOModel(circuit, [(0, 1)], ["port"])
end
module HalfWaveExample
using AdmittanceModels
ν, Z0, δ = 1e8, 50.0, 150e-6
resonator_length = 10e-3
coupler_locs = resonator_length * [1/3, 2/3]
resonator = TransmissionLine(["short_1", "coupler_1", "coupler_2", "short_2"],
ν, Z0, resonator_length, coupler_locs, δ)
coupling_cs = [10, 15] * 1e-15
capacitors = [SeriesComponent("coupler_$i", "qubit_$i", 0, 0, coupling_cs[i]) for i in 1:2]
qubit_cs = [100, 120] * 1e-15
qubits = [ParallelComponent("qubit_$i", 0, 0, qubit_cs[i]) for i in 1:2]
casc = Cascade([resonator; capacitors; qubits], [short_ports => ["short_1", "short_2"],
open_ports_except => ["qubit_1", "qubit_2"]])
pso = PSOModel(casc)
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 279 | include("examples.jl")
include("test_linear_algebra.jl")
include("test_circuit.jl")
include("test_pso_model.jl")
include("test_blackbox.jl")
include("test_circuit_components.jl")
include("test_ansys.jl")
include("../paper/radiative_loss.jl")
include("../paper/hybridization.jl")
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 1533 | @testset "Q3D plain text parsing" begin
data(x) = joinpath(@__DIR__, "data", x)
# file should satisfy some basic checks
@test_throws AssertionError Circuit(data("empty.txt"))
@test_throws AssertionError Circuit(data("one_block.txt"))
# test expected output
d = data("dummy_gc_1.txt")
@test Circuit(d).vertices == ["net1", "net2", "net3", "net4"]
design_variation, vertex_names, capacitance_matrix =
AdmittanceModels.parse_q3d_txt(d, :capacitance)
# test negative val + no units
@test design_variation["dummy1"] == (-1.23, "")
# test negative exponent + units
@test design_variation["dummy2"] == (9.0e-7, "mm")
# test negative val, positive exponent + units
@test design_variation["dummy3"] == (-1.0e21, "pF")
# test units that start with "e" (the parser should look for things like 'e09' or 'e-12')
@test design_variation["dummy4"] == (1.2, "eunits")
# unit not implemented
@test_throws ErrorException try
Circuit(data("dummy_gc_2.txt"); matrix_types = [:conductance])
catch e
buf = IOBuffer()
showerror(buf, e)
message = String(take!(buf))
@test occursin("not implemented", message)
rethrow(e)
end
@test_throws ErrorException try
Circuit(data("dummy_gc_3.txt"); matrix_types = [:conductance])
catch e
buf = IOBuffer()
showerror(buf, e)
message = String(take!(buf))
@test occursin("units not given", message)
rethrow(e)
end
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 3056 | using Test, AdmittanceModels, LinearAlgebra
import .PSOModelExample, .LRCExample, .CircuitCascadeExample
const ae = PSOModelExample
const lrce = LRCExample
const cce = CircuitCascadeExample
@testset "PSOModel to Blackbox" begin
# test 1
ω = collect(range(4, stop=6, length=1000)) * 1e9 * 2π
bbox = Blackbox(ω, ae.pso)
@test get_ports(bbox) == get_ports(ae.pso)
@test length(get_Y(bbox)) == length(ω)
@test size(get_Y(bbox)[1]) == size(ae.pso.K)
bbox = canonical_gauge(bbox)
@test size(get_Y(bbox)[1]) == (2,2)
# test 2
l, r, c, ω₀ = lrce.l, lrce.r, lrce.c, lrce.ω
ω = collect(range(.8, stop=1.2, length=1000)) * ω₀
bbox = Blackbox(ω, lrce.pso)
z = 1 ./(1 ./(l * 1im * ω) .+ 1/r .+ c * 1im * ω)
@test length(get_Y(bbox)) == length(ω)
impedance = impedance_matrices(bbox)
@test all([size(x) == (1,1) for x in impedance])
@test [x[1,1] for x in impedance] ≈ z
end
@testset "cascade, unite_ports, open_ports, short_ports" begin
# cascade
pso0 = PSOModel(cce.circuit0, [(0,1), (0,2)], [1, 2])
pso1 = PSOModel(cce.circuit1, [(4,5), (4,6)], [5, 6])
pso2 = PSOModel(cce.circuit2, [(8,9), (8,10)], [9, 10])
pso = cascade(pso0, pso1, pso2)
ω = collect(range(.1, stop=100, length=1000)) * 2π
bbox_from_pso = Blackbox(ω, pso)
@test get_ports(bbox_from_pso) == get_ports(pso)
bboxes0 = [Blackbox(ω, a) for a in [pso0, pso1, pso2]]
bbox0 = cascade(bboxes0)
@test bbox0 ≈ bbox_from_pso
bboxes1 = [canonical_gauge(b) for b in bboxes0]
bbox1 = cascade(bboxes1)
@test bbox1 ≈ canonical_gauge(bbox_from_pso)
# unite_ports
united_pso = unite_ports(pso, 1, 5, 9)
bbox_from_pso = Blackbox(ω, united_pso)
@test get_ports(bbox_from_pso) == get_ports(united_pso)
united_bbox0 = unite_ports(bbox0, 1, 5, 9)
@test united_bbox0 ≈ bbox_from_pso
united_bbox1 = unite_ports(bbox1, 1, 5, 9)
@test canonical_gauge(united_bbox1) ≈ canonical_gauge(bbox_from_pso)
# open_ports
open_pso = open_ports(united_pso, 2, 6)
bbox_from_pso = Blackbox(ω, open_pso)
open_bbox = open_ports(united_bbox1, 2, 6)
@test canonical_gauge(open_bbox) ≈ canonical_gauge(bbox_from_pso)
# short_ports
short_pso = short_ports(united_pso, 2, 6)
bbox_from_pso = Blackbox(ω, short_pso)
short_bbox = short_ports(united_bbox1, 2, 6)
@test canonical_gauge(short_bbox) ≈ canonical_gauge(bbox_from_pso)
end
# Pozar p 192
@testset "transfer function conversions" begin
a, b, c, d = 1.0, 2.0, 3.0, 4.0
Z0 = 10.0
Y = [[d, -1] [b * c - a * d, a]] ./ b
Z = [[a, 1] [a * d - b * c, d]] ./ c
denom = a + b/Z0 + c * Z0 + d
S = [[a + b/Z0 - c * Z0 - d, 2] [2 * (a * d - b * c), -a + b/Z0 - c * Z0 + d]] ./ denom
@test inv(Y) ≈ Z
Z0s = [Z0, Z0]
@test AdmittanceModels.admittance_to_scattering(Y, Z0s) ≈ S
@test AdmittanceModels.scattering_to_admittance(S, Z0s) ≈ Y
@test AdmittanceModels.impedance_to_scattering(Z, Z0s) ≈ S
@test AdmittanceModels.scattering_to_impedance(S, Z0s) ≈ Z
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 2088 | using Test, AdmittanceModels, LinearAlgebra
import .CircuitExample, .CircuitCascadeExample
const ce = CircuitExample
const cce = CircuitCascadeExample
@testset "Circuit" begin
@test length(ce.circuit.vertices) == 5
for m in matrices(ce.circuit)
@test size(m) == (5,5)
@test issymmetric(m)
end
@test get_inv_inductance(ce.circuit, ce.Q0_SIGNAL, ce.Q0_GROUND) == .1
@test get_inv_inductance(ce.circuit, ce.Q0_GROUND, ce.Q0_SIGNAL) == .1
@test get_conductance(ce.circuit, ce.Q0_SIGNAL, ce.Q0_GROUND) == 0
@test get_conductance(ce.circuit, ce.Q0_GROUND, ce.Q0_SIGNAL) == 0
@test get_capacitance(ce.circuit, ce.Q0_SIGNAL, ce.Q0_GROUND) == 100
@test get_capacitance(ce.circuit, ce.Q0_GROUND, ce.Q0_SIGNAL) == 100
end
@testset "coordinate_matrix" begin
@test coordinate_matrix(3) == [[0,0] [1,0] [0,1]]
@test coordinate_matrix(ce.circuit) == coordinate_matrix(5)
coordinate_matrix(ce.circuit, SpanningTree(ce.circuit.vertices)) == coordinate_matrix(5)
correct_matrix = [[1, 1, 0, 0] [0, 1, 0, 0] [0, 0, 1, 1] [0, 0, 0, 1] [0, 0, 0, 0]]
@test coordinate_matrix(ce.circuit, ce.tree) == correct_matrix
end
@testset "cascade and unite_vertices" begin
circ = cascade(cce.circuit0, cce.circuit1, cce.circuit2)
@test circ.vertices == 0:11
l = length(circ.vertices)
@test size(circ.c) == (l, l)
united_circ = unite_vertices(circ, 0, 4, 8)
united_circ = unite_vertices(united_circ, 1, 5, 9)
@test united_circ.vertices == [0, 1, 2, 3, 6, 7, 10, 11]
l = length(united_circ.vertices)
@test size(united_circ.c) == (l, l)
@test get_capacitance(united_circ, 2, 3) == get_capacitance(circ, 2, 3)
@test get_inv_inductance(united_circ, 6, 1) == get_inv_inductance(circ, 6, 5)
s = get_conductance(circ, 0, 1) + get_conductance(circ, 4, 5) + get_conductance(circ, 8, 9)
@test get_conductance(united_circ, 0, 1) == s
united_circ = unite_vertices(united_circ, 0, 1)
s = get_capacitance(circ, 3, 0) + get_capacitance(circ, 3, 1)
@test get_capacitance(united_circ, 3, 0) == s
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 2363 | using Test, AdmittanceModels, LinearAlgebra
@testset "TransmissionLine with terminations" begin
Z0 = 50.0
tline = TransmissionLine(["0", "1"], 1e8, Z0, 5e-3, δ=50e-6)
ω = 2π * collect(range(4, stop=6, length=100)) * 1e9
pso = PSOModel(tline)
bbox0 = canonical_gauge(Blackbox(ω, pso))
bbox1 = Blackbox(ω, tline)
@test isapprox(admittance_matrices(bbox0), admittance_matrices(bbox1), atol=1e-5)
@test !isapprox(admittance_matrices(bbox0), admittance_matrices(bbox1), atol=1e-6)
# now terminate it with Z0
resistor = ParallelComponent("1", 0, 1/Z0, 0)
casc = Cascade([tline, resistor], [open_ports_except => ["0"]])
S = [x[1,1] for x in scattering_matrices(Blackbox(ω, PSOModel(casc)), [Z0])]
@test all([abs(x) < 1e-4 for x in S])
S = [x[1,1] for x in scattering_matrices(Blackbox(ω, casc), [Z0])]
@test all([abs(x) < 1e-15 for x in S])
# now terminate it with Z0/2
z0 = Z0/2
resistor = ParallelComponent("1", 0, 1/z0, 0)
casc = Cascade([tline, resistor], [open_ports_except => ["0"]])
S = [x[1,1] for x in scattering_matrices(Blackbox(ω, PSOModel(casc)), [Z0])]
correct_S = ((z0 - Z0)/(z0 + Z0)) * exp.(-2im * ω * tline.len/tline.propagation_speed)
@test isapprox(S, correct_S, rtol=1e-4)
S = [x[1,1] for x in scattering_matrices(Blackbox(ω, casc), [Z0])]
@test isapprox(S, correct_S, rtol=1e-14)
end
@testset "reflection λ/4 resonator" begin
Z0 = 50.0
tline = TransmissionLine(["open", "coupler", "short"], 1e8, Z0, 5e-3, locations=[1e-3], δ=50e-6)
capacitor = SeriesComponent("in", "coupler", 0, 0, 10e-15)
casc = Cascade([tline, capacitor], [short_ports => ["short"], open_ports_except => ["in"]])
ω = 2π * collect(range(4, stop=6, length=500)) * 1e9
bbox0 = canonical_gauge(Blackbox(ω, PSOModel(casc)))
bbox1 = Blackbox(ω, casc)
circ = cascade_and_unite(Circuit(tline, "tline"), Circuit(capacitor))
g = AdmittanceModels.ground
circ = unite_vertices(circ, g, "short")
pso = PSOModel(circ, [("in", g)], ["in"])
bbox2 = canonical_gauge(Blackbox(ω, pso))
@test isapprox(admittance_matrices(bbox0), admittance_matrices(bbox1), atol=1e-3)
@test isapprox(admittance_matrices(bbox0), admittance_matrices(bbox2), atol=1e-11)
@test !isapprox(admittance_matrices(bbox0), admittance_matrices(bbox1), atol=1e-4)
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 3252 | using Test, AdmittanceModels
using LinearAlgebra: eigen, rank, nullspace
using SparseArrays: sparse, SparseMatrixCSC
@testset "closest_permutation" begin
mat = [[1, 0, 2, 0, 1.5] [1, 0, 3, 0, 2] [1, 0, 1.3, 0, 1.4]]
u = AdmittanceModels.closest_permutation(mat)
@test vcat(sum(u, dims=1)...) == [1,1,1]
_, indices = findmax(u, dims=1)
@test [index[1] for index in vcat(indices...)] == [5,3,1]
end
@testset "inv_power_eigen" begin
M = [1im 2.2 4; 3.1 0.2 3; 4 1 2im]
F = eigen(M)
for i in 1:size(M, 1)
v0, λ0 = F.vectors[:,i], F.values[i]
λ, v = AdmittanceModels.inv_power_eigen(M, v0=v0)
@test λ ≈ λ0
λ, v = AdmittanceModels.inv_power_eigen(M, λ0=λ0)
@test λ ≈ λ0
λ, v = AdmittanceModels.inv_power_eigen(M, v0=v0, λ0=λ0)
@test λ ≈ λ0
end
end
@testset "row_column_graph" begin
rows = [[1.0, 2.0, -3.0, 0, 0, 0, 0],
[ 0, 0, 1.0, -4.0, 0, 0, 0],
[ 0.1, 0, 0, -0.3, 0, 0, 0],
[ 0, 0, 0, 0, 1, 1, 0],
[ 0, 0, 0, 0, 0, 1, -1]]
mat = sparse(transpose(hcat(rows...)))
correct_adj = zeros(Int, size(rows, 1)+1, size(rows, 1)+1)
correct_adj[1, 2] = correct_adj[2, 1] = 3
correct_adj[1, 3] = correct_adj[3, 1] = 1
correct_adj[1, 6] = correct_adj[6, 1] = 2
correct_adj[2, 3] = correct_adj[3, 2] = 4
correct_adj[4, 5] = correct_adj[5, 4] = 6
correct_adj[4, 6] = correct_adj[6, 4] = 5
correct_adj[5, 6] = correct_adj[6, 5] = 7
adj = AdmittanceModels.row_column_graph(mat)
@test adj == correct_adj
end
@testset "sparse_nullbasis and nullbasis" begin
# example with no redundancies or inconsistentices
rows = [[1.0, 2.0, -3.0, 0, 0, 0, 0],
[ 0, 0, 1.0, -4.0, 0, 0, 0],
[0.1, 0, 0, -0.3, 0, 0, 0],
[ 0, 0, 0, 0, 1, 1, 0],
[ 0, 0, 0, 0, 0, 1, -1]]
mat = sparse(transpose(hcat(rows...)))
null_basis = AdmittanceModels.sparse_nullbasis(mat)
@test count(!iszero, mat * null_basis) == 0
@test rank(collect(mat)) + rank(collect(null_basis)) == size(mat, 2) # rank nullity theorem
@test count(!iszero, nullspace(collect(mat))) == 14 # dense
@test count(!iszero, null_basis) == 7 # sparse
@test AdmittanceModels.nullbasis(mat) == null_basis
# example with redundancies and inconsistentices
rows = [[1, -1, 0, 0, 0, 0],
[1, 0, -1, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, -1, 0],
[0, 0, 0, 1, 0, -1],
[0, 0, 0, 0, 1, -1]]
mat = sparse(transpose(hcat(rows...)))
null_basis = AdmittanceModels.sparse_nullbasis(mat)
@test count(!iszero, mat * null_basis) == 0
@test rank(collect(mat)) + rank(collect(null_basis)) == size(mat, 2) # rank nullity theorem
@test AdmittanceModels.sparse_nullbasis(sparse(mat)) == null_basis
@test AdmittanceModels.nullbasis(mat) == null_basis
# example where sparse nullbasis algorithm does not apply
mat = reshape(collect(1:9), 3,3)
@test_throws AssertionError AdmittanceModels.sparse_nullbasis(sparse(mat))
@test AdmittanceModels.nullbasis(mat, warn=false) == nullspace(mat)
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | code | 5120 | using Test, AdmittanceModels, LinearAlgebra
const ce = CircuitExample
const ae = PSOModelExample
const cce = CircuitCascadeExample
const lrce = LRCExample
const hwe = HalfWaveExample
using SparseArrays: SparseMatrixCSC
@testset "PSOModel" begin
@test length(ae.pso.ports) == 2
for m in get_Y(ae.pso)
@test size(m) == (4,4)
@test issymmetric(m)
end
@test size(get_P(ae.pso)) == (4, 2)
@test get_Q(ae.pso) == get_P(ae.pso)
end
@testset "coordinate_transform" begin
coord_matrix_from = coordinate_matrix(ce.circuit)
coord_matrix_to = coordinate_matrix(ce.circuit, ce.tree)
transform = AdmittanceModels.coordinate_transform(coord_matrix_from, coord_matrix_to)
@test AdmittanceModels.coordinate_transform(coord_matrix_from) == I
@test AdmittanceModels.coordinate_transform(coord_matrix_to) != I
@test transform * AdmittanceModels.coordinate_transform(coord_matrix_from) ==
AdmittanceModels.coordinate_transform(coord_matrix_to)
end
@testset "Circuit to PSOModel" begin
converted_pso = PSOModel(ce.circuit, [(ce.Q0_SIGNAL, ce.Q0_GROUND),
(ce.Q1_SIGNAL, ce.Q1_GROUND)],
get_ports(ae.pso), ce.tree)
@test ae.pso == converted_pso
end
@testset "cascade, unite_ports, open_ports, short_ports" begin
# cascade and unite_ports
circ = cascade(cce.circuit0, cce.circuit1, cce.circuit2)
united_circ = unite_vertices(circ, 0, 4, 8)
united_circ = unite_vertices(united_circ, 1, 5, 9)
port_edges = [(united_circ.vertices[1], v) for v in united_circ.vertices[2:end]]
port_names = united_circ.vertices[2:end]
pso_from_circuit = PSOModel(united_circ, port_edges, port_names)
pso0 = PSOModel(cce.circuit0, [(0,1), (0,2), (0, 3)], [1, 2, 3])
pso1 = PSOModel(cce.circuit1, [(4,5), (4,6), (4,7)], [5, 6, 7])
pso2 = PSOModel(cce.circuit2, [(8,9), (8,10), (8,11)], [9, 10, 11])
pso = cascade(pso0, pso1, pso2)
united_pso = unite_ports(pso, 1, 5, 9)
transform = transpose(get_P(united_pso)/get_P(pso_from_circuit))
pso_transform = apply_transform(pso_from_circuit, transform)
@test pso_transform ≈ united_pso
# open_ports
port_edges = port_edges[1:2]
port_names = port_names[1:2]
pso_from_circuit = PSOModel(united_circ, port_edges, port_names)
pso_transform = apply_transform(pso_from_circuit, transform)
united_pso = open_ports(united_pso, get_ports(united_pso)[3:end])
@test pso_transform ≈ united_pso
# short_ports
united_circ = unite_vertices(united_circ, 0, 2, 6)
port_edges = [(united_circ.vertices[1], v) for v in united_circ.vertices[2:end]]
port_names = united_circ.vertices[2:end]
pso_from_circuit = PSOModel(united_circ, port_edges, port_names)
united_pso = unite_ports(pso, 1, 5, 9)
united_pso = short_ports(united_pso, 2, 6)
transform = transpose(get_P(united_pso)/get_P(pso_from_circuit))
pso_transform = apply_transform(pso_from_circuit, transform)
@test pso_transform ≈ united_pso
end
@testset "lossy_modes_dense and lossless_modes_dense" begin
eigenvalues, eigenvectors = lossy_modes_dense(lrce.pso)
@test length(eigenvalues) == 1
@test size(eigenvectors) == (1,1)
decay_rate = -2 * real(eigenvalues[1])
frequency = imag(eigenvalues[1])/(2π)
@test frequency ≈ lrce.ω/(2π)
@test decay_rate ≈ lrce.κ
eigenvalues, eigenvectors = lossless_modes_dense(lrce.pso)
@test length(eigenvalues) == 1
@test size(eigenvectors) == (1,1)
decay_rate = -2 * real(eigenvalues[1])
frequency = imag(eigenvalues[1])/(2π)
@test frequency ≈ 1/(sqrt(lrce.l * lrce.c) * 2π)
@test decay_rate == 0
end
@testset "lossless_modes_sparse and tline resonator modes" begin
ν, Z0 = 1.2e8, 50.0
L = 5e-3
δ = 50e-6
resonator = TransmissionLine(["0", "1"], ν, Z0, L, δ=δ)
pso = PSOModel(resonator)
pso = short_ports(pso, pso.ports)
for Y in get_Y(pso) # pso model is sparse
@test count(!iszero, Y)/(size(Y,1) * size(Y, 2)) < .05
end
num_modes = 5
values_s, vectors_s = lossless_modes_sparse(pso, num_modes=num_modes)
values_d, vectors_d = lossless_modes_dense(pso)
values_d, vectors_d = values_d[1:num_modes], vectors_d[:, 1:num_modes]
@test isapprox(values_s, values_d, rtol=1e-6)
for i in 1:5
v_s, v_d = vectors_s[:, i], vectors_d[:, i]
j = argmax(abs.(v_s))
v_s /= v_s[j]
v_d /= v_d[j]
@test isapprox(v_s, v_d, rtol=1e-2)
end
@test isapprox(ν/(2*L) * (1:num_modes), imag.(values_s)/(2π), rtol=1e-3)
@test isapprox(ν/(2*L) * (1:num_modes), imag.(values_d)/(2π), rtol=1e-3)
end
@testset "canonical_gauge" begin
circ = cce.circuit0
port_edges = [(1,2), (2,3)]
port_names = [1, 2]
pso = PSOModel(circ, port_edges, port_names)
P = canonical_gauge(pso).P
@test typeof(pso.P) <: SparseMatrixCSC
@test typeof(P) <: Matrix
m, n = size(P)
@test P ≈ [Matrix(I, n, n); zeros(m-n, n)]
m, n = size(hwe.pso.P)
@test canonical_gauge(hwe.pso).P ≈ [Matrix(I, n, n); zeros(m-n, n)]
end
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | docs | 728 | AdmittanceModels.jl was developed in 2019 by Michael G. Scheer. The package accompanies the paper by Michael G. Scheer and Maxwell B. Block titled [Computational modeling of decay and hybridization in superconducting circuits](https://arxiv.org/abs/1810.11510). Michael and Max previously coauthored a Python implementation of the functionality in this package. The Python implementation was used in early drafts of the paper cited above, but the figures in the latest draft of the paper were created with the code in the `paper` folder of this repository. Thanks to Andrew Keller and Alex Mellnik for helpful advice on Julia best practices and to Dan Girshovich for helpful advice on both the Python and Julia implementations.
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.0 | 7d3081e94a9f20a5b8ea90f3f7bdb26105a22b11 | docs | 4777 | # AdmittanceModels.jl
[paper-url]: https://arxiv.org/abs/1810.11510
[travis-img]: https://travis-ci.com/rigetti/AdmittanceModels.jl.svg?branch=master
[travis-url]: https://travis-ci.com/rigetti/AdmittanceModels.jl
[codecov-img]: https://codecov.io/gh/rigetti/AdmittanceModels.jl/branch/master/graph/badge.svg
[codecov-url]: https://codecov.io/gh/rigetti/AdmittanceModels.jl
[![][travis-img]][travis-url]
[![][codecov-img]][codecov-url]
AdmittanceModels.jl is a package for creating and manipulating linear input-output models of the form `YΦ = Px`, `y = QᵀΦ` where `x` are the inputs and `y` are the outputs. One example of such a model is a Positive Second Order model, defined in [[1]][paper-url]. Such models can capture the equations of motion of a circuit consisting of inductors, capacitors, and resistors.
The scripts in `paper` were used to generate the figures in [[1]][paper-url].
If you use this package in a publication, please cite our paper:
```
@article{ScheerBlock2018,
author = {Michael G. Scheer and Maxwell B. Block},
title = "{Computational modeling of decay and hybridization in superconducting circuits}",
year = "2018",
month = "Oct",
note = {arXiv:1810.11510},
archivePrefix = {arXiv},
eprint = {1810.11510},
primaryClass = {quant-ph},
}
```
[1] [Computational modeling of decay and hybridization in superconducting circuits][paper-url]
## Installation
Clone the repository from GitHub and install Julia 1.1. No build is required beyond the default Julia compilation.
## Example usage: the circuit in Appendix A of [[1]][paper-url]
Construct the circuit in Appendix A, with arbitrarily chosen values.
```julia
using AdmittanceModels
vertices = collect(0:4)
circuit = Circuit(vertices)
set_capacitance!(circuit, 0, 1, 10.0)
set_capacitance!(circuit, 1, 2, 4.0)
set_capacitance!(circuit, 0, 3, 4.0)
set_capacitance!(circuit, 2, 3, 5.0)
set_capacitance!(circuit, 3, 4, 5.0)
set_inv_inductance!(circuit, 1, 2, 3.5)
set_inv_inductance!(circuit, 0, 3, 4.5)
```
Use the spanning tree in Appendix A to find a Positive Second Order model.
```julia
root = 0
edges = [(1, 0),
(3, 0),
(4, 0),
(2, 1)]
tree = SpanningTree(root, edges)
PSOModel(circuit, [(4, 0)], ["port"], tree)
```
The tree is optional because a change of spanning tree is simply an invertible change of coordinates.
```julia
PSOModel(circuit, [(4, 0)], ["port"])
```
## Example usage: a λ/4 transmission line resonator capacitively coupled to a transmission line
The model we will analyze is similar the device shown below, from [Manufacturing low dissipation superconducting quantum processors](https://arxiv.org/abs/1901.08042).

Create `CircuitComponent` objects for the model.
```julia
using AdmittanceModels
ν = 1.2e8 # propagation_speed
Z0 = 50.0 # characteristic_impedance
δ = 100e-6 # discretization length
resonator = TransmissionLine(["coupler_0", "short"], ν, Z0, 5e-3, δ=δ)
tline = TransmissionLine(["in", "coupler_1", "out"], ν, Z0, 2e-3, locations=[1e-3], δ=δ)
coupler = SeriesComponent("coupler_0", "coupler_1", 0, 0, 10e-15)
components = [resonator, tline, coupler]
```
Use `Cascade` and `PSOModel` objects to compute the frequency and decay rate of quarter wave resonator mode. Include resistors at the ports in order to get the correct decay rate.
```julia
resistors = [ParallelComponent(name, 0, 1/Z0, 0) for name in ["in", "out"]]
pso = PSOModel(Cascade([components; resistors], [short_ports => ["short"]]))
λs, _ = lossy_modes_dense(pso, min_freq=3e9, max_freq=7e9)
freq = imag(λs[1])/(2π)
decay = -2*real(λs[1])/(2π)
```
Compute the transmission scattering parameters using `Cascade` and `Blackbox`. This uses a closed form representation of the transmission lines.
```julia
ω = collect(range(freq - 2 * decay, stop=freq + 2 * decay, length=300)) * 2π
bbox = Blackbox(ω, Cascade(components, [short_ports => ["short"], open_ports_except => ["in", "out"]]))
S = [x[1,2] for x in scattering_matrices(bbox, [Z0, Z0])]
```
Plot the magnitude of the scattering parameters.
```julia
using PlotlyJS
plot(scatter(x=ω/(2π*1e9), y=abs.(S)), Layout(xaxis_title="Frequency [GHz]", yaxis_title="|S|"))
```

Plot the phase of the scattering parameters.
```julia
plot(scatter(x=ω/(2π*1e9), y=angle.(S)), Layout(xaxis_title="Frequency [GHz]", yaxis_title="Phase(S)"))
```

## Using with ANSYS Q3D Extractor
Plain text files containing RLGC parameters exported by ANSYS® Q3D Extractor®
software can be used to construct a `Circuit` object via `Circuit(file_path)`.
Currently only capacitance matrices are supported.
ANSYS and Q3D Extractor are registered trademarks of ANSYS, Inc. or its
subsidiaries in the United States or other countries.
| AdmittanceModels | https://github.com/rigetti/AdmittanceModels.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | code | 733 | using Crystallography
using Documenter
DocMeta.setdocmeta!(Crystallography, :DocTestSetup, :(using Crystallography); recursive=true)
makedocs(;
modules=[Crystallography],
authors="singularitti <[email protected]> and contributors",
repo="https://github.com/MineralsCloud/Crystallography.jl/blob/{commit}{path}#{line}",
sitename="Crystallography.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://MineralsCloud.github.io/Crystallography.jl",
edit_link="main",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
deploydocs(;
repo="github.com/MineralsCloud/Crystallography.jl",
devbranch="main",
)
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | code | 1562 | module Crystallography
using CrystallographyBase:
Bravais,
CartesianFromFractional,
CartesianToFractional,
Cell,
CrystalSystem,
CrystallographyBase,
FractionalFromCartesian,
FractionalToCartesian,
Lattice,
LatticeSystem,
MetricTensor,
MonkhorstPackGrid,
PrimitiveFromStandardized,
PrimitiveToStandardized,
ReciprocalLattice,
ReciprocalPoint,
StandardizedFromPrimitive,
StandardizedToPrimitive,
atomicmass,
atomtypes,
basisvectors,
cellvolume,
coordinates,
crystaldensity,
distance,
eachatom,
edge,
edges,
faces,
isrighthanded,
latticeconstants,
latticesystem,
natoms,
periodicity,
reciprocal,
supercell,
vertices,
weights
export Bravais,
CartesianFromFractional,
CartesianToFractional,
Cell,
CrystalSystem,
CrystallographyBase,
FractionalFromCartesian,
FractionalToCartesian,
Lattice,
LatticeSystem,
MetricTensor,
MonkhorstPackGrid,
PrimitiveFromStandardized,
PrimitiveToStandardized,
ReciprocalLattice,
ReciprocalPoint,
StandardizedFromPrimitive,
StandardizedToPrimitive,
atomicmass,
atomtypes,
basisvectors,
cellvolume,
coordinates,
crystaldensity,
distance,
eachatom,
edge,
edges,
faces,
isrighthanded,
latticeconstants,
latticesystem,
natoms,
periodicity,
reciprocal,
supercell,
vertices,
weights
# include("Symmetry.jl")
# include("PointGroups.jl")
end
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | code | 6707 | module PointGroups
using MLStyle: @match
using CrystallographyBase.CrystalSystem:
Triclinic, Monoclinic, Orthorhombic, Tetragonal, Cubic, Trigonal, Hexagonal
export PointGroup
export pointgroups,
hermann_mauguin, international, schönflies, schoenflies, orderof, laueclasses
abstract type PointGroup end
abstract type CyclicGroup <: PointGroup end
struct C1 <: CyclicGroup end
struct C2 <: CyclicGroup end
struct C3 <: CyclicGroup end
struct C4 <: CyclicGroup end
struct C6 <: CyclicGroup end
struct C2v <: CyclicGroup end
struct C3v <: CyclicGroup end
struct C4v <: CyclicGroup end
struct C6v <: CyclicGroup end
struct C1h <: CyclicGroup end
struct C2h <: CyclicGroup end
struct C3h <: CyclicGroup end
struct C4h <: CyclicGroup end
struct C6h <: CyclicGroup end
abstract type SpiegelGroup <: PointGroup end
struct S2 <: SpiegelGroup end
struct S4 <: SpiegelGroup end
struct S6 <: SpiegelGroup end
abstract type DihedralGroup <: PointGroup end
struct D2 <: DihedralGroup end
struct D3 <: DihedralGroup end
struct D4 <: DihedralGroup end
struct D6 <: DihedralGroup end
struct D2h <: DihedralGroup end
struct D3h <: DihedralGroup end
struct D4h <: DihedralGroup end
struct D6h <: DihedralGroup end
struct D2d <: DihedralGroup end
struct D3d <: DihedralGroup end
abstract type TetrahedralGroup <: PointGroup end
struct T <: TetrahedralGroup end
struct Th <: TetrahedralGroup end
struct Td <: TetrahedralGroup end
abstract type OctahedralGroup <: PointGroup end
struct O <: OctahedralGroup end
struct Oh <: OctahedralGroup end
const C1v = C1h
const Cs = C1h
const Ci = S2
const C3i = S6
const D1 = C2
const V = D2
const D1h = C2v
const D1d = C2h
const V2 = D2d
const Vh = D2h
function PointGroup(str::AbstractString)
str = lowercase(filter(!isspace, str))
return if isnumeric(first(str)) # International notation
@match str begin
"1" => C1()
"1̄" => S2()
"2" => C2()
"m" => C1h()
"3" => C3()
"4" => C4()
"4̄" => S4()
"2/m" => C2h()
"222" => D2()
"mm2" => C2v()
"3̄" => S6()
"6" => C6()
"6̄" => C3h()
"32" => D3()
"3m" => C3v()
"mmm" => D2h()
"4/m" => C4h()
"422" => D4()
"4mm" => C4v()
"4̄2m" => D2d()
"6/m" => C6h()
"23" => T()
"3̄m" => D3d()
"622" => D6()
"6mm" => C6v()
"6̄m2" => D3h()
"4/mmm" => D4h()
"6/mmm" => D6h()
"m3̄" => Th()
"432" => O()
"4̄3m" => Td()
"m3̄m" => Oh()
_ => throw(ArgumentError("\"$str\" is not a valid point group symbol!"))
end
else # Schoenflies notation
@match str begin
"c1" => C1()
"c2" => C2()
"c3" => C3()
"c4" => C4()
"c6" => C6()
"c2v" => C2v()
"c3v" => C3v()
"c4v" => C4v()
"c6v" => C6v()
"c1h" => C1h()
"c2h" => C2h()
"c3h" => C3h()
"c4h" => C4h()
"c6h" => C6h()
"s2" => S2()
"s4" => S4()
"s6" => S6()
"d2" => D2()
"d3" => D3()
"d4" => D4()
"d6" => D6()
"d2h" => D2h()
"d3h" => D3h()
"d4h" => D4h()
"d6h" => D6h()
"d2d" => D2d()
"d3d" => D3d()
"t" => T()
"th" => Th()
"td" => Td()
"o" => O()
"oh" => Oh()
"c1v" => C1h()
"cs" => C1h()
"ci" => S2()
"c3i" => S6()
"d1" => C2()
"v" => D2()
"d1h" => C2v()
"d1d" => C2h()
"v2" => D2d()
"vh" => D2h()
_ => throw(ArgumentError("\"$str\" is not a valid point group symbol!"))
end
end
end
struct LaueClass{T<:PointGroup} end
laueclasses(::Triclinic) = (LaueClass{Ci}(),)
laueclasses(::Monoclinic) = (LaueClass{C2h}(),)
laueclasses(::Orthorhombic) = (LaueClass{D2h}(),)
laueclasses(::Tetragonal) = (LaueClass{C4h}(), LaueClass{D4h}())
laueclasses(::Trigonal) = (LaueClass{C3i}(), LaueClass{D3d}())
laueclasses(::Hexagonal) = (LaueClass{C6h}(), LaueClass{D6h}())
laueclasses(::Cubic) = (LaueClass{Th}(), LaueClass{Oh}())
pointgroups(::Triclinic) = (C1(), S2())
pointgroups(::Monoclinic) = (C2(), C1h(), C2h())
pointgroups(::Orthorhombic) = (D2(), C2v(), D2h())
pointgroups(::Tetragonal) = (C4(), S4(), C4h(), D4(), C4v(), D2d(), D4h())
pointgroups(::Trigonal) = (C3(), S6(), D3(), C3v(), D3d())
pointgroups(::Hexagonal) = (C6(), C3h(), C6h(), D6(), C6v(), D3h(), D6h())
pointgroups(::Cubic) = (T(), Th(), O(), Td(), Oh())
hermann_mauguin(::C1) = "1"
hermann_mauguin(::S2) = "1̄"
hermann_mauguin(::C2) = "2"
hermann_mauguin(::C1h) = "m"
hermann_mauguin(::C3) = "3"
hermann_mauguin(::C4) = "4"
hermann_mauguin(::S4) = "4̄"
hermann_mauguin(::C2h) = "2/m"
hermann_mauguin(::D2) = "222"
hermann_mauguin(::C2v) = "mm2"
hermann_mauguin(::S6) = "3̄"
hermann_mauguin(::C6) = "6"
hermann_mauguin(::C3h) = "6̄"
hermann_mauguin(::D3) = "32"
hermann_mauguin(::C3v) = "3m"
hermann_mauguin(::D2h) = "mmm"
hermann_mauguin(::C4h) = "4/m"
hermann_mauguin(::D4) = "422"
hermann_mauguin(::C4v) = "4mm"
hermann_mauguin(::D2d) = "4̄2m"
hermann_mauguin(::C6h) = "6/m"
hermann_mauguin(::T) = "23"
hermann_mauguin(::D3d) = "3̄m"
hermann_mauguin(::D6) = "622"
hermann_mauguin(::C6v) = "6mm"
hermann_mauguin(::D3h) = "6̄m2"
hermann_mauguin(::D4h) = "4/mmm"
hermann_mauguin(::D6h) = "6/mmm"
hermann_mauguin(::Th) = "m3̄"
hermann_mauguin(::O) = "432"
hermann_mauguin(::Td) = "4̄3m"
hermann_mauguin(::Oh) = "m3̄m"
const international = hermann_mauguin
function schönflies(g::PointGroup)
if isconcretetype(typeof(g))
return string(nameof(typeof(g)))
else
throw(ArgumentError("$g is not a specific point group!"))
end
end
const schoenflies = schönflies
orderof(::C1) = 1
orderof(::S2) = 2
orderof(::C2) = 2
orderof(::C1h) = 2
orderof(::C3) = 3
orderof(::C4) = 4
orderof(::S4) = 4
orderof(::C2h) = 4
orderof(::D2) = 4
orderof(::C2v) = 4
orderof(::S6) = 6
orderof(::C6) = 6
orderof(::C3h) = 6
orderof(::D3) = 6
orderof(::C3v) = 6
orderof(::D2h) = 8
orderof(::C4h) = 8
orderof(::D4) = 8
orderof(::C4v) = 8
orderof(::D2d) = 8
orderof(::C6h) = 12
orderof(::T) = 12
orderof(::D3d) = 12
orderof(::D6) = 12
orderof(::C6v) = 12
orderof(::D3h) = 12
orderof(::D4h) = 16
orderof(::D6h) = 24
orderof(::Th) = 24
orderof(::O) = 24
orderof(::Td) = 24
orderof(::Oh) = 48
end
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | code | 8716 | module Symmetry
using CoordinateTransformations: AffineMap, Translation, LinearMap
using LinearAlgebra: I, diagm
using StaticArrays: SVector, SMatrix, SDiagonal
using Crystallography
import LinearAlgebra: det, tr
export SeitzOperator,
symmetrytype,
isidentity,
istranslation,
ispointsymmetry,
genpath,
pearsonsymbol,
arithmeticclass
pearsonsymbol(::Triclinic) = "a"
pearsonsymbol(::Monoclinic) = "m"
pearsonsymbol(::Orthorhombic) = "o"
pearsonsymbol(::Tetragonal) = "t"
pearsonsymbol(::Cubic) = "c"
pearsonsymbol(::Hexagonal) = "h"
pearsonsymbol(::Trigonal) = "h"
pearsonsymbol(::Primitive) = "P"
pearsonsymbol(::BaseCentering{T}) where {T} = string(T)
pearsonsymbol(::BodyCentering) = "I"
pearsonsymbol(::FaceCentering) = "F"
pearsonsymbol(::RhombohedralCentering) = "R"
pearsonsymbol(b::Bravais) = pearsonsymbol(crystalsystem(b)) * pearsonsymbol(centering(b))
arithmeticclass(::Triclinic) = "-1"
arithmeticclass(::Monoclinic) = "2/m"
arithmeticclass(::Orthorhombic) = "mmm"
arithmeticclass(::Tetragonal) = "4/mmm"
arithmeticclass(::Hexagonal) = "6/mmm"
arithmeticclass(::Cubic) = "m-3m"
arithmeticclass(::Primitive) = "P"
arithmeticclass(::BaseCentering) = "S"
arithmeticclass(::BodyCentering) = "I"
arithmeticclass(::FaceCentering) = "F"
arithmeticclass(::RhombohedralCentering) = "R"
arithmeticclass(b::Bravais) =
arithmeticclass(crystalsystem(b)) * arithmeticclass(centering(b))
arithmeticclass(::RCenteredHexagonal) = "-3mR"
abstract type PointSymmetry end
struct Identity <: PointSymmetry end
struct RotationAxis{N} <: PointSymmetry end
struct Inversion <: PointSymmetry end
struct RotoInversion{N} <: PointSymmetry end
const Mirror = RotoInversion{2}
function RotationAxis(N::Integer)
if N ∈ (2, 3, 4, 6)
return RotationAxis{N}()
else
throw(ArgumentError("rotation axis must be either 2, 3, 4 or 6!"))
end
end
function RotoInversion(N::Integer)
if N ∈ (2, 3, 4, 6)
return RotoInversion{N}()
else
throw(ArgumentError("rotoinversion axis must be either 2, 3, 4 or 6!"))
end
end
struct PointSymmetryPower{T<:PointSymmetry,N} end
PointSymmetryPower(X::PointSymmetry, N::Int) = PointSymmetryPower{typeof(X),N}()
function PointSymmetryPower(::RotationAxis{N}, M::Int) where {N}
if M >= N
if M == N
Identity()
else
PointSymmetryPower(RotationAxis(N), M - N) # Recursive call
end
else # Until M < N
PointSymmetryPower{RotationAxis{N},M}()
end
end
function symmetrytype(trace, determinant)
return Dict(
(3, 1) => Identity(),
(-1, 1) => RotationAxis(2),
(0, 1) => RotationAxis(3),
(1, 1) => RotationAxis(4),
(2, 1) => RotationAxis(6),
(-3, -1) => Inversion(),
(1, -1) => Mirror(),
(0, -1) => RotoInversion(3),
(-1, -1) => RotoInversion(4),
(-2, -1) => RotoInversion(6),
)[(trace, determinant)]
end
symmetrytype(op::PointSymmetry) = symmetrytype(tr(op), det(op))
"""
SeitzOperator(m::AbstractMatrix)
Construct a `SeitzOperator` from a 4×4 matrix.
"""
struct SeitzOperator{T}
data::SMatrix{4,4,T,16}
end
SeitzOperator(m::AbstractMatrix) = SeitzOperator(SMatrix{4,4}(m))
function SeitzOperator(l::LinearMap)
m = l.linear
@assert size(m) == (3, 3)
x = diagm(ones(eltype(m), 4))
x[1:3, 1:3] = m
return SeitzOperator(x)
end # function PointSymmetryOperator
function SeitzOperator(t::Translation)
v = t.translation
@assert length(v) == 3
x = diagm(ones(eltype(v), 4))
x[1:3, 4] = v
return SeitzOperator(x)
end
"""
SeitzOperator(l::LinearMap, t::Translation)
SeitzOperator(a::AffineMap)
SeitzOperator(l::LinearMap)
SeitzOperator(t::Translation)
Construct a `SeitzOperator` from `LinearMap`s, `Translation`s or `AffineMap`s by the
following equation:
```math
S = \\left(
\\begin{array}{ccc|c}
& & & \\\\
& R & & {\\boldsymbol \\tau} \\\\
& & & \\\\
\\hline 0 & 0 & 0 & 1
\\end{array}
\\right),
```
where ``R`` is a `LinearMap` and ``{\\boldsymbol \\tau}`` is a `Translation`.
"""
function SeitzOperator(l::LinearMap, t::Translation)
m, v = l.linear, t.translation
return SeitzOperator(vcat(hcat(m, v), [zeros(eltype(m), 3)... one(eltype(v))]))
end # function SeitzOperator
SeitzOperator(a::AffineMap) = SeitzOperator(LinearMap(a.linear), Translation(a.translation))
"""
SeitzOperator(s::SeitzOperator, pos::AbstractVector)
Construct a `SeitzOperator` that locates at `pos` from a `SeitzOperator` passing through the
origin.
"""
function SeitzOperator(s::SeitzOperator, pos::AbstractVector)
@assert length(pos) == 3
t = SeitzOperator(Translation(pos))
return t * s * inv(t)
end # function SeitzOperator
(op::SeitzOperator)(v::AbstractVector) = (op.data * [v; 1])[1:3]
isidentity(op::SeitzOperator) = op.data == I
function istranslation(op::SeitzOperator)
m = op.data
if m[1:3, 1:3] != I || !(iszero(m[4, 1:3]) && isone(m[4, 4]))
return false
end
return true
end
function ispointsymmetry(op::SeitzOperator)
m = op.data
if !(
iszero(m[4, 1:3]) &&
iszero(m[1:3, 4]) &&
isone(m[4, 4]) &&
abs(det(m[1:3, 1:3])) == 1
)
return false
end
return true
end
"""
genpath(nodes, densities)
genpath(nodes, density::Integer, iscircular = false)
Generate a reciprocal space path from each node.
# Arguments
- `nodes::AbstractVector`: a vector of 3-element k-points.
- `densities::AbstractVector{<:Integer}`: number of segments between current node and the next node.
- `density::Integer`: assuming constant density between nodes.
# Examples
```jldoctest
julia> nodes = [
[0.0, 0.0, 0.5],
[0.0, 0.0, 0.0],
[0.3333333333, 0.3333333333, 0.5],
[0.3333333333, 0.3333333333, -0.5],
[0.3333333333, 0.3333333333, 0.0],
[0.5, 0.0, 0.5],
[0.5, 0.0, 0.0]
];
julia> genpath(nodes, 100, true) # Generate a circular path
700-element Array{Array{Float64,1},1}:
...
julia> genpath(nodes, 100, false) # Generate a noncircular path
600-element Array{Array{Float64,1},1}:
...
julia> genpath(nodes, [10 * i for i in 1:6]) # Generate a noncircular path
210-element Array{Array{Float64,1},1}:
...
```
"""
function genpath(nodes, densities)
if length(densities) == length(nodes) || length(densities) == length(nodes) - 1
path = similar(nodes, sum(densities .- 1) + length(densities))
s = 0
for (i, (thisnode, nextnode, density)) in
enumerate(zip(nodes, circshift(nodes, -1), densities))
step = @. (nextnode - thisnode) / density
for j in 1:density
path[s + j] = @. thisnode + j * step
end
s += density
end
return path
else
throw(
DimensionMismatch(
"the length of `densities` is either `length(nodes)` or `length(nodes) - 1`!",
),
)
end
end
genpath(nodes, density::Integer, iscircular::Bool=false) =
genpath(nodes, (density for _ in 1:(length(nodes) - (iscircular ? 0 : 1))))
Base.getindex(A::SeitzOperator, I::Vararg{Int}) = getindex(A.data, I...)
Base.one(::Type{SeitzOperator{T}}) where {T} =
SeitzOperator(SDiagonal(SVector{4}(ones(T, 4))))
Base.one(A::SeitzOperator) = one(typeof(A))
Base.inv(op::SeitzOperator) = SeitzOperator(Base.inv(op.data))
Base.:*(::Identity, ::Identity) = Identity()
Base.:*(::Identity, x::Union{PointSymmetryPower,PointSymmetry}) = x
Base.:*(x::Union{PointSymmetryPower,PointSymmetry}, ::Identity) = x
Base.:*(::Inversion, ::Inversion) = Identity()
Base.:*(::RotationAxis{N}, ::Inversion) where {N} = RotoInversion(N)
Base.:*(i::Inversion, r::RotationAxis) = r * i
Base.:*(::RotationAxis{N}, ::RotationAxis{N}) where {N} =
PointSymmetryPower(RotationAxis(N), 2)
Base.:*(::RotationAxis{2}, ::RotationAxis{2}) = Identity()
Base.:*(::PointSymmetryPower{RotationAxis{N},M}, ::RotationAxis{N}) where {N,M} =
PointSymmetryPower(RotationAxis(N), M + 1)
Base.:∘(a::SeitzOperator, b::SeitzOperator) = SeitzOperator(a.data * b.data)
function Base.convert(::Type{Translation}, op::SeitzOperator)
@assert(istranslation(op), "operator is not a translation!")
return Translation(collect(op.data[1:3, 4]))
end
function Base.convert(::Type{LinearMap}, op::SeitzOperator)
@assert(ispointsymmetry(op), "operator is not a point symmetry!")
return LinearMap(collect(op.data[1:3, 1:3]))
end
tr(::Identity) = 3
tr(::RotationAxis) where {N} = N - 3 # 2, 3, 4
tr(::RotationAxis{6}) = 2
tr(::Inversion) = -3
tr(::RotoInversion{N}) where {N} = -tr(RotationAxis(N))
det(::Union{Identity,RotationAxis}) = 1
det(::Inversion) = -1
det(::RotoInversion) = -1
end
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | code | 74 | using Crystallography
using Test
@testset "Crystallography.jl" begin
end
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | docs | 4201 | # Crystallography
| **Documentation** | **Build Status** | **Others** |
| :--------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------: |
| [![Stable][docs-stable-img]][docs-stable-url] [![Dev][docs-dev-img]][docs-dev-url] | [![Build Status][gha-img]][gha-url] [![Build Status][appveyor-img]][appveyor-url] [![Build Status][cirrus-img]][cirrus-url] [![pipeline status][gitlab-img]][gitlab-url] [![Coverage][codecov-img]][codecov-url] | [![GitHub license][license-img]][license-url] [![Code Style: Blue][style-img]][style-url] |
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://MineralsCloud.github.io/Crystallography.jl/stable
[docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
[docs-dev-url]: https://MineralsCloud.github.io/Crystallography.jl/dev
[gha-img]: https://github.com/MineralsCloud/Crystallography.jl/workflows/CI/badge.svg
[gha-url]: https://github.com/MineralsCloud/Crystallography.jl/actions
[appveyor-img]: https://ci.appveyor.com/api/projects/status/github/MineralsCloud/Crystallography.jl?svg=true
[appveyor-url]: https://ci.appveyor.com/project/singularitti/Crystallography-jl
[cirrus-img]: https://api.cirrus-ci.com/github/MineralsCloud/Crystallography.jl.svg
[cirrus-url]: https://cirrus-ci.com/github/MineralsCloud/Crystallography.jl
[gitlab-img]: https://gitlab.com/singularitti/Crystallography.jl/badges/main/pipeline.svg
[gitlab-url]: https://gitlab.com/singularitti/Crystallography.jl/-/pipelines
[codecov-img]: https://codecov.io/gh/MineralsCloud/Crystallography.jl/branch/main/graph/badge.svg
[codecov-url]: https://codecov.io/gh/MineralsCloud/Crystallography.jl
[license-img]: https://img.shields.io/github/license/MineralsCloud/Crystallography.jl
[license-url]: https://github.com/MineralsCloud/Crystallography.jl/blob/main/LICENSE
[style-img]: https://img.shields.io/badge/code%20style-blue-4495d1.svg
[style-url]: https://github.com/invenia/BlueStyle
This package:
- Builds Bravais lattices, cells, etc.
- Converts coordinates between crystal and Cartesian frames, real and reciprocal spaces
The code is [hosted on GitHub](https://github.com/MineralsCloud/Crystallography.jl),
with some continuous integration services to test its validity.
This repository is created and maintained by [@singularitti](https://github.com/singularitti).
You are very welcome to contribute.
## Installation
The package can be installed with the Julia package manager.
From the Julia REPL, type `]` to enter the Pkg REPL mode and run:
```
pkg> add Crystallography
```
Or, equivalently, via the [`Pkg` API](https://pkgdocs.julialang.org/v1/getting-started/):
```julia
julia> import Pkg; Pkg.add("Crystallography")
```
## Documentation
- [**STABLE**][docs-stable-url] — **documentation of the most recently tagged version.**
- [**DEV**][docs-dev-url] — _documentation of the in-development version._
## Project status
The package is tested against, and being developed for, Julia `1.6` and above on Linux,
macOS, and Windows.
## Questions and contributions
You are welcome to post usage questions on [our discussion page][discussions-url].
Contributions are very welcome, as are feature requests and suggestions. Please open an
[issue][issues-url] if you encounter any problems. The [Contributing](@ref) page has
guidelines that should be followed when opening pull requests and contributing code.
[discussions-url]: https://github.com/MineralsCloud/Crystallography.jl/discussions
[issues-url]: https://github.com/MineralsCloud/Crystallography.jl/issues
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | docs | 985 | ```@meta
CurrentModule = CrystallographyBase
```
# API
```@contents
Pages = ["api.md"]
Depth = 3
```
### Lattice
```@docs
CrystalSystem
Triclinic
Monoclinic
Orthorhombic
Tetragonal
Cubic
Trigonal
Hexagonal
Centering
BaseCentering
Primitive
BodyCentering
FaceCentering
RhombohedralCentering
BaseCentering
Bravais
Lattice
centering
crystalsystem
basis_vectors
cellparameters
supercell
```
### Reciprocal space
Note that we take ``2pi`` as ``1``, not the solid-state physics convention.
```@docs
ReciprocalPoint
ReciprocalLattice
inv
reciprocal_mesh
coordinates
weights
```
### Miller and Miller–Bravais indices
```@docs
Miller
MillerBravais
ReciprocalMiller
ReciprocalMillerBravais
family
@m_str
```
### Metric tensor
```@docs
MetricTensor
directioncosine
directionangle
distance
interplanar_spacing
```
### Transformations
```@docs
CartesianFromFractional
FractionalFromCartesian
PrimitiveFromStandardized
StandardizedFromPrimitive
```
### Others
```@docs
cellvolume
```
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | docs | 2005 | ```@meta
CurrentModule = Crystallography
```
# Crystallography
Documentation for [Crystallography](https://github.com/MineralsCloud/Crystallography.jl).
See the [Index](@ref main-index) for the complete list of documented functions
and types.
The code is [hosted on GitHub](https://github.com/MineralsCloud/Crystallography.jl),
with some continuous integration services to test its validity.
This repository is created and maintained by [@singularitti](https://github.com/singularitti).
You are very welcome to contribute.
## Installation
The package can be installed with the Julia package manager.
From the Julia REPL, type `]` to enter the Pkg REPL mode and run:
```julia
pkg> add Crystallography
```
Or, equivalently, via the `Pkg` API:
```@repl
import Pkg; Pkg.add("Crystallography")
```
## Documentation
- [**STABLE**](https://MineralsCloud.github.io/Crystallography.jl/stable) — **documentation of the most recently tagged version.**
- [**DEV**](https://MineralsCloud.github.io/Crystallography.jl/dev) — _documentation of the in-development version._
## Project status
The package is tested against, and being developed for, Julia `1.6` and above on Linux,
macOS, and Windows.
## Questions and contributions
Usage questions can be posted on
[our discussion page](https://github.com/MineralsCloud/Crystallography.jl/discussions).
Contributions are very welcome, as are feature requests and suggestions. Please open an
[issue](https://github.com/MineralsCloud/Crystallography.jl/issues)
if you encounter any problems. The [Contributing](@ref) page has
a few guidelines that should be followed when opening pull requests and contributing code.
## Manual outline
```@contents
Pages = [
"installation.md",
"developers/contributing.md",
"developers/style-guide.md",
"developers/design-principles.md",
"troubleshooting.md",
]
Depth = 3
```
## Library outline
```@contents
Pages = ["public.md"]
```
### [Index](@id main-index)
```@index
Pages = ["public.md"]
```
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | docs | 5244 | # [Installation Guide](@id installation)
Here are the installation instructions for package
[Crystallography](https://github.com/MineralsCloud/Crystallography.jl).
If you have trouble installing it, please refer to our [Troubleshooting](@ref) page
for more information.
## Install Julia
First, you should install [Julia](https://julialang.org/). We recommend downloading it from
[its official website](https://julialang.org/downloads/). Please follow the detailed
instructions on its website if you have to
[build Julia from source](https://docs.julialang.org/en/v1/devdocs/build/build/).
Some computing centers provide preinstalled Julia. Please contact your administrator for
more information in that case.
Here's some additional information on
[how to set up Julia on HPC systems](https://github.com/hlrs-tasc/julia-on-hpc-systems).
If you have [Homebrew](https://brew.sh) installed,
[open `Terminal.app`](https://support.apple.com/guide/terminal/open-or-quit-terminal-apd5265185d-f365-44cb-8b09-71a064a42125/mac)
and type
```shell
brew install julia
```
to install it as a [formula](https://docs.brew.sh/Formula-Cookbook).
If you are also using macOS and want to install it as a prebuilt binary app, type
```shell
brew install --cask julia
```
instead.
If you want to install multiple Julia versions in the same operating system,
a recommended way is to use a version manager such as
[`juliaup`](https://github.com/JuliaLang/juliaup).
First, [install `juliaup`](https://github.com/JuliaLang/juliaup#installation).
Then, run
```shell
juliaup add release
juliaup default release
```
to configure the `julia` command to start the latest stable version of
Julia (this is also the default value).
There is a [short video introduction to `juliaup`](https://youtu.be/14zfdbzq5BM)
made by its authors.
### Which version should I pick?
You can install the "Current stable release" or the "Long-term support (LTS)
release".
- The "Current stable release" is the latest release of Julia. It has access to
newer features, and is likely faster.
- The "Long-term support release" is an older version of Julia that has
continued to receive bug and security fixes. However, it may not have the
latest features or performance improvements.
For most users, you should install the "Current stable release", and whenever
Julia releases a new version of the current stable release, you should update
your version of Julia. Note that any code you write on one version of the
current stable release will continue to work on all subsequent releases.
For users in restricted software environments (e.g., your enterprise IT controls
what software you can install), you may be better off installing the long-term
support release because you will not have to update Julia as frequently.
Versions higher than `v1.3`,
especially `v1.6`, are strongly recommended. This package may not work on `v1.0` and below.
Since the Julia team has set `v1.6` as the LTS release,
we will gradually drop support for versions below `v1.6`.
Julia and Julia packages support multiple operating systems and CPU architectures; check
[this table](https://julialang.org/downloads/#supported_platforms) to see if it can be
installed on your machine. For Mac computers with M-series processors, this package and its
dependencies may not work. Please install the Intel-compatible version of Julia (for macOS
x86-64) if any platform-related error occurs.
## Install Crystallography
Now I am using [macOS](https://en.wikipedia.org/wiki/MacOS) as a standard
platform to explain the following steps:
1. Open `Terminal.app`, and type `julia` to start an interactive session (known as the
[REPL](https://docs.julialang.org/en/v1/stdlib/REPL/)).
2. Run the following commands and wait for them to finish:
```julia-repl
julia> using Pkg
julia> Pkg.update()
julia> Pkg.add("Crystallography")
```
3. Run
```julia-repl
julia> using Crystallography
```
and have fun!
4. While using, please keep this Julia session alive. Restarting might cost some time.
If you want to install the latest in-development (probably buggy)
version of Crystallography, type
```@repl
using Pkg
Pkg.update()
pkg"add https://github.com/MineralsCloud/Crystallography.jl"
```
in the second step above.
## Update Crystallography
Please [watch](https://docs.github.com/en/account-and-profile/managing-subscriptions-and-notifications-on-github/setting-up-notifications/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)
our [GitHub repository](https://github.com/MineralsCloud/Crystallography.jl)
for new releases.
Once we release a new version, you can update Crystallography by typing
```@repl
using Pkg
Pkg.update("Crystallography")
Pkg.gc()
```
in the Julia REPL.
## Uninstall and reinstall Crystallography
Sometimes errors may occur if the package is not properly installed.
In this case, you may want to uninstall and reinstall the package. Here is how to do that:
1. To uninstall, in a Julia session, run
```julia-repl
julia> using Pkg
julia> Pkg.rm("Crystallography")
julia> Pkg.gc()
```
2. Press `ctrl+d` to quit the current session. Start a new Julia session and
reinstall Crystallography.
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | docs | 2153 | # Troubleshooting
```@contents
Pages = ["troubleshooting.md"]
Depth = 3
```
This page collects some possible errors you may encounter and trick how to fix them.
If you have some questions about how to use this code, you are welcome to
[discuss with us](https://github.com/MineralsCloud/Crystallography.jl/discussions).
If you have additional tips, please either
[report an issue](https://github.com/MineralsCloud/Crystallography.jl/issues/new) or
[submit a PR](https://github.com/MineralsCloud/Crystallography.jl/compare) with suggestions.
## Installation problems
### Cannot find the `julia` executable
Make sure you have Julia installed in your environment. Please download the latest
[stable version](https://julialang.org/downloads/#current_stable_release) for your platform.
If you are using a *nix system, the recommended way is to use
[Juliaup](https://github.com/JuliaLang/juliaup). If you do not want to install Juliaup
or you are using other platforms that Julia supports, download the corresponding binaries.
Then, create a symbolic link to the Julia executable. If the path is not in your `$PATH`
environment variable, export it to your `$PATH`.
Some clusters, like
[Habanero](https://confluence.columbia.edu/confluence/display/rcs/Habanero+HPC+Cluster+User+Documentation),
[Comet](https://www.sdsc.edu/support/user_guides/comet.html),
or [Expanse](https://www.sdsc.edu/services/hpc/expanse/index.html),
already have Julia installed as a module, you may
just `module load julia` to use it. If not, either install by yourself or contact your
administrator.
## Loading Crystallography
### Julia compiles/loads slow
First, we recommend you download the latest version of Julia. Usually, the newest version
has the best performance.
If you just want Julia to do a simple task and only once, you could start the Julia REPL with
```bash
julia --compile=min
```
to minimize compilation or
```bash
julia --optimize=0
```
to minimize optimizations, or just use both. Or you could make a system image
and run with
```bash
julia --sysimage custom-image.so
```
See [Fredrik Ekre's talk](https://youtu.be/IuwxE3m0_QQ?t=313) for details.
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | docs | 8548 | # Contributing
```@contents
Pages = ["contributing.md"]
Depth = 3
```
Welcome! This document explains some ways you can contribute to Crystallography.
## Code of conduct
This project and everyone participating in it is governed by the
["Contributor Covenant Code of Conduct"](https://github.com/MineralsCloud/.github/blob/main/CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code.
## Join the community forum
First up, join the [community forum](https://github.com/MineralsCloud/Crystallography.jl/discussions).
The forum is a good place to ask questions about how to use Crystallography. You can also
use the forum to discuss possible feature requests and bugs before raising a
GitHub issue (more on this below).
Aside from asking questions, the easiest way you can contribute to Crystallography is to
help answer questions on the forum!
## Improve the documentation
Chances are, if you asked (or answered) a question on the community forum, then
it is a sign that the [documentation](https://MineralsCloud.github.io/Crystallography.jl/dev/) could be
improved. Moreover, since it is your question, you are probably the best-placed
person to improve it!
The docs are written in Markdown and are built using
[Documenter.jl](https://github.com/JuliaDocs/Documenter.jl).
You can find the source of all the docs
[here](https://github.com/MineralsCloud/Crystallography.jl/tree/main/docs).
If your change is small (like fixing typos, or one or two sentence corrections),
the easiest way to do this is via GitHub's online editor. (GitHub has
[help](https://help.github.com/articles/editing-files-in-another-user-s-repository/)
on how to do this.)
If your change is larger, or touches multiple files, you will need to make the
change locally and then use Git to submit a
[pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests).
(See [Contribute code to Crystallography](@ref) below for more on this.)
## File a bug report
Another way to contribute to Crystallography is to file
[bug reports](https://github.com/MineralsCloud/Crystallography.jl/issues/new?template=bug_report.md).
Make sure you read the info in the box where you write the body of the issue
before posting. You can also find a copy of that info
[here](https://github.com/MineralsCloud/Crystallography.jl/blob/main/.github/ISSUE_TEMPLATE/bug_report.md).
!!! tip
If you're unsure whether you have a real bug, post on the
[community forum](https://github.com/MineralsCloud/Crystallography.jl/discussions)
first. Someone will either help you fix the problem, or let you know the
most appropriate place to open a bug report.
## Contribute code to Crystallography
Finally, you can also contribute code to Crystallography!
!!! warning
If you do not have experience with Git, GitHub, and Julia development, the
first steps can be a little daunting. However, there are lots of tutorials
available online, including:
- [GitHub](https://guides.github.com/activities/hello-world/)
- [Git and GitHub](https://try.github.io/)
- [Git](https://git-scm.com/book/en/v2)
- [Julia package development](https://docs.julialang.org/en/v1/stdlib/Pkg/#Developing-packages-1)
Once you are familiar with Git and GitHub, the workflow for contributing code to
Crystallography is similar to the following:
### Step 1: decide what to work on
The first step is to find an [open issue](https://github.com/MineralsCloud/Crystallography.jl/issues)
(or open a new one) for the problem you want to solve. Then, _before_ spending
too much time on it, discuss what you are planning to do in the issue to see if
other contributors are fine with your proposed changes. Getting feedback early can
improve code quality, and avoid time spent writing code that does not get merged into
Crystallography.
!!! tip
At this point, remember to be patient and polite; you may get a _lot_ of
comments on your issue! However, do not be afraid! Comments mean that people are
willing to help you improve the code that you are contributing to Crystallography.
### Step 2: fork Crystallography
Go to [https://github.com/MineralsCloud/Crystallography.jl](https://github.com/MineralsCloud/Crystallography.jl)
and click the "Fork" button in the top-right corner. This will create a copy of
Crystallography under your GitHub account.
### Step 3: install Crystallography locally
Similar to [Installation](@ref), open the Julia REPL and run:
```@repl
using Pkg
Pkg.update()
Pkg.develop("Crystallography")
```
Then the package will be cloned to your local machine. On *nix systems, the default path is
`~/.julia/dev/Crystallography` unless you modify the
[`JULIA_DEPOT_PATH`](http://docs.julialang.org/en/v1/manual/environment-variables/#JULIA_DEPOT_PATH-1)
environment variable. If you're on
Windows, this will be `C:\\Users\\<my_name>\\.julia\\dev\\Crystallography`.
In the following text, we will call it `PKGROOT`.
Go to `PKGROOT`, start a new Julia session and run
```@repl
using Pkg
Pkg.instantiate()
```
to instantiate the project.
### Step 4: checkout a new branch
!!! note
In the following, replace any instance of `GITHUB_ACCOUNT` with your GitHub
username.
The next step is to checkout a development branch. In a terminal (or command
prompt on Windows), run:
```shell
cd ~/.julia/dev/Crystallography
git remote add GITHUB_ACCOUNT https://github.com/GITHUB_ACCOUNT/Crystallography.jl.git
git checkout main
git pull
git checkout -b my_new_branch
```
### Step 5: make changes
Now make any changes to the source code inside the `~/.julia/dev/Crystallography`
directory.
Make sure you:
- Follow our [Style Guide](@ref style) and [run `JuliaFormatter.jl`](@ref formatter)
- Add tests and documentation for any changes or new features
!!! tip
When you change the source code, you'll need to restart Julia for the
changes to take effect. This is a pain, so install
[Revise.jl](https://github.com/timholy/Revise.jl).
### Step 6a: test your code changes
To test that your changes work, run the Crystallography test-suite by opening Julia and
running:
```@repl
cd("~/.julia/dev/Crystallography")
using Pkg
Pkg.activate(".")
Pkg.test()
```
!!! warning
Running the tests might take a long time.
!!! tip
If you're using `Revise.jl`, you can also run the tests by calling `include`:
```julia
include("test/runtests.jl")
```
This can be faster if you want to re-run the tests multiple times.
### Step 6b: test your documentation changes
Open Julia, then run:
```@repl
cd("~/.julia/dev/Crystallography/docs")
using Pkg
Pkg.activate(".")
include("src/make.jl")
```
After a while, a folder `PKGROOT/docs/build` will appear. Open
`PKGROOT/docs/build/index.html` with your favorite browser, and have fun!
!!! warning
Building the documentation might take a long time.
!!! tip
If there's a problem with the tests that you don't know how to fix, don't
worry. Continue to step 5, and one of the Crystallography contributors will comment
on your pull request telling you how to fix things.
### Step 7: make a pull request
Once you've made changes, you're ready to push the changes to GitHub. Run:
```shell
cd ~/.julia/dev/Crystallography
git add .
git commit -m "A descriptive message of the changes"
git push -u GITHUB_ACCOUNT my_new_branch
```
Then go to [https://github.com/MineralsCloud/Crystallography.jl/pulls](https://github.com/MineralsCloud/Crystallography.jl/pulls)
and follow the instructions that pop up to open a pull request.
### Step 8: respond to comments
At this point, remember to be patient and polite; you may get a _lot_ of
comments on your pull request! However, do not be afraid! A lot of comments
means that people are willing to help you improve the code that you are
contributing to Crystallography.
To respond to the comments, go back to step 5, make any changes, test the
changes in step 6, and then make a new commit in step 7. Your PR will
automatically update.
### Step 9: cleaning up
Once the PR is merged, clean-up your Git repository ready for the
next contribution!
```shell
cd ~/.julia/dev/Crystallography
git checkout main
git pull
```
!!! note
If you have suggestions to improve this guide, please make a pull request!
It's particularly helpful if you do this after your first pull request
because you'll know all the parts that could be explained better.
Thanks for contributing to Crystallography!
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | docs | 15492 | # Design Principles
```@contents
Pages = ["design-principles.md"]
Depth = 3
```
We adopt some [`SciML`](https://sciml.ai/) design [guidelines](https://github.com/SciML/SciMLStyle)
here. Please read it before contributing!
## Consistency vs adherence
According to PEP8:
> A style guide is about consistency. Consistency with this style guide is important.
> Consistency within a project is more important. Consistency within one module or function is the most important.
>
> However, know when to be inconsistent—sometimes style guide recommendations just aren't
> applicable. When in doubt, use your best judgment. Look at other examples and decide what
> looks best. And don’t hesitate to ask!
## Community contribution guidelines
For a comprehensive set of community contribution guidelines, refer to [ColPrac](https://github.com/SciML/ColPrac).
A relevant point to highlight PRs should do one thing. In the context of style, this means that PRs which update
the style of a package's code should not be mixed with fundamental code contributions. This separation makes it
easier to ensure that large style improvement are isolated from substantive (and potentially breaking) code changes.
## Open source contributions are allowed to start small and grow over time
If the standard for code contributions is that every PR needs to support every possible input type that anyone can
think of, the barrier would be too high for newcomers. Instead, the principle is to be as correct as possible to
begin with, and grow the generic support over time. All recommended functionality should be tested, any known
generality issues should be documented in an issue (and with a `@test_broken` test when possible). However, a
function which is known to not be GPU-compatible is not grounds to block merging, rather it is an encouragement for a
follow-up PR to improve the general type support!
## Generic code is preferred unless code is known to be specific
For example, the code:
```@repl
function f(A, B)
for i in 1:length(A)
A[i] = A[i] + B[i]
end
end
```
would not be preferred for two reasons. One is that it assumes `A` uses one-based indexing, which would fail in cases
like [OffsetArrays](https://github.com/JuliaArrays/OffsetArrays.jl) and [FFTViews](https://github.com/JuliaArrays/FFTViews.jl).
Another issue is that it requires indexing, while not all array types support indexing (for example,
[CuArrays](https://github.com/JuliaGPU/CuArrays.jl)). A more generic compatible implementation of this function would be
to use broadcast, for example:
```@repl
function f(A, B)
@. A = A + B
end
```
which would allow support for a wider variety of array types.
## Internal types should match the types used by users when possible
If `f(A)` takes the input of some collections and computes an output from those collections, then it should be
expected that if the user gives `A` as an `Array`, the computation should be done via `Array`s. If `A` was a
`CuArray`, then it should be expected that the computation should be internally done using a `CuArray` (or appropriately
error if not supported). For these reasons, constructing arrays via generic methods, like `similar(A)`, is preferred when
writing `f` instead of using non-generic constructors like `Array(undef,size(A))` unless the function is documented as
being non-generic.
## Trait definition and adherence to generic interface is preferred when possible
Julia provides many interfaces, for example:
- [Iteration](https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-iteration)
- [Indexing](https://docs.julialang.org/en/v1/manual/interfaces/#Indexing)
- [Broadcast](https://docs.julialang.org/en/v1/manual/interfaces/#man-interfaces-broadcasting)
Those interfaces should be followed when possible. For example, when defining broadcast overloads,
one should implement a `BroadcastStyle` as suggested by the documentation instead of simply attempting
to bypass the broadcast system via `copyto!` overloads.
When interface functions are missing, these should be added to Base Julia or an interface package,
like [ArrayInterface.jl](https://github.com/JuliaArrays/ArrayInterface.jl). Such traits should be
declared and used when appropriate. For example, if a line of code requires mutation, the trait
`ArrayInterface.ismutable(A)` should be checked before attempting to mutate, and informative error
messages should be written to capture the immutable case (or, an alternative code which does not
mutate should be given).
One example of this principle is demonstrated in the generation of Jacobian matrices. In many scientific
applications, one may wish to generate a Jacobian cache from the user's input `u0`. A naive way to generate
this Jacobian is `J = similar(u0,length(u0),length(u0))`. However, this will generate a Jacobian `J` such
that `J isa Matrix`.
## Macros should be limited and only be used for syntactic sugar
Macros define new syntax, and for this reason they tend to be less composable than other coding styles
and require prior familiarity to be easily understood. One principle to keep in mind is, "can the person
reading the code easily picture what code is being generated?". For example, a user of Soss.jl may not know
what code is being generated by:
```julia
@model (x, α) begin
σ ~ Exponential()
β ~ Normal()
y ~ For(x) do xj
Normal(α + β * xj, σ)
end
return y
end
```
and thus using such a macro as the interface is not preferred when possible. However, a macro like
[`@muladd`](https://github.com/SciML/MuladdMacro.jl) is trivial to picture on a code (it recursively
transforms `a*b + c` to `muladd(a,b,c)` for more
[accuracy and efficiency](https://en.wikipedia.org/wiki/Multiply%E2%80%93accumulate_operation)), so using
such a macro for example:
```julia
julia> @macroexpand(@muladd k3 = f(t + c3 * dt, @. uprev + dt * (a031 * k1 + a032 * k2)))
:(k3 = f((muladd)(c3, dt, t), (muladd).(dt, (muladd).(a032, k2, (*).(a031, k1)), uprev)))
```
is recommended. Some macros in this category are:
- `@inbounds`
- [`@muladd`](https://github.com/SciML/MuladdMacro.jl)
- `@view`
- [`@named`](https://github.com/SciML/ModelingToolkit.jl)
- `@.`
- [`@..`](https://github.com/YingboMa/FastBroadcast.jl)
Some performance macros, like `@simd`, `@threads`, or
[`@turbo` from LoopVectorization.jl](https://github.com/JuliaSIMD/LoopVectorization.jl),
make an exception in that their generated code may be foreign to many users. However, they still are
classified as appropriate uses as they are syntactic sugar since they do (or should) not change the behavior
of the program in measurable ways other than performance.
## Errors should be caught as high as possible, and error messages should be contextualized for newcomers
Whenever possible, defensive programming should be used to check for potential errors before they are encountered
deeper within a package. For example, if one knows that `f(u0,p)` will error unless `u0` is the size of `p`, this
should be caught at the start of the function to throw a domain specific error, for example "parameters and initial
condition should be the same size".
## Subpackaging and interface packages is preferred over conditional modules via Requires.jl
Requires.jl should be avoided at all costs. If an interface package exists, such as
[ChainRulesCore.jl](https://github.com/JuliaDiff/ChainRulesCore.jl) for defining automatic differentiation
rules without requiring a dependency on the whole ChainRules.jl system, or
[RecipesBase.jl](https://github.com/JuliaPlots/RecipesBase.jl) which allows for defining Plots.jl
plot recipes without a dependency on Plots.jl, a direct dependency on these interface packages is
preferred.
Otherwise, instead of resorting to a conditional dependency using Requires.jl, it is
preferred one creates subpackages, i.e. smaller independent packages kept within the same Github repository
with independent versioning and package management. An example of this is seen in
[Optimization.jl](https://github.com/SciML/Optimization.jl) which has subpackages like
[OptimizationBBO.jl](https://github.com/SciML/Optimization.jl/tree/master/lib/OptimizationBBO) for
BlackBoxOptim.jl support.
Some important interface packages to know about are:
- [ChainRulesCore.jl](https://github.com/JuliaDiff/ChainRulesCore.jl)
- [RecipesBase.jl](https://github.com/JuliaPlots/RecipesBase.jl)
- [ArrayInterface.jl](https://github.com/JuliaArrays/ArrayInterface.jl)
- [CommonSolve.jl](https://github.com/SciML/CommonSolve.jl)
- [SciMLBase.jl](https://github.com/SciML/SciMLBase.jl)
## Functions should either attempt to be non-allocating and reuse caches, or treat inputs as immutable
Mutating codes and non-mutating codes fall into different worlds. When a code is fully immutable,
the compiler can better reason about dependencies, optimize the code, and check for correctness.
However, many times a code making the fullest use of mutation can outperform even what the best compilers
of today can generate. That said, the worst of all worlds is when code mixes mutation with non-mutating
code. Not only is this a mishmash of coding styles, it has the potential non-locality and compiler
proof issues of mutating code while not fully benefiting from the mutation.
## Out-Of-Place and Immutability is preferred when sufficient performant
Mutation is used to get more performance by decreasing the amount of heap allocations. However,
if it's not helpful for heap allocations in a given spot, do not use mutation. Mutation is scary
and should be avoided unless it gives an immediate benefit. For example, if
matrices are sufficiently large, then `A*B` is as fast as `mul!(C,A,B)`, and thus writing
`A*B` is preferred (unless the rest of the function is being careful about being fully non-allocating,
in which case this should be `mul!` for consistency).
Similarly, when defining types, using `struct` is preferred to `mutable struct` unless mutating
the struct is a common occurrence. Even if mutating the struct is a common occurrence, see whether
using [Setfield.jl](https://github.com/jw3126/Setfield.jl) is sufficient. The compiler will optimize
the construction of immutable structs, and thus this can be more efficient if it's not too much of a
code hassle.
## Tests should attempt to cover a wide gamut of input types
Code coverage numbers are meaningless if one does not consider the input types. For example, one can
hit all the code with `Array`, but that does not test whether `CuArray` is compatible! Thus, it's
always good to think of coverage not in terms of lines of code but in terms of type coverage. A good
list of number types to think about are:
- `Float64`
- `Float32`
- `Complex`
- [`Dual`](https://github.com/JuliaDiff/ForwardDiff.jl)
- `BigFloat`
Array types to think about testing are:
- `Array`
- [`OffsetArray`](https://github.com/JuliaArrays/OffsetArrays.jl)
- [`CuArray`](https://github.com/JuliaGPU/CUDA.jl)
## When in doubt, a submodule should become a subpackage or separate package
Keep packages to one core idea. If there's something separate enough to be a submodule, could it
instead be a separate well-tested and documented package to be used by other packages? Most likely
yes.
## Globals should be avoided whenever possible
Global variables should be avoided whenever possible. When required, global variables should be
constants and have an all uppercase name separated with underscores (e.g. `MY_CONSTANT`). They should be
defined at the top of the file, immediately after imports and exports but before an `__init__` function.
If you truly want mutable global style behavior you may want to look into mutable containers.
## Type-stable and Type-grounded code is preferred wherever possible
Type-stable and type-grounded code helps the compiler create not only more optimized code, but also
faster to compile code. Always keep containers well-typed, functions specializing on the appropriate
arguments, and types concrete.
## Closures should be avoided whenever possible
Closures can cause accidental type instabilities that are difficult to track down and debug; in the
long run it saves time to always program defensively and avoid writing closures in the first place,
even when a particular closure would not have been problematic. A similar argument applies to reading
code with closures; if someone is looking for type instabilities, this is faster to do when code does
not contain closures.
Furthermore, if you want to update variables in an outer scope, do so explicitly with `Ref`s or self
defined structs.
For example,
```julia
map(Base.Fix2(getindex, i), vector_of_vectors)
```
is preferred over
```julia
map(v -> v[i], vector_of_vectors)
```
or
```julia
[v[i] for v in vector_of_vectors]
```
## Numerical functionality should use the appropriate generic numerical interfaces
While you can use `A\b` to do a linear solve inside a package, that does not mean that you should.
This interface is only sufficient for performing factorizations, and so that limits the scaling
choices, the types of `A` that can be supported, etc. Instead, linear solves within packages should
use LinearSolve.jl. Similarly, nonlinear solves should use NonlinearSolve.jl. Optimization should use
Optimization.jl. Etc. This allows the full generic choice to be given to the user without depending
on every solver package (effectively recreating the generic interfaces within each package).
## Functions should capture one underlying principle
Functions mean one thing. Every dispatch of `+` should be "the meaning of addition on these types".
While in theory you could add dispatches to `+` that mean something different, that will fail in
generic code for which `+` means addition. Thus, for generic code to work, code needs to adhere to
one meaning for each function. Every dispatch should be an instantiation of that meaning.
## Internal choices should be exposed as options whenever possible
Whenever possible, numerical values and choices within scripts should be exposed as options
to the user. This promotes code reusability beyond the few cases the author may have expected.
## Prefer code reuse over rewrites whenever possible
If a package has a function you need, use the package. Add a dependency if you need to. If the
function is missing a feature, prefer to add that feature to said package and then add it as a
dependency. If the dependency is potentially troublesome, for example because it has a high
load time, prefer to spend time helping said package fix these issues and add the dependency.
Only when it does not seem possible to make the package "good enough" should using the package
be abandoned. If it is abandoned, consider building a new package for this functionality as you
need it, and then make it a dependency.
## Prefer to not shadow functions
Two functions can have the same name in Julia by having different namespaces. For example,
`X.f` and `Y.f` can be two different functions, with different dispatches, but the same name.
This should be avoided whenever possible. Instead of creating `MyPackage.sort`, consider
adding dispatches to `Base.sort` for your types if these new dispatches match the underlying
principle of the function. If it doesn't, prefer to use a different name. While using `MyPackage.sort`
is not conflicting, it is going to be confusing for most people unfamiliar with your code,
so `MyPackage.special_sort` would be more helpful to newcomers reading the code.
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"MIT"
] | 0.6.0 | 69fca5d8d3bd617303aec6fad80a7264bbef233a | docs | 2297 | # [Style Guide](@id style)
```@contents
Pages = ["style.md"]
Depth = 3
```
This section describes the coding style rules that apply to our code and that
we recommend you to use it also.
In some cases, our style guide diverges from Julia's official
[Style Guide](https://docs.julialang.org/en/v1/manual/style-guide/) (Please read it!).
All such cases will be explicitly noted and justified.
Our style guide adopts many recommendations from the
[BlueStyle](https://github.com/invenia/BlueStyle).
Please read the [BlueStyle](https://github.com/invenia/BlueStyle)
before contributing to this package.
If not following, your pull requests may not be accepted.
!!! info
The style guide is always a work in progress, and not all Crystallography code
follows the rules. When modifying Crystallography, please fix the style violations
of the surrounding code (i.e., leave the code tidier than when you
started). If large changes are needed, consider separating them into
another pull request.
## Formatting
### [Run JuliaFormatter](@id formatter)
Crystallography uses [JuliaFormatter](https://github.com/domluna/JuliaFormatter.jl) as
an auto-formatting tool.
We use the options contained in [`.JuliaFormatter.toml`](https://github.com/MineralsCloud/Crystallography.jl/blob/main/.JuliaFormatter.toml).
To format your code, `cd` to the Crystallography directory, then run:
```@repl
using Pkg
Pkg.add("JuliaFormatter")
using JuliaFormatter: format
format("docs");
format("src");
format("test");
```
!!! info
A continuous integration check verifies that all PRs made to Crystallography have
passed the formatter.
The following sections outline extra style guide points that are not fixed
automatically by JuliaFormatter.
### Use the Julia extension for Visual Studio Code
Please use [VS Code](https://code.visualstudio.com/) with the
[Julia extension](https://marketplace.visualstudio.com/items?itemName=julialang.language-julia)
to edit, format, and test your code.
We do not recommend using other editors to edit your code for the time being.
This extension already has [JuliaFormatter](https://github.com/domluna/JuliaFormatter.jl)
integrated. So to format your code, follow the steps listed
[here](https://www.julia-vscode.org/docs/stable/userguide/formatter/).
| Crystallography | https://github.com/MineralsCloud/Crystallography.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2637 | using Pkg
using GenericTensorNetworks
using GenericTensorNetworks: TropicalNumbers, Polynomials, OMEinsum, OMEinsum.OMEinsumContractionOrders, LuxorGraphPlot
using Documenter
using DocThemeIndigo
using Literate
for each in readdir(pkgdir(GenericTensorNetworks, "examples"))
input_file = pkgdir(GenericTensorNetworks, "examples", each)
endswith(input_file, ".jl") || continue
@info "building" input_file
output_dir = pkgdir(GenericTensorNetworks, "docs", "src", "generated")
Literate.markdown(input_file, output_dir; name=each[1:end-3], execute=false)
end
indigo = DocThemeIndigo.install(GenericTensorNetworks)
DocMeta.setdocmeta!(GenericTensorNetworks, :DocTestSetup, :(using GenericTensorNetworks); recursive=true)
makedocs(;
modules=[GenericTensorNetworks, TropicalNumbers, OMEinsum, OMEinsumContractionOrders, LuxorGraphPlot],
authors="Jinguo Liu",
repo="https://github.com/QuEraComputing/GenericTensorNetworks.jl/blob/{commit}{path}#{line}",
sitename="GenericTensorNetworks.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://QuEraComputing.github.io/GenericTensorNetworks.jl",
assets=String[indigo],
),
pages=[
"Home" => "index.md",
"Problems" => [
"Independent set problem" => "generated/IndependentSet.md",
"Maximal independent set problem" => "generated/MaximalIS.md",
"Spin glass problem" => "generated/SpinGlass.md",
"Cutting problem" => "generated/MaxCut.md",
"Vertex matching problem" => "generated/Matching.md",
"Binary paint shop problem" => "generated/PaintShop.md",
"Coloring problem" => "generated/Coloring.md",
"Dominating set problem" => "generated/DominatingSet.md",
"Satisfiability problem" => "generated/Satisfiability.md",
"Set covering problem" => "generated/SetCovering.md",
"Set packing problem" => "generated/SetPacking.md",
#"Other problems" => "generated/Others.md",
],
"Topics" => [
"Gist" => "gist.md",
"Save and load solutions" => "generated/saveload.md",
"Sum product tree representation" => "sumproduct.md",
"Weighted problems" => "generated/weighted.md",
"Open and fixed degrees of freedom" => "generated/open.md"
],
"Performance Tips" => "performancetips.md",
"References" => "ref.md",
],
doctest=false,
warnonly = :missing_docs,
)
deploydocs(;
repo="github.com/QuEraComputing/GenericTensorNetworks.jl",
)
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 832 | function serve(;host::String="0.0.0.0", port::Int=8000)
# setup environment
docs_dir = @__DIR__
julia_cmd = "using Pkg; Pkg.instantiate()"
run(`$(Base.julia_exename()) --project=$docs_dir -e $julia_cmd`)
serve_cmd = """
using LiveServer;
LiveServer.servedocs(;
doc_env=true,
skip_dirs=[
#joinpath("docs", "src", "generated"),
joinpath("docs", "src"),
joinpath("docs", "build"),
joinpath("docs", "Manifest.toml"),
],
literate="examples",
host=\"$host\",
port=$port,
)
"""
try
run(`$(Base.julia_exename()) --project=$docs_dir -e $serve_cmd`)
catch e
if e isa InterruptException
return
else
rethrow(e)
end
end
return
end
serve()
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 3040 | # # Coloring problem
# !!! note
# It is highly recommended to read the [Independent set problem](@ref) chapter before reading this one.
# ## Problem definition
# A [vertex coloring](https://en.wikipedia.org/wiki/Graph_coloring) is an assignment of labels or colors to each vertex of a graph such that no edge connects two identically colored vertices.
# In the following, we are going to defined a 3-coloring problem for the Petersen graph.
using GenericTensorNetworks, Graphs
graph = Graphs.smallgraph(:petersen)
# We can visualize this graph using the following function
rot15(a, b, i::Int) = cos(2i*π/5)*a + sin(2i*π/5)*b, cos(2i*π/5)*b - sin(2i*π/5)*a
locations = [[rot15(0.0, 60.0, i) for i=0:4]..., [rot15(0.0, 30, i) for i=0:4]...]
show_graph(graph, locations; format=:svg)
# ## Generic tensor network representation
# We can define the 3-coloring problem with the [`Coloring`](@ref) type as
coloring = Coloring{3}(graph)
# The tensor network representation of the 3-coloring problem can be obtained by
problem = GenericTensorNetwork(coloring)
# ### Theory (can skip)
# Type [`Coloring`](@ref) can be used for constructing the tensor network with optimized contraction order for a coloring problem.
# Let us use 3-coloring problem defined on vertices as an example.
# For a vertex ``v``, we define the degrees of freedom ``c_v\in\{1,2,3\}`` and a vertex tensor labelled by it as
# ```math
# W(v) = \left(\begin{matrix}
# 1\\
# 1\\
# 1
# \end{matrix}\right).
# ```
# For an edge ``(u, v)``, we define an edge tensor as a matrix labelled by ``(c_u, c_v)`` to specify the constraint
# ```math
# B = \left(\begin{matrix}
# 1 & x & x\\
# x & 1 & x\\
# x & x & 1
# \end{matrix}\right).
# ```
# The number of possible coloring can be obtained by contracting this tensor network by setting vertex tensor elements ``r_v, g_v`` and ``b_v`` to 1.
# ## Solving properties
# ##### counting all possible coloring
num_of_coloring = solve(problem, CountingMax())[]
# ##### finding one best coloring
single_solution = solve(problem, SingleConfigMax())[]
read_config(single_solution)
is_vertex_coloring(graph, read_config(single_solution))
vertex_color_map = Dict(0=>"red", 1=>"green", 2=>"blue")
show_graph(graph, locations; format=:svg, vertex_colors=[vertex_color_map[Int(c)]
for c in read_config(single_solution)])
# Let us try to solve the same issue on its line graph, a graph that generated by mapping an edge to a vertex and two edges sharing a common vertex will be connected.
linegraph = line_graph(graph)
show_graph(linegraph, [(locations[e.src] .+ locations[e.dst])
for e in edges(graph)]; format=:svg)
# Let us construct the tensor network and see if there are solutions.
lineproblem = Coloring{3}(linegraph);
num_of_coloring = solve(GenericTensorNetwork(lineproblem), CountingMax())[]
read_size_count(num_of_coloring)
# You will see the maximum size 28 is smaller than the number of edges in the `linegraph`,
# meaning no solution for the 3-coloring on edges of a Petersen graph.
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 3677 | # # Dominating set problem
# !!! note
# It is highly recommended to read the [Independent set problem](@ref) chapter before reading this one.
# ## Problem definition
# In graph theory, a [dominating set](https://en.wikipedia.org/wiki/Dominating_set) for a graph ``G = (V, E)`` is a subset ``D`` of ``V`` such that every vertex not in ``D`` is adjacent to at least one member of ``D``.
# The domination number ``\gamma(G)`` is the number of vertices in a smallest dominating set for ``G``.
# The decision version of finding the minimum dominating set is an NP-complete.
# In the following, we are going to solve the dominating set problem on the Petersen graph.
using GenericTensorNetworks, Graphs
graph = Graphs.smallgraph(:petersen)
# We can visualize this graph using the following function
rot15(a, b, i::Int) = cos(2i*π/5)*a + sin(2i*π/5)*b, cos(2i*π/5)*b - sin(2i*π/5)*a
locations = [[rot15(0.0, 60.0, i) for i=0:4]..., [rot15(0.0, 30, i) for i=0:4]...]
show_graph(graph, locations; format=:svg)
# ## Generic tensor network representation
# We can use [`DominatingSet`](@ref) to construct the tensor network for solving the dominating set problem as
dom = DominatingSet(graph)
# The tensor network representation of the dominating set problem can be obtained by
problem = GenericTensorNetwork(dom; optimizer=TreeSA())
# where the key word argument `optimizer` specifies the tensor network contraction order optimizer as a local search based optimizer [`TreeSA`](@ref).
# ### Theory (can skip)
# Let ``G=(V,E)`` be the target graph that we want to solve.
# The tensor network representation map a vertex ``v\in V`` to a boolean degree of freedom ``s_v\in\{0, 1\}``.
# We defined the restriction on a vertex and its neighboring vertices ``N(v)``:
# ```math
# T(x_v)_{s_1,s_2,\ldots,s_{|N(v)|},s_v} = \begin{cases}
# 0 & s_1=s_2=\ldots=s_{|N(v)|}=s_v=0,\\
# 1 & s_v=0,\\
# x_v^{w_v} & \text{otherwise},
# \end{cases}
# ```
# where ``w_v`` is the weight of vertex ``v``.
# This tensor means if both ``v`` and its neighboring vertices are not in ``D``, i.e., ``s_1=s_2=\ldots=s_{|N(v)|}=s_v=0``,
# this configuration is forbidden because ``v`` is not adjacent to any member in the set.
# otherwise, if ``v`` is in ``D``, it has a contribution ``x_v^{w_v}`` to the final result.
# One can check the contraction time space complexity of a [`DominatingSet`](@ref) instance by typing:
contraction_complexity(problem)
# ## Solving properties
# ### Counting properties
# ##### Domination polynomial
# The graph polynomial for the dominating set problem is known as the domination polynomial (see [arXiv:0905.2251](https://arxiv.org/abs/0905.2251)).
# It is defined as
# ```math
# D(G, x) = \sum_{k=0}^{\gamma(G)} d_k x^k,
# ```
# where ``d_k`` is the number of dominating sets of size ``k`` in graph ``G=(V, E)``.
domination_polynomial = solve(problem, GraphPolynomial())[]
# The domination number ``\gamma(G)`` can be computed with the [`SizeMin`](@ref) property:
domination_number = solve(problem, SizeMin())[]
# Similarly, we have its counting [`CountingMin`](@ref):
counting_min_dominating_set = solve(problem, CountingMin())[]
# ### Configuration properties
# ##### finding minimum dominating set
# One can enumerate all minimum dominating sets with the [`ConfigsMin`](@ref) property in the program.
min_configs = read_config(solve(problem, ConfigsMin())[])
all(c->is_dominating_set(graph, c), min_configs)
#
show_configs(graph, locations, reshape(collect(min_configs), 2, 5); padding_left=20)
# Similarly, if one is only interested in computing one of the minimum dominating sets,
# one can use the graph property [`SingleConfigMin`](@ref).
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 8592 | # # Independent set problem
# ## Problem definition
# In graph theory, an [independent set](https://en.wikipedia.org/wiki/Independent_set_(graph_theory)) is a set of vertices in a graph, no two of which are adjacent.
#
# In the following, we are going to solve the solution space properties of the independent set problem on the Petersen graph. To start, let us define a Petersen graph instance.
using GenericTensorNetworks, Graphs
graph = Graphs.smallgraph(:petersen)
# We can visualize this graph using the [`show_graph`](@ref) function
## set the vertex locations manually instead of using the default spring layout
rot15(a, b, i::Int) = cos(2i*π/5)*a + sin(2i*π/5)*b, cos(2i*π/5)*b - sin(2i*π/5)*a
locations = [[rot15(0.0, 60.0, i) for i=0:4]..., [rot15(0.0, 30, i) for i=0:4]...]
show_graph(graph, locations; format=:svg)
# The graphical display is available in the following editors
# * a [VSCode](https://github.com/julia-vscode/julia-vscode) editor,
# * a [Jupyter](https://github.com/JunoLab/Juno.jl) notebook,
# * or a [Pluto](https://github.com/fonsp/Pluto.jl) notebook,
# ## Generic tensor network representation
# The independent set problem can be constructed with [`IndependentSet`](@ref) type as
iset = IndependentSet(graph)
# The tensor network representation of the independent set problem can be obtained by
problem = GenericTensorNetwork(iset; optimizer=TreeSA())
# where the key word argument `optimizer` specifies the tensor network contraction order optimizer as a local search based optimizer [`TreeSA`](@ref).
# Here, the key word argument `optimizer` specifies the tensor network contraction order optimizer as a local search based optimizer [`TreeSA`](@ref).
# The resulting contraction order optimized tensor network is contained in the `code` field of `problem`.
#
# ### Theory (can skip)
# Let ``G=(V, E)`` be a graph with each vertex $v\in V$ associated with a weight ``w_v``.
# To reduce the independent set problem on it to a tensor network contraction, we first map a vertex ``v\in V`` to a label ``s_v \in \{0, 1\}`` of dimension ``2``, where we use ``0`` (``1``) to denote a vertex absent (present) in the set.
# For each vertex ``v``, we defined a parameterized rank-one tensor indexed by ``s_v`` as
# ```math
# W(x_v^{w_v}) = \left(\begin{matrix}
# 1 \\
# x_v^{w_v}
# \end{matrix}\right)
# ```
# where ``x_v`` is a variable associated with ``v``.
# Similarly, for each edge ``(u, v) \in E``, we define a matrix ``B`` indexed by ``s_u`` and ``s_v`` as
# ```math
# B = \left(\begin{matrix}
# 1 & 1\\
# 1 & 0
# \end{matrix}\right).
# ```
# Ideally, an optimal contraction order has a space complexity ``2^{{\rm tw}(G)}``,
# where ``{\rm tw(G)}`` is the [tree-width](https://en.wikipedia.org/wiki/Treewidth) of ``G`` (or `graph` in the code).
# We can check the time, space and read-write complexities by typing
contraction_complexity(problem)
# For more information about how to improve the contraction order, please check the [Performance Tips](@ref).
# ## Solution space properties
# ### Maximum independent set size ``\alpha(G)``
# We can compute solution space properties with the [`solve`](@ref) function, which takes two positional arguments, the problem instance and the wanted property.
maximum_independent_set_size = solve(problem, SizeMax())[]
# Here [`SizeMax`](@ref) means finding the solution with maximum set size.
# The return value has [`Tropical`](@ref) type. We can get its content by typing
read_size(maximum_independent_set_size)
# ### Counting properties
# ##### Count all solutions and best several solutions
# We can count all independent sets with the [`CountingAll`](@ref) property.
count_all_independent_sets = solve(problem, CountingAll())[]
# The return value has type `Float64`. The counting of all independent sets is equivalent to the infinite temperature partition function
solve(problem, PartitionFunction(0.0))[]
# We can count the maximum independent sets with [`CountingMax`](@ref).
count_maximum_independent_sets = solve(problem, CountingMax())[]
# The return value has type [`CountingTropical`](@ref), which contains two fields.
# They are `n` being the maximum independent set size and `c` being the number of the maximum independent sets.
read_size_count(count_maximum_independent_sets)
# Similarly, we can count independent sets of sizes ``\alpha(G)`` and ``\alpha(G)-1`` by feeding an integer positional argument to [`CountingMax`](@ref).
count_max2_independent_sets = solve(problem, CountingMax(2))[]
# The return value has type [`TruncatedPoly`](@ref), which contains two fields.
# They are `maxorder` being the maximum independent set size and `coeffs` being the number of independent sets having sizes ``\alpha(G)-1`` and ``\alpha(G)``.
read_size_count(count_max2_independent_sets)
# ##### Find the graph polynomial
# We can count the number of independent sets at any size, which is equivalent to finding the coefficients of an independence polynomial that defined as
# ```math
# I(G, x) = \sum_{k=0}^{\alpha(G)} a_k x^k,
# ```
# where ``\alpha(G)`` is the maximum independent set size,
# ``a_k`` is the number of independent sets of size ``k``.
# The total number of independent sets is thus equal to ``I(G, 1)``.
# There are 3 methods to compute a graph polynomial, `:finitefield`, `:fft` and `:polynomial`.
# These methods are introduced in the docstring of [`GraphPolynomial`](@ref).
independence_polynomial = solve(problem, GraphPolynomial(; method=:finitefield))[]
# The return type is [`Polynomial`](https://juliamath.github.io/Polynomials.jl/stable/polynomials/polynomial/#Polynomial-2).
read_size_count(independence_polynomial)
# ### Configuration properties
# ##### Find one best solution
# We can use the bounded or unbounded [`SingleConfigMax`](@ref) to find one of the solutions with largest size.
# The unbounded (default) version uses a joint type of [`CountingTropical`](@ref) and [`ConfigSampler`](@ref) in computation,
# where `CountingTropical` finds the maximum size and `ConfigSampler` samples one of the best solutions.
# The bounded version uses the binary gradient back-propagation (see our paper) to compute the gradients.
# It requires caching intermediate states, but is often faster (on CPU) because it can use [`TropicalGEMM`](https://github.com/TensorBFS/TropicalGEMM.jl) (see [Performance Tips](@ref)).
max_config = solve(problem, SingleConfigMax(; bounded=false))[]
# The return value has type [`CountingTropical`](@ref) with its counting field having [`ConfigSampler`](@ref) type. The `data` field of [`ConfigSampler`](@ref) is a bit string that corresponds to the solution
single_solution = read_config(max_config)
# This bit string should be read from left to right, with the i-th bit being 1 (0) to indicate the i-th vertex is present (absent) in the set.
# We can visualize this MIS with the following function.
show_graph(graph, locations; format=:svg, vertex_colors=
[iszero(single_solution[i]) ? "white" : "red" for i=1:nv(graph)])
# ##### Enumerate all solutions and best several solutions
# We can use bounded or unbounded [`ConfigsMax`](@ref) to find all solutions with largest-K set sizes.
# In most cases, the bounded (default) version is preferred because it can reduce the memory usage significantly.
all_max_configs = solve(problem, ConfigsMax(; bounded=true))[]
# The return value has type [`CountingTropical`](@ref), while its counting field having type [`ConfigEnumerator`](@ref). The `data` field of a [`ConfigEnumerator`](@ref) instance contains a vector of bit strings.
_, configs_vector = read_size_config(all_max_configs)
# These solutions can be visualized with the [`show_configs`](@ref) function.
show_configs(graph, locations, reshape(configs_vector, 1, :); padding_left=20)
# We can use [`ConfigsAll`](@ref) to enumerate all sets satisfying the independence constraint.
all_independent_sets = solve(problem, ConfigsAll())[]
# The return value has type [`ConfigEnumerator`](@ref).
# ##### Sample solutions
# It is often difficult to store all configurations in a vector.
# A more clever way to store the data is using the sum product tree format.
all_independent_sets_tree = solve(problem, ConfigsAll(; tree_storage=true))[]
# The return value has the [`SumProductTree`](@ref) type. Its length corresponds to the number of configurations.
length(all_independent_sets_tree)
# We can use `Base.collect` function to create a [`ConfigEnumerator`](@ref) or use [`generate_samples`](@ref) to generate samples from it.
collect(all_independent_sets_tree)
generate_samples(all_independent_sets_tree, 10)
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2976 | # # Vertex matching problem
# !!! note
# It is highly recommended to read the [Independent set problem](@ref) chapter before reading this one.
# ## Problem definition
# A ``k``-matching in a graph ``G`` is a set of k edges, no two of which have a vertex in common.
using GenericTensorNetworks, Graphs
# In the following, we are going to defined a matching problem for the Petersen graph.
graph = Graphs.smallgraph(:petersen)
# We can visualize this graph using the following function
rot15(a, b, i::Int) = cos(2i*π/5)*a + sin(2i*π/5)*b, cos(2i*π/5)*b - sin(2i*π/5)*a
locations = [[rot15(0.0, 60.0, i) for i=0:4]..., [rot15(0.0, 30, i) for i=0:4]...]
show_graph(graph, locations; format=:svg)
# ## Generic tensor network representation
# We can define the matching problem with the [`Matching`](@ref) type as
matching = Matching(graph)
# The tensor network representation of the matching problem can be obtained by
problem = GenericTensorNetwork(matching)
# ### Theory (can skip)
#
# Type [`Matching`](@ref) can be used for constructing the tensor network with optimized contraction order for a matching problem.
# We map an edge ``(u, v) \in E`` to a label ``\langle u, v\rangle \in \{0, 1\}`` in a tensor network,
# where 1 means two vertices of an edge are matched, 0 means otherwise.
# Then we define a tensor of rank ``d(v) = |N(v)|`` on vertex ``v`` such that,
# ```math
# W_{\langle v, n_1\rangle, \langle v, n_2 \rangle, \ldots, \langle v, n_{d(v)}\rangle} = \begin{cases}
# 1, & \sum_{i=1}^{d(v)} \langle v, n_i \rangle \leq 1,\\
# 0, & \text{otherwise},
# \end{cases}
# ```
# and a tensor of rank 1 on the bond
# ```math
# B_{\langle v, w\rangle} = \begin{cases}
# 1, & \langle v, w \rangle = 0 \\
# x, & \langle v, w \rangle = 1,
# \end{cases}
# ```
# where label ``\langle v, w \rangle`` is equivalent to ``\langle w,v\rangle``.
#
# ## Solving properties
# The maximum matching size can be obtained by
max_matching = solve(problem, SizeMax())[]
read_size(max_matching)
# The largest number of matching is 5, which means we have a perfect matching (vertices are all paired).
# The graph polynomial defined for the matching problem is known as the matching polynomial.
# Here, we adopt the first definition in the [wiki page](https://en.wikipedia.org/wiki/Matching_polynomial).
# ```math
# M(G, x) = \sum\limits_{k=1}^{|V|/2} c_k x^k,
# ```
# where ``k`` is the number of matches, and coefficients ``c_k`` are the corresponding counting.
matching_poly = solve(problem, GraphPolynomial())[]
read_size_count(matching_poly)
# ### Configuration properties
# ##### one of the perfect matches
match_config = solve(problem, SingleConfigMax())[]
read_size_config(match_config)
# Let us show the result by coloring the matched edges to red
show_graph(graph, locations; format=:svg, edge_colors=
[isone(read_config(match_config)[i]) ? "red" : "black" for i=1:ne(graph)])
# where we use edges with red color to related pairs of matched vertices.
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 3461 | # # Cutting problem
# !!! note
# It is highly recommended to read the [Independent set problem](@ref) chapter before reading this one.
# ## Problem definition
# In graph theory, a [cut](https://en.wikipedia.org/wiki/Cut_(graph_theory)) is a partition of the vertices of a graph into two disjoint subsets.
# It is closely related to the [Spin-glass problem](@ref) in physics.
# Finding the maximum cut is NP-Hard, where a maximum cut is a cut whose size is at least the size of any other cut,
# where the size of a cut is the number of edges (or the sum of weights on edges) crossing the cut.
using GenericTensorNetworks, Graphs
# In the following, we are going to defined an cutting problem for the Petersen graph.
graph = Graphs.smallgraph(:petersen)
# We can visualize this graph using the following function
rot15(a, b, i::Int) = cos(2i*π/5)*a + sin(2i*π/5)*b, cos(2i*π/5)*b - sin(2i*π/5)*a
locations = [[rot15(0.0, 60.0, i) for i=0:4]..., [rot15(0.0, 30, i) for i=0:4]...]
show_graph(graph, locations; format=:svg)
# ## Generic tensor network representation
# We can define the cutting problem with the [`MaxCut`](@ref) type as
maxcut = MaxCut(graph)
# The tensor network representation of the cutting problem can be obtained by
problem = GenericTensorNetwork(maxcut)
# ### Theory (can skip)
#
# We associated a vertex ``v\in V`` with a boolean degree of freedom ``s_v\in\{0, 1\}``.
# Then the maximum cutting problem can be encoded to tensor networks by mapping an edge ``(i,j)\in E`` to an edge matrix labelled by ``s_i`` and ``s_j``
# ```math
# B(x_i, x_j, w_{ij}) = \left(\begin{matrix}
# 1 & x_{i}^{w_{ij}}\\
# x_{j}^{w_{ij}} & 1
# \end{matrix}\right),
# ```
# where ``w_{ij}`` is a real number associated with edge ``(i, j)`` as the edge weight.
# If and only if the bipartition cuts on edge ``(i, j)``,
# this tensor contributes a factor ``x_{i}^{w_{ij}}`` or ``x_{j}^{w_{ij}}``.
# Similarly, one can assign weights to vertices, which corresponds to the onsite energy terms in the spin glass.
# The vertex tensor is
# ```math
# W(x_i, w_i) = \left(\begin{matrix}
# 1\\
# x_{i}^{w_i}
# \end{matrix}\right),
# ```
# where ``w_i`` is a real number associated with vertex ``i`` as the vertex weight.
# Its contraction time space complexity is ``2^{{\rm tw}(G)}``, where ``{\rm tw(G)}`` is the [tree-width](https://en.wikipedia.org/wiki/Treewidth) of ``G``.
# ## Solving properties
# ### Maximum cut size ``\gamma(G)``
max_cut_size = solve(problem, SizeMax())[]
# ### Counting properties
# ##### graph polynomial
# The graph polynomial defined for the cutting problem is
# ```math
# C(G, x) = \sum_{k=0}^{\gamma(G)} c_k x^k,
# ```
# where ``\gamma(G)`` is the maximum cut size,
# ``c_k/2`` is the number of cuts of size ``k`` in graph ``G=(V,E)``.
# Since the variable ``x`` is defined on edges,
# the coefficients of the polynomial is the number of configurations having different number of anti-parallel edges.
max_config = solve(problem, GraphPolynomial())[]
# ### Configuration properties
# ##### finding one max cut solution
max_vertex_config = read_config(solve(problem, SingleConfigMax())[])
max_cut_size_verify = cut_size(graph, max_vertex_config)
# You should see a consistent result as above `max_cut_size`.
show_graph(graph, locations; vertex_colors=[
iszero(max_vertex_config[i]) ? "white" : "red" for i=1:nv(graph)], format=:svg)
# where red vertices and white vertices are separated by the cut.
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 4228 | # # Maximal independent set problem
# !!! note
# It is highly recommended to read the [Independent set problem](@ref) chapter before reading this one.
# ## Problem definition
# In graph theory, a [maximal independent set](https://en.wikipedia.org/wiki/Maximal_independent_set) is an independent set that is not a subset of any other independent set.
# It is different from maximum independent set because it does not require the set to have the max size.
# In the following, we are going to solve the maximal independent set problem on the Petersen graph.
using GenericTensorNetworks, Graphs
graph = Graphs.smallgraph(:petersen)
# We can visualize this graph using the following function
rot15(a, b, i::Int) = cos(2i*π/5)*a + sin(2i*π/5)*b, cos(2i*π/5)*b - sin(2i*π/5)*a
locations = [[rot15(0.0, 60.0, i) for i=0:4]..., [rot15(0.0, 30, i) for i=0:4]...]
show_graph(graph, locations; format=:svg)
# ## Generic tensor network representation
# We can use [`MaximalIS`](@ref) to construct the tensor network for solving the maximal independent set problem as
maximalis = MaximalIS(graph)
# The tensor network representation of the maximal independent set problem can be obtained by
problem = GenericTensorNetwork(maximalis)
# ### Theory (can skip)
# Let ``G=(V,E)`` be the target graph that we want to solve.
# The tensor network representation map a vertex ``v\in V`` to a boolean degree of freedom ``s_v\in\{0, 1\}``.
# We defined the restriction on its neighborhood ``N(v)``:
# ```math
# T(x_v)_{s_1,s_2,\ldots,s_{|N(v)|},s_v} = \begin{cases}
# s_vx_v^{w_v} & s_1=s_2=\ldots=s_{|N(v)|}=0,\\
# 1-s_v& \text{otherwise}.
# \end{cases}
# ```
# The first case corresponds to all the neighborhood vertices of ``v`` are not in ``I_{m}``, then ``v`` must be in ``I_{m}`` and contribute a factor ``x_{v}^{w_v}``,
# where ``w_v`` is the weight of vertex ``v``.
# Otherwise, if any of the neighboring vertices of ``v`` is in ``I_{m}``, ``v`` must not be in ``I_{m}`` by the independence requirement.
# Its contraction time space complexity of a [`MaximalIS`](@ref) instance is no longer determined by the tree-width of the original graph ``G``.
# It is often harder to contract this tensor network than to contract the one for regular independent set problem.
contraction_complexity(problem)
# ## Solving properties
# ### Counting properties
# ##### maximal independence polynomial
# The graph polynomial defined for the maximal independent set problem is
# ```math
# I_{\rm max}(G, x) = \sum_{k=0}^{\alpha(G)} b_k x^k,
# ```
# where ``b_k`` is the number of maximal independent sets of size ``k`` in graph ``G=(V, E)``.
maximal_indenpendence_polynomial = solve(problem, GraphPolynomial())[]
# One can see the first several coefficients are 0, because it only counts the maximal independent sets,
# The minimum maximal independent set size is also known as the independent domination number.
# It can be computed with the [`SizeMin`](@ref) property:
independent_domination_number = solve(problem, SizeMin())[]
# Similarly, we have its counting [`CountingMin`](@ref):
counting_min_maximal_independent_set = solve(problem, CountingMin())[]
# ### Configuration properties
# ##### finding all maximal independent set
maximal_configs = read_config(solve(problem, ConfigsAll())[])
all(c->is_maximal_independent_set(graph, c), maximal_configs)
#
show_configs(graph, locations, reshape(collect(maximal_configs), 3, 5); padding_left=20)
# This result should be consistent with that given by the [Bron Kerbosch algorithm](https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm) on the complement of Petersen graph.
cliques = maximal_cliques(complement(graph))
# For sparse graphs, the generic tensor network approach is usually much faster and memory efficient than the Bron Kerbosch algorithm.
# ##### finding minimum maximal independent set
# It is the [`ConfigsMin`](@ref) property in the program.
minimum_maximal_configs = read_config(solve(problem, ConfigsMin())[])
show_configs(graph, locations, reshape(collect(minimum_maximal_configs), 2, 5); padding_left=20)
# Similarly, if one is only interested in computing one of the minimum sets,
# one can use the graph property [`SingleConfigMin`](@ref).
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 4529 | # # Binary paint shop problem
# !!! note
# It is highly recommended to read the [Independent set problem](@ref) chapter before reading this one.
# ## Problem Definition
# The [binary paint shop problem](http://m-hikari.com/ams/ams-2012/ams-93-96-2012/popovAMS93-96-2012-2.pdf) is defined as follows:
# we are given a ``2m`` length sequence containing ``m`` cars, where each car appears twice.
# Each car need to be colored red in one occurrence, and blue in the other.
# We need to choose which occurrence for each car to color with which color — the goal is to minimize the number of times we need to change the current color.
# In the following, we use a character to represent a car,
# and defined a binary paint shop problem as a string that each character appear exactly twice.
using GenericTensorNetworks, Graphs
sequence = collect("iadgbeadfcchghebif")
# We can visualize this paint shop problem as a graph
rot(a, b, θ) = cos(θ)*a + sin(θ)*b, cos(θ)*b - sin(θ)*a
locations = [rot(0.0, 100.0, -0.25π - 1.5*π*(i-0.5)/length(sequence)) for i=1:length(sequence)]
graph = path_graph(length(sequence))
for i=1:length(sequence)
j = findlast(==(sequence[i]), sequence)
i != j && add_edge!(graph, i, j)
end
show_graph(graph, locations; texts=string.(sequence), format=:svg, edge_colors=
[sequence[e.src] == sequence[e.dst] ? "blue" : "black" for e in edges(graph)])
# Vertices connected by blue edges must have different colors,
# and the goal becomes a min-cut problem defined on black edges.
# ## Generic tensor network representation
# We can define the binary paint shop problem with the [`PaintShop`](@ref) type as
pshop = PaintShop(sequence)
# The tensor network representation of the binary paint shop problem can be obtained by
problem = GenericTensorNetwork(pshop)
# ### Theory (can skip)
# Type [`PaintShop`](@ref) can be used for constructing the tensor network with optimized contraction order for solving a binary paint shop problem.
# To obtain its tensor network representation, we associating car ``c_i`` (the ``i``-th character in our example) with a degree of freedom ``s_{c_i} \in \{0, 1\}``,
# where we use ``0`` to denote the first appearance of a car is colored red and ``1`` to denote the first appearance of a car is colored blue.
# For each black edges ``(i, i+1)``, we define an edge tensor labeled by ``(s_{c_i}, s_{c_{i+1}})`` as follows:
# If both cars on this edge are their first or second appearance
# ```math
# B^{\rm parallel} = \left(\begin{matrix}
# x & 1 \\
# 1 & x \\
# \end{matrix}\right),
# ```
#
# otherwise,
# ```math
# B^{\rm anti-parallel} = \left(\begin{matrix}
# 1 & x \\
# x & 1 \\
# \end{matrix}\right).
# ```
# It can be understood as, when both cars are their first appearance,
# they tend to have the same configuration so that the color is not changed.
# Otherwise, they tend to have different configuration to keep the color unchanged.
# ### Counting properties
# ##### graph polynomial
# The graph polynomial defined for the maximal independent set problem is
# ```math
# I_{\rm max}(G, x) = \sum_{k=0}^{\alpha(G)} b_k x^k,
# ```
# where ``b_k`` is the number of maximal independent sets of size ``k`` in graph ``G=(V, E)``.
max_config = solve(problem, GraphPolynomial())[]
# Since it only counts the maximal independent sets, the first several coefficients are 0.
# ### Counting properties
# ##### graph polynomial
# The graph polynomial of the binary paint shop problem in our convention is defined as
# ```math
# P(G, x) = \sum_{k=0}^{\delta(G)} p_k x^k
# ```
# where ``p_k`` is the number of possible coloring with number of color changes ``2m-1-k``.
paint_polynomial = solve(problem, GraphPolynomial())[]
# ### Configuration properties
# ##### finding best solutions
best_configs = solve(problem, ConfigsMin())[]
# One can see to identical bitstrings corresponding two different vertex configurations, they are related to bit-flip symmetry.
painting1 = paint_shop_coloring_from_config(pshop, read_config(best_configs)[1])
show_graph(graph, locations; format=:svg, texts=string.(sequence),
edge_colors=[sequence[e.src] == sequence[e.dst] ? "blue" : "black" for e in edges(graph)],
vertex_colors=[isone(c) ? "red" : "black" for c in painting1], config=GraphDisplayConfig(;vertex_text_color="white"))
# Since we have different choices of initial color, the number of best solution is 2.
# The following function will check the solution and return you the number of color switches
num_paint_shop_color_switch(sequence, painting1)
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2874 | # # Satisfiability problem
# !!! note
# It is highly recommended to read the [Independent set problem](@ref) chapter before reading this one.
# ## Problem definition
# In logic and computer science, the [boolean satisfiability problem](https://en.wikipedia.org/wiki/Boolean_satisfiability_problem) is the problem of determining if there exists an interpretation that satisfies a given boolean formula.
# One can specify a satisfiable problem in the [conjunctive normal form](https://en.wikipedia.org/wiki/Conjunctive_normal_form).
# In boolean logic, a formula is in conjunctive normal form (CNF) if it is a conjunction (∧) of one or more clauses,
# where a clause is a disjunction (∨) of literals.
using GenericTensorNetworks
@bools a b c d e f g
cnf = ∧(∨(a, b, ¬d, ¬e), ∨(¬a, d, e, ¬f), ∨(f, g), ∨(¬b, c))
# To goal is to find an assignment to satisfy the above CNF.
# For a satisfiability problem at this size, we can find the following assignment to satisfy this assignment manually.
assignment = Dict([:a=>true, :b=>false, :c=>false, :d=>true, :e=>false, :f=>false, :g=>true])
satisfiable(cnf, assignment)
# ## Generic tensor network representation
# We can use [`Satisfiability`](@ref) to construct the tensor network for solving the satisfiability problem as
sat = Satisfiability(cnf)
# The tensor network representation of the satisfiability problem can be obtained by
problem = GenericTensorNetwork(sat)
# ### Theory (can skip)
# We can construct a [`Satisfiability`](@ref) problem to solve the above problem.
# To generate a tensor network, we map a boolean variable ``x`` and its negation ``\neg x`` to a degree of freedom (label) ``s_x \in \{0, 1\}``,
# where 0 stands for variable ``x`` having value `false` while 1 stands for having value `true`.
# Then we map a clause to a tensor. For example, a clause ``¬x ∨ y ∨ ¬z`` can be mapped to a tensor labeled by ``(s_x, s_y, s_z)``.
# ```math
# C = \left(\begin{matrix}
# \left(\begin{matrix}
# x & x \\
# x & x
# \end{matrix}\right) \\
# \left(\begin{matrix}
# x & x \\
# 1 & x
# \end{matrix}\right)
# \end{matrix}\right).
# ```
# There is only one entry ``(s_x, s_y, s_z) = (1, 0, 1)`` that makes this clause unsatisfied.
# ## Solving properties
# #### Satisfiability and its counting
# The size of a satisfiability problem is defined by the number of satisfiable clauses.
num_satisfiable = solve(problem, SizeMax())[]
# The [`GraphPolynomial`](@ref) of a satisfiability problem counts the number of solutions that `k` clauses satisfied.
num_satisfiable_count = read_size_count(solve(problem, GraphPolynomial())[])
# #### Find one of the solutions
single_config = read_config(solve(problem, SingleConfigMax())[])
# One will see a bit vector printed.
# One can create an assignment and check the validity with the following statement:
satisfiable(cnf, Dict(zip(labels(problem), single_config)))
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 3509 | # # Set covering problem
# !!! note
# It is highly recommended to read the [Independent set problem](@ref) chapter before reading this one.
# ## Problem definition
# The [set covering problem](https://en.wikipedia.org/wiki/Set_cover_problem) is a significant NP-hard problem in combinatorial optimization. Given a collection of elements, the set covering problem aims to find the minimum number of sets that incorporate (cover) all of these elements.
# In the following, we will find the solution space properties for the camera location and stadium area example in the [Cornell University Computational Optimization Open Textbook](https://optimization.cbe.cornell.edu/index.php?title=Set_covering_problem).
using GenericTensorNetworks, Graphs
# The covering stadium areas of cameras are represented as the following sets.
sets = [[1,3,4,6,7], [4,7,8,12], [2,5,9,11,13],
[1,2,14,15], [3,6,10,12,14], [8,14,15],
[1,2,6,11], [1,2,4,6,8,12]]
# ## Generic tensor network representation
# We can define the set covering problem with the [`SetCovering`](@ref) type as
setcover = SetCovering(sets)
# The tensor network representation of the set covering problem can be obtained by
problem = GenericTensorNetwork(setcover)
# ### Theory (can skip)
# Let ``S`` be the target set covering problem that we want to solve.
# For each set ``s \in S``, we associate it with a weight ``w_s`` to it.
# The tensor network representation map a set ``s\in S`` to a boolean degree of freedom ``v_s\in\{0, 1\}``.
# For each set ``s``, we defined a parameterized rank-one tensor indexed by ``v_s`` as
# ```math
# W(x_s^{w_s}) = \left(\begin{matrix}
# 1 \\
# x_s^{w_s}
# \end{matrix}\right)
# ```
# where ``x_s`` is a variable associated with ``s``.
# For each unique element ``a``, we defined the constraint over all sets containing it ``N(a) = \{s | s \in S \land a\in s\}``:
# ```math
# B_{s_1,s_2,\ldots,s_{|N(a)|}} = \begin{cases}
# 0 & s_1=s_2=\ldots=s_{|N(a)|}=0,\\
# 1 & \text{otherwise}.
# \end{cases}
# ```
# This tensor means if none of the sets containing element ``a`` are included, then this configuration is forbidden,
# One can check the contraction time space complexity of a [`SetCovering`](@ref) instance by typing:
contraction_complexity(problem)
# ## Solving properties
# ### Counting properties
# ##### The "graph" polynomial
# The graph polynomial for the set covering problem is defined as
# ```math
# P(S, x) = \sum_{k=0}^{|S|} c_k x^k,
# ```
# where ``c_k`` is the number of configurations having ``k`` sets.
covering_polynomial = solve(problem, GraphPolynomial())[]
# The minimum number of sets that covering the set of elements can be computed with the [`SizeMin`](@ref) property:
min_cover_size = solve(problem, SizeMin())[]
# Similarly, we have its counting [`CountingMin`](@ref):
counting_minimum_setcovering = solve(problem, CountingMin())[]
# ### Configuration properties
# ##### Finding minimum set covering
# One can enumerate all minimum set covering with the [`ConfigsMin`](@ref) property in the program.
min_configs = read_config(solve(problem, ConfigsMin())[])
# Hence the two optimal solutions are ``\{z_1, z_3, z_5, z_6\}`` and ``\{z_2, z_3, z_4, z_5\}``.
# The correctness of this result can be checked with the [`is_set_covering`](@ref) function.
all(c->is_set_covering(sets, c), min_configs)
# Similarly, if one is only interested in computing one of the minimum set coverings,
# one can use the graph property [`SingleConfigMin`](@ref).
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 3432 | # # Set packing problem
# !!! note
# It is highly recommended to read the [Independent set problem](@ref) chapter before reading this one.
# ## Problem definition
# The [set packing problem](https://en.wikipedia.org/wiki/Set_packing) is generalization of the [`IndependentSet`](@ref) problem from the simple graph to the multigraph.
# Suppose one has a finite set ``S`` and a list of subsets of ``S``. Then, the set packing problem asks if some ``k`` subsets in the list are pairwise disjoint.
# In the following, we will find the solution space properties for the set in the [Set covering problem](@ref).
using GenericTensorNetworks, Graphs
# The packing stadium areas of cameras are represented as the following sets.
sets = [[1,3,4,6,7], [4,7,8,12], [2,5,9,11,13],
[1,2,14,15], [3,6,10,12,14], [8,14,15],
[1,2,6,11], [1,2,4,6,8,12]]
# ## Generic tensor network representation
# We can define the set packing problem with the [`SetPacking`](@ref) type as
problem = SetPacking(sets)
# The tensor network representation of the set packing problem can be obtained by
problem = GenericTensorNetwork(problem)
# ### Theory (can skip)
# Let ``S`` be the target set packing problem that we want to solve.
# For each set ``s \in S``, we associate it with a weight ``w_s`` to it.
# The tensor network representation map a set ``s\in S`` to a boolean degree of freedom ``v_s\in\{0, 1\}``.
# For each set ``s``, we defined a parameterized rank-one tensor indexed by ``v_s`` as
# ```math
# W(x_s^{w_s}) = \left(\begin{matrix}
# 1 \\
# x_s^{w_s}
# \end{matrix}\right)
# ```
# where ``x_s`` is a variable associated with ``s``.
# For each unique element ``a``, we defined the constraint over all sets containing it ``N(a) = \{s | s \in S \land a\in s\}``:
# ```math
# B_{s_1,s_2,\ldots,s_{|N(a)|}} = \begin{cases}
# 0 & s_1+s_2+\ldots+s_{|N(a)|} > 1,\\
# 1 & \text{otherwise}.
# \end{cases}
# ```
# This tensor means if in a configuration, two sets contain the element ``a``, then this configuration is forbidden,
# One can check the contraction time space complexity of a [`SetPacking`](@ref) instance by typing:
contraction_complexity(problem)
# ## Solving properties
# ### Counting properties
# ##### The "graph" polynomial
# The graph polynomial for the set packing problem is defined as
# ```math
# P(S, x) = \sum_{k=0}^{\alpha(S)} c_k x^k,
# ```
# where ``c_k`` is the number of configurations having ``k`` sets, and ``\alpha(S)`` is the maximum size of the packing.
packing_polynomial = solve(problem, GraphPolynomial())[]
# The maximum number of sets that packing the set of elements can be computed with the [`SizeMax`](@ref) property:
max_packing_size = solve(problem, SizeMax())[]
# Similarly, we have its counting [`CountingMax`](@ref):
counting_maximum_set_packing = solve(problem, CountingMax())[]
# ### Configuration properties
# ##### Finding maximum set packing
# One can enumerate all maximum set packing with the [`ConfigsMax`](@ref) property in the program.
max_configs = read_config(solve(problem, ConfigsMax())[])
# Hence the only optimal solution is ``\{z_1, z_3, z_6\}`` that has size 3.
# The correctness of this result can be checked with the [`is_set_packing`](@ref) function.
all(c->is_set_packing(sets, c), max_configs)
# Similarly, if one is only interested in computing one of the maximum set packing,
# one can use the graph property [`SingleConfigMax`](@ref).
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 7023 | # # Spin-glass problem
# !!! note
# It is highly recommended to read the [Independent set problem](@ref) chapter before reading this one.
using GenericTensorNetworks
# ## Spin-glass problem on a simple graph
# Let ``G=(V, E)`` be a graph, the [spin-glass](https://en.wikipedia.org/wiki/Spin_glass) problem in physics is characterized by the following energy function
# ```math
# H = \sum_{ij \in E} J_{ij} s_i s_j + \sum_{i \in V} h_i s_i,
# ```
# where ``h_i`` is an onsite energy term associated with spin ``s_i \in \{-1, 1\}``, and ``J_{ij}`` is the coupling strength between spins ``s_i`` and ``s_j``.
# In the program, we use boolean variable ``n_i = \frac{1-s_i}{2}`` to represent a spin configuration.
using Graphs
# In the following, we are going to defined an spin glass problem for the Petersen graph.
graph = Graphs.smallgraph(:petersen)
# We can visualize this graph using the following function
rot15(a, b, i::Int) = cos(2i*π/5)*a + sin(2i*π/5)*b, cos(2i*π/5)*b - sin(2i*π/5)*a
locations = [[rot15(0.0, 60.0, i) for i=0:4]..., [rot15(0.0, 30, i) for i=0:4]...]
show_graph(graph, locations; format=:svg)
# ## Generic tensor network representation
# An anti-ferromagnetic spin glass problem can be defined with the [`SpinGlass`](@ref) type as
spinglass = SpinGlass(graph, fill(1, ne(graph)))
# The tensor network representation of the set packing problem can be obtained by
problem = GenericTensorNetwork(spinglass)
# The contraction order is already optimized.
# ### The tensor network reduction
# We defined the reduction of the spin-glass problem to a tensor network on a hypergraph.
# Let ``H = (V, E)`` be a hypergraph, the tensor network for the spin glass problem on ``H`` can be defined as the following triple of (alphabet of labels $\Lambda$, input tensors $\mathcal{T}$, output labels $\sigma_o$).
# ```math
# \begin{cases}
# \Lambda &= \{s_v \mid v \in V\}\\
# \mathcal{T} &= \{B^{(c)}_{s_{N(c, 1),N(c, 2),\ldots,N(c, d(c))}} \mid c \in E\} \cup \{W^{(v)}_{s_v} \mid v \in V\}\\
# \sigma_o &= \varepsilon
# \end{cases}
# ```
# where ``s_v \in \{0, 1\}`` is the boolean degreen associated to vertex ``v``,
# ``N(c, k)`` is the ``k``th vertex of hyperedge ``c``, and ``d(c)`` is the degree of ``c``.
# The edge tensor ``B^{(c)}`` is defined as
# ```math
# B^{(c)} = \begin{cases}
# x^{w_c} & (\sum_{v\in c} s_v) \;is\; even, \\
# x^{-w_c} & otherwise.
# \end{cases}
# ```
# and the vertex tensor ``W^{(v)}`` (used to carry labels) is defined as
# ```math
# W^{(v)} = \left(\begin{matrix}1_v\\ 1_v\end{matrix}\right)
# ```
# ## Graph properties
# ### Minimum and maximum energies
# To find the minimum and maximum energies of the spin glass problem, we can use the [`SizeMin`](@ref) and [`SizeMax`](@ref) solvers.
Emin = solve(problem, SizeMin())[]
# The state with the highest energy is the one with all spins having the same value.
Emax = solve(problem, SizeMax())[]
# ### Counting properties
# In the following, we are going to find the partition function and the graph polynomial of the spin glass problem.
# Consider a spin glass problem on a graph ``G = (V, E)`` with integer coupling strength ``J`` and onsite energy ``h``.
# Its graph polynomial is a Laurent polynomial
# ```math
# Z(G, J, h, x) = \sum_{k=E_{\rm min}}^{E_{\rm max}} c_k x^k,
# ```
# where ``E_{\rm min}`` and ``E_{\rm max}`` are minimum and maximum energies,
# ``c_k`` is the number of spin configurations with energy ``k``.
# The partition function at temperature ``\beta^{-1}`` can be computed by the graph polynomial at ``x = e^-\beta``.
partition_function = solve(problem, GraphPolynomial())[]
# ### Configuration properties
# The ground state of the spin glass problem can be found by the [`SingleConfigMin`](@ref) solver.
ground_state = read_config(solve(problem, SingleConfigMin())[])
# The energy of the ground state can be verified by the [`spinglass_energy`](@ref) function.
Emin_verify = spinglass_energy(spinglass, ground_state)
# You should see a consistent result as above `Emin`.
show_graph(graph, locations; vertex_colors=[
iszero(ground_state[i]) ? "white" : "red" for i=1:nv(graph)], format=:svg)
# In the plot, the red vertices are the ones with spin value `-1` (or `1` in the boolean representation).
# ## Spin-glass problem on a hypergraph
# A spin-glass problem on hypergraph ``H = (V, E)`` can be characterized by the following energy function
# ```math
# E = \sum_{c \in E} w_{c} \prod_{v\in c} S_v
# ```
# where ``S_v \in \{-1, 1\}``, ``w_c`` is coupling strength associated with hyperedge ``c``.
# In the program, we use boolean variable ``s_v = \frac{1-S_v}{2}`` to represent a spin configuration.
# In the following, we are going to defined an spin glass problem for the following hypergraph.
num_vertices = 15
hyperedges = [[1,3,4,6,7], [4,7,8,12], [2,5,9,11,13],
[1,2,14,15], [3,6,10,12,14], [8,14,15],
[1,2,6,11], [1,2,4,6,8,12]]
weights = [-1, 1, -1, 1, -1, 1, -1, 1];
# The energy function of the spin glass problem is
# ```math
# \begin{align*}
# E = &-S_1S_3S_4S_6S_7 + S_4S_7S_8S_{12} - S_2S_5S_9S_{11}S_{13} +\\
# &S_1S_2S_{14}S_{15} - S_3S_6S_{10}S_{12}S_{14} + S_8S_{14}S_{15} +\\
# &S_1S_2S_6S_{11} - S_1s_2S_4S_6S_8S_{12}
# \end{align*}
# ```
# A spin glass problem can be defined with the [`SpinGlass`](@ref) type as
hyperspinglass = SpinGlass(num_vertices, hyperedges, weights)
# The tensor network representation of the set packing problem can be obtained by
hyperproblem = GenericTensorNetwork(hyperspinglass)
# ## Graph properties
# ### Minimum and maximum energies
# To find the minimum and maximum energies of the spin glass problem, we can use the [`SizeMin`](@ref) and [`SizeMax`](@ref) solvers.
Emin = solve(hyperproblem, SizeMin())[]
#
Emax = solve(hyperproblem, SizeMax())[]
# In this example, the spin configurations can be chosen to make all hyperedges having even or odd spin parity.
# ### Counting properties
# ##### partition function and graph polynomial
# The graph polynomial defined for the spin-glass problem is a Laurent polynomial
# ```math
# Z(G, w, x) = \sum_{k=E_{\rm min}}^{E_{\rm max}} c_k x^k,
# ```
# where ``E_{\rm min}`` and ``E_{\rm max}`` are minimum and maximum energies,
# ``c_k`` is the number of spin configurations with energy ``k``.
# Let the inverse temperature ``\beta = 2``, the partition function is
β = 2.0
Z = solve(hyperproblem, PartitionFunction(β))[]
# The infinite temperature partition function is the counting of all feasible configurations
solve(hyperproblem, PartitionFunction(0.0))[]
# The graph polynomial is
poly = solve(hyperproblem, GraphPolynomial())[]
# ### Configuration properties
# The ground state of the spin glass problem can be found by the [`SingleConfigMin`](@ref) solver.
ground_state = read_config(solve(hyperproblem, SingleConfigMin())[])
# The energy of the ground state can be verified by the [`spinglass_energy`](@ref) function.
Emin_verify = spinglass_energy(hyperspinglass, ground_state)
# You should see a consistent result as above `Emin`. | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 1883 | # # Open and fixed degrees of freedom
# Open degrees of freedom is useful when one want to get the marginal about certain degrees of freedom.
# When one specifies the `openvertices` keyword argument in [`solve`](@ref) function as a tuple of vertices, the output will be a tensor that can be indexed by these degrees of freedom.
# Let us use the maximum independent set problem on Petersen graph as an example.
#
using GenericTensorNetworks, Graphs
graph = Graphs.smallgraph(:petersen)
# The following code computes the MIS tropical tensor (reference to be added) with open vertices 1, 2 and 3.
problem = GenericTensorNetwork(IndependentSet(graph); openvertices=[1,2,3]);
marginal = solve(problem, SizeMax())
# The return value is a rank-3 tensor, with its elements being the MIS sizes under different configuration of open vertices.
# For the maximum independent set problem, this tensor is also called the MIS tropical tensor, which can be useful in the MIS tropical tensor analysis (reference to be added).
# One can also specify the fixed degrees of freedom by providing the `fixedvertices` keyword argument as a `Dict`, which can be used to get conditioned probability.
# For example, we can use the following code to do the same calculation as using `openvertices`.
problem = GenericTensorNetwork(IndependentSet(graph); fixedvertices=Dict(1=>0, 2=>0, 3=>0));
output = zeros(TropicalF64,2,2,2);
marginal_alternative = map(CartesianIndices((2,2,2))) do ci
problem.fixedvertices[1] = ci.I[1]-1
problem.fixedvertices[2] = ci.I[2]-1
problem.fixedvertices[3] = ci.I[3]-1
output[ci] = solve(problem, SizeMax())[]
end
# One can easily check this one also gets the correct marginal on vertices 1, 2 and 3.
# As a reminder, their computational hardness can be different, because the contraction order optimization program can optimize over open degrees of freedom. | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2314 | # # Save and load solutions
# Let us use the maximum independent set problem on Petersen graph as an example.
# The following code enumerates all independent sets.
using GenericTensorNetworks, Graphs
problem = GenericTensorNetwork(IndependentSet(Graphs.smallgraph(:petersen)))
all_independent_sets = solve(problem, ConfigsAll())[]
# The return value has type [`ConfigEnumerator`](@ref).
# We can use [`save_configs`](@ref) and [`load_configs`](@ref) to save and read a [`ConfigEnumerator`](@ref) instance to the disk.
filename = tempname()
save_configs(filename, all_independent_sets; format=:binary)
loaded_sets = load_configs(filename; format=:binary, bitlength=10)
# !!! note
# When loading the data in the binary format, bit string length information `bitlength` is required.
#
# For the [`SumProductTree`](@ref) type output, we can use [`save_sumproduct`](@ref) and [`load_sumproduct`](@ref) to save and load serialized data.
all_independent_sets_tree = solve(problem, ConfigsAll(; tree_storage=true))[]
save_sumproduct(filename, all_independent_sets_tree)
loaded_sets_tree = load_sumproduct(filename)
# ## Loading solutions to python
# The following python script loads and unpacks the solutions as a numpy array from a `:binary` format file.
# ```python
# import numpy as np
#
# def loadfile(filename:str, bitlength:int):
# C = int(np.ceil(bitlength / 64))
# arr = np.fromfile(filename, dtype="uint8")
# # Some axes should be transformed from big endian to little endian
# res = np.unpackbits(arr).reshape(-1, C, 8, 8)[:,::-1,::-1,:]
# res = res.reshape(-1, C*64)[:, :(64*C-bitlength)-1:-1]
# print("number of solutions = %d"%(len(res)))
# return res # in big endian format
#
# res = loadfile(filename, 10)
# ```
# !!! note
# Check section [Maximal independent set problem](@ref) for solution space properties related the maximal independent sets. That example also contains using cases of finding solution space properties related to minimum sizes:
# * [`SizeMin`](@ref) for finding minimum several set sizes,
# * [`CountingMin`](@ref) for counting minimum several set sizes,
# * [`SingleConfigMin`](@ref) for finding one solution with minimum several sizes,
# * [`ConfigsMin`](@ref) for enumerating solutions with minimum several sizes,
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 2262 | # # Weighted problems
# Let us use the maximum independent set problem on Petersen graph as an example.
using GenericTensorNetworks, Graphs
graph = Graphs.smallgraph(:petersen)
# The following code constructs a weighted MIS problem instance.
problem = GenericTensorNetwork(IndependentSet(graph, collect(1:10)));
GenericTensorNetworks.get_weights(problem)
# The tensor labels that associated with the weights can be accessed by
GenericTensorNetworks.energy_terms(problem)
# Here, the `weights` keyword argument can be a vector for weighted graphs or `UnitWeight()` for unweighted graphs.
# Most solution space properties work for unweighted graphs also work for the weighted graphs.
# For example, the maximum independent set can be found as follows.
max_config_weighted = solve(problem, SingleConfigMax())[]
# Let us visualize the solution.
rot15(a, b, i::Int) = cos(2i*π/5)*a + sin(2i*π/5)*b, cos(2i*π/5)*b - sin(2i*π/5)*a
locations = [[rot15(0.0, 60.0, i) for i=0:4]..., [rot15(0.0, 30, i) for i=0:4]...]
show_graph(graph, locations; format=:svg, vertex_colors=
[iszero(max_config_weighted.c.data[i]) ? "white" : "red" for i=1:nv(graph)])
# The only solution space property that can not be defined for general real-weighted (not including integer-weighted) graphs is the [`GraphPolynomial`](@ref).
# For the weighted MIS problem, a useful solution space property is the "energy spectrum", i.e. the largest several configurations and their weights.
# We can use the solution space property is [`SizeMax`](@ref)`(10)` to compute the largest 10 weights.
spectrum = solve(problem, SizeMax(10))[]
# The return value has type [`ExtendedTropical`](@ref), which contains one field `orders`.
spectrum.orders
# We can see the `order` is a vector of [`Tropical`](@ref) numbers.
# Similarly, we can get weighted independent sets with maximum 5 sizes as follows.
max5_configs = read_config(solve(problem, SingleConfigMax(5))[])
# The return value of `solve` has type [`ExtendedTropical`](@ref), but this time the element type of `orders` has been changed to [`CountingTropical`](@ref)`{Float64,`[`ConfigSampler`](@ref)`}`.
# Let us visually check these configurations
show_configs(graph, locations, [max5_configs[j] for i=1:1, j=1:5]; padding_left=20) | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 559 | module GenericTensorNetworksCUDAExt
using CUDA
using GenericTensorNetworks
import GenericTensorNetworks: onehotmask!, togpu
# patch
# Base.ndims(::Base.Broadcast.Broadcasted{CUDA.CuArrayStyle{0}}) = 0
togpu(x::AbstractArray) = CuArray(x)
function onehotmask!(A::CuArray{T}, X::CuArray{T}) where T
@assert length(A) == length(X)
mask = X .≈ inv.(A)
ci = argmax(mask)
mask .= false
CUDA.@allowscalar mask[ci] = true
# set some elements in X to zero to help back propagating.
X[(!).(mask)] .= Ref(zero(T))
return mask
end
end | GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 3420 | module GenericTensorNetworks
using Core: Argument
using TropicalNumbers
using OMEinsum
using OMEinsum: contraction_complexity, timespace_complexity, timespacereadwrite_complexity, getixsv, NestedEinsum, getixs, getiy, DynamicEinCode
using Graphs, Random
using DelimitedFiles, Serialization, Printf
using LuxorGraphPlot
using LuxorGraphPlot.Luxor.Colors: @colorant_str
using LuxorGraphPlot: Layered
import Polynomials
using Polynomials: Polynomial, LaurentPolynomial, printpoly, fit
using FFTW
using Primes
using DocStringExtensions
using Base.Cartesian
import AbstractTrees: children, printnode, print_tree
import StatsBase
# OMEinsum
export timespace_complexity, timespacereadwrite_complexity, contraction_complexity, @ein_str, getixsv, getiyv
export GreedyMethod, TreeSA, SABipartite, KaHyParBipartite, MergeVectors, MergeGreedy
# estimate memory
export estimate_memory
# Algebras
export StaticBitVector, StaticElementVector, @bv_str, hamming_distance
export is_commutative_semiring
export Max2Poly, TruncatedPoly, Polynomial, LaurentPolynomial, Tropical, CountingTropical, StaticElementVector, Mod
export ConfigEnumerator, onehotv, ConfigSampler, SumProductTree
export CountingTropicalF64, CountingTropicalF32, TropicalF64, TropicalF32, ExtendedTropical
export generate_samples, OnehotVec
# Graphs
export random_regular_graph, diagonal_coupled_graph
export square_lattice_graph, unit_disk_graph, random_diagonal_coupled_graph, random_square_lattice_graph
export line_graph
# Tensor Networks (Graph problems)
export GraphProblem, GenericTensorNetwork, optimize_code, UnitWeight, ZeroWeight
export flavors, labels, nflavor, get_weights, fixedvertices, chweights, energy_terms
export IndependentSet, mis_compactify!, is_independent_set
export MaximalIS, is_maximal_independent_set
export cut_size, MaxCut
export spinglass_energy, spin_glass_from_matrix, SpinGlass
export PaintShop, paintshop_from_pairs, num_paint_shop_color_switch, paint_shop_coloring_from_config, paint_shop_from_pairs
export Coloring, is_vertex_coloring
export Satisfiability, CNF, CNFClause, BoolVar, satisfiable, @bools, ∨, ¬, ∧
export DominatingSet, is_dominating_set
export Matching, is_matching
export SetPacking, is_set_packing
export SetCovering, is_set_covering
export OpenPitMining, is_valid_mining, print_mining
# Interfaces
export solve, SizeMax, SizeMin, PartitionFunction, CountingAll, CountingMax, CountingMin, GraphPolynomial, SingleConfigMax, SingleConfigMin, ConfigsAll, ConfigsMax, ConfigsMin, Single
# Utilities
export save_configs, load_configs, hamming_distribution, save_sumproduct, load_sumproduct
# Readers
export read_size, read_count, read_config, read_size_count, read_size_config
# Visualization
export show_graph, show_configs, show_einsum, GraphDisplayConfig, render_locs, show_landscape
export AbstractLayout, SpringLayout, StressLayout, SpectralLayout, Layered, LayeredSpringLayout, LayeredStressLayout
project_relative_path(xs...) = normpath(joinpath(dirname(dirname(pathof(@__MODULE__))), xs...))
# Mods.jl fixed to v1.3.4
include("Mods.jl/src/Mods.jl")
using .Mods
include("utils.jl")
include("bitvector.jl")
include("arithematics.jl")
include("networks/networks.jl")
include("graph_polynomials.jl")
include("configurations.jl")
include("graphs.jl")
include("bounding.jl")
include("fileio.jl")
include("interfaces.jl")
include("deprecate.jl")
include("multiprocessing.jl")
include("visualize.jl")
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 34661 | @enum TreeTag LEAF SUM PROD ZERO ONE
# pirate
Base.abs(x::Mod) = x
Base.isless(x::Mod{N}, y::Mod{N}) where N = mod(x.val, N) < mod(y.val, N)
"""
is_commutative_semiring(a::T, b::T, c::T) where T
Check if elements `a`, `b` and `c` satisfied the commutative semiring requirements.
```math
\\begin{align*}
(a \\oplus b) \\oplus c = a \\oplus (b \\oplus c) & \\hspace{5em}\\triangleright\\text{commutative monoid \$\\oplus\$ with identity \$\\mathbb{0}\$}\\\\
a \\oplus \\mathbb{0} = \\mathbb{0} \\oplus a = a &\\\\
a \\oplus b = b \\oplus a &\\\\
&\\\\
(a \\odot b) \\odot c = a \\odot (b \\odot c) & \\hspace{5em}\\triangleright \\text{commutative monoid \$\\odot\$ with identity \$\\mathbb{1}\$}\\\\
a \\odot \\mathbb{1} = \\mathbb{1} \\odot a = a &\\\\
a \\odot b = b \\odot a &\\\\
&\\\\
a \\odot (b\\oplus c) = a\\odot b \\oplus a\\odot c & \\hspace{5em}\\triangleright \\text{left and right distributive}\\\\
(a\\oplus b) \\odot c = a\\odot c \\oplus b\\odot c &\\\\
&\\\\
a \\odot \\mathbb{0} = \\mathbb{0} \\odot a = \\mathbb{0}
\\end{align*}
```
"""
function is_commutative_semiring(a::T, b::T, c::T) where T
# +
if (a + b) + c != a + (b + c)
@debug "(a + b) + c != a + (b + c)"
return false
end
if !(a + zero(T) == zero(T) + a == a)
@debug "!(a + zero(T) == zero(T) + a == a)"
return false
end
if a + b != b + a
@debug "a + b != b + a"
return false
end
# *
if (a * b) * c != a * (b * c)
@debug "(a * b) * c != a * (b * c)"
return false
end
if !(a * one(T) == one(T) * a == a)
@debug "!(a * one(T) == one(T) * a == a)"
return false
end
if a * b != b * a
@debug "a * b != b * a"
return false
end
# more
if a * (b+c) != a*b + a*c
@debug "a * (b+c) != a*b + a*c"
return false
end
if (a+b) * c != a*c + b*c
@debug "(a+b) * c != a*c + b*c"
return false
end
if !(a * zero(T) == zero(T) * a == zero(T))
@debug "!(a * zero(T) == zero(T) * a == zero(T))"
return false
end
if !(a * zero(T) == zero(T) * a == zero(T))
@debug "!(a * zero(T) == zero(T) * a == zero(T))"
return false
end
return true
end
######################## Truncated Polynomial ######################
# TODO: store orders to support non-integer weights
# (↑) Maybe not so nessesary, no use case for counting degeneracy when using floating point weights.
"""
TruncatedPoly{K,T,TO} <: Number
TruncatedPoly(coeffs::Tuple, maxorder)
Polynomial truncated to largest `K` orders. `T` is the coefficients type and `TO` is the orders type.
Fields
------------------------
* `coeffs` is the largest-K coefficients of a polynomial. In `GenericTensorNetworks`, it can be the counting or enumeration of solutions.
* `maxorder` is the order of a polynomial.
Examples
------------------------
```jldoctest; setup=(using GenericTensorNetworks)
julia> TruncatedPoly((1,2,3), 6)
x^4 + 2*x^5 + 3*x^6
julia> TruncatedPoly((1,2,3), 6) * TruncatedPoly((5,2,1), 3)
20*x^7 + 8*x^8 + 3*x^9
julia> TruncatedPoly((1,2,3), 6) + TruncatedPoly((5,2,1), 3)
x^4 + 2*x^5 + 3*x^6
```
"""
struct TruncatedPoly{K,T,TO} <: Number
coeffs::NTuple{K,T}
maxorder::TO
end
Base.:(==)(t1::TruncatedPoly{K}, t2::TruncatedPoly{K}) where K = t1.maxorder == t2.maxorder && all(i->t1.coeffs[i] == t2.coeffs[i], 1:K)
"""
Max2Poly{T,TO} = TruncatedPoly{2,T,TO}
Max2Poly(a, b, maxorder)
A shorthand of [`TruncatedPoly`](@ref){2}.
"""
const Max2Poly{T,TO} = TruncatedPoly{2,T,TO}
Max2Poly(a, b, maxorder) = TruncatedPoly((a, b), maxorder)
Max2Poly{T,TO}(a, b, maxorder) where {T,TO} = TruncatedPoly{2,T,TO}((a, b), maxorder)
function Base.:+(a::Max2Poly, b::Max2Poly)
aa, ab = a.coeffs
ba, bb = b.coeffs
if a.maxorder == b.maxorder
return Max2Poly(aa+ba, ab+bb, a.maxorder)
elseif a.maxorder == b.maxorder-1
return Max2Poly(ab+ba, bb, b.maxorder)
elseif a.maxorder == b.maxorder+1
return Max2Poly(aa+bb, ab, a.maxorder)
elseif a.maxorder < b.maxorder
return b
else
return a
end
end
@generated function Base.:+(a::TruncatedPoly{K}, b::TruncatedPoly{K}) where K
quote
if a.maxorder == b.maxorder
return TruncatedPoly(a.coeffs .+ b.coeffs, a.maxorder)
elseif a.maxorder > b.maxorder
offset = a.maxorder - b.maxorder
return TruncatedPoly((@ntuple $K i->i+offset <= $K ? a.coeffs[convert(Int, i)] + b.coeffs[convert(Int, i+offset)] : a.coeffs[convert(Int, i)]), a.maxorder)
else
offset = b.maxorder - a.maxorder
return TruncatedPoly((@ntuple $K i->i+offset <= $K ? b.coeffs[convert(Int, i)] + a.coeffs[convert(Int, i+offset)] : b.coeffs[convert(Int, i)]), b.maxorder)
end
end
end
@generated function Base.:*(a::TruncatedPoly{K,T}, b::TruncatedPoly{K,T}) where {K,T}
tupleexpr = Expr(:tuple, [K-k+1 > 1 ? Expr(:call, :+, [:(a.coeffs[$(i+k-1)]*b.coeffs[$(K-i+1)]) for i=1:K-k+1]...) : :(a.coeffs[$k]*b.coeffs[$K]) for k=1:K]...)
quote
maxorder = a.maxorder + b.maxorder
TruncatedPoly($tupleexpr, maxorder)
end
end
Base.zero(::Type{TruncatedPoly{K,T,TO}}) where {K,T,TO} = TruncatedPoly(ntuple(i->zero(T), K), zero(Tropical{TO}).n)
Base.one(::Type{TruncatedPoly{K,T,TO}}) where {K,T,TO} = TruncatedPoly(ntuple(i->i==K ? one(T) : zero(T), K), zero(TO))
Base.zero(::TruncatedPoly{K,T,TO}) where {K,T,TO} = zero(TruncatedPoly{K,T,TO})
Base.one(::TruncatedPoly{K,T,TO}) where {K,T,TO} = one(TruncatedPoly{K,T,TO})
Base.show(io::IO, x::TruncatedPoly) = show(io, MIME"text/plain"(), x)
function Base.show(io::IO, ::MIME"text/plain", x::TruncatedPoly{K}) where K
if isinf(x.maxorder)
print(io, 0)
else
print(io, Polynomial(x))
end
end
Polynomials.Polynomial(x::TruncatedPoly{K, T}) where {K, T} = Polynomial(vcat(zeros(T, Int(x.maxorder)-K+1), [x.coeffs...]))
Polynomials.LaurentPolynomial(x::TruncatedPoly{K, T}) where {K, T} = LaurentPolynomial([x.coeffs...], Int(x.maxorder-K+1))
Base.literal_pow(::typeof(^), a::TruncatedPoly, ::Val{b}) where b = a ^ b
function Base.:^(x::TruncatedPoly{K,T,TO}, b::Integer) where {K,T,TO}
if b >= 0
return Base.power_by_squaring(x, b)
else
if count(!iszero, x.coeffs) <= 1
return TruncatedPoly{K,T,TO}(ntuple(i->iszero(x.coeffs[i]) ? x.coeffs[i] : x.coeffs[i] ^ b, K), x.maxorder*b)
else
error("can not apply negative power over truncated polynomial: $x")
end
end
end
############################ ExtendedTropical #####################
"""
ExtendedTropical{K,TO} <: Number
ExtendedTropical{K}(orders)
Extended Tropical numbers with largest `K` orders keeped,
or the [`TruncatedPoly`](@ref) without coefficients,
`TO` is the element type of orders, usually [`Tropical`](@ref) numbers.
This algebra maps
* `+` to finding largest `K` values of union of two sets.
* `*` to finding largest `K` values of sum combination of two sets.
* `0` to set [-Inf, -Inf, ..., -Inf, -Inf]
* `1` to set [-Inf, -Inf, ..., -Inf, 0]
Fields
------------------------
* `orders` is a vector of [`Tropical`](@ref) ([`CountingTropical`](@ref)) numbers as the largest-K solution sizes (solutions).
Examples
------------------------------
```jldoctest; setup=(using GenericTensorNetworks)
julia> x = ExtendedTropical{3}(Tropical.([1.0, 2, 3]))
ExtendedTropical{3, Tropical{Float64}}(Tropical{Float64}[1.0ₜ, 2.0ₜ, 3.0ₜ])
julia> y = ExtendedTropical{3}(Tropical.([-Inf, 2, 5]))
ExtendedTropical{3, Tropical{Float64}}(Tropical{Float64}[-Infₜ, 2.0ₜ, 5.0ₜ])
julia> x * y
ExtendedTropical{3, Tropical{Float64}}(Tropical{Float64}[6.0ₜ, 7.0ₜ, 8.0ₜ])
julia> x + y
ExtendedTropical{3, Tropical{Float64}}(Tropical{Float64}[2.0ₜ, 3.0ₜ, 5.0ₜ])
julia> one(x)
ExtendedTropical{3, Tropical{Float64}}(Tropical{Float64}[-Infₜ, -Infₜ, 0.0ₜ])
julia> zero(x)
ExtendedTropical{3, Tropical{Float64}}(Tropical{Float64}[-Infₜ, -Infₜ, -Infₜ])
```
"""
struct ExtendedTropical{K,TO} <: Number
orders::Vector{TO}
end
function ExtendedTropical{K}(x::Vector{T}) where {T, K}
@assert length(x) == K
@assert issorted(x)
ExtendedTropical{K,T}(x)
end
Base.:(==)(a::ExtendedTropical{K}, b::ExtendedTropical{K}) where K = all(i->a.orders[i] == b.orders[i], 1:K)
function Base.:*(a::ExtendedTropical{K,TO}, b::ExtendedTropical{K,TO}) where {K,TO}
res = Vector{TO}(undef, K)
return ExtendedTropical{K,TO}(sorted_sum_combination!(res, a.orders, b.orders))
end
# 1. bisect over summed value and find the critical value `c`,
# 2. collect the values with sum combination `≥ c`,
# 3. sort the collected values
function sorted_sum_combination!(res::AbstractVector{TO}, A::AbstractVector{TO}, B::AbstractVector{TO}) where TO
K = length(res)
@assert length(B) == length(A) == K
@inbounds high = A[K] * B[K]
mA = findfirst(!iszero, A)
mB = findfirst(!iszero, B)
if mA === nothing || mB === nothing
res .= Ref(zero(TO))
return res
end
@inbounds low = A[mA] * B[mB]
# count number bigger than x
c, _ = count_geq(A, B, mB, low, true)
@inbounds if c <= K # return
res[K-c+1:K] .= sort!(collect_geq!(view(res,1:c), A, B, mB, low))
if c < K
res[1:K-c] .= zero(TO)
end
return res
end
# calculate by bisection for at most 30 times.
@inbounds for _ = 1:30
mid = mid_point(high, low)
c, nB = count_geq(A, B, mB, mid, true)
if c > K
low = mid
mB = nB
elseif c == K # return
# NOTE: this is the bottleneck
return sort!(collect_geq!(res, A, B, mB, mid))
else
high = mid
end
end
clow, _ = count_geq(A, B, mB, low, false)
@inbounds res .= sort!(collect_geq!(similar(res, clow), A, B, mB, low))[end-K+1:end]
return res
end
# count the number of sum-combinations with the sum >= low
function count_geq(A, B, mB, low, earlybreak)
K = length(A)
k = 1 # TODO: we should tighten mA, mB later!
@inbounds Ak = A[K-k+1]
@inbounds Bq = B[K-mB+1]
c = 0
nB = mB
@inbounds for q = K-mB+1:-1:1
Bq = B[K-q+1]
while k < K && Ak * Bq >= low
k += 1
Ak = A[K-k+1]
end
if Ak * Bq >= low
c += k
else
c += (k-1)
if k==1
nB += 1
end
end
if earlybreak && c > K
return c, nB
end
end
return c, nB
end
function collect_geq!(res, A, B, mB, low)
K = length(A)
k = 1 # TODO: we should tighten mA, mB later!
Ak = A[K-k+1]
l = 0
for q = K-mB+1:-1:1
Bq = B[K-q+1]
while k < K && Ak * Bq >= low
k += 1
Ak = A[K-k+1]
end
# push data
ck = Ak * Bq >= low ? k : k-1
for j=1:ck
l += 1
res[l] = Bq * A[end-j+1]
end
end
return res
end
# for bisection
mid_point(a::Tropical{T}, b::Tropical{T}) where T = Tropical{T}((a.n + b.n) / 2)
mid_point(a::CountingTropical{T,CT}, b::CountingTropical{T,CT}) where {T,CT} = CountingTropical{T,CT}((a.n + b.n) / 2, a.c)
mid_point(a::Tropical{T}, b::Tropical{T}) where T<:Integer = Tropical{T}((a.n + b.n) ÷ 2)
mid_point(a::CountingTropical{T,CT}, b::CountingTropical{T,CT}) where {T<:Integer,CT} = CountingTropical{T,CT}((a.n + b.n) ÷ 2, a.c)
function Base.:+(a::ExtendedTropical{K,TO}, b::ExtendedTropical{K,TO}) where {K,TO}
res = Vector{TO}(undef, K)
ptr1, ptr2 = K, K
@inbounds va, vb = a.orders[ptr1], b.orders[ptr2]
@inbounds for i=K:-1:1
if va > vb
res[i] = va
if ptr1 != 1
ptr1 -= 1
va = a.orders[ptr1]
end
else
res[i] = vb
if ptr2 != 1
ptr2 -= 1
vb = b.orders[ptr2]
end
end
end
return ExtendedTropical{K,TO}(res)
end
Base.literal_pow(::typeof(^), a::ExtendedTropical, ::Val{b}) where b = a ^ b
Base.:^(a::ExtendedTropical, b::Integer) = Base.invoke(^, Tuple{ExtendedTropical, Real}, a, b)
function Base.:^(a::ExtendedTropical{K,TO}, b::Real) where {K,TO}
if iszero(b) # to avoid NaN
return one(ExtendedTropical{K,TO})
else
# sort for negative order
# the -Inf cannot become possitive after powering
return ExtendedTropical{K,TO}(sort!(map(x->iszero(x) ? x : x^b, a.orders)))
end
end
Base.zero(::Type{ExtendedTropical{K,TO}}) where {K,TO} = ExtendedTropical{K,TO}(fill(zero(TO), K))
Base.one(::Type{ExtendedTropical{K,TO}}) where {K,TO} = ExtendedTropical{K,TO}(map(i->i==K ? one(TO) : zero(TO), 1:K))
Base.zero(::ExtendedTropical{K,TO}) where {K,TO} = zero(ExtendedTropical{K,TO})
Base.one(::ExtendedTropical{K,TO}) where {K,TO} = one(ExtendedTropical{K,TO})
############################ SET Numbers ##########################
abstract type AbstractSetNumber end
"""
ConfigEnumerator{N,S,C} <: AbstractSetNumber
Set algebra for enumerating configurations, where `N` is the length of configurations,
`C` is the size of storage in unit of `UInt64`,
`S` is the bit width to store a single element in a configuration, i.e. `log2(# of flavors)`, for bitstrings, it is `1``.
Fields
------------------------
* `data` is a vector of [`StaticElementVector`](@ref) as the solution set.
Examples
----------------------
```jldoctest; setup=:(using GenericTensorNetworks)
julia> a = ConfigEnumerator([StaticBitVector([1,1,1,0,0]), StaticBitVector([1,0,0,0,1])])
{11100, 10001}
julia> b = ConfigEnumerator([StaticBitVector([0,0,0,0,0]), StaticBitVector([1,0,1,0,1])])
{00000, 10101}
julia> a + b
{11100, 10001, 00000, 10101}
julia> one(a)
{00000}
julia> zero(a)
{}
```
"""
struct ConfigEnumerator{N,S,C} <: AbstractSetNumber
data::Vector{StaticElementVector{N,S,C}}
end
Base.length(x::ConfigEnumerator{N}) where N = length(x.data)
Base.iterate(x::ConfigEnumerator{N}) where N = iterate(x.data)
Base.iterate(x::ConfigEnumerator{N}, state) where N = iterate(x.data, state)
Base.getindex(x::ConfigEnumerator, i) = x.data[i]
Base.:(==)(x::ConfigEnumerator{N,S,C}, y::ConfigEnumerator{N,S,C}) where {N,S,C} = Set(x.data) == Set(y.data)
function Base.:+(x::ConfigEnumerator{N,S,C}, y::ConfigEnumerator{N,S,C}) where {N,S,C}
length(x) == 0 && return y
length(y) == 0 && return x
return ConfigEnumerator{N,S,C}(vcat(x.data, y.data))
end
function Base.:*(x::ConfigEnumerator{L,S,C}, y::ConfigEnumerator{L,S,C}) where {L,S,C}
M, N = length(x), length(y)
M == 0 && return x
N == 0 && return y
z = Vector{StaticElementVector{L,S,C}}(undef, M*N)
@inbounds for j=1:N, i=1:M
z[(j-1)*M+i] = x.data[i] | y.data[j]
end
return ConfigEnumerator{L,S,C}(z)
end
Base.zero(::Type{ConfigEnumerator{N,S,C}}) where {N,S,C} = ConfigEnumerator{N,S,C}(StaticElementVector{N,S,C}[])
Base.one(::Type{ConfigEnumerator{N,S,C}}) where {N,S,C} = ConfigEnumerator{N,S,C}([zero(StaticElementVector{N,S,C})])
Base.zero(::ConfigEnumerator{N,S,C}) where {N,S,C} = zero(ConfigEnumerator{N,S,C})
Base.one(::ConfigEnumerator{N,S,C}) where {N,S,C} = one(ConfigEnumerator{N,S,C})
Base.show(io::IO, x::ConfigEnumerator) = print(io, "{", join(x.data, ", "), "}")
Base.show(io::IO, ::MIME"text/plain", x::ConfigEnumerator) = Base.show(io, x)
# the algebra sampling one of the configurations
"""
ConfigSampler{N,S,C} <: AbstractSetNumber
ConfigSampler(elements::StaticElementVector)
The algebra for sampling one configuration, where `N` is the length of configurations,
`C` is the size of storage in unit of `UInt64`,
`S` is the bit width to store a single element in a configuration, i.e. `log2(# of flavors)`, for bitstrings, it is `1``.
!!! note
`ConfigSampler` is a **probabilistic** commutative semiring, adding two config samplers do not give you deterministic results.
Fields
----------------------
* `data` is a [`StaticElementVector`](@ref) as the sampled solution.
Examples
----------------------
```jldoctest; setup=:(using GenericTensorNetworks, Random; Random.seed!(2))
julia> ConfigSampler(StaticBitVector([1,1,1,0,0]))
ConfigSampler{5, 1, 1}(11100)
julia> ConfigSampler(StaticBitVector([1,1,1,0,0])) + ConfigSampler(StaticBitVector([1,0,1,0,0]))
ConfigSampler{5, 1, 1}(10100)
julia> ConfigSampler(StaticBitVector([1,1,1,0,0])) * ConfigSampler(StaticBitVector([0,0,0,0,1]))
ConfigSampler{5, 1, 1}(11101)
julia> one(ConfigSampler{5, 1, 1})
ConfigSampler{5, 1, 1}(00000)
julia> zero(ConfigSampler{5, 1, 1})
ConfigSampler{5, 1, 1}(11111)
```
"""
struct ConfigSampler{N,S,C} <: AbstractSetNumber
data::StaticElementVector{N,S,C}
end
Base.:(==)(x::ConfigSampler{N,S,C}, y::ConfigSampler{N,S,C}) where {N,S,C} = x.data == y.data
function Base.:+(x::ConfigSampler{N,S,C}, y::ConfigSampler{N,S,C}) where {N,S,C} # biased sampling: return `x`, maybe using random sampler is better.
return randn() > 0.5 ? x : y
end
function Base.:*(x::ConfigSampler{L,S,C}, y::ConfigSampler{L,S,C}) where {L,S,C}
ConfigSampler(x.data | y.data)
end
@generated function Base.zero(::Type{ConfigSampler{N,S,C}}) where {N,S,C}
ex = Expr(:call, :(StaticElementVector{$N,$S,$C}), Expr(:tuple, fill(typemax(UInt64), C)...))
:(ConfigSampler{N,S,C}($ex))
end
Base.one(::Type{ConfigSampler{N,S,C}}) where {N,S,C} = ConfigSampler{N,S,C}(zero(StaticElementVector{N,S,C}))
Base.zero(::ConfigSampler{N,S,C}) where {N,S,C} = zero(ConfigSampler{N,S,C})
Base.one(::ConfigSampler{N,S,C}) where {N,S,C} = one(ConfigSampler{N,S,C})
"""
SumProductTree{ET} <: AbstractSetNumber
Configuration enumerator encoded in a tree, it is the most natural representation given by a sum-product network
and is often more memory efficient than putting the configurations in a vector.
One can use [`generate_samples`](@ref) to sample configurations from this tree structure efficiently.
Fields
-----------------------
* `tag` is one of `ZERO`, `ONE`, `LEAF`, `SUM`, `PROD`.
* `data` is the element stored in a `LEAF` node.
* `left` and `right` are two operands of a `SUM` or `PROD` node.
Examples
------------------------
```jldoctest; setup=:(using GenericTensorNetworks)
julia> s = SumProductTree(bv"00111")
00111
julia> q = SumProductTree(bv"10000")
10000
julia> x = s + q
+ (count = 2.0)
├─ 00111
└─ 10000
julia> y = x * x
* (count = 4.0)
├─ + (count = 2.0)
│ ├─ 00111
│ └─ 10000
└─ + (count = 2.0)
├─ 00111
└─ 10000
julia> collect(y)
4-element Vector{StaticBitVector{5, 1}}:
00111
10111
10111
10000
julia> zero(s)
∅
julia> one(s)
00000
```
"""
mutable struct SumProductTree{ET} <: AbstractSetNumber
tag::TreeTag
count::Float64
data::ET
left::SumProductTree{ET}
right::SumProductTree{ET}
# zero(ET) can be undef
function SumProductTree(tag::TreeTag, left::SumProductTree{ET}, right::SumProductTree{ET}) where {ET}
@assert tag === SUM || tag === PROD
res = new{ET}(tag, tag === SUM ? left.count + right.count : left.count * right.count)
res.left = left
res.right = right
return res
end
function SumProductTree(data::ET) where ET
return new{ET}(LEAF, 1.0, data)
end
function SumProductTree{ET}(tag::TreeTag) where {ET}
@assert tag === ZERO || tag === ONE
return new{ET}(tag, tag === ZERO ? 0.0 : 1.0)
end
end
# these two interfaces must be implemented in order to collect elements
_data_mul(x::StaticElementVector, y::StaticElementVector) = x | y
_data_one(::Type{T}) where T<:StaticElementVector = zero(T) # NOTE: might be optional
"""
OnehotVec{N,NF}
OnehotVec{N,NF}(loc, val)
Onehot vector type, `N` is the number of vector length, `NF` is the number of flavors.
"""
struct OnehotVec{N,NF}
loc::Int32
val::Int32
end
_data_one(::Type{T}) where T<:OnehotVec = _data_one(convert_ev(T)) # NOTE: might be optional
Base.convert(::Type{ET}, v::OnehotVec{N,NF}) where {N,NF,S,C,ET<:StaticElementVector{N,S,C}} = onehotv(ET, v.loc, v.val)
function convert_ev(::Type{OnehotVec{N,NF}}) where {N,NF}
s = ceil(Int, log2(NF))
c = _nints(N,s)
return StaticElementVector{N,s,c}
end
# AbstractTree APIs
function children(t::SumProductTree)
if t.tag == ZERO || t.tag == LEAF || t.tag == ONE
return typeof(t)[]
else
return [t.left, t.right]
end
end
function printnode(io::IO, t::SumProductTree{ET}) where {ET}
if t.tag === LEAF
print(io, t.data)
elseif t.tag === ZERO
print(io, "∅")
elseif t.tag === ONE
print(io, _data_one(ET))
elseif t.tag === SUM
print(io, "+ (count = $(t.count))")
else # PROD
print(io, "* (count = $(t.count))")
end
end
# it must be mutable, otherwise, objectid might be slow serialization might fail.
# IdDict is much slower than Dict, it is useless.
Base.length(x::SumProductTree) = x.count
num_nodes(x::SumProductTree) = _num_nodes(x, Dict{UInt, Int}())
function _num_nodes(x, d)
id = objectid(x)
haskey(d, id) && return 0
if x.tag == ZERO || x.tag == ONE
res = 1
elseif x.tag == LEAF
res = 1
else
res = _num_nodes(x.left, d) + _num_nodes(x.right, d) + 1
end
d[id] = res
return res
end
function Base.:(==)(x::SumProductTree{ET}, y::SumProductTree{ET}) where {ET}
return Set(collect(x)) == Set(collect(y))
end
Base.show(io::IO, t::SumProductTree) = print_tree(io, t)
Base.collect(x::SumProductTree{ET}) where ET = collect(ET, x)
function Base.collect(x::SumProductTree{OnehotVec{N,NF}}) where {N,NF}
s = ceil(Int, log2(NF))
c = _nints(N,s)
return collect(StaticElementVector{N,s,c}, x)
end
function Base.collect(::Type{T}, x::SumProductTree{ET}) where {T, ET}
if x.tag == ZERO
return T[]
elseif x.tag == ONE
return [_data_one(T)]
elseif x.tag == LEAF
return [convert(T, x.data)]
elseif x.tag == SUM
return vcat(collect(T, x.left), collect(T, x.right))
else # PROD
return vec([reduce(_data_mul, si) for si in Iterators.product(collect(T, x.left), collect(T, x.right))])
end
end
function Base.:+(x::SumProductTree{ET}, y::SumProductTree{ET}) where {ET}
if x.tag == ZERO
return y
elseif y.tag == ZERO
return x
else
return SumProductTree(SUM, x, y)
end
end
function Base.:*(x::SumProductTree{ET}, y::SumProductTree{ET}) where {ET}
if x.tag == ONE
return y
elseif y.tag == ONE
return x
elseif x.tag == ZERO
return x
elseif y.tag == ZERO
return y
else
return SumProductTree(PROD, x, y)
end
end
Base.zero(::Type{SumProductTree{ET}}) where {ET} = SumProductTree{ET}(ZERO)
Base.one(::Type{SumProductTree{ET}}) where {ET} = SumProductTree{ET}(ONE)
Base.zero(::SumProductTree{ET}) where {ET} = zero(SumProductTree{ET})
Base.one(::SumProductTree{ET}) where {ET} = one(SumProductTree{ET})
# todo, check siblings too?
function Base.iszero(t::SumProductTree)
if t.tag == SUM
iszero(t.left) && iszero(t.right)
elseif t.tag == ZERO
true
elseif t.tag == LEAF || t.tag == ONE
false
else
iszero(t.left) || iszero(t.right)
end
end
"""
generate_samples(t::SumProductTree, nsamples::Int)
Direct sampling configurations from a [`SumProductTree`](@ref) instance.
Examples
-----------------------------
```jldoctest; setup=:(using GenericTensorNetworks)
julia> using Graphs
julia> g= smallgraph(:petersen)
{10, 15} undirected simple Int64 graph
julia> t = solve(GenericTensorNetwork(IndependentSet(g)), ConfigsAll(; tree_storage=true))[];
julia> samples = generate_samples(t, 1000);
julia> all(s->is_independent_set(g, s), samples)
true
```
"""
function generate_samples(t::SumProductTree{ET}, nsamples::Int) where {ET}
# get length dict
res = fill(_data_one(ET), nsamples)
d = Dict{UInt, Float64}()
sample_descend!(res, t)
return res
end
function sample_descend!(res::AbstractVector{T}, t::SumProductTree) where T
res_stack = Any[res]
t_stack = [t]
while !isempty(t_stack) && !isempty(res_stack)
t = pop!(t_stack)
res = pop!(res_stack)
if t.tag == LEAF
res .= _data_mul.(res, Ref(convert(T, t.data)))
elseif t.tag == SUM
ratio = length(t.left)/length(t)
nleft = 0
for _ = 1:length(res)
if rand() < ratio
nleft += 1
end
end
shuffle!(res) # shuffle the `res` to avoid biased sampling, very important.
if nleft >= 1
push!(res_stack, view(res,1:nleft))
push!(t_stack, t.left)
end
if length(res) > nleft
push!(res_stack, view(res,nleft+1:length(res)))
push!(t_stack, t.right)
end
elseif t.tag == PROD
push!(res_stack, res)
push!(res_stack, res)
push!(t_stack, t.left)
push!(t_stack, t.right)
elseif t.tag == ZERO
error("Meet zero when descending.")
else
# pass for 1
end
end
return res
end
# A patch to make `Polynomial{ConfigEnumerator}` work
function Base.:*(a::Int, y::AbstractSetNumber)
a == 0 && return zero(y)
a == 1 && return y
error("multiplication between int and `$(typeof(y))` is not defined.")
end
# convert from counting type to bitstring type
for F in [:set_type, :sampler_type, :treeset_type]
@eval begin
function $F(::Type{T}, n::Int, nflavor::Int) where {OT, K, T<:TruncatedPoly{K,C,OT} where C}
TruncatedPoly{K, $F(n,nflavor),OT}
end
function $F(::Type{T}, n::Int, nflavor::Int) where {TX, T<:Polynomial{C,TX} where C}
Polynomial{$F(n,nflavor),:x}
end
function $F(::Type{T}, n::Int, nflavor::Int) where {TV, T<:CountingTropical{TV}}
CountingTropical{TV, $F(n,nflavor)}
end
function $F(::Type{Real}, n::Int, nflavor::Int)
$F(n, nflavor)
end
end
end
for (F,TP) in [(:set_type, :ConfigEnumerator), (:sampler_type, :ConfigSampler)]
@eval function $F(n::Integer, nflavor::Integer)
s = ceil(Int, log2(nflavor))
c = _nints(n,s)
return $TP{n,s,c}
end
end
function treeset_type(n::Integer, nflavor::Integer)
return SumProductTree{OnehotVec{n, nflavor}}
end
sampler_type(::Type{ExtendedTropical{K,T}}, n::Int, nflavor::Int) where {K,T} = ExtendedTropical{K, sampler_type(T, n, nflavor)}
# utilities for creating onehot vectors
onehotv(::Type{ConfigEnumerator{N,S,C}}, i::Integer, v) where {N,S,C} = ConfigEnumerator([onehotv(StaticElementVector{N,S,C}, i, v)])
# we treat `v == 0` specially because we want the final result not containing one leaves.
onehotv(::Type{SumProductTree{OnehotVec{N,F}}}, i::Integer, v) where {N,F} = v == 0 ? one(SumProductTree{OnehotVec{N,F}}) : SumProductTree(OnehotVec{N,F}(i, v))
onehotv(::Type{ConfigSampler{N,S,C}}, i::Integer, v) where {N,S,C} = ConfigSampler(onehotv(StaticElementVector{N,S,C}, i, v))
# just to make matrix transpose work
Base.transpose(c::ConfigEnumerator) = c
Base.copy(c::ConfigEnumerator) = ConfigEnumerator(copy(c.data))
Base.transpose(c::SumProductTree) = c
function Base.copy(c::SumProductTree{ET}) where {ET}
if c.tag == LEAF
SumProductTree(c.data)
elseif c.tag == ZERO || c.tag == ONE
SumProductTree{ET}(c.tag)
else
SumProductTree(c.tag, c.left, c.right)
end
end
# Handle boolean, this is a patch for CUDA matmul
for TYPE in [:AbstractSetNumber, :TruncatedPoly, :ExtendedTropical]
@eval Base.:*(a::Bool, y::$TYPE) = a ? y : zero(y)
@eval Base.:*(y::$TYPE, a::Bool) = a ? y : zero(y)
end
# to handle power of polynomials
Base.literal_pow(::typeof(^), x::SumProductTree, ::Val{y}) where y = Base.:^(x, y)
function Base.:^(x::SumProductTree, y::Real)
if y == 0
return one(x)
elseif x.tag == LEAF || x.tag == ONE || x.tag == ZERO
return x
else
error("pow of non-leaf nodes is forbidden!")
end
end
Base.literal_pow(::typeof(^), x::ConfigEnumerator, ::Val{y}) where y = Base.:^(x, y)
function Base.:^(x::ConfigEnumerator, y::Real)
if y <= 0
return one(x)
elseif length(x) <= 1
return x
else
error("pow of configuration enumerator of `size > 1` is forbidden!")
end
end
Base.literal_pow(::typeof(^), x::ConfigSampler, ::Val{y}) where y = Base.:^(x, y)
function Base.:^(x::ConfigSampler, y::Real)
if y <= 0
return one(x)
else
return x
end
end
# variable `x`
function _x(::Type{Polynomial{BS,X}}; invert) where {BS,X}
@assert !invert # not supported, because it is not useful
return Polynomial{BS,X}([zero(BS), one(BS)])
end
# will be used in spin-glass polynomial
function _x(::Type{LaurentPolynomial{BS,X}}; invert) where {BS,X}
return LaurentPolynomial{BS,X}([one(BS)], invert ? -1 : 1)
end
function _x(::Type{TruncatedPoly{K,BS,OS}}; invert) where {K,BS,OS}
ret = TruncatedPoly{K,BS,OS}(ntuple(i->i<K ? zero(BS) : one(BS), K),one(OS))
return invert ? pre_invert_exponent(ret) : ret
end
function _x(::Type{CountingTropical{TV,BS}}; invert) where {TV,BS}
ret = CountingTropical{TV,BS}(one(TV), one(BS))
return invert ? pre_invert_exponent(ret) : ret
end
function _x(::Type{Tropical{TV}}; invert) where {TV}
ret = Tropical{TV}(one(TV))
return invert ? pre_invert_exponent(ret) : ret
end
function _x(::Type{ExtendedTropical{K,TO}}; invert) where {K,TO}
return ExtendedTropical{K,TO}(map(i->i==K ? _x(TO; invert=invert) : zero(TO), 1:K))
end
# invert the exponents of polynomial, returns a Laurent polynomial
function invert_polynomial(poly::Polynomial{BS,X}) where {BS,X}
return LaurentPolynomial{BS,X}(poly.coeffs[end:-1:1], -length(poly.coeffs)+1)
end
function invert_polynomial(poly::LaurentPolynomial{BS,X}) where {BS,X}
return LaurentPolynomial{BS,X}(poly.coeffs[end:-1:1], -poly.order[]-length(poly.coeffs)+1)
end
# for finding all solutions
function _x(::Type{T}; invert) where {T<:AbstractSetNumber}
ret = one(T)
invert ? pre_invert_exponent(ret) : ret
end
function _onehotv(::Type{Polynomial{BS,X}}, x, v) where {BS,X}
Polynomial{BS,X}([onehotv(BS, x, v)])
end
function _onehotv(::Type{TruncatedPoly{K,BS,OS}}, x, v) where {K,BS,OS}
TruncatedPoly{K,BS,OS}(ntuple(i->i != K ? zero(BS) : onehotv(BS, x, v), K),zero(OS))
end
function _onehotv(::Type{CountingTropical{TV,BS}}, x, v) where {TV,BS}
CountingTropical{TV,BS}(zero(TV), onehotv(BS, x, v))
end
function _onehotv(::Type{BS}, x, v) where {BS<:AbstractSetNumber}
onehotv(BS, x, v)
end
function _onehotv(::Type{ExtendedTropical{K,TO}}, x, v) where {K,T,BS<:AbstractSetNumber,TO<:CountingTropical{T,BS}}
ExtendedTropical{K,TO}(map(i->i==K ? _onehotv(TO, x, v) : zero(TO), 1:K))
end
# negate the exponents before entering the solver
pre_invert_exponent(t::TruncatedPoly{K}) where K = TruncatedPoly(t.coeffs, -t.maxorder)
pre_invert_exponent(t::TropicalNumbers.TropicalTypes) = inv(t)
# negate the exponents after entering the solver
post_invert_exponent(t::TruncatedPoly{K}) where K = TruncatedPoly(ntuple(i->t.coeffs[K-i+1], K), -t.maxorder+(K-1))
post_invert_exponent(t::LaurentPolynomial) = error("This method is not implemented yet, please file an issue if you find a using case!")
post_invert_exponent(t::TropicalNumbers.TropicalTypes) = inv(t)
post_invert_exponent(t::ExtendedTropical{K}) where K = ExtendedTropical{K}(map(i->inv(t.orders[i]), K:-1:1))
# Data reading
"""
read_size(x)
Read the size information from the generic element.
"""
read_size(x::Tropical) = x.n
read_size(x::ExtendedTropical) = x.orders
"""
read_count(x)
Read the counting information from the generic element.
"""
function read_count end
"""
read_size_count(x)
Read the size and counting information from the generic element.
"""
read_size_count(x::CountingTropical{TV, T}) where {TV, T<:Real} = x.n => x.c
read_size_count(x::TruncatedPoly{K, T}) where {K, T<:Real} = [(x.maxorder-K+i => x.coeffs[i]) for i=1:K]
read_size_count(x::Polynomial{<:Real}) = [(i-1 => x.coeffs[i]) for i=1:length(x.coeffs)]
read_size_count(x::LaurentPolynomial{<:Real}) = [(i-1+x.order[] => x.coeffs[i]) for i=1:length(x.coeffs)]
for T in [:(CountingTropical{TV, <:Real} where TV), :(TruncatedPoly{K, <:Real} where K), :(Polynomial{<:Real}), :(LaurentPolynomial{<:Real})]
@eval read_size(x::$T) = extract_first(read_size_count(x))
@eval read_count(x::$T) = extract_second(read_size_count(x))
end
extract_first(x::Pair) = x.first
extract_second(x::Pair) = x.second
extract_first(x::AbstractVector{<:Pair}) = getfield.(x, :first)
extract_second(x::AbstractVector{<:Pair}) = getfield.(x, :second)
"""
read_config(x; keeptree=false)
Read the configuration information from the generic element, if `keeptree=true`, the tree structure will not be flattened.
"""
read_config(x::ConfigEnumerator; keeptree=false) = x.data
read_config(x::SumProductTree; keeptree=false) = keeptree ? x : collect(x)
read_config(x::ConfigSampler; keeptree=false) = x.data
"""
read_size_config(x; keeptree=false)
Read the size and configuration information from the generic element. If `keeptree=true`, the tree structure will not be flattened.
"""
read_size_config(x::TruncatedPoly{K, T}; keeptree=false) where {K, T<:AbstractSetNumber} = [(x.maxorder-K+i => read_config(x.coeffs[i]; keeptree)) for i=1:K]
read_size_config(x::CountingTropical{TV, T}; keeptree=false) where {TV, T<:AbstractSetNumber} = x.n => read_config(x.c; keeptree)
read_size_config(x::ExtendedTropical{N, CountingTropical{TV, T}}; keeptree=false) where {N, TV, T<:AbstractSetNumber} = read_size_config.(x.orders; keeptree)
read_size_config(x::Polynomial{T}; keeptree=false) where T<:AbstractSetNumber = [(i-1 => read_config(x.coeffs[i]; keeptree)) for i=1:length(x.coeffs)]
read_size_config(x::LaurentPolynomial{T}; keeptree=false) where T<:AbstractSetNumber = [(i-1+x.order[] => read_config(x.coeffs[i]; keeptree)) for i=1:length(x.coeffs)]
for T in [:(CountingTropical{TV, <:AbstractSetNumber} where TV), :(TruncatedPoly{K, <:AbstractSetNumber} where K), :(Polynomial{<:AbstractSetNumber}), :(LaurentPolynomial{<:AbstractSetNumber}), :(ExtendedTropical{N, CountingTropical{TV, S}} where {N, TV, S<:AbstractSetNumber})]
@eval read_size(x::$T) = extract_first(read_size_config(x; keeptree=true))
@eval read_config(x::$T; keeptree=false) = extract_second(read_size_config(x; keeptree))
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
|
[
"Apache-2.0"
] | 2.2.0 | 26cc8aa65a7824b02ed936966e76a5b28d49606e | code | 6342 | """
StaticElementVector{N,S,C}
StaticElementVector(nflavor::Int, x::AbstractVector)
`N` is the length of vector, `C` is the size of storage in unit of `UInt64`,
`S` is the stride defined as the `log2(# of flavors)`.
When the number of flavors is 2, it is a `StaticBitVector`.
Fields
-------------------------------
* `data` is a tuple of `UInt64` for storing the configuration of static elements.
Examples
-------------------------------
```jldoctest; setup=:(using GenericTensorNetworks)
julia> ev = StaticElementVector(3, [1,2,0,1,2])
12012
julia> ev[2]
0x0000000000000002
julia> collect(Int, ev)
5-element Vector{Int64}:
1
2
0
1
2
```
"""
struct StaticElementVector{N,S,C} <: AbstractVector{UInt64}
data::NTuple{C,UInt64}
end
Base.length(::StaticElementVector{N,S,C}) where {N,S,C} = N
Base.size(::StaticElementVector{N,S,C}) where {N,S,C} = (N,)
Base.:(==)(x::StaticElementVector, y::AbstractVector) = [x...] == [y...]
Base.:(==)(x::AbstractVector, y::StaticElementVector) = [x...] == [y...]
Base.:(==)(x::StaticElementVector{N,S,C}, y::StaticElementVector{N,S,C}) where {N,S,C} = x.data == y.data
Base.eltype(::Type{<:StaticElementVector}) = UInt64
@inline function Base.getindex(x::StaticElementVector{N,S,C}, i::Integer) where {N,S,C}
@boundscheck i <= N || throw(BoundsError(x, i))
i1 = (i-1)*S+1 # start point
i2 = i*S # stop point
ii1 = (i1-1) ÷ 64
ii2 = (i2-1) ÷ 64
@inbounds if ii1 == ii2
(x.data[ii1+1] >> (i1-ii1*64-1)) & (1<<S - 1)
else # cross two integers
(x.data[ii1+1] >> (i1-ii*64-S+1)) | (x.data[ii2+1] & (1<<(i2-ii1*64) - 1))
end
end
function StaticElementVector(nflavor::Int, x::AbstractVector)
if any(x->x<0 || x>=nflavor, x)
throw(ArgumentError("Vector elements must be in range `[0, $(nflavor-1)]`, got $x."))
end
N = length(x)
S = ceil(Int,log2(nflavor)) # sometimes can not devide 64.
convert(StaticElementVector{N,S,_nints(N,S)}, x)
end
function Base.convert(::Type{StaticElementVector{N,S,C}}, x::AbstractVector) where {N,S,C}
@assert length(x) == N
data = zeros(UInt64,C)
for i=1:N
i1 = (i-1)*S+1 # start point
i2 = i*S # stop point
ii1 = (i1-1) ÷ 64
ii2 = (i2-1) ÷ 64
@inbounds if ii1 == ii2
data[ii1+1] |= UInt64(x[i]) << (i1-ii1*64-1)
else # cross two integers
data[ii1+1] |= UInt64(x[i]) << (i1-ii1*64-1)
data[ii2+1] |= UInt64(x[i]) >> (i2-ii1*64)
end
end
return StaticElementVector{N,S,C}((data...,))
end
# joining two element sets
Base.:(|)(x::StaticElementVector{N,S,C}, y::StaticElementVector{N,S,C}) where {N,S,C} = StaticElementVector{N,S,C}(x.data .| y.data)
# intersection of two element sets
Base.:(&)(x::StaticElementVector{N,S,C}, y::StaticElementVector{N,S,C}) where {N,S,C} = StaticElementVector{N,S,C}(x.data .& y.data)
# difference of two element sets
Base.:(⊻)(x::StaticElementVector{N,S,C}, y::StaticElementVector{N,S,C}) where {N,S,C} = StaticElementVector{N,S,C}(x.data .⊻ y.data)
"""
onehotv(::Type{<:StaticElementVector}, i, v)
onehotv(::Type{<:StaticBitVector, i)
Returns a static element vector, with the value at location `i` being `v` (1 if not specified).
"""
function onehotv(::Type{StaticElementVector{N,S,C}}, i, v) where {N,S,C}
x = zeros(Int,N)
x[i] = v
return convert(StaticElementVector{N,S,C}, x)
end
##### BitVectors
"""
StaticBitVector{N,C} = StaticElementVector{N,1,C}
StaticBitVector(x::AbstractVector)
Examples
-------------------------------
```jldoctest; setup=:(using GenericTensorNetworks)
julia> sb = StaticBitVector([1,0,0,1,1])
10011
julia> sb[3]
0x0000000000000000
julia> collect(Int, sb)
5-element Vector{Int64}:
1
0
0
1
1
```
"""
const StaticBitVector{N,C} = StaticElementVector{N,1,C}
@inline function Base.getindex(x::StaticBitVector{N,C}, i::Integer) where {N,C}
@boundscheck (i <= N || throw(BoundsError(x, i))) # NOTE: still checks bounds in global scope, why?
i -= 1
ii = i ÷ 64
return @inbounds (x.data[ii+1] >> (i-ii*64)) & 1
end
function StaticBitVector(x::AbstractVector)
N = length(x)
StaticBitVector{N,_nints(N,1)}((convert(BitVector, x).chunks...,))
end
# to void casting StaticBitVector itself
StaticBitVector(x::StaticBitVector) = x
function Base.convert(::Type{StaticBitVector{N,C}}, x::AbstractVector) where {N,C}
@assert length(x) == N
StaticBitVector(x)
end
_nints(x,s) = (x*s-1)÷64+1
@generated function Base.zero(::Type{StaticElementVector{N,S,C}}) where {N,S,C}
Expr(:call, :(StaticElementVector{$N,$S,$C}), Expr(:tuple, zeros(UInt64, C)...))
end
staticfalses(::Type{StaticBitVector{N,C}}) where {N,C} = zero(StaticBitVector{N,C})
@generated function statictrues(::Type{StaticBitVector{N,C}}) where {N,C}
Expr(:call, :(StaticBitVector{$N,$C}), Expr(:tuple, fill(typemax(UInt64), C)...))
end
onehotv(::Type{StaticBitVector{N,C}}, i, v) where {N,C} = v > 0 ? onehotv(StaticBitVector{N,C}, i) : zero(StaticBitVector{N,C})
function onehotv(::Type{StaticBitVector{N,C}}, i) where {N,C}
x = falses(N)
x[i] = true
return StaticBitVector(x)
end
function Base.iterate(x::StaticElementVector{N,S,C}, state=1) where {N,S,C}
if state > N
return nothing
else
return x[state], state+1
end
end
Base.show(io::IO, t::StaticElementVector) = Base.print(io, "$(join(Int.(t), ""))")
Base.show(io::IO, ::MIME"text/plain", t::StaticElementVector) = Base.show(io, t)
function Base.count_ones(x::StaticBitVector)
sum(v->count_ones(v),x.data)
end
"""
hamming_distance(x::StaticBitVector, y::StaticBitVector)
Calculate the Hamming distance between two static bit vectors.
"""
hamming_distance(x::StaticBitVector, y::StaticBitVector) = count_ones(x ⊻ y)
"""
Constructing a static bit vector.
"""
macro bv_str(str)
return parse_vector(2, str)
end
function parse_vector(nflavor::Int, str::String)
val = Int[]
k = 1
for each in filter(x -> x != '_', str)
if each == '1'
push!(val, 1)
k += 1
elseif each == '0'
push!(val, 0)
k += 1
elseif each == '_'
continue
else
error("expect 0 or 1, got $each at $k-th bit")
end
end
return StaticElementVector(nflavor, val)
end
| GenericTensorNetworks | https://github.com/QuEraComputing/GenericTensorNetworks.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.