licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
docs
8302
```@meta CurrentModule = TypeClasses DocTestSetup = quote using TypeClasses using Dictionaries end ``` # TypeClasses ## [Functor, Applicative, Monad](@id functor_applicative_monad) Typeclass | Interface | Helpers from `TypeClasses` --------- | --------- | ---------------------------   | `TypeClasses.foreach = Base.foreach` | `@syntax_foreach` Functor, Applicative, Monad | `TypeClasses.map = Base.map` | `@syntax_map` Applicative, Monad | `TypeClasses.pure`, `TypeClasses.ap` | `ap` is automatically defined if you defined `Base.map` and `TypeClasses.flatmap`. Further helpers: `mapn`, `@mapn`, `tupled`, `neutral_applicative`, `combine_applicative`, `orelse_applicative` Monad | `TypeClasses.flatmap` | `flatten`, `↠` (\twoheadrightarrow), `@syntax_flatmap` There are three syntax supported, where `@syntax_flatmap` is the most useful, however sometimes `@syntax_foreach` may also be handy because of its power and simplicity in a programming language with side-effects (like Julia). ```jldoctest julia> @syntax_foreach begin # translates to foreach calls a = [1, 2] b = [3, 4] @pure println("a = $a, b = $b") end a = 1, b = 3 a = 1, b = 4 a = 2, b = 3 a = 2, b = 4 julia> @syntax_map begin # translates to map calls a = [1, 2] b = [3, 4] @pure "a = $a, b = $b" end 2-element Vector{Vector{String}}: ["a = 1, b = 3", "a = 1, b = 4"] ["a = 2, b = 3", "a = 2, b = 4"] julia> @syntax_flatmap begin # translates to map/flatmap calls a = [1, 2] b = [3, 4] @pure "a = $a, b = $b" end 4-element Vector{String}: "a = 1, b = 3" "a = 1, b = 4" "a = 2, b = 3" "a = 2, b = 4" ``` For **Applicatives** there are a couple of additional helpers ```jldoctest julia> f(a, b, c) = a + b + c f (generic function with 1 method) julia> @mapn f([1,2], [10], [100, 200]) # can also be written as `mapn(f, [1,2], [10], [100,200])` 4-element Vector{Int64}: 111 211 112 212 julia> tupled([1,2], [3, 4]) 4-element Vector{Tuple{Int64, Int64}}: (1, 3) (1, 4) (2, 3) (2, 4) ``` And for **Monads** you have ```jldoctest julia> flatten([[1,2], [3,4]]) 4-element Vector{Int64}: 1 2 3 4 julia> [1, 2] ↠ [3, 4] # flatmap(_ -> [3,4], [1,2]) 4-element Vector{Int64}: 3 4 3 4 julia> Option(3) ↠ Option() ↠ Option("hi") # stopping behaviour with operator syntax Const(nothing) ``` ### Considerations #### Functor - map You can overload `TypeClasses.map` or `Base.map`, as you like, they are both the very same. #### Monad - flatmap We decided to use `flatmap` as the interface, because it is often more intuitiv to implement than `flatten` and also comes quite natural next to `map`. In order to enable simple interactions between monads, all `flatmap` implementations use `convert` before flattening. The exception is `Identity` which for convenience just returns whatever inner monad may appear, without forcing a conversion to `Identity`. For example, this enables you to combine `Vector` with `OPtion`, `Try`, `Either` in all ways. `@syntax_flatmap` provides monadic syntax (similar to haskell do-notation). However, the macro translates to `flatmap` and `map` only, and does not need `pure`. #### Applicative - ap / mapn / map `mapn` is explicitly an extra function, because it has a generic definition which uses `pure` and `ap`, which can also be derived given the implementation of `flatmap` and single `map`. Many types define `Base.map(f, a, b, c, ...)` which is in this sense a `mapn`. However, they sometimes do not conform to the respective implementation of `flatten`/`flatmap`. For example `Vector` defines `Base.map(f, a, b, c, ...)` for Vectors of equal length, however flattening vectors is collecting all combinations of all vectors. These are two different semantics and it is hard to forsee which error-potentials this would bring if they are intermixed. Another example is `Dictionaries.Dictionary`, which supports map similar to Vector, checking for same indices first and raising an error otherwise. For convenience, `Base.map(f, a, b, c...)` is defined as an alias for `TypeClasses.mapn(f, a, b, c...)` for the data types `Option`, `Try`, `Either`, `ContextManager`, `Callable`, `Writer`, and `State`. Each Applicative can lift an underlying Monoid. In addition some Applicatives also define Monoids themselves (e.g. Vector). Hence, we distinguish both by adding functions `neutral_applicative`, `combine_applicative`, `orelse_applicative`. ## [Semigroup, Monoid, Alternative](@id semigroup_monoid_alternative) Typeclass | Interface | Helpers from `TypeClasses` --------- | --------- | -------------- Monoid, Alternative | `TypeClasses.neutral` | Monoid, Semigroup | `TypeClasses.combine` | alias `⊕` (\oplus), `reduce_monoid`, `foldr_monoid`, `foldl_monoid` Alternative | `TypeClasses.orelse` | alias `⊘` (\oslash) A **Semigroup** just supports `combine`, a **Monoid** in addition supports `neutral`. We define the generic neutral element `neutral` which is neutral to everything, hence every Semigroup is actually a Monoid in Julia. Hence `TypeClasses.neutral` is both a function which returns the neutral element (defaulting to `neutral`), as well as the generic neutral element itself. Sometimes, the type itself has an obvious way of combining multiple values, like for `String` or `Vector`. Other times, the `combine` is forwarded to inner elements in case it is needed. ```jldoctest julia> neutral(Vector) ⊕ [1,2] ⊕ [3] 3-element Vector{Any}: 1 2 3 julia> d = Dict(:a => "hello.", :b => 4) ⊕ Dict(:a => "world.", :c => 1.0) Dict{Symbol, Any} with 3 entries: :a => "hello.world." :b => 4 :c => 1.0 julia> combine(Option(), Option([1]), Option([2, 3])) Identity([1, 2, 3]) ``` Let's look at **Alternative**. Take the `Dict` as an example of a container. If we find the same key in both dictionaries, `combine` is going to recursively call `combine` on them. Alternatively, we could just grab the one or the other. This is implemented within the `orelse` function, which will always take the first value it finds. ```jldoctest julia> Dict(:a => "first", :b => 4) ⊘ Dict(:a => true, :c => 1.0) Dict{Symbol, Any} with 3 entries: :a => "first" :b => 4 :c => 1.0 julia> orelse(Option(), Option(1), Option(4)) Identity(1) ``` ### Considerations We decided to use the same `neutral` for both Monoid and Alternative because of simplicity. Julia does not have stable typeparameters (for optimization a typeparameter may be inferred as Any instead of more concrete type), and hence Alternative (which is concept targeted at Functors, i.e. things with one typeparameter) becomes way more similar to Monoid. ## [FlipTypes](@id flip_types) Typeclass | Interface | Helpers from `TypeClasses` --------- | --------- | -------------------------- FlipTypes | `TypeClasses.flip_types` | `TypeClasses.default_flip_types_having_pure_combine_apEltype` `flip_types(::A{B{C}})` should return `::B{A{C}}`. Hence the name: it flips the first two types. Here are some examples ```jldoctest julia> flip_types([Option(:a), Option(:b)]) Identity([:a, :b]) julia> flip_types(Identity([:a, :b])) 2-element Vector{Identity{Symbol}}: Identity(:a) Identity(:b) julia> flip_types([Option(:a), Option()]) Const(nothing) julia> using Dictionaries julia> flip_types(dictionary((:a => [1,2], :b => [3, 4]))) 4-element Vector{Dictionary{Symbol, Int64}}: {:a = 1, :b = 3} {:a = 1, :b = 4} {:a = 2, :b = 3} {:a = 2, :b = 4} julia> flip_types([dictionary((:a => 1, :b => 2)), dictionary((:a => 10, :b => 20)), dictionary((:b => 200, :c => 300))]) 1-element Dictionaries.Dictionary{Symbol, Vector{Int64}} :b │ [2, 20, 200] ``` You see that flip_types may actually forget information. This is normal, but very important to remember. Hence, applying flip_types twice usually not return to the original value, but will change the result. ### Considerations FlipTypes is not an official TypeClass, however proofs to be a very essential abstraction. Normally this comes with the TypeClass Traversable and is called `sequence`, however that name is not very self-explanatory and sounds quite specific. `TypeClasses.flip_types` has already one big usage in `ExtensibleEffects.jl`, for a generic implementation of effect handling.
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
docs
5295
```@meta CurrentModule = TypeClasses DocTestSetup = quote using TypeClasses using Dictionaries end ``` # Introduction Welcome to `TypeClasses.jl`. TypeClasses defines general programmatic abstractions taken from Scala cats and Haskell TypeClasses. We use "interface" and "typeclass" synonymously. The following interfaces are defined: TypeClass | Methods | Description ----------- | ----------------------------------- | -------------------------------------------------------------------- [Functor ](@ref functor_applicative_monad) | `Base.map` | The basic definition of a container or computational context. [Applicative](@ref functor_applicative_monad) | Functor & `TypeClasses.pure` & `TypeClasses.ap` (automatically defined when `map` and `flatmap` are defined) | Computational context with support for parallel execution. [Monad](@ref functor_applicative_monad) | Applicative & `TypeClasses.flatmap` | Computational context with support for sequential, nested execution. [Semigroup](@ref semigroup_monoid_alternative) | `TypeClasses.combine`, alias `⊕` | The notion of something which can be combined with other things of its kind. [Monoid](@ref semigroup_monoid_alternative) | Semigroup & `TypeClasses.neutral` | A semigroup with a neutral element is called a Monoid, an often used category. [Alternative](@ref semigroup_monoid_alternative) | `TypeClasses.neutral` & `TypeClasses.orelse`, alias `⊘` | Slightly different than Monoid, the `orelse` semantic does not merge two values, but just takes one of the two. [FlipTypes](@ref flip_types) | `TypeClasses.flip_types` | Enables dealing with nested types. Transforms an `A{B{C}}` into an `B{A{C}}`. ## Installation ```julia using Pkg Pkg.add("TypeClasses") ``` Use it like ```julia using TypeClasses ``` ## More Details For detailed information of the TypeClasses, see [TypeClasses](@ref). For detailed information about implementations of the TypeClasses for concrete DataTypes, see [DataTypes](@ref). ## General Design Decisions * reuse as much `Base` as possible * make it stable (hence so far we only support the most important type-classes) * make it simple * make it convenient * bring examples ### No dispatch on `eltype` With Functors and the like a typical thing you want to do is to get to know more about the inner type, i.e. the `eltype`. It turns out this is unwanted. Julia's type-inference is seriously incomplete and there is also no sign that this will ever change. The compiler tries very hard to always infer the maximal specific type, but may fallback to more generic types if unsure or because of time-constraints. A calculation which may build up a `Vector{Number}` may easily turn out as a `Vector{Any}`, and even for a method returning `Vector{String}`, the underlying code may be that dynamic in nature, that the compiler just cannot infer the type and will return `Vector{Any}`. The take home message here is that, practically, `eltype` is an instable function. It's concrete behaviour, somewhere within a nested stack of function calls, may change between versions, depending on changing undocumented compiler-heuristics, or may even change because another layer of abstractions is added somewhere within the nested calls, which again triggers different compiler-heuristics. If you dispatch on `Vector{Number}` in order to implement something specific for Number, that may fail to catch the Vector{Number} which was interpreted as `Vector{Any}` because of approximate type inference. You need to make sure that the semantics of the method for `Vector{Any}` is actually identical to the specialised version `Vector{Number}`. You should only ever do performance optimisations when dispatching on `eltype`, never base your semantics on `eltype`. With Functors, specifically with Monads, we have exactly the setting where we may dispatch on `eltype` to define different semantics. They key reason is that there are a couple of Monads where you cannot inspect the concrete elements, for instance `Callable` where the element is hidden behind an arbitrary function. Hence you may not be able to implement a function for `Callable{Any}` in a sensible way, while it actually is well-defined for `Callable{Callable}`. That is not Julia. Another example is the typeclass `neutral`. It turns out you can define `neutral` for each `Applicative` which ElementType itself implements `neutral`. It is really tempting to define the generic implementation for Applicatives, dispatching on `eltype`... Instead we provide specific applicative versions `neutral_applicative` and `combine_applicative` which assume the elements comply to the `Neutral` and `Semigroup` interface respectively. Similar for `orelse`. As we cannot safely dispatch on `eltype`, the Julia way is to just assume your ElementType has the characteristics needed for your function, i.e. use duck-typing instead of dispatch. Naturally, this will work for all containers with the right elements. And in case the elements do not implement the required interfaces, it will fail with a well self-explaining `MethodError`. This you can then debug which will bring you directly to the place where you can inspect the elements in detail.
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.11.1
ae3bb1eb3bba077cd276bc5cfc337cc65c3075c0
code
780
@static if Base.VERSION >= v"1.6" using TOML using Test else using Pkg: TOML using Test end # To generate the new UUID, we simply modify the first character of the original UUID const original_uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" const new_uuid = "20745b16-79ce-11e8-11f9-7d13ad32a3b2" # `@__DIR__` is the `.ci/` folder. # Therefore, `dirname(@__DIR__)` is the repository root. const project_filename = joinpath(dirname(@__DIR__), "Project.toml") @testset "Test that the UUID is unchanged" begin project_dict = TOML.parsefile(project_filename) @test project_dict["uuid"] == original_uuid end write( project_filename, replace( read(project_filename, String), r"uuid = .*?\n" => "uuid = \"$(new_uuid)\"\n", ), )
Statistics
https://github.com/JuliaStats/Statistics.jl.git
[ "MIT" ]
1.11.1
ae3bb1eb3bba077cd276bc5cfc337cc65c3075c0
code
366
using Documenter, Statistics # Workaround for JuliaLang/julia/pull/28625 if Base.HOME_PROJECT[] !== nothing Base.HOME_PROJECT[] = abspath(Base.HOME_PROJECT[]) end makedocs( modules = [Statistics], sitename = "Statistics", pages = Any[ "Statistics" => "index.md" ] ) deploydocs(repo = "github.com/JuliaStats/Statistics.jl.git")
Statistics
https://github.com/JuliaStats/Statistics.jl.git
[ "MIT" ]
1.11.1
ae3bb1eb3bba077cd276bc5cfc337cc65c3075c0
code
3069
module SparseArraysExt ##### SparseArrays optimizations ##### using Base: require_one_based_indexing using LinearAlgebra using SparseArrays using Statistics using Statistics: centralize_sumabs2, unscaled_covzm # extended functions import Statistics: cov, centralize_sumabs2! function cov(X::SparseMatrixCSC; dims::Int=1, corrected::Bool=true) vardim = dims a, b = size(X) n, p = vardim == 1 ? (a, b) : (b, a) # The covariance can be decomposed into two terms # 1/(n - 1) ∑ (x_i - x̄)*(x_i - x̄)' = 1/(n - 1) (∑ x_i*x_i' - n*x̄*x̄') # which can be evaluated via a sparse matrix-matrix product # Compute ∑ x_i*x_i' = X'X using sparse matrix-matrix product out = Matrix(unscaled_covzm(X, vardim)) # Compute x̄ x̄ᵀ = mean(X, dims=vardim) # Subtract n*x̄*x̄' from X'X @inbounds for j in 1:p, i in 1:p out[i,j] -= x̄ᵀ[i] * x̄ᵀ[j]' * n end # scale with the sample size n or the corrected sample size n - 1 return rmul!(out, inv(n - corrected)) end # This is the function that does the reduction underlying var/std function centralize_sumabs2!(R::AbstractArray{S}, A::SparseMatrixCSC{Tv,Ti}, means::AbstractArray) where {S,Tv,Ti} require_one_based_indexing(R, A, means) lsiz = Base.check_reducedims(R,A) for i in 1:max(ndims(R), ndims(means)) if axes(means, i) != axes(R, i) throw(DimensionMismatch("dimension $i of `mean` should have indices $(axes(R, i)), but got $(axes(means, i))")) end end isempty(R) || fill!(R, zero(S)) isempty(A) && return R rowval = rowvals(A) nzval = nonzeros(A) m = size(A, 1) n = size(A, 2) if size(R, 1) == size(R, 2) == 1 # Reduction along both columns and rows R[1, 1] = centralize_sumabs2(A, means[1]) elseif size(R, 1) == 1 # Reduction along rows @inbounds for col = 1:n mu = means[col] r = convert(S, (m - length(nzrange(A, col)))*abs2(mu)) @simd for j = nzrange(A, col) r += abs2(nzval[j] - mu) end R[1, col] = r end elseif size(R, 2) == 1 # Reduction along columns rownz = fill(convert(Ti, n), m) @inbounds for col = 1:n @simd for j = nzrange(A, col) row = rowval[j] R[row, 1] += abs2(nzval[j] - means[row]) rownz[row] -= 1 end end for i = 1:m R[i, 1] += rownz[i]*abs2(means[i]) end else # Reduction along a dimension > 2 @inbounds for col = 1:n lastrow = 0 @simd for j = nzrange(A, col) row = rowval[j] for i = lastrow+1:row-1 R[i, col] = abs2(means[i, col]) end R[row, col] = abs2(nzval[j] - means[row, col]) lastrow = row end for i = lastrow+1:m R[i, col] = abs2(means[i, col]) end end end return R end end # module
Statistics
https://github.com/JuliaStats/Statistics.jl.git
[ "MIT" ]
1.11.1
ae3bb1eb3bba077cd276bc5cfc337cc65c3075c0
code
35912
# This file is a part of Julia. License is MIT: https://julialang.org/license """ Statistics Standard library module for basic statistics functionality. """ module Statistics using LinearAlgebra using Base: has_offset_axes, require_one_based_indexing export cor, cov, std, stdm, var, varm, mean!, mean, median!, median, middle, quantile!, quantile ##### mean ##### """ mean(itr) Compute the mean of all elements in a collection. !!! note If `itr` contains `NaN` or [`missing`](@ref) values, the result is also `NaN` or `missing` (`missing` takes precedence if array contains both). Use the [`skipmissing`](@ref) function to omit `missing` entries and compute the mean of non-missing values. # Examples ```jldoctest julia> using Statistics julia> mean(1:20) 10.5 julia> mean([1, missing, 3]) missing julia> mean(skipmissing([1, missing, 3])) 2.0 ``` """ mean(itr) = mean(identity, itr) """ mean(f, itr) Apply the function `f` to each element of collection `itr` and take the mean. ```jldoctest julia> using Statistics julia> mean(√, [1, 2, 3]) 1.3820881233139908 julia> mean([√1, √2, √3]) 1.3820881233139908 ``` """ function mean(f, itr) y = iterate(itr) if y === nothing return Base.mapreduce_empty_iter(f, +, itr, Base.IteratorEltype(itr)) / 0 end count = 1 value, state = y f_value = f(value)/1 total = Base.reduce_first(+, f_value) y = iterate(itr, state) while y !== nothing value, state = y total += _mean_promote(total, f(value)) count += 1 y = iterate(itr, state) end return total/count end """ mean(f, A::AbstractArray; dims) Apply the function `f` to each element of array `A` and take the mean over dimensions `dims`. !!! compat "Julia 1.3" This method requires at least Julia 1.3. ```jldoctest julia> using Statistics julia> mean(√, [1, 2, 3]) 1.3820881233139908 julia> mean([√1, √2, √3]) 1.3820881233139908 julia> mean(√, [1 2 3; 4 5 6], dims=2) 2×1 Matrix{Float64}: 1.3820881233139908 2.2285192400943226 ``` """ mean(f, A::AbstractArray; dims=:) = _mean(f, A, dims) function mean(f::Number, itr::Number) f_value = try f(itr) catch err if err isa MethodError && err.f === f && err.args == (itr,) rethrow(ArgumentError("""mean(f, itr) requires a function and an iterable. Perhaps you meant mean((x, y))?""")) else rethrow(err) end end Base.reduce_first(+, f_value)/1 end """ mean!(r, v) Compute the mean of `v` over the singleton dimensions of `r`, and write results to `r`. # Examples ```jldoctest julia> using Statistics julia> v = [1 2; 3 4] 2×2 Matrix{Int64}: 1 2 3 4 julia> mean!([1., 1.], v) 2-element Vector{Float64}: 1.5 3.5 julia> mean!([1. 1.], v) 1×2 Matrix{Float64}: 2.0 3.0 ``` """ function mean!(R::AbstractArray, A::AbstractArray) sum!(R, A; init=true) x = max(1, length(R)) // length(A) R .= R .* x return R end """ mean(A::AbstractArray; dims) Compute the mean of an array over the given dimensions. !!! compat "Julia 1.1" `mean` for empty arrays requires at least Julia 1.1. # Examples ```jldoctest julia> using Statistics julia> A = [1 2; 3 4] 2×2 Matrix{Int64}: 1 2 3 4 julia> mean(A, dims=1) 1×2 Matrix{Float64}: 2.0 3.0 julia> mean(A, dims=2) 2×1 Matrix{Float64}: 1.5 3.5 ``` """ mean(A::AbstractArray; dims=:) = _mean(identity, A, dims) _mean_promote(x::T, y::S) where {T,S} = convert(promote_type(T, S), y) # ::Dims is there to force specializing on Colon (as it is a Function) function _mean(f, A::AbstractArray, dims::Dims=:) where Dims isempty(A) && return sum(f, A, dims=dims)/0 if dims === (:) n = length(A) else n = mapreduce(i -> size(A, i), *, unique(dims); init=1) end x1 = f(first(A)) / 1 result = sum(x -> _mean_promote(x1, f(x)), A, dims=dims) if dims === (:) return result / n else return result ./= n end end function mean(r::AbstractRange{T}) where T isempty(r) && return zero(T)/0 return first(r)/2 + last(r)/2 end ##### variances ##### # faster computation of real(conj(x)*y) realXcY(x::Real, y::Real) = x*y realXcY(x::Complex, y::Complex) = real(x)*real(y) + imag(x)*imag(y) var(iterable; corrected::Bool=true, mean=nothing) = _var(iterable, corrected, mean) function _var(iterable, corrected::Bool, mean) y = iterate(iterable) if y === nothing T = eltype(iterable) return oftype((abs2(zero(T)) + abs2(zero(T)))/2, NaN) end count = 1 value, state = y y = iterate(iterable, state) if mean === nothing # Use Welford algorithm as seen in (among other places) # Knuth's TAOCP, Vol 2, page 232, 3rd edition. M = value / 1 S = real(zero(M)) while y !== nothing value, state = y y = iterate(iterable, state) count += 1 new_M = M + (value - M) / count S = S + realXcY(value - M, value - new_M) M = new_M end return S / (count - Int(corrected)) elseif isa(mean, Number) # mean provided # Cannot use a compensated version, e.g. the one from # "Updating Formulae and a Pairwise Algorithm for Computing Sample Variances." # by Chan, Golub, and LeVeque, Technical Report STAN-CS-79-773, # Department of Computer Science, Stanford University, # because user can provide mean value that is different to mean(iterable) sum2 = abs2(value - mean::Number) while y !== nothing value, state = y y = iterate(iterable, state) count += 1 sum2 += abs2(value - mean) end return sum2 / (count - Int(corrected)) else throw(ArgumentError("invalid value of mean, $(mean)::$(typeof(mean))")) end end centralizedabs2fun(m) = x -> abs2.(x - m) centralize_sumabs2(A::AbstractArray, m) = mapreduce(centralizedabs2fun(m), +, A) centralize_sumabs2(A::AbstractArray, m, ifirst::Int, ilast::Int) = Base.mapreduce_impl(centralizedabs2fun(m), +, A, ifirst, ilast) function centralize_sumabs2!(R::AbstractArray{S}, A::AbstractArray, means::AbstractArray) where S # following the implementation of _mapreducedim! at base/reducedim.jl lsiz = Base.check_reducedims(R,A) for i in 1:max(ndims(R), ndims(means)) if axes(means, i) != axes(R, i) throw(DimensionMismatch("dimension $i of `mean` should have indices $(axes(R, i)), but got $(axes(means, i))")) end end isempty(R) || fill!(R, zero(S)) isempty(A) && return R if Base.has_fast_linear_indexing(A) && lsiz > 16 && !has_offset_axes(R, means) nslices = div(length(A), lsiz) ibase = first(LinearIndices(A))-1 for i = 1:nslices @inbounds R[i] = centralize_sumabs2(A, means[i], ibase+1, ibase+lsiz) ibase += lsiz end return R end indsAt, indsRt = Base.safe_tail(axes(A)), Base.safe_tail(axes(R)) # handle d=1 manually keep, Idefault = Broadcast.shapeindexer(indsRt) if Base.reducedim1(R, A) i1 = first(Base.axes1(R)) @inbounds for IA in CartesianIndices(indsAt) IR = Broadcast.newindex(IA, keep, Idefault) r = R[i1,IR] m = means[i1,IR] @simd for i in axes(A, 1) r += abs2(A[i,IA] - m) end R[i1,IR] = r end else @inbounds for IA in CartesianIndices(indsAt) IR = Broadcast.newindex(IA, keep, Idefault) @simd for i in axes(A, 1) R[i,IR] += abs2(A[i,IA] - means[i,IR]) end end end return R end function varm!(R::AbstractArray{S}, A::AbstractArray, m::AbstractArray; corrected::Bool=true) where S if isempty(A) fill!(R, convert(S, NaN)) else rn = div(length(A), length(R)) - Int(corrected) centralize_sumabs2!(R, A, m) R .= R .* (1 // rn) end return R end """ varm(itr, mean; dims, corrected::Bool=true) Compute the sample variance of collection `itr`, with known mean(s) `mean`. The algorithm returns an estimator of the generative distribution's variance under the assumption that each entry of `itr` is a sample drawn from the same unknown distribution, with the samples uncorrelated. For arrays, this computation is equivalent to calculating `sum((itr .- mean(itr)).^2) / (length(itr) - 1)`. If `corrected` is `true`, then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` with `n` the number of elements in `itr`. If `itr` is an `AbstractArray`, `dims` can be provided to compute the variance over dimensions. In that case, `mean` must be an array with the same shape as `mean(itr, dims=dims)` (additional trailing singleton dimensions are allowed). !!! note If array contains `NaN` or [`missing`](@ref) values, the result is also `NaN` or `missing` (`missing` takes precedence if array contains both). Use the [`skipmissing`](@ref) function to omit `missing` entries and compute the variance of non-missing values. """ varm(A::AbstractArray, m::AbstractArray; corrected::Bool=true, dims=:) = _varm(A, m, corrected, dims) _varm(A::AbstractArray{T}, m, corrected::Bool, region) where {T} = varm!(Base.reducedim_init(t -> abs2(t)/2, +, A, region), A, m; corrected=corrected) varm(A::AbstractArray, m; corrected::Bool=true) = _varm(A, m, corrected, :) function _varm(A::AbstractArray{T}, m, corrected::Bool, ::Colon) where T n = length(A) n == 0 && return oftype((abs2(zero(T)) + abs2(zero(T)))/2, NaN) return centralize_sumabs2(A, m) / (n - Int(corrected)) end """ var(itr; corrected::Bool=true, mean=nothing[, dims]) Compute the sample variance of collection `itr`. The algorithm returns an estimator of the generative distribution's variance under the assumption that each entry of `itr` is a sample drawn from the same unknown distribution, with the samples uncorrelated. For arrays, this computation is equivalent to calculating `sum((itr .- mean(itr)).^2) / (length(itr) - 1)`. If `corrected` is `true`, then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` where `n` is the number of elements in `itr`. If `itr` is an `AbstractArray`, `dims` can be provided to compute the variance over dimensions. A pre-computed `mean` may be provided. When `dims` is specified, `mean` must be an array with the same shape as `mean(itr, dims=dims)` (additional trailing singleton dimensions are allowed). !!! note If array contains `NaN` or [`missing`](@ref) values, the result is also `NaN` or `missing` (`missing` takes precedence if array contains both). Use the [`skipmissing`](@ref) function to omit `missing` entries and compute the variance of non-missing values. """ var(A::AbstractArray; corrected::Bool=true, mean=nothing, dims=:) = _var(A, corrected, mean, dims) function _var(A::AbstractArray, corrected::Bool, mean, dims) if mean === nothing mean = Statistics.mean(A, dims=dims) end return varm(A, mean; corrected=corrected, dims=dims) end function _var(A::AbstractArray, corrected::Bool, mean, ::Colon) if mean === nothing mean = Statistics.mean(A) end return real(varm(A, mean; corrected=corrected)) end varm(iterable, m; corrected::Bool=true) = _var(iterable, corrected, m) ## variances over ranges varm(v::AbstractRange, m::AbstractArray) = range_varm(v, m) varm(v::AbstractRange, m) = range_varm(v, m) function range_varm(v::AbstractRange, m) f = first(v) - m s = step(v) l = length(v) vv = f^2 * l / (l - 1) + f * s * l + s^2 * l * (2 * l - 1) / 6 if l == 0 || l == 1 return typeof(vv)(NaN) end return vv end function var(v::AbstractRange) s = step(v) l = length(v) vv = abs2(s) * (l + 1) * l / 12 if l == 0 || l == 1 return typeof(vv)(NaN) end return vv end ##### standard deviation ##### function sqrt!(A::AbstractArray) for i in eachindex(A) @inbounds A[i] = sqrt(A[i]) end A end """ std(itr; corrected::Bool=true, mean=nothing[, dims]) Compute the sample standard deviation of collection `itr`. The algorithm returns an estimator of the generative distribution's standard deviation under the assumption that each entry of `itr` is a sample drawn from the same unknown distribution, with the samples uncorrelated. For arrays, this computation is equivalent to calculating `sqrt(sum((itr .- mean(itr)).^2) / (length(itr) - 1))`. If `corrected` is `true`, then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` with `n` the number of elements in `itr`. If `itr` is an `AbstractArray`, `dims` can be provided to compute the standard deviation over dimensions. A pre-computed `mean` may be provided. When `dims` is specified, `mean` must be an array with the same shape as `mean(itr, dims=dims)` (additional trailing singleton dimensions are allowed). !!! note If array contains `NaN` or [`missing`](@ref) values, the result is also `NaN` or `missing` (`missing` takes precedence if array contains both). Use the [`skipmissing`](@ref) function to omit `missing` entries and compute the standard deviation of non-missing values. """ std(A::AbstractArray; corrected::Bool=true, mean=nothing, dims=:) = _std(A, corrected, mean, dims) _std(A::AbstractArray, corrected::Bool, mean, dims) = sqrt.(var(A; corrected=corrected, mean=mean, dims=dims)) _std(A::AbstractArray, corrected::Bool, mean, ::Colon) = sqrt.(var(A; corrected=corrected, mean=mean)) _std(A::AbstractArray{<:AbstractFloat}, corrected::Bool, mean, dims) = sqrt!(var(A; corrected=corrected, mean=mean, dims=dims)) _std(A::AbstractArray{<:AbstractFloat}, corrected::Bool, mean, ::Colon) = sqrt.(var(A; corrected=corrected, mean=mean)) std(iterable; corrected::Bool=true, mean=nothing) = sqrt(var(iterable, corrected=corrected, mean=mean)) """ stdm(itr, mean; corrected::Bool=true[, dims]) Compute the sample standard deviation of collection `itr`, with known mean(s) `mean`. The algorithm returns an estimator of the generative distribution's standard deviation under the assumption that each entry of `itr` is a sample drawn from the same unknown distribution, with the samples uncorrelated. For arrays, this computation is equivalent to calculating `sqrt(sum((itr .- mean(itr)).^2) / (length(itr) - 1))`. If `corrected` is `true`, then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` with `n` the number of elements in `itr`. If `itr` is an `AbstractArray`, `dims` can be provided to compute the standard deviation over dimensions. In that case, `mean` must be an array with the same shape as `mean(itr, dims=dims)` (additional trailing singleton dimensions are allowed). !!! note If array contains `NaN` or [`missing`](@ref) values, the result is also `NaN` or `missing` (`missing` takes precedence if array contains both). Use the [`skipmissing`](@ref) function to omit `missing` entries and compute the standard deviation of non-missing values. """ stdm(A::AbstractArray, m::AbstractArray; corrected::Bool=true, dims=:) = _std(A, corrected, m, dims) stdm(iterable, m; corrected::Bool=true) = sqrt(var(iterable, corrected=corrected, mean=m)) ###### covariance ###### # auxiliary functions _conj(x::AbstractArray{<:Real}) = x _conj(x::AbstractArray) = conj(x) _getnobs(x::AbstractVector, vardim::Int) = length(x) _getnobs(x::AbstractMatrix, vardim::Int) = size(x, vardim) function _getnobs(x::AbstractVecOrMat, y::AbstractVecOrMat, vardim::Int) n = _getnobs(x, vardim) _getnobs(y, vardim) == n || throw(DimensionMismatch("dimensions of x and y mismatch")) return n end _vmean(x::AbstractVector, vardim::Int) = mean(x) _vmean(x::AbstractMatrix, vardim::Int) = mean(x, dims=vardim) # core functions unscaled_covzm(x::AbstractVector{<:Number}) = sum(abs2, x) unscaled_covzm(x::AbstractVector) = sum(t -> t*t', x) unscaled_covzm(x::AbstractMatrix, vardim::Int) = (vardim == 1 ? _conj(x'x) : x * x') function unscaled_covzm(x::AbstractVector, y::AbstractVector) (isempty(x) || isempty(y)) && throw(ArgumentError("covariance only defined for non-empty vectors")) return *(adjoint(y), x) end unscaled_covzm(x::AbstractVector, y::AbstractMatrix, vardim::Int) = (vardim == 1 ? *(transpose(x), _conj(y)) : *(transpose(x), transpose(_conj(y)))) unscaled_covzm(x::AbstractMatrix, y::AbstractVector, vardim::Int) = (c = vardim == 1 ? *(transpose(x), _conj(y)) : x * _conj(y); reshape(c, length(c), 1)) unscaled_covzm(x::AbstractMatrix, y::AbstractMatrix, vardim::Int) = (vardim == 1 ? *(transpose(x), _conj(y)) : *(x, adjoint(y))) # covzm (with centered data) covzm(x::AbstractVector; corrected::Bool=true) = unscaled_covzm(x) / (length(x) - Int(corrected)) function covzm(x::AbstractMatrix, vardim::Int=1; corrected::Bool=true) C = unscaled_covzm(x, vardim) T = promote_type(typeof(first(C) / 1), eltype(C)) A = convert(AbstractMatrix{T}, C) b = 1//(size(x, vardim) - corrected) A .= A .* b return A end covzm(x::AbstractVector, y::AbstractVector; corrected::Bool=true) = unscaled_covzm(x, y) / (length(x) - Int(corrected)) function covzm(x::AbstractVecOrMat, y::AbstractVecOrMat, vardim::Int=1; corrected::Bool=true) C = unscaled_covzm(x, y, vardim) T = promote_type(typeof(first(C) / 1), eltype(C)) A = convert(AbstractArray{T}, C) b = 1//(_getnobs(x, y, vardim) - corrected) A .= A .* b return A end # covm (with provided mean) ## Use map(t -> t - xmean, x) instead of x .- xmean to allow for Vector{Vector} ## which can't be handled by broadcast covm(x::AbstractVector, xmean; corrected::Bool=true) = covzm(map(t -> t - xmean, x); corrected=corrected) covm(x::AbstractMatrix, xmean, vardim::Int=1; corrected::Bool=true) = covzm(x .- xmean, vardim; corrected=corrected) covm(x::AbstractVector, xmean, y::AbstractVector, ymean; corrected::Bool=true) = covzm(map(t -> t - xmean, x), map(t -> t - ymean, y); corrected=corrected) covm(x::AbstractVecOrMat, xmean, y::AbstractVecOrMat, ymean, vardim::Int=1; corrected::Bool=true) = covzm(x .- xmean, y .- ymean, vardim; corrected=corrected) # cov (API) """ cov(x::AbstractVector; corrected::Bool=true) Compute the variance of the vector `x`. If `corrected` is `true` (the default) then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` where `n = length(x)`. """ cov(x::AbstractVector; corrected::Bool=true) = covm(x, mean(x); corrected=corrected) """ cov(X::AbstractMatrix; dims::Int=1, corrected::Bool=true) Compute the covariance matrix of the matrix `X` along the dimension `dims`. If `corrected` is `true` (the default) then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` where `n = size(X, dims)`. """ cov(X::AbstractMatrix; dims::Int=1, corrected::Bool=true) = covm(X, _vmean(X, dims), dims; corrected=corrected) """ cov(x::AbstractVector, y::AbstractVector; corrected::Bool=true) Compute the covariance between the vectors `x` and `y`. If `corrected` is `true` (the default), computes ``\\frac{1}{n-1}\\sum_{i=1}^n (x_i-\\bar x) (y_i-\\bar y)^*`` where ``*`` denotes the complex conjugate and `n = length(x) = length(y)`. If `corrected` is `false`, computes ``\\frac{1}{n}\\sum_{i=1}^n (x_i-\\bar x) (y_i-\\bar y)^*``. """ cov(x::AbstractVector, y::AbstractVector; corrected::Bool=true) = covm(x, mean(x), y, mean(y); corrected=corrected) """ cov(X::AbstractVecOrMat, Y::AbstractVecOrMat; dims::Int=1, corrected::Bool=true) Compute the covariance between the vectors or matrices `X` and `Y` along the dimension `dims`. If `corrected` is `true` (the default) then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` where `n = size(X, dims) = size(Y, dims)`. """ cov(X::AbstractVecOrMat, Y::AbstractVecOrMat; dims::Int=1, corrected::Bool=true) = covm(X, _vmean(X, dims), Y, _vmean(Y, dims), dims; corrected=corrected) ##### correlation ##### """ clampcor(x) Clamp a real correlation to between -1 and 1, leaving complex correlations unchanged """ clampcor(x::Real) = clamp(x, -1, 1) clampcor(x) = x # cov2cor! function cov2cor!(C::AbstractMatrix{T}, xsd::AbstractArray) where T require_one_based_indexing(C, xsd) nx = length(xsd) size(C) == (nx, nx) || throw(DimensionMismatch("inconsistent dimensions")) for j = 1:nx for i = 1:j-1 C[i,j] = adjoint(C[j,i]) end C[j,j] = oneunit(T) for i = j+1:nx C[i,j] = clampcor(C[i,j] / (xsd[i] * xsd[j])) end end return C end function cov2cor!(C::AbstractMatrix, xsd, ysd::AbstractArray) require_one_based_indexing(C, ysd) nx, ny = size(C) length(ysd) == ny || throw(DimensionMismatch("inconsistent dimensions")) for (j, y) in enumerate(ysd) # fixme (iter): here and in all `cov2cor!` we assume that `C` is efficiently indexed by integers for i in 1:nx C[i,j] = clampcor(C[i, j] / (xsd * y)) end end return C end function cov2cor!(C::AbstractMatrix, xsd::AbstractArray, ysd) require_one_based_indexing(C, xsd) nx, ny = size(C) length(xsd) == nx || throw(DimensionMismatch("inconsistent dimensions")) for j in 1:ny for (i, x) in enumerate(xsd) C[i,j] = clampcor(C[i,j] / (x * ysd)) end end return C end function cov2cor!(C::AbstractMatrix, xsd::AbstractArray, ysd::AbstractArray) require_one_based_indexing(C, xsd, ysd) nx, ny = size(C) (length(xsd) == nx && length(ysd) == ny) || throw(DimensionMismatch("inconsistent dimensions")) for (i, x) in enumerate(xsd) for (j, y) in enumerate(ysd) C[i,j] = clampcor(C[i,j] / (x * y)) end end return C end # corzm (non-exported, with centered data) corzm(x::AbstractVector{T}) where {T} = T === Missing ? missing : one(float(nonmissingtype(T))) function corzm(x::AbstractMatrix, vardim::Int=1) c = unscaled_covzm(x, vardim) return cov2cor!(c, collect(sqrt(c[i,i]) for i in 1:min(size(c)...))) end corzm(x::AbstractVector, y::AbstractMatrix, vardim::Int=1) = cov2cor!(unscaled_covzm(x, y, vardim), sqrt(sum(abs2, x)), sqrt!(sum(abs2, y, dims=vardim))) corzm(x::AbstractMatrix, y::AbstractVector, vardim::Int=1) = cov2cor!(unscaled_covzm(x, y, vardim), sqrt!(sum(abs2, x, dims=vardim)), sqrt(sum(abs2, y))) corzm(x::AbstractMatrix, y::AbstractMatrix, vardim::Int=1) = cov2cor!(unscaled_covzm(x, y, vardim), sqrt!(sum(abs2, x, dims=vardim)), sqrt!(sum(abs2, y, dims=vardim))) # corm corm(x::AbstractVector{T}, xmean) where {T} = T === Missing ? missing : one(float(nonmissingtype(T))) corm(x::AbstractMatrix, xmean, vardim::Int=1) = corzm(x .- xmean, vardim) function corm(x::AbstractVector, mx, y::AbstractVector, my) require_one_based_indexing(x, y) n = length(x) length(y) == n || throw(DimensionMismatch("inconsistent lengths")) n > 0 || throw(ArgumentError("correlation only defined for non-empty vectors")) @inbounds begin # Initialize the accumulators xx = zero(sqrt(abs2(one(x[1])))) yy = zero(sqrt(abs2(one(y[1])))) xy = zero(x[1] * y[1]') @simd for i in eachindex(x, y) xi = x[i] - mx yi = y[i] - my xx += abs2(xi) yy += abs2(yi) xy += xi * yi' end end return clampcor(xy / max(xx, yy) / sqrt(min(xx, yy) / max(xx, yy))) end corm(x::AbstractVecOrMat, xmean, y::AbstractVecOrMat, ymean, vardim::Int=1) = corzm(x .- xmean, y .- ymean, vardim) # cor """ cor(x::AbstractVector) Return the number one. """ cor(x::AbstractVector{T}) where {T} = T === Missing ? missing : one(float(nonmissingtype(T))) """ cor(X::AbstractMatrix; dims::Int=1) Compute the Pearson correlation matrix of the matrix `X` along the dimension `dims`. """ cor(X::AbstractMatrix; dims::Int=1) = corm(X, _vmean(X, dims), dims) """ cor(x::AbstractVector, y::AbstractVector) Compute the Pearson correlation between the vectors `x` and `y`. """ cor(x::AbstractVector, y::AbstractVector) = corm(x, mean(x), y, mean(y)) """ cor(X::AbstractVecOrMat, Y::AbstractVecOrMat; dims=1) Compute the Pearson correlation between the vectors or matrices `X` and `Y` along the dimension `dims`. """ cor(x::AbstractVecOrMat, y::AbstractVecOrMat; dims::Int=1) = corm(x, _vmean(x, dims), y, _vmean(y, dims), dims) ##### median & quantiles ##### """ middle(x) Compute the middle of a scalar value, which is equivalent to `x` itself, but of the type of `middle(x, x)` for consistency. """ middle(x::Union{Bool,Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128}) = Float64(x) # Specialized functions for number types allow for improved performance middle(x::AbstractFloat) = x middle(x::Number) = (x + zero(x)) / 1 """ middle(x, y) Compute the middle of two numbers `x` and `y`, which is equivalent in both value and type to computing their mean (`(x + y) / 2`). """ middle(x::Number, y::Number) = x/2 + y/2 """ middle(a::AbstractArray) Compute the middle of an array `a`, which consists of finding its extrema and then computing their mean. ```jldoctest julia> using Statistics julia> middle(1:10) 5.5 julia> a = [1,2,3.6,10.9] 4-element Vector{Float64}: 1.0 2.0 3.6 10.9 julia> middle(a) 5.95 ``` """ middle(a::AbstractArray) = ((v1, v2) = extrema(a); middle(v1, v2)) function middle(a::AbstractRange) isempty(a) && throw(ArgumentError("middle of an empty range is undefined.")) return middle(first(a), last(a)) end """ median!(v) Like [`median`](@ref), but may overwrite the input vector. """ function median!(v::AbstractVector) isempty(v) && throw(ArgumentError("median of an empty array is undefined, $(repr(v))")) eltype(v)>:Missing && any(ismissing, v) && return missing any(x -> x isa Number && isnan(x), v) && return convert(eltype(v), NaN) inds = axes(v, 1) n = length(inds) mid = div(first(inds)+last(inds),2) if isodd(n) return middle(partialsort!(v,mid)) else m = partialsort!(v, mid:mid+1) return middle(m[1], m[2]) end end median!(v::AbstractArray) = median!(vec(v)) """ median(itr) Compute the median of all elements in a collection. For an even number of elements no exact median element exists, so the result is equivalent to calculating mean of two median elements. !!! note If `itr` contains `NaN` or [`missing`](@ref) values, the result is also `NaN` or `missing` (`missing` takes precedence if `itr` contains both). Use the [`skipmissing`](@ref) function to omit `missing` entries and compute the median of non-missing values. # Examples ```jldoctest julia> using Statistics julia> median([1, 2, 3]) 2.0 julia> median([1, 2, 3, 4]) 2.5 julia> median([1, 2, missing, 4]) missing julia> median(skipmissing([1, 2, missing, 4])) 2.0 ``` """ median(itr) = median!(collect(itr)) """ median(A::AbstractArray; dims) Compute the median of an array along the given dimensions. # Examples ```jldoctest julia> using Statistics julia> median([1 2; 3 4], dims=1) 1×2 Matrix{Float64}: 2.0 3.0 ``` """ median(v::AbstractArray; dims=:) = _median(v, dims) _median(v::AbstractArray, dims) = mapslices(median!, v, dims = dims) _median(v::AbstractArray{T}, ::Colon) where {T} = median!(copyto!(Array{T,1}(undef, length(v)), v)) median(r::AbstractRange{<:Real}) = mean(r) """ quantile!([q::AbstractArray, ] v::AbstractVector, p; sorted=false, alpha::Real=1.0, beta::Real=alpha) Compute the quantile(s) of a vector `v` at a specified probability or vector or tuple of probabilities `p` on the interval [0,1]. If `p` is a vector, an optional output array `q` may also be specified. (If not provided, a new output array is created.) The keyword argument `sorted` indicates whether `v` can be assumed to be sorted; if `false` (the default), then the elements of `v` will be partially sorted in-place. Samples quantile are defined by `Q(p) = (1-γ)*x[j] + γ*x[j+1]`, where `x[j]` is the j-th order statistic of `v`, `j = floor(n*p + m)`, `m = alpha + p*(1 - alpha - beta)` and `γ = n*p + m - j`. By default (`alpha = beta = 1`), quantiles are computed via linear interpolation between the points `((k-1)/(n-1), x[k])`, for `k = 1:n` where `n = length(v)`. This corresponds to Definition 7 of Hyndman and Fan (1996), and is the same as the R and NumPy default. The keyword arguments `alpha` and `beta` correspond to the same parameters in Hyndman and Fan, setting them to different values allows to calculate quantiles with any of the methods 4-9 defined in this paper: - Def. 4: `alpha=0`, `beta=1` - Def. 5: `alpha=0.5`, `beta=0.5` (MATLAB default) - Def. 6: `alpha=0`, `beta=0` (Excel `PERCENTILE.EXC`, Python default, Stata `altdef`) - Def. 7: `alpha=1`, `beta=1` (Julia, R and NumPy default, Excel `PERCENTILE` and `PERCENTILE.INC`, Python `'inclusive'`) - Def. 8: `alpha=1/3`, `beta=1/3` - Def. 9: `alpha=3/8`, `beta=3/8` !!! note An `ArgumentError` is thrown if `v` contains `NaN` or [`missing`](@ref) values. # References - Hyndman, R.J and Fan, Y. (1996) "Sample Quantiles in Statistical Packages", *The American Statistician*, Vol. 50, No. 4, pp. 361-365 - [Quantile on Wikipedia](https://en.m.wikipedia.org/wiki/Quantile) details the different quantile definitions # Examples ```jldoctest julia> using Statistics julia> x = [3, 2, 1]; julia> quantile!(x, 0.5) 2.0 julia> x 3-element Vector{Int64}: 1 2 3 julia> y = zeros(3); julia> quantile!(y, x, [0.1, 0.5, 0.9]) === y true julia> y 3-element Vector{Float64}: 1.2000000000000002 2.0 2.8000000000000003 ``` """ function quantile!(q::AbstractArray, v::AbstractVector, p::AbstractArray; sorted::Bool=false, alpha::Real=1.0, beta::Real=alpha) require_one_based_indexing(q, v, p) if size(p) != size(q) throw(DimensionMismatch("size of p, $(size(p)), must equal size of q, $(size(q))")) end isempty(q) && return q minp, maxp = extrema(p) _quantilesort!(v, sorted, minp, maxp) for (i, j) in zip(eachindex(p), eachindex(q)) @inbounds q[j] = _quantile(v,p[i], alpha=alpha, beta=beta) end return q end function quantile!(v::AbstractVector, p::Union{AbstractArray, Tuple{Vararg{Real}}}; sorted::Bool=false, alpha::Real=1., beta::Real=alpha) if !isempty(p) minp, maxp = extrema(p) _quantilesort!(v, sorted, minp, maxp) end return map(x->_quantile(v, x, alpha=alpha, beta=beta), p) end quantile!(a::AbstractArray, p::Union{AbstractArray,Tuple{Vararg{Real}}}; sorted::Bool=false, alpha::Real=1.0, beta::Real=alpha) = quantile!(vec(a), p, sorted=sorted, alpha=alpha, beta=alpha) quantile!(q::AbstractArray, a::AbstractArray, p::Union{AbstractArray,Tuple{Vararg{Real}}}; sorted::Bool=false, alpha::Real=1.0, beta::Real=alpha) = quantile!(q, vec(a), p, sorted=sorted, alpha=alpha, beta=alpha) quantile!(v::AbstractVector, p::Real; sorted::Bool=false, alpha::Real=1.0, beta::Real=alpha) = _quantile(_quantilesort!(v, sorted, p, p), p, alpha=alpha, beta=beta) # Function to perform partial sort of v for quantiles in given range function _quantilesort!(v::AbstractVector, sorted::Bool, minp::Real, maxp::Real) isempty(v) && throw(ArgumentError("empty data vector")) require_one_based_indexing(v) if !sorted lv = length(v) lo = floor(Int,minp*(lv)) hi = ceil(Int,1+maxp*(lv)) # only need to perform partial sort sort!(v, 1, lv, Base.Sort.PartialQuickSort(lo:hi), Base.Sort.Forward) end if (sorted && (ismissing(v[end]) || (v[end] isa Number && isnan(v[end])))) || any(x -> ismissing(x) || (x isa Number && isnan(x)), v) throw(ArgumentError("quantiles are undefined in presence of NaNs or missing values")) end return v end # Core quantile lookup function: assumes `v` sorted @inline function _quantile(v::AbstractVector, p::Real; alpha::Real=1.0, beta::Real=alpha) 0 <= p <= 1 || throw(ArgumentError("input probability out of [0,1] range")) 0 <= alpha <= 1 || throw(ArgumentError("alpha parameter out of [0,1] range")) 0 <= beta <= 1 || throw(ArgumentError("beta parameter out of [0,1] range")) require_one_based_indexing(v) n = length(v) @assert n > 0 # this case should never happen here m = alpha + p * (one(alpha) - alpha - beta) aleph = n*p + oftype(p, m) j = clamp(trunc(Int, aleph), 1, n-1) γ = clamp(aleph - j, 0, 1) if n == 1 a = v[1] b = v[1] else a = v[j] b = v[j + 1] end # When a ≉ b, b-a may overflow # When a ≈ b, (1-γ)*a + γ*b may not be increasing with γ due to rounding if isfinite(a) && isfinite(b) && (!(a isa Number) || !(b isa Number) || a ≈ b) return a + γ*(b-a) else return (1-γ)*a + γ*b end end """ quantile(itr, p; sorted=false, alpha::Real=1.0, beta::Real=alpha) Compute the quantile(s) of a collection `itr` at a specified probability or vector or tuple of probabilities `p` on the interval [0,1]. The keyword argument `sorted` indicates whether `itr` can be assumed to be sorted. Samples quantile are defined by `Q(p) = (1-γ)*x[j] + γ*x[j+1]`, where `x[j]` is the j-th order statistic of `itr`, `j = floor(n*p + m)`, `m = alpha + p*(1 - alpha - beta)` and `γ = n*p + m - j`. By default (`alpha = beta = 1`), quantiles are computed via linear interpolation between the points `((k-1)/(n-1), x[k])`, for `k = 1:n` where `n = length(itr)`. This corresponds to Definition 7 of Hyndman and Fan (1996), and is the same as the R and NumPy default. The keyword arguments `alpha` and `beta` correspond to the same parameters in Hyndman and Fan, setting them to different values allows to calculate quantiles with any of the methods 4-9 defined in this paper: - Def. 4: `alpha=0`, `beta=1` - Def. 5: `alpha=0.5`, `beta=0.5` (MATLAB default) - Def. 6: `alpha=0`, `beta=0` (Excel `PERCENTILE.EXC`, Python default, Stata `altdef`) - Def. 7: `alpha=1`, `beta=1` (Julia, R and NumPy default, Excel `PERCENTILE` and `PERCENTILE.INC`, Python `'inclusive'`) - Def. 8: `alpha=1/3`, `beta=1/3` - Def. 9: `alpha=3/8`, `beta=3/8` !!! note An `ArgumentError` is thrown if `v` contains `NaN` or [`missing`](@ref) values. Use the [`skipmissing`](@ref) function to omit `missing` entries and compute the quantiles of non-missing values. # References - Hyndman, R.J and Fan, Y. (1996) "Sample Quantiles in Statistical Packages", *The American Statistician*, Vol. 50, No. 4, pp. 361-365 - [Quantile on Wikipedia](https://en.m.wikipedia.org/wiki/Quantile) details the different quantile definitions # Examples ```jldoctest julia> using Statistics julia> quantile(0:20, 0.5) 10.0 julia> quantile(0:20, [0.1, 0.5, 0.9]) 3-element Vector{Float64}: 2.0 10.0 18.000000000000004 julia> quantile(skipmissing([1, 10, missing]), 0.5) 5.5 ``` """ quantile(itr, p; sorted::Bool=false, alpha::Real=1.0, beta::Real=alpha) = quantile!(collect(itr), p, sorted=sorted, alpha=alpha, beta=beta) quantile(v::AbstractVector, p; sorted::Bool=false, alpha::Real=1.0, beta::Real=alpha) = quantile!(sorted ? v : Base.copymutable(v), p; sorted=sorted, alpha=alpha, beta=beta) # If package extensions are not supported in this Julia version if !isdefined(Base, :get_extension) include("../ext/SparseArraysExt.jl") end end # module
Statistics
https://github.com/JuliaStats/Statistics.jl.git
[ "MIT" ]
1.11.1
ae3bb1eb3bba077cd276bc5cfc337cc65c3075c0
code
41068
# This file is a part of Julia. License is MIT: https://julialang.org/license using Statistics, Test, Random, LinearAlgebra, SparseArrays, Dates using Test: guardseed Random.seed!(123) @testset "middle" begin @test middle(3) === 3.0 @test middle(2, 3) === 2.5 let x = ((floatmax(1.0)/4)*3) @test middle(x, x) === x end @test middle(1:8) === 4.5 @test middle([1:8;]) === 4.5 @test middle(5.0 + 2.0im, 2.0 + 3.0im) == 3.5 + 2.5im @test middle(5.0 + 2.0im) == 5.0 + 2.0im # ensure type-correctness for T in [Bool,Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128,Float16,Float32,Float64] @test middle(one(T)) === middle(one(T), one(T)) end @test_throws Union{MethodError, ArgumentError} middle(Int[]) @test_throws ArgumentError middle(1:0) @test middle(0:typemax(Int)) === typemax(Int) / 2 end @testset "median" begin @test median([1.]) === 1. @test median([1.,3]) === 2. @test median([1.,3,2]) === 2. @test median([1,3,2]) === 2.0 @test median([1,3,2,4]) === 2.5 @test median([0.0,Inf]) == Inf @test median([0.0,-Inf]) == -Inf @test median([0.,Inf,-Inf]) == 0.0 @test median([1.,-1.,Inf,-Inf]) == 0.0 @test isnan(median([-Inf,Inf])) X = [2 3 1 -1; 7 4 5 -4] @test all(median(X, dims=2) .== [1.5, 4.5]) @test all(median(X, dims=1) .== [4.5 3.5 3.0 -2.5]) @test X == [2 3 1 -1; 7 4 5 -4] # issue #17153 @test_throws ArgumentError median([]) @test isnan(median([NaN])) @test isnan(median([0.0,NaN])) @test isnan(median([NaN,0.0])) @test isnan(median([NaN,0.0,1.0])) @test isnan(median(Any[NaN,0.0,1.0])) @test isequal(median([NaN 0.0; 1.2 4.5], dims=2), reshape([NaN; 2.85], 2, 1)) @test ismissing(median([1, missing])) @test ismissing(median([1, 2, missing])) @test ismissing(median([NaN, 2.0, missing])) @test ismissing(median([NaN, missing])) @test ismissing(median([missing, NaN])) @test ismissing(median(Any[missing, 2.0, 3.0, 4.0, NaN])) @test median(skipmissing([1, missing, 2])) === 1.5 @test median!([1 2 3 4]) == 2.5 @test median!([1 2; 3 4]) == 2.5 @test invoke(median, Tuple{AbstractVector}, 1:10) == median(1:10) == 5.5 @test @inferred(median(Float16[1, 2, NaN])) === Float16(NaN) @test @inferred(median(Float16[1, 2, 3])) === Float16(2) @test @inferred(median(Float32[1, 2, NaN])) === NaN32 @test @inferred(median(Float32[1, 2, 3])) === 2.0f0 # custom type implementing minimal interface struct A x end Statistics.middle(x::A, y::A) = A(middle(x.x, y.x)) Base.isless(x::A, y::A) = isless(x.x, y.x) @test median([A(1), A(2)]) === A(1.5) @test median(Any[A(1), A(2)]) === A(1.5) end @testset "mean" begin @test mean((1,2,3)) === 2. @test mean([0]) === 0. @test mean([1.]) === 1. @test mean([1.,3]) == 2. @test mean([1,2,3]) == 2. @test mean([0 1 2; 4 5 6], dims=1) == [2. 3. 4.] @test mean([1 2 3; 4 5 6], dims=1) == [2.5 3.5 4.5] @test mean(-, [1 2 3 ; 4 5 6], dims=1) == [-2.5 -3.5 -4.5] @test mean(-, [1 2 3 ; 4 5 6], dims=2) == transpose([-2.0 -5.0]) @test mean(-, [1 2 3 ; 4 5 6], dims=(1, 2)) == -3.5 .* ones(1, 1) @test mean(-, [1 2 3 ; 4 5 6], dims=(1, 1)) == [-2.5 -3.5 -4.5] @test mean(-, [1 2 3 ; 4 5 6], dims=()) == Float64[-1 -2 -3 ; -4 -5 -6] @test mean(i->i+1, 0:2) === 2. @test mean(isodd, [3]) === 1. @test mean(x->3x, (1,1)) === 3. # mean of iterables: n = 10; a = randn(n); b = randn(n) @test mean(Tuple(a)) ≈ mean(a) @test mean(Tuple(a + b*im)) ≈ mean(a + b*im) @test mean(cos, Tuple(a)) ≈ mean(cos, a) @test mean(x->x/2, a + b*im) ≈ mean(a + b*im) / 2. @test ismissing(mean(Tuple((1, 2, missing, 4, 5)))) @test isnan(mean([NaN])) @test isnan(mean([0.0,NaN])) @test isnan(mean([NaN,0.0])) @test isnan(mean([0.,Inf,-Inf])) @test isnan(mean([1.,-1.,Inf,-Inf])) @test isnan(mean([-Inf,Inf])) @test isequal(mean([NaN 0.0; 1.2 4.5], dims=2), reshape([NaN; 2.85], 2, 1)) @test ismissing(mean([1, missing])) @test ismissing(mean([NaN, missing])) @test ismissing(mean([missing, NaN])) @test isequal(mean([missing 1.0; 2.0 3.0], dims=1), [missing 2.0]) @test mean(skipmissing([1, missing, 2])) === 1.5 @test isequal(mean(Complex{Float64}[]), NaN+NaN*im) @test mean(Complex{Float64}[]) isa Complex{Float64} @test isequal(mean(skipmissing(Complex{Float64}[])), NaN+NaN*im) @test mean(skipmissing(Complex{Float64}[])) isa Complex{Float64} @test isequal(mean(abs, Complex{Float64}[]), NaN) @test mean(abs, Complex{Float64}[]) isa Float64 @test isequal(mean(abs, skipmissing(Complex{Float64}[])), NaN) @test mean(abs, skipmissing(Complex{Float64}[])) isa Float64 @test isequal(mean(Int[]), NaN) @test mean(Int[]) isa Float64 @test isequal(mean(skipmissing(Int[])), NaN) @test mean(skipmissing(Int[])) isa Float64 @test_throws Exception mean([]) @test_throws Exception mean(skipmissing([])) @test_throws ArgumentError mean((1 for i in 2:1)) if VERSION >= v"1.6.0-DEV.83" @test_throws ArgumentError mean(()) @test_throws ArgumentError mean(Union{}[]) end # Check that small types are accumulated using wider type for T in (Int8, UInt8) x = [typemax(T) typemax(T)] g = (v for v in x) @test mean(x) == mean(g) == typemax(T) @test mean(identity, x) == mean(identity, g) == typemax(T) @test mean(x, dims=2) == [typemax(T)]' end # Check that mean avoids integer overflow (#22) let x = fill(typemax(Int), 10), a = tuple(x...) @test (mean(x) == mean(x, dims=1)[] == mean(float, x) == mean(a) == mean(v for v in x) == mean(v for v in a) ≈ float(typemax(Int))) end let x = rand(10000) # mean should use sum's accurate pairwise algorithm @test mean(x) == sum(x) / length(x) end @test mean(Number[1, 1.5, 2+3im]) === 1.5+1im # mixed-type array @test mean(v for v in Number[1, 1.5, 2+3im]) === 1.5+1im @test isnan(@inferred mean(Int[])) @test isnan(@inferred mean(Float32[])) @test isnan(@inferred mean(Float64[])) @test isnan(@inferred mean(Iterators.filter(x -> true, Int[]))) @test isnan(@inferred mean(Iterators.filter(x -> true, Float32[]))) @test isnan(@inferred mean(Iterators.filter(x -> true, Float64[]))) # using a number as a "function" @test_throws "ArgumentError: mean(f, itr) requires a function and an iterable.\nPerhaps you meant mean((x, y))" mean(1, 2) struct T <: Number x::Int end (t::T)(y) = t.x == 0 ? t(y, y + 1, y + 2) : t.x * y @test mean(T(2), 3) === 6.0 @test_throws MethodError mean(T(0), 3) struct U <: Number x::Int end (t::U)(y) = t.x == 0 ? throw(MethodError(T)) : t.x * y @test @inferred mean(U(2), 3) === 6.0 end @testset "mean/median for ranges" begin for f in (mean, median) for n = 2:5 @test f(2:n) == f([2:n;]) @test f(2:0.1:n) ≈ f([2:0.1:n;]) end end @test mean(2:0.1:4) === 3.0 # N.B. mean([2:0.1:4;]) != 3 @test mean(LinRange(2im, 4im, 21)) === 3.0im @test mean(2:1//10:4) === 3//1 @test isnan(@inferred(mean(2:1))::Float64) @test isnan(@inferred(mean(big(2):1))::BigFloat) z = @inferred(mean(LinRange(2im, 1im, 0)))::ComplexF64 @test isnan(real(z)) & isnan(imag(z)) @test_throws DivideError mean(2//1:1) @test mean(typemax(Int):typemax(Int)) === float(typemax(Int)) @test mean(prevfloat(Inf):prevfloat(Inf)) === prevfloat(Inf) end @testset "var & std" begin # edge case: empty vector # iterable; this has to throw for type stability @test_throws Exception var(()) @test_throws Exception var((); corrected=false) @test_throws Exception var((); mean=2) @test_throws Exception var((); mean=2, corrected=false) # reduction @test isnan(var(Int[])) @test isnan(var(Int[]; corrected=false)) @test isnan(var(Int[]; mean=2)) @test isnan(var(Int[]; mean=2, corrected=false)) # reduction across dimensions @test isequal(var(Int[], dims=1), [NaN]) @test isequal(var(Int[], dims=1; corrected=false), [NaN]) @test isequal(var(Int[], dims=1; mean=[2]), [NaN]) @test isequal(var(Int[], dims=1; mean=[2], corrected=false), [NaN]) # edge case: one-element vector # iterable @test isnan(@inferred(var((1,)))) @test var((1,); corrected=false) === 0.0 @test var((1,); mean=2) === Inf @test var((1,); mean=2, corrected=false) === 1.0 # reduction @test isnan(@inferred(var([1]))) @test var([1]; corrected=false) === 0.0 @test var([1]; mean=2) === Inf @test var([1]; mean=2, corrected=false) === 1.0 # reduction across dimensions @test isequal(@inferred(var([1], dims=1)), [NaN]) @test var([1], dims=1; corrected=false) ≈ [0.0] @test var([1], dims=1; mean=[2]) ≈ [Inf] @test var([1], dims=1; mean=[2], corrected=false) ≈ [1.0] @test var(1:8) == 6. @test varm(1:8,1) == varm(Vector(1:8),1) @test isnan(varm(1:1,1)) @test isnan(var(1:1)) @test isnan(var(1:-1)) @test @inferred(var(1.0:8.0)) == 6. @test varm(1.0:8.0,1.0) == varm(Vector(1.0:8.0),1) @test isnan(varm(1.0:1.0,1.0)) @test isnan(var(1.0:1.0)) @test isnan(var(1.0:-1.0)) @test @inferred(var(1.0f0:8.0f0)) === 6.f0 @test varm(1.0f0:8.0f0,1.0f0) == varm(Vector(1.0f0:8.0f0),1) @test isnan(varm(1.0f0:1.0f0,1.0f0)) @test isnan(var(1.0f0:1.0f0)) @test isnan(var(1.0f0:-1.0f0)) @test varm([1,2,3], 2) ≈ 1. @test var([1,2,3]) ≈ 1. @test var([1,2,3]; corrected=false) ≈ 2.0/3 @test var([1,2,3]; mean=0) ≈ 7. @test var([1,2,3]; mean=0, corrected=false) ≈ 14.0/3 @test varm((1,2,3), 2) ≈ 1. @test var((1,2,3)) ≈ 1. @test var((1,2,3); corrected=false) ≈ 2.0/3 @test var((1,2,3); mean=0) ≈ 7. @test var((1,2,3); mean=0, corrected=false) ≈ 14.0/3 @test_throws ArgumentError var((1,2,3); mean=()) @test var([1 2 3 4 5; 6 7 8 9 10], dims=2) ≈ [2.5 2.5]' @test var([1 2 3 4 5; 6 7 8 9 10], dims=2; corrected=false) ≈ [2.0 2.0]' @test var(collect(1:99), dims=1) ≈ [825] @test var(Matrix(transpose(collect(1:99))), dims=2) ≈ [825] @test stdm([1,2,3], 2) ≈ 1. @test std([1,2,3]) ≈ 1. @test std([1,2,3]; corrected=false) ≈ sqrt(2.0/3) @test std([1,2,3]; mean=0) ≈ sqrt(7.0) @test std([1,2,3]; mean=0, corrected=false) ≈ sqrt(14.0/3) @test stdm([1.0,2,3], 2) ≈ 1. @test std([1.0,2,3]) ≈ 1. @test std([1.0,2,3]; corrected=false) ≈ sqrt(2.0/3) @test std([1.0,2,3]; mean=0) ≈ sqrt(7.0) @test std([1.0,2,3]; mean=0, corrected=false) ≈ sqrt(14.0/3) @test stdm([1.0,2,3], [0]; dims=1, corrected=false)[] ≈ sqrt(14.0/3) @test std([1.0,2,3]; dims=1)[] ≈ 1. @test std([1.0,2,3]; dims=1, corrected=false)[] ≈ sqrt(2.0/3) @test std([1.0,2,3]; dims=1, mean=[0])[] ≈ sqrt(7.0) @test std([1.0,2,3]; dims=1, mean=[0], corrected=false)[] ≈ sqrt(14.0/3) @test stdm((1,2,3), 2) ≈ 1. @test std((1,2,3)) ≈ 1. @test std((1,2,3); corrected=false) ≈ sqrt(2.0/3) @test std((1,2,3); mean=0) ≈ sqrt(7.0) @test std((1,2,3); mean=0, corrected=false) ≈ sqrt(14.0/3) @test stdm([1 2 3 4 5; 6 7 8 9 10], [3.0,8.0], dims=2) ≈ sqrt.([2.5 2.5]') @test stdm([1 2 3 4 5; 6 7 8 9 10], [3.0,8.0], dims=2; corrected=false) ≈ sqrt.([2.0 2.0]') @test std([1 2 3 4 5; 6 7 8 9 10], dims=2) ≈ sqrt.([2.5 2.5]') @test std([1 2 3 4 5; 6 7 8 9 10], dims=2; corrected=false) ≈ sqrt.([2.0 2.0]') let A = ComplexF64[exp(i*im) for i in 1:10^4] @test varm(A, 0.) ≈ sum(map(abs2, A)) / (length(A) - 1) @test varm(A, mean(A)) ≈ var(A) end @test var([1//1, 2//1]) isa Rational{Int} @test var([1//1, 2//1], dims=1) isa Vector{Rational{Int}} @test std([1//1, 2//1]) isa Float64 @test std([1//1, 2//1], dims=1) isa Vector{Float64} @testset "var: empty cases" begin A = Matrix{Int}(undef, 0,1) @test var(A) === NaN @test isequal(var(A, dims=1), fill(NaN, 1, 1)) @test isequal(var(A, dims=2), fill(NaN, 0, 1)) @test isequal(var(A, dims=(1, 2)), fill(NaN, 1, 1)) @test isequal(var(A, dims=3), fill(NaN, 0, 1)) end # issue #6672 @test std(AbstractFloat[1,2,3], dims=1) == [1.0] for f in (var, std) @test ismissing(f([1, missing])) @test ismissing(f([NaN, missing])) @test ismissing(f([missing, NaN])) @test isequal(f([missing 1.0; 2.0 3.0], dims=1), [missing f([1.0, 3.0])]) @test f(skipmissing([1, missing, 2])) === f([1, 2]) end for f in (varm, stdm) @test ismissing(f([1, missing], 0)) @test ismissing(f([1, 2], missing)) @test ismissing(f([1, NaN], missing)) @test ismissing(f([NaN, missing], 0)) @test ismissing(f([missing, NaN], 0)) @test ismissing(f([NaN, missing], missing)) @test ismissing(f([missing, NaN], missing)) @test f(skipmissing([1, missing, 2]), 0) === f([1, 2], 0) end @test isequal(var(Complex{Float64}[]), NaN) @test var(Complex{Float64}[]) isa Float64 @test isequal(var(skipmissing(Complex{Float64}[])), NaN) @test var(skipmissing(Complex{Float64}[])) isa Float64 @test_throws Exception var([]) @test_throws Exception var(skipmissing([])) @test_throws Exception var((1 for i in 2:1)) @test isequal(var(Int[]), NaN) @test var(Int[]) isa Float64 @test isequal(var(skipmissing(Int[])), NaN) @test var(skipmissing(Int[])) isa Float64 # over dimensions with provided means for x in ([1 2 3; 4 5 6], sparse([1 2 3; 4 5 6])) @test var(x, dims=1, mean=mean(x, dims=1)) == var(x, dims=1) @test var(x, dims=1, mean=reshape(mean(x, dims=1), 1, :, 1)) == var(x, dims=1) @test var(x, dims=2, mean=mean(x, dims=2)) == var(x, dims=2) @test var(x, dims=2, mean=reshape(mean(x, dims=2), :)) == var(x, dims=2) @test var(x, dims=2, mean=reshape(mean(x, dims=2), :, 1, 1)) == var(x, dims=2) @test_throws DimensionMismatch var(x, dims=1, mean=ones(size(x, 1))) @test_throws DimensionMismatch var(x, dims=1, mean=ones(size(x, 1), 1)) @test_throws DimensionMismatch var(x, dims=2, mean=ones(1, size(x, 2))) @test_throws DimensionMismatch var(x, dims=1, mean=ones(1, 1, size(x, 2))) @test_throws DimensionMismatch var(x, dims=2, mean=ones(1, size(x, 2), 1)) @test_throws DimensionMismatch var(x, dims=2, mean=ones(size(x, 1), 1, 5)) @test_throws DimensionMismatch var(x, dims=1, mean=ones(1, size(x, 2), 5)) end end function safe_cov(x, y, zm::Bool, cr::Bool) n = length(x) if !zm x = x .- mean(x) y = y .- mean(y) end dot(vec(x), vec(y)) / (n - Int(cr)) end X = [1.0 5.0; 2.0 4.0; 3.0 6.0; 4.0 2.0; 5.0 1.0] Y = [6.0 2.0; 1.0 7.0; 5.0 8.0; 3.0 4.0; 2.0 3.0] @testset "covariance" begin for vd in [1, 2], zm in [true, false], cr in [true, false] # println("vd = $vd: zm = $zm, cr = $cr") if vd == 1 k = size(X, 2) Cxx = zeros(k, k) Cxy = zeros(k, k) for i = 1:k, j = 1:k Cxx[i,j] = safe_cov(X[:,i], X[:,j], zm, cr) Cxy[i,j] = safe_cov(X[:,i], Y[:,j], zm, cr) end x1 = vec(X[:,1]) y1 = vec(Y[:,1]) else k = size(X, 1) Cxx = zeros(k, k) Cxy = zeros(k, k) for i = 1:k, j = 1:k Cxx[i,j] = safe_cov(X[i,:], X[j,:], zm, cr) Cxy[i,j] = safe_cov(X[i,:], Y[j,:], zm, cr) end x1 = vec(X[1,:]) y1 = vec(Y[1,:]) end c = zm ? Statistics.covm(x1, 0, corrected=cr) : cov(x1, corrected=cr) @test isa(c, Float64) @test c ≈ Cxx[1,1] @inferred cov(x1, corrected=cr) @test cov(X) == Statistics.covm(X, mean(X, dims=1)) C = zm ? Statistics.covm(X, 0, vd, corrected=cr) : cov(X, dims=vd, corrected=cr) @test size(C) == (k, k) @test C ≈ Cxx @inferred cov(X, dims=vd, corrected=cr) @test cov(x1, y1) == Statistics.covm(x1, mean(x1), y1, mean(y1)) c = zm ? Statistics.covm(x1, 0, y1, 0, corrected=cr) : cov(x1, y1, corrected=cr) @test isa(c, Float64) @test c ≈ Cxy[1,1] @inferred cov(x1, y1, corrected=cr) if vd == 1 @test cov(x1, Y) == Statistics.covm(x1, mean(x1), Y, mean(Y, dims=1)) end C = zm ? Statistics.covm(x1, 0, Y, 0, vd, corrected=cr) : cov(x1, Y, dims=vd, corrected=cr) @test size(C) == (1, k) @test vec(C) ≈ Cxy[1,:] @inferred cov(x1, Y, dims=vd, corrected=cr) if vd == 1 @test cov(X, y1) == Statistics.covm(X, mean(X, dims=1), y1, mean(y1)) end C = zm ? Statistics.covm(X, 0, y1, 0, vd, corrected=cr) : cov(X, y1, dims=vd, corrected=cr) @test size(C) == (k, 1) @test vec(C) ≈ Cxy[:,1] @inferred cov(X, y1, dims=vd, corrected=cr) @test cov(X, Y) == Statistics.covm(X, mean(X, dims=1), Y, mean(Y, dims=1)) C = zm ? Statistics.covm(X, 0, Y, 0, vd, corrected=cr) : cov(X, Y, dims=vd, corrected=cr) @test size(C) == (k, k) @test C ≈ Cxy @inferred cov(X, Y, dims=vd, corrected=cr) end @testset "floating point accuracy for `cov`" begin # Large numbers A = [4.0, 7.0, 13.0, 16.0] C = A .+ 1.0e10 @test cov(A) ≈ cov(A, A) ≈ cov(reshape(A, :, 1))[1] ≈ cov(reshape(A, :, 1))[1] ≈ cov(C, C) ≈ var(C) # Large Vector{Float32} A = 20*randn(Float32, 10_000_000) .+ 100 @test cov(A) ≈ cov(A, A) ≈ cov(reshape(A, :, 1))[1] ≈ cov(reshape(A, :, 1))[1] ≈ var(A) end @testset "cov with missing" begin @test cov([missing]) === cov([1, missing]) === missing @test cov([1, missing], [2, 3]) === cov([1, 3], [2, missing]) === missing @test_throws Exception cov([1 missing; 2 3]) @test_throws Exception cov([1 missing; 2 3], [1, 2]) @test_throws Exception cov([1, 2], [1 missing; 2 3]) @test isequal(cov([1 2; 2 3], [1, missing]), [missing missing]') @test isequal(cov([1, missing], [1 2; 2 3]), [missing missing]) end end function safe_cor(x, y, zm::Bool) if !zm x = x .- mean(x) y = y .- mean(y) end x = vec(x) y = vec(y) dot(x, y) / (sqrt(dot(x, x)) * sqrt(dot(y, y))) end @testset "correlation" begin for vd in [1, 2], zm in [true, false] # println("vd = $vd: zm = $zm") if vd == 1 k = size(X, 2) Cxx = zeros(k, k) Cxy = zeros(k, k) for i = 1:k, j = 1:k Cxx[i,j] = safe_cor(X[:,i], X[:,j], zm) Cxy[i,j] = safe_cor(X[:,i], Y[:,j], zm) end x1 = vec(X[:,1]) y1 = vec(Y[:,1]) else k = size(X, 1) Cxx = zeros(k, k) Cxy = zeros(k, k) for i = 1:k, j = 1:k Cxx[i,j] = safe_cor(X[i,:], X[j,:], zm) Cxy[i,j] = safe_cor(X[i,:], Y[j,:], zm) end x1 = vec(X[1,:]) y1 = vec(Y[1,:]) end c = zm ? Statistics.corm(x1, 0) : cor(x1) @test isa(c, Float64) @test c ≈ Cxx[1,1] @inferred cor(x1) @test cor(X) == Statistics.corm(X, mean(X, dims=1)) C = zm ? Statistics.corm(X, 0, vd) : cor(X, dims=vd) @test size(C) == (k, k) @test C ≈ Cxx @inferred cor(X, dims=vd) @test cor(x1, y1) == Statistics.corm(x1, mean(x1), y1, mean(y1)) c = zm ? Statistics.corm(x1, 0, y1, 0) : cor(x1, y1) @test isa(c, Float64) @test c ≈ Cxy[1,1] @inferred cor(x1, y1) if vd == 1 @test cor(x1, Y) == Statistics.corm(x1, mean(x1), Y, mean(Y, dims=1)) end C = zm ? Statistics.corm(x1, 0, Y, 0, vd) : cor(x1, Y, dims=vd) @test size(C) == (1, k) @test vec(C) ≈ Cxy[1,:] @inferred cor(x1, Y, dims=vd) if vd == 1 @test cor(X, y1) == Statistics.corm(X, mean(X, dims=1), y1, mean(y1)) end C = zm ? Statistics.corm(X, 0, y1, 0, vd) : cor(X, y1, dims=vd) @test size(C) == (k, 1) @test vec(C) ≈ Cxy[:,1] @inferred cor(X, y1, dims=vd) @test cor(X, Y) == Statistics.corm(X, mean(X, dims=1), Y, mean(Y, dims=1)) C = zm ? Statistics.corm(X, 0, Y, 0, vd) : cor(X, Y, dims=vd) @test size(C) == (k, k) @test C ≈ Cxy @inferred cor(X, Y, dims=vd) end @test cor(repeat(1:17, 1, 17))[2] <= 1.0 @test cor(1:17, 1:17) <= 1.0 @test cor(1:17, 18:34) <= 1.0 @test cor(Any[1, 2], Any[1, 2]) == 1.0 @test isnan(cor([0], Int8[81])) let tmp = range(1, stop=85, length=100) tmp2 = Vector(tmp) @test cor(tmp, tmp) <= 1.0 @test cor(tmp, tmp2) <= 1.0 end @test cor(Int[]) === 1.0 @test cor([im]) === 1.0 + 0.0im @test_throws Exception cor([]) @test_throws Exception cor(Any[1.0]) @test cor([1, missing]) === 1.0 @test ismissing(cor([missing])) @test_throws Exception cor(Any[1.0, missing]) @test Statistics.corm([true], 1.0) === 1.0 @test_throws Exception Statistics.corm(Any[0.0, 1.0], 0.5) @test Statistics.corzm([true]) === 1.0 @test_throws Exception Statistics.corzm(Any[0.0, 1.0]) @testset "cor with missing" begin @test cor([missing]) === missing @test cor([1, missing]) == 1 @test cor([1, missing], [2, 3]) === cor([1, 3], [2, missing]) === missing @test_throws Exception cor([1 missing; 2 3]) @test_throws Exception cor([1 missing; 2 3], [1, 2]) @test_throws Exception cor([1, 2], [1 missing; 2 3]) @test isequal(cor([1 2; 2 3], [1, missing]), [missing missing]') @test isequal(cor([1, missing], [1 2; 2 3]), [missing missing]) end end @testset "quantile" begin @test quantile([1,2,3,4],0.5) ≈ 2.5 @test quantile([1,2,3,4],[0.5]) ≈ [2.5] @test quantile([1., 3],[.25,.5,.75])[2] ≈ median([1., 3]) @test quantile(100.0:-1.0:0.0, 0.0:0.1:1.0) ≈ 0.0:10.0:100.0 @test quantile(0.0:100.0, 0.0:0.1:1.0, sorted=true) ≈ 0.0:10.0:100.0 @test quantile(100f0:-1f0:0.0, 0.0:0.1:1.0) ≈ 0f0:10f0:100f0 @test quantile([Inf,Inf],0.5) == Inf @test quantile([-Inf,1],0.5) == -Inf # here it is required to introduce an absolute tolerance because the calculated value is 0 @test quantile([0,1],1e-18) ≈ 1e-18 atol=1e-18 @test quantile([1, 2, 3, 4],[]) == [] @test quantile([1, 2, 3, 4], (0.5,)) == (2.5,) @test quantile([4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11], (0.1, 0.2, 0.4, 0.9)) == (2.0, 3.0, 5.0, 11.0) @test quantile(Union{Int, Missing}[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11], [0.1, 0.2, 0.4, 0.9]) ≈ [2.0, 3.0, 5.0, 11.0] @test quantile(Any[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11], [0.1, 0.2, 0.4, 0.9]) ≈ [2.0, 3.0, 5.0, 11.0] @test quantile([4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11], Any[0.1, 0.2, 0.4, 0.9]) ≈ [2.0, 3.0, 5.0, 11.0] @test quantile([4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11], Any[0.1, 0.2, 0.4, 0.9]) isa Vector{Float64} @test quantile(Any[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11], Any[0.1, 0.2, 0.4, 0.9]) ≈ [2, 3, 5, 11] @test quantile(Any[4, 9, 1, 5, 7, 8, 2, 3, 5, 17, 11], Any[0.1, 0.2, 0.4, 0.9]) isa Vector{Float64} @test quantile([1, 2, 3, 4], ()) == () @test isempty(quantile([1, 2, 3, 4], Float64[])) @test quantile([1, 2, 3, 4], Float64[]) isa Vector{Float64} @test quantile([1, 2, 3, 4], []) isa Vector{Any} @test quantile([1, 2, 3, 4], [0, 1]) isa Vector{Int} @test quantile(Any[1, 2, 3], 0.5) isa Float64 @test quantile(Any[1, big(2), 3], 0.5) isa BigFloat @test quantile(Any[1, 2, 3], Float16(0.5)) isa Float16 @test quantile(Any[1, Float16(2), 3], Float16(0.5)) isa Float16 @test quantile(Any[1, big(2), 3], Float16(0.5)) isa BigFloat @test quantile(reshape(1:100, (10, 10)), [0.00, 0.25, 0.50, 0.75, 1.00]) == [1.0, 25.75, 50.5, 75.25, 100.0] # Need a large vector to actually check consequences of partial sorting x = rand(50) for sorted in (false, true) x[10] = NaN @test_throws ArgumentError quantile(x, 0.5, sorted=sorted) x = Vector{Union{Float64, Missing}}(x) x[10] = missing @test_throws ArgumentError quantile(x, 0.5, sorted=sorted) end @test quantile(skipmissing([1, missing, 2]), 0.5) === 1.5 @test quantile([1], 0.5) === 1.0 # make sure that type inference works correctly in normal cases for T in [Int, BigInt, Float64, Float16, BigFloat, Rational{Int}, Rational{BigInt}] for S in [Float64, Float16, BigFloat, Rational{Int}, Rational{BigInt}] @inferred quantile(T[1, 2, 3], S(0.5)) @inferred quantile(T[1, 2, 3], S(0.6)) @inferred quantile(T[1, 2, 3], S[0.5, 0.6]) @inferred quantile(T[1, 2, 3], (S(0.5), S(0.6))) end end x = [3; 2; 1] y = zeros(3) @test quantile!(y, x, [0.1, 0.5, 0.9]) === y @test y ≈ [1.2, 2.0, 2.8] x = reshape(collect(1:100), (10, 10)) y = zeros(5) @test quantile!(y, x, [0.00, 0.25, 0.50, 0.75, 1.00]) === y @test y ≈ [1.0, 25.75, 50.5, 75.25, 100.0] #tests for quantile calculation with configurable alpha and beta parameters v = [2, 3, 4, 6, 9, 2, 6, 2, 21, 17] # tests against scipy.stats.mstats.mquantiles method @test quantile(v, 0.0, alpha=0.0, beta=0.0) ≈ 2.0 @test quantile(v, 0.2, alpha=1.0, beta=1.0) ≈ 2.0 @test quantile(v, 0.4, alpha=0.0, beta=0.0) ≈ 3.4 @test quantile(v, 0.4, alpha=0.0, beta=0.2) ≈ 3.32 @test quantile(v, 0.4, alpha=0.0, beta=0.4) ≈ 3.24 @test quantile(v, 0.4, alpha=0.0, beta=0.6) ≈ 3.16 @test quantile(v, 0.4, alpha=0.0, beta=0.8) ≈ 3.08 @test quantile(v, 0.4, alpha=0.0, beta=1.0) ≈ 3.0 @test quantile(v, 0.4, alpha=0.2, beta=0.0) ≈ 3.52 @test quantile(v, 0.4, alpha=0.2, beta=0.2) ≈ 3.44 @test quantile(v, 0.4, alpha=0.2, beta=0.4) ≈ 3.36 @test quantile(v, 0.4, alpha=0.2, beta=0.6) ≈ 3.28 @test quantile(v, 0.4, alpha=0.2, beta=0.8) ≈ 3.2 @test quantile(v, 0.4, alpha=0.2, beta=1.0) ≈ 3.12 @test quantile(v, 0.4, alpha=0.4, beta=0.0) ≈ 3.64 @test quantile(v, 0.4, alpha=0.4, beta=0.2) ≈ 3.56 @test quantile(v, 0.4, alpha=0.4, beta=0.4) ≈ 3.48 @test quantile(v, 0.4, alpha=0.4, beta=0.6) ≈ 3.4 @test quantile(v, 0.4, alpha=0.4, beta=0.8) ≈ 3.32 @test quantile(v, 0.4, alpha=0.4, beta=1.0) ≈ 3.24 @test quantile(v, 0.4, alpha=0.6, beta=0.0) ≈ 3.76 @test quantile(v, 0.4, alpha=0.6, beta=0.2) ≈ 3.68 @test quantile(v, 0.4, alpha=0.6, beta=0.4) ≈ 3.6 @test quantile(v, 0.4, alpha=0.6, beta=0.6) ≈ 3.52 @test quantile(v, 0.4, alpha=0.6, beta=0.8) ≈ 3.44 @test quantile(v, 0.4, alpha=0.6, beta=1.0) ≈ 3.36 @test quantile(v, 0.4, alpha=0.8, beta=0.0) ≈ 3.88 @test quantile(v, 0.4, alpha=0.8, beta=0.2) ≈ 3.8 @test quantile(v, 0.4, alpha=0.8, beta=0.4) ≈ 3.72 @test quantile(v, 0.4, alpha=0.8, beta=0.6) ≈ 3.64 @test quantile(v, 0.4, alpha=0.8, beta=0.8) ≈ 3.56 @test quantile(v, 0.4, alpha=0.8, beta=1.0) ≈ 3.48 @test quantile(v, 0.4, alpha=1.0, beta=0.0) ≈ 4.0 @test quantile(v, 0.4, alpha=1.0, beta=0.2) ≈ 3.92 @test quantile(v, 0.4, alpha=1.0, beta=0.4) ≈ 3.84 @test quantile(v, 0.4, alpha=1.0, beta=0.6) ≈ 3.76 @test quantile(v, 0.4, alpha=1.0, beta=0.8) ≈ 3.68 @test quantile(v, 0.4, alpha=1.0, beta=1.0) ≈ 3.6 @test quantile(v, 0.6, alpha=0.0, beta=0.0) ≈ 6.0 @test quantile(v, 0.6, alpha=1.0, beta=1.0) ≈ 6.0 @test quantile(v, 0.8, alpha=0.0, beta=0.0) ≈ 15.4 @test quantile(v, 0.8, alpha=0.0, beta=0.2) ≈ 14.12 @test quantile(v, 0.8, alpha=0.0, beta=0.4) ≈ 12.84 @test quantile(v, 0.8, alpha=0.0, beta=0.6) ≈ 11.56 @test quantile(v, 0.8, alpha=0.0, beta=0.8) ≈ 10.28 @test quantile(v, 0.8, alpha=0.0, beta=1.0) ≈ 9.0 @test quantile(v, 0.8, alpha=0.2, beta=0.0) ≈ 15.72 @test quantile(v, 0.8, alpha=0.2, beta=0.2) ≈ 14.44 @test quantile(v, 0.8, alpha=0.2, beta=0.4) ≈ 13.16 @test quantile(v, 0.8, alpha=0.2, beta=0.6) ≈ 11.88 @test quantile(v, 0.8, alpha=0.2, beta=0.8) ≈ 10.6 @test quantile(v, 0.8, alpha=0.2, beta=1.0) ≈ 9.32 @test quantile(v, 0.8, alpha=0.4, beta=0.0) ≈ 16.04 @test quantile(v, 0.8, alpha=0.4, beta=0.2) ≈ 14.76 @test quantile(v, 0.8, alpha=0.4, beta=0.4) ≈ 13.48 @test quantile(v, 0.8, alpha=0.4, beta=0.6) ≈ 12.2 @test quantile(v, 0.8, alpha=0.4, beta=0.8) ≈ 10.92 @test quantile(v, 0.8, alpha=0.4, beta=1.0) ≈ 9.64 @test quantile(v, 0.8, alpha=0.6, beta=0.0) ≈ 16.36 @test quantile(v, 0.8, alpha=0.6, beta=0.2) ≈ 15.08 @test quantile(v, 0.8, alpha=0.6, beta=0.4) ≈ 13.8 @test quantile(v, 0.8, alpha=0.6, beta=0.6) ≈ 12.52 @test quantile(v, 0.8, alpha=0.6, beta=0.8) ≈ 11.24 @test quantile(v, 0.8, alpha=0.6, beta=1.0) ≈ 9.96 @test quantile(v, 0.8, alpha=0.8, beta=0.0) ≈ 16.68 @test quantile(v, 0.8, alpha=0.8, beta=0.2) ≈ 15.4 @test quantile(v, 0.8, alpha=0.8, beta=0.4) ≈ 14.12 @test quantile(v, 0.8, alpha=0.8, beta=0.6) ≈ 12.84 @test quantile(v, 0.8, alpha=0.8, beta=0.8) ≈ 11.56 @test quantile(v, 0.8, alpha=0.8, beta=1.0) ≈ 10.28 @test quantile(v, 0.8, alpha=1.0, beta=0.0) ≈ 17.0 @test quantile(v, 0.8, alpha=1.0, beta=0.2) ≈ 15.72 @test quantile(v, 0.8, alpha=1.0, beta=0.4) ≈ 14.44 @test quantile(v, 0.8, alpha=1.0, beta=0.6) ≈ 13.16 @test quantile(v, 0.8, alpha=1.0, beta=0.8) ≈ 11.88 @test quantile(v, 0.8, alpha=1.0, beta=1.0) ≈ 10.6 @test quantile(v, 1.0, alpha=0.0, beta=0.0) ≈ 21.0 @test quantile(v, 1.0, alpha=1.0, beta=1.0) ≈ 21.0 end # StatsBase issue 164 let y = [0.40003674665581906, 0.4085630862624367, 0.41662034698690303, 0.41662034698690303, 0.42189053966652057, 0.42189053966652057, 0.42553514344518345, 0.43985732442991354] @test issorted(quantile(y, range(0.01, stop=0.99, length=17))) end @testset "issue #144: no overflow with quantile" begin @test quantile(Float16[-9000, 100], 1.0) ≈ 100 @test quantile(Float16[-9000, 100], 0.999999999) ≈ 99.99999 @test quantile(Float32[-1e9, 100], 1) ≈ 100 @test quantile(Float32[-1e9, 100], 0.9999999999) ≈ 99.89999998 @test quantile(Float64[-1e20, 100], 1) ≈ 100 @test quantile(Float32[-1e15, -1e14, -1e13, -1e12, -1e11, -1e10, -1e9, 100], 1) ≈ 100 @test quantile(Int8[-68, 60], 0.5) ≈ -4 @test quantile(Int32[-1e9, 2e9], 1.0) ≈ 2.0e9 @test quantile(Int64[-5e18, -2e18, 9e18], 1.0) ≈ 9.0e18 # check that quantiles are increasing with a, b and p even in corner cases @test issorted(quantile([1.0, 1.0, 1.0+eps(), 1.0+eps()], range(0, 1, length=100))) @test issorted(quantile([1.0, 1.0+1eps(), 1.0+2eps(), 1.0+3eps()], range(0, 1, length=100))) @test issorted(quantile([1.0, 1.0+2eps(), 1.0+4eps(), 1.0+6eps()], range(0, 1, length=100))) end @testset "quantiles with Date and DateTime" begin # this is the historical behavior @test quantile([Date(2023, 09, 02)], .1) == Date(2023, 09, 02) @test quantile([Date(2023, 09, 02), Date(2023, 09, 02)], .1) == Date(2023, 09, 02) @test_throws InexactError quantile([Date(2023, 09, 02), Date(2023, 09, 03)], .1) @test quantile([DateTime(2023, 09, 02)], .1) == DateTime(2023, 09, 02) @test quantile([DateTime(2023, 09, 02), DateTime(2023, 09, 02)], .1) == DateTime(2023, 09, 02) @test_throws InexactError quantile([DateTime(2023, 09, 02), DateTime(2023, 09, 03)], .1) end @testset "variance of complex arrays (#13309)" begin z = rand(ComplexF64, 10) @test var(z) ≈ invoke(var, Tuple{Any}, z) ≈ cov(z) ≈ var(z,dims=1)[1] ≈ sum(abs2, z .- mean(z))/9 @test isa(var(z), Float64) @test isa(invoke(var, Tuple{Any}, z), Float64) @test isa(cov(z), Float64) @test isa(var(z,dims=1), Vector{Float64}) @test varm(z, 0.0) ≈ invoke(varm, Tuple{Any,Float64}, z, 0.0) ≈ sum(abs2, z)/9 @test isa(varm(z, 0.0), Float64) @test isa(invoke(varm, Tuple{Any,Float64}, z, 0.0), Float64) @test cor(z) === 1.0+0.0im v = varm([1.0+2.0im], 0; corrected = false) @test v ≈ 5 @test isa(v, Float64) end @testset "cov and cor of complex arrays (issue #21093)" begin x = [2.7 - 3.3im, 0.9 + 5.4im, 0.1 + 0.2im, -1.7 - 5.8im, 1.1 + 1.9im] y = [-1.7 - 1.6im, -0.2 + 6.5im, 0.8 - 10.0im, 9.1 - 3.4im, 2.7 - 5.5im] @test cov(x, y) ≈ 4.8365 - 12.119im @test cov(y, x) ≈ 4.8365 + 12.119im @test cov(x, reshape(y, :, 1)) ≈ reshape([4.8365 - 12.119im], 1, 1) @test cov(reshape(x, :, 1), y) ≈ reshape([4.8365 - 12.119im], 1, 1) @test cov(reshape(x, :, 1), reshape(y, :, 1)) ≈ reshape([4.8365 - 12.119im], 1, 1) @test cov([x y]) ≈ [21.779 4.8365-12.119im; 4.8365+12.119im 54.548] @test cor(x, y) ≈ 0.14032104449218274 - 0.35160772008699703im @test cor(y, x) ≈ 0.14032104449218274 + 0.35160772008699703im @test cor(x, reshape(y, :, 1)) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1) @test cor(reshape(x, :, 1), y) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1) @test cor(reshape(x, :, 1), reshape(y, :, 1)) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1) @test cor([x y]) ≈ [1.0 0.14032104449218274-0.35160772008699703im 0.14032104449218274+0.35160772008699703im 1.0] end @testset "Issue #17153 and PR #17154" begin a = rand(10,10) b = copy(a) x = median(a, dims=1) @test b == a x = median(a, dims=2) @test b == a x = mean(a, dims=1) @test b == a x = mean(a, dims=2) @test b == a x = var(a, dims=1) @test b == a x = var(a, dims=2) @test b == a x = std(a, dims=1) @test b == a x = std(a, dims=2) @test b == a end # dimensional correctness const BASE_TEST_PATH = joinpath(Sys.BINDIR, "..", "share", "julia", "test") isdefined(Main, :Furlongs) || @eval Main include(joinpath($(BASE_TEST_PATH), "testhelpers", "Furlongs.jl")) using .Main.Furlongs Statistics.middle(x::Furlong{p}) where {p} = Furlong{p}(middle(x.val)) Statistics.middle(x::Furlong{p}, y::Furlong{p}) where {p} = Furlong{p}(middle(x.val, y.val)) @testset "Unitful elements" begin r = Furlong(1):Furlong(1):Furlong(2) a = Vector(r) @test sum(r) == sum(a) == Furlong(3) @test cumsum(r) == Furlong.([1,3]) @test mean(r) == mean(a) == median(a) == median(r) == Furlong(1.5) @test var(r) == var(a) == Furlong{2}(0.5) @test std(r) == std(a) == Furlong{1}(sqrt(0.5)) # Issue #21786 A = [Furlong{1}(rand(-5:5)) for i in 1:2, j in 1:2] @test mean(mean(A, dims=1), dims=2)[1] === mean(A) @test var(A, dims=1)[1] === var(A[:, 1]) @test std(A, dims=1)[1] === std(A[:, 1]) end # Issue #22901 @testset "var and quantile of Any arrays" begin x = Any[1, 2, 4, 10] y = Any[1, 2, 4, 10//1] @test var(x) === 16.25 @test var(y) === 16.25 @test std(x) === sqrt(16.25) @test quantile(x, 0.5) === 3.0 @test quantile(x, 1//2) === 3//1 end @testset "Promotion in covzm. Issue #8080" begin A = [1 -1 -1; -1 1 1; -1 1 -1; 1 -1 -1; 1 -1 1] @test Statistics.covzm(A) - mean(A, dims=1)'*mean(A, dims=1)*size(A, 1)/(size(A, 1) - 1) ≈ cov(A) A = [1//1 -1 -1; -1 1 1; -1 1 -1; 1 -1 -1; 1 -1 1] @test (A'A - size(A, 1)*mean(A, dims=1)'*mean(A, dims=1))/4 == cov(A) end @testset "Mean along dimension of empty array" begin a0 = zeros(0) a00 = zeros(0, 0) a01 = zeros(0, 1) a10 = zeros(1, 0) @test isequal(mean(a0, dims=1) , fill(NaN, 1)) @test isequal(mean(a00, dims=(1, 2)), fill(NaN, 1, 1)) @test isequal(mean(a01, dims=1) , fill(NaN, 1, 1)) @test isequal(mean(a10, dims=2) , fill(NaN, 1, 1)) end @testset "cov/var/std of Vector{Vector}" begin x = [[2,4,6],[4,6,8]] @test var(x) ≈ vec(var([x[1] x[2]], dims=2)) @test std(x) ≈ vec(std([x[1] x[2]], dims=2)) @test cov(x) ≈ cov([x[1] x[2]], dims=2) end @testset "var of sparse array" begin se33 = SparseMatrixCSC{Float64}(I, 3, 3) sA = sprandn(3, 7, 0.5) pA = sparse(rand(3, 7)) for arr in (se33, sA, pA) farr = Array(arr) @test var(arr) ≈ var(farr) @test var(arr, dims=1) ≈ var(farr, dims=1) @test var(arr, dims=2) ≈ var(farr, dims=2) @test var(arr, dims=(1, 2)) ≈ [var(farr)] @test isequal(var(arr, dims=3), var(farr, dims=3)) end @testset "empty cases" begin @test var(sparse(Int[])) === NaN @test isequal(var(spzeros(0, 1), dims=1), var(Matrix{Int}(I, 0, 1), dims=1)) @test isequal(var(spzeros(0, 1), dims=2), var(Matrix{Int}(I, 0, 1), dims=2)) @test isequal(var(spzeros(0, 1), dims=(1, 2)), var(Matrix{Int}(I, 0, 1), dims=(1, 2))) @test isequal(var(spzeros(0, 1), dims=3), var(Matrix{Int}(I, 0, 1), dims=3)) end end # Faster covariance function for sparse matrices # Prevents densifying the input matrix when subtracting the mean # Test against dense implementation # PR https://github.com/JuliaLang/julia/pull/22735 # Part of this test needed to be hacked due to the treatment # of Inf in sparse matrix algebra # https://github.com/JuliaLang/julia/issues/22921 # The issue will be resolved in # https://github.com/JuliaLang/julia/issues/22733 @testset "optimizing sparse $elty covariance" for elty in (Float64, Complex{Float64}) n = 10 p = 5 np2 = div(n*p, 2) nzvals, x_sparse = guardseed(1) do if elty <: Real nzvals = randn(np2) else nzvals = complex.(randn(np2), randn(np2)) end nzvals, sparse(rand(1:n, np2), rand(1:p, np2), nzvals, n, p) end x_dense = convert(Matrix{elty}, x_sparse) @testset "Test with no Infs and NaNs, vardim=$vardim, corrected=$corrected" for vardim in (1, 2), corrected in (true, false) @test cov(x_sparse, dims=vardim, corrected=corrected) ≈ cov(x_dense , dims=vardim, corrected=corrected) end @testset "Test with $x11, vardim=$vardim, corrected=$corrected" for x11 in (NaN, Inf), vardim in (1, 2), corrected in (true, false) x_sparse[1,1] = x11 x_dense[1 ,1] = x11 cov_sparse = cov(x_sparse, dims=vardim, corrected=corrected) cov_dense = cov(x_dense , dims=vardim, corrected=corrected) @test cov_sparse[2:end, 2:end] ≈ cov_dense[2:end, 2:end] @test isfinite.(cov_sparse) == isfinite.(cov_dense) @test isfinite.(cov_sparse) == isfinite.(cov_dense) end @testset "Test with NaN and Inf, vardim=$vardim, corrected=$corrected" for vardim in (1, 2), corrected in (true, false) x_sparse[1,1] = Inf x_dense[1 ,1] = Inf x_sparse[2,1] = NaN x_dense[2 ,1] = NaN cov_sparse = cov(x_sparse, dims=vardim, corrected=corrected) cov_dense = cov(x_dense , dims=vardim, corrected=corrected) @test cov_sparse[(1 + vardim):end, (1 + vardim):end] ≈ cov_dense[ (1 + vardim):end, (1 + vardim):end] @test isfinite.(cov_sparse) == isfinite.(cov_dense) @test isfinite.(cov_sparse) == isfinite.(cov_dense) end end @testset "var, std, cov and cor on empty inputs" begin @test isnan(var(Int[])) @test isnan(std(Int[])) @test isequal(cov(Int[]), -0.0) @test isequal(cor(Int[]), 1.0) @test_throws ArgumentError cov(Int[], Int[]) @test_throws ArgumentError cor(Int[], Int[]) mx = Matrix{Int}(undef, 0, 2) my = Matrix{Int}(undef, 0, 3) @test isequal(var(mx, dims=1), fill(NaN, 1, 2)) @test isequal(std(mx, dims=1), fill(NaN, 1, 2)) @test isequal(var(mx, dims=2), fill(NaN, 0, 1)) @test isequal(std(mx, dims=2), fill(NaN, 0, 1)) @test isequal(cov(mx, my), fill(-0.0, 2, 3)) @test isequal(cor(mx, my), fill(NaN, 2, 3)) @test isequal(cov(my, mx, dims=1), fill(-0.0, 3, 2)) @test isequal(cor(my, mx, dims=1), fill(NaN, 3, 2)) @test isequal(cov(mx, Int[]), fill(-0.0, 2, 1)) @test isequal(cor(mx, Int[]), fill(NaN, 2, 1)) @test isequal(cov(Int[], my), fill(-0.0, 1, 3)) @test isequal(cor(Int[], my), fill(NaN, 1, 3)) end
Statistics
https://github.com/JuliaStats/Statistics.jl.git
[ "MIT" ]
1.11.1
ae3bb1eb3bba077cd276bc5cfc337cc65c3075c0
docs
1166
# Statistics.jl [![Build status](https://github.com/JuliaStats/Statistics.jl/workflows/CI/badge.svg)](https://github.com/JuliaStats/Statistics.jl/actions?query=workflow%3ACI+branch%3Amaster) Development repository for the Statistics standard library (stdlib) that ships with Julia. #### Using the development version of Statistics.jl If you want to develop this package, do the following steps: - Clone the repo anywhere. - In line 2 of the `Project.toml` file (the line that begins with `uuid = ...`), modify the UUID, e.g. change the `107` to `207`. - Change the current directory to the Statistics repo you just cloned and start julia with `julia --project`. - `import Statistics` will now load the files in the cloned repo instead of the Statistics stdlib. - To test your changes, simply do `include("test/runtests.jl")`. If you need to build Julia from source with a git checkout of Statistics, then instead use `make DEPS_GIT=Statistics` when building Julia. The `Statistics` repo is in `stdlib/Statistics`, and created initially with a detached `HEAD`. If you're doing this from a pre-existing Julia repository, you may need to `make clean` beforehand.
Statistics
https://github.com/JuliaStats/Statistics.jl.git
[ "MIT" ]
1.11.1
ae3bb1eb3bba077cd276bc5cfc337cc65c3075c0
docs
186
# Statistics The Statistics standard library module contains basic statistics functionality. ```@docs std stdm var varm cor cov mean! mean median! median middle quantile! quantile ```
Statistics
https://github.com/JuliaStats/Statistics.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
1741
using Documenter using QuantumCircuitOpt using DocumenterTools: Themes for w in ("light", "dark") header = read(joinpath(@__DIR__, "src/assets/themes/style.scss"), String) theme = read(joinpath(@__DIR__, "src/assets/themes/$(w)defs.scss"), String) write(joinpath(@__DIR__, "src/assets/themes/$(w).scss"), header*"\n"*theme) end Themes.compile( joinpath(@__DIR__, "src/assets/themes/documenter-light.css"), joinpath(@__DIR__, "src/assets/themes/light.scss"), ) Themes.compile( joinpath(@__DIR__, "src/assets/themes/documenter-dark.css"), joinpath(@__DIR__, "src/assets/themes/dark.scss"), ) makedocs( modules = [QuantumCircuitOpt], sitename = "QuantumCircuitOpt.jl", format = Documenter.HTML(mathengine = Documenter.MathJax(), assets = [asset("https://fonts.googleapis.com/css?family=Montserrat|Source+Code+Pro&display=swap", class=:css), "assets/extra_styles.css"], prettyurls = get(ENV, "CI", nothing) == "true", sidebar_sitename=false ), # strict = true, authors = "Harsha Nagarajan", pages = [ "Introduction" => "index.md", "Quick Start guide" => "quickguide.md", "Quantum Gates Library" => [ "1-qubit gates" => "1_qubit_gates.md", "2-qubit gates" => "2_qubit_gates.md", "3-qubit gates" => "3_qubit_gates.md", "Multi-qubit gates" => "multi_qubit_gates.md", ], "Function References" => "function_references.md", ], ) deploydocs( repo = "github.com/harshangrjn/QuantumCircuitOpt.jl.git", push_preview = true )
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
12497
function hadamard() println(">>>>> Hadamard Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 3, "elementary_gates" => ["U3_1", "CNot_1_2", "Identity"], "target_gate" => QCOpt.get_unitary("H_1", 2), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => [0, π/2], "U3_ϕ_discretization" => [0, π/2], "U3_λ_discretization" => [0, π], ) end function controlled_Z() println(">>>>> Controlled-Z Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 4, "elementary_gates" => ["U3_1", "U3_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.CZGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -π:π/2:π, "U3_ϕ_discretization" => -π:π/2:π, "U3_λ_discretization" => -π:π/2:π, ) end function controlled_V() println(">>>>> Controlled-V Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 7, "elementary_gates" => ["H_1", "H_2", "T_1", "T_2", "Tdagger_1", "Tdagger_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCOpt.CVGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", ) end function controlled_H() println(">>>>> Controlled-H Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["U3_1", "U3_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCOpt.CHGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -2*π:π/4:2*π, "U3_ϕ_discretization" => [0], "U3_λ_discretization" => [0], ) end function controlled_H_with_R() println(">>>>> Controlled-H with R Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["RY_1", "RY_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.CHGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "RY_discretization" => [-π/4, π/4, π/2, -π/2], "set_cnot_lower_bound" => 1, "set_cnot_upper_bound" => 2, ) end function magic() println(">>>>> M Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 4, "elementary_gates" => ["U3_1", "U3_2", "CNot_2_1", "CNot_1_2", "Identity"], "target_gate" => QCOpt.MGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -π:π/2:π, "U3_ϕ_discretization" => -π:π/2:π, "U3_λ_discretization" => -π:π/2:π, ) end function magic_using_CNOT_1_2() println(">>>>> M Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["U3_1", "U3_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.MGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -π:π/2:π, "U3_ϕ_discretization" => -π:π:π, "U3_λ_discretization" => -π:π/2:π, ) end function magic_using_SHCnot() println(">>>>> M gate using S, H and CNOT Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["S_1", "S_2", "H_1", "H_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCOpt.MGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) end function S_using_U3() println(">>>>> S Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 3, "elementary_gates" => ["U3_1", "U3_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.get_unitary("S_1", 2), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => [0, π/4, π/2], "U3_ϕ_discretization" => [-π/2, 0, π/2], "U3_λ_discretization" => [0, π], ) end function revcnot() println(">>>>> Reverse CNOT Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["H_1", "H_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.CNotRevGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) end function revcnot_with_U() println(">>>>> Reverse CNOT using U3 and CNOT Gates <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["U3_1", "U3_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.CNotRevGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -π:π/4:π, "U3_ϕ_discretization" => [0], "U3_λ_discretization" => [0], ) end function swap() println(">>>>> SWAP Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["CNot_2_1", "CNot_1_2", "Identity"], "target_gate" => QCOpt.SwapGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", ) end function W_using_U3() println(">>>>> W Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["U3_2", "CNot_2_1", "CNot_1_2", "Identity"], "target_gate" => QCOpt.WGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => [-π/4, 0, π/4], "U3_ϕ_discretization" => [0, π/4], "U3_λ_discretization" => [0, π/2], ) end function W_using_HSTCnot() println(">>>>> W Gate using H, S, T and CNOT gates <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 11, "elementary_gates" => ["S_1", "S_2", "Sdagger_1", "Sdagger_2", "T_1", "T_2", "Tdagger_1", "Tdagger_2", "H_1", "H_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.WGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", ) end function W_using_HCnot() println(">>>>> W Gate using H and CNOT gates <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 6, "elementary_gates" => ["CH_1_2", "CNot_2_1", "CNot_1_2", "Identity"], "target_gate" => QCOpt.WGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", ) end function hadamard_coin() println(">>>>> Hadamard Coin gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 12, "elementary_gates" => ["Y_1", "Y_2", "Z_1", "Z_2", "T_2", "Tdagger_1", "Sdagger_1", "SX_1", "SXdagger_2", "CNot_2_1", "CNot_1_2", "Identity"], "target_gate" => QCOpt.HCoinGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_feasible", ) end function GroverDiffusion_using_HX() println(">>>>> Grover's Diffusion Operator <<<<<") return Dict{String, Any}( #Reference: https://arxiv.org/pdf/1804.03719.pdf (Fig 6) "num_qubits" => 2, "maximum_depth" => 10, "elementary_gates" => ["X_1", "X_1xX_2", "H_1xH_2", "X_2", "H_1", "H_2", "CNot_1_2", "Identity"], # "elementary_gates" => ["X_1", "X_2", "H_1", "H_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.GroverDiffusionGate(), "objective" => "minimize_depth", "decomposition_type" => "optimal_global_phase", ) end function GroverDiffusion_using_Clifford() println(">>>>> Grover's Diffusion Operator <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 6, "elementary_gates" => ["X_1", "X_2", "H_1", "H_2", "S_1", "S_2", "T_1", "T_2", "Y_1", "Y_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.GroverDiffusionGate(), "objective" => "minimize_depth", "decomposition_type" => "optimal_global_phase", ) end function GroverDiffusion_using_U3() println(">>>>> Grover's Diffusion Operator using U3 gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 10, "elementary_gates" => ["U3_1", "CNot_1_2", "Identity"], "target_gate" => QCOpt.GroverDiffusionGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -π:π/2:π, "U3_ϕ_discretization" => -π:π/2:π, "U3_λ_discretization" => [0], ) end function iSwap() println(">>>>> iSwap Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 10, "elementary_gates" => ["T_1", "T_2", "Tdagger_1", "Tdagger_2", "H_1", "H_2", "CNot_1_2", "CNot_2_1", "Identity"], # "elementary_gates" => ["S_1", "S_2", "Sdagger_1", "Sdagger_2", "H_1", "H_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCOpt.iSwapGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", ) end function qft2_using_R() println(">>>>> QFT2 Gate using R and CNOT gates <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 10, "elementary_gates" => ["RX_1", "RZ_1", "RZ_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCOpt.QFT2Gate(), "objective" => "minimize_depth", "decomposition_type" => "exact_feasible", "RX_discretization" => [π/2], "RZ_discretization" => [-π/4, π/2, 3*π/4, 7*π/4], ) end function qft2_using_HT() println(">>>>> QFT2 Gate using H, T, CNOT gates <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 8, "elementary_gates" => ["H_1", "H_2", "T_1", "T_2", "Tdagger_1", "Tdagger_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCOpt.QFT2Gate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", ) end function GR_using_R() println(">>>>> GRGate testing <<<<<") GR1 = QCOpt.get_unitary("GR", 2; angle = [π/6, π/3]) # GR2 = QCOpt.get_unitary("GR", 2; angle = [π/3, π/6]) CNot_1_2 = QCOpt.get_unitary("CNot_1_2", 2) T = QCOpt.round_complex_values(GR1 * CNot_1_2) return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 3, "elementary_gates" => ["R_1", "R_2", "CNot_1_2", "Identity"], "R_θ_discretization" => [π/3, π/6], "R_ϕ_discretization" => [π/3, π/6], "target_gate" => T, "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", ) end function X_using_GR() println(">>>>> Pauli-X Gate using global rotation <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["GR", "R_1", "R_2", "CZ_1_2", "Identity"], "target_gate" => QCOpt.get_unitary("X_1", 2), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "GR_θ_discretization" => [-π, -π/2, 0, π/2, π], "GR_ϕ_discretization" => [0], # "RZ_discretization" => [-π, -π/2, 0, π/2, π], "R_θ_discretization" => [π/2, π], "R_ϕ_discretization" => [π/2], ) end function CNOT_using_GR() println(">>>>> CNOT Gate using global rotation <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["GR", "R_1", "R_2", "CZ_1_2", "Identity"], "target_gate" => QCOpt.CNotGate(), "objective" => "minimize_depth", "decomposition_type" => "optimal_global_phase", "GR_θ_discretization" => -2π:π/2:2π, "GR_ϕ_discretization" => [0], "R_θ_discretization" => 0:π/4:π, "R_ϕ_discretization" => [π/2], ) end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
8411
function RX_on_q3() println(">>>>> RX Gate on third qubit using U3Gate <<<<<") return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 3, "elementary_gates" => ["U3_3", "Identity"], "target_gate" => QCOpt.kron_single_qubit_gate(3, QCOpt.RXGate(π/4), "q3"), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => [0, π/4], "U3_ϕ_discretization" => [0, -π/2], "U3_λ_discretization" => [0, π/2], ) end function toffoli() function toffoli_circuit() # [(depth, gate)] return [(1, "T_1"), (2, "T_2"), (3, "H_3"), (4, "CNot_2_3"), (5, "Tdagger_3"), (6, "CNot_1_3"), (7, "T_3"), (8, "CNot_2_3"), (9, "Tdagger_3"), (10, "CNot_1_3"), (11, "T_3"), (12, "H_3"), (13, "CNot_1_2"), (14, "Tdagger_2"), (15, "CNot_1_2") ] end println(">>>>> Toffoli gate <<<<<") return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 15, "elementary_gates" => ["T_1", "T_2", "T_3", "H_3", "CNot_1_2", "CNot_1_3", "CNot_2_3", "Tdagger_1", "Tdagger_2", "Tdagger_3", "Identity"], "target_gate" => QCOpt.ToffoliGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "input_circuit" => toffoli_circuit(), "set_cnot_lower_bound" => 6, "set_cnot_upper_bound" => 6, ) end function toffoli_using_kronecker() println(">>>>> Toffoli gate using Kronecker <<<<<") return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 12, "elementary_gates" => ["T_3", "H_3", "CNot_1_2", "CNot_1_3", "CNot_2_3", "Tdagger_3", "I_1xT_2xT_3", "CNot_1_2xH_3", "T_1xTdagger_2xI_3", "Identity"], "target_gate" => QCOpt.ToffoliGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "set_cnot_lower_bound" => 6, ) end function toffoli_using_2qubit_gates() # Reference: https://doi.org/10.1109/TCAD.2005.858352 println(">>>>> Toffoli gate with controlled gates <<<<<") return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 5, "elementary_gates" => ["CV_1_3", "CV_2_3", "CV_1_2", "CVdagger_1_3", "CVdagger_2_3", "CVdagger_1_2", "CNot_2_1", "CNot_1_2", "Identity"], "target_gate" => QCOpt.ToffoliGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", ) end function CNot_1_3() return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 8, # "elementary_gates" => ["CNot_1_2", "CNot_2_3", "Identity"], "elementary_gates" => ["H_1", "H_3", "H_2", "CNot_2_1", "CNot_3_2", "Identity"], "target_gate" => QCOpt.get_unitary("CNot_1_3", 3), "objective" => "minimize_depth", ) end function fredkin() return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 7, # Reference: https://doi.org/10.1103/PhysRevA.53.2855 "elementary_gates" => ["CV_1_2", "CV_2_3", "CV_1_3", "CVdagger_1_2", "CVdagger_2_3", "CVdagger_1_3", "CNot_1_2", "CNot_3_2", "CNot_2_3", "CNot_1_3", "Identity"], "target_gate" => QCOpt.CSwapGate(), #also Fredkin "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) end function fredkin_using_SSwap() return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 8, "elementary_gates" => ["SSwap_2_3", "SX_1", "SX_2", "SX_3", "H_1", "H_2", "H_3", "CNot_1_2", "CNot_3_2", "CNot_2_3", "CNot_1_3", "Identity"], "target_gate" => QCOpt.CSwapGate(), #also Fredkin "decomposition_type" => "exact_optimal", "objective" => "minimize_depth" ) end function toffoli_left() # Reference: https://arxiv.org/pdf/0803.2316.pdf function target_gate() H_3 = QCOpt.get_unitary("H_3", 3) Tdagger_3 = QCOpt.get_unitary("Tdagger_3", 3) T_3 = QCOpt.get_unitary("T_3", 3) cnot_23 = QCOpt.get_unitary("CNot_2_3", 3) CNot_1_3 = QCOpt.get_unitary("CNot_1_3", 3) return H_3 * cnot_23 * Tdagger_3 * CNot_1_3 * T_3 * cnot_23 * Tdagger_3 end return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 7, "elementary_gates" => ["H_3", "T_1", "T_2", "T_3", "Tdagger_1", "Tdagger_2", "Tdagger_3", "CNot_1_2", "CNot_2_3", "CNot_1_3", "Identity"], "target_gate" => target_gate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) end function toffoli_right() # Reference: https://arxiv.org/pdf/0803.2316.pdf function target_gate() H_3 = QCOpt.get_unitary("H_3", 3) Tdagger_2 = QCOpt.get_unitary("Tdagger_2", 3) T_1 = QCOpt.get_unitary("T_1", 3) T_2 = QCOpt.get_unitary("T_2", 3) T_3 = QCOpt.get_unitary("T_3", 3) CNot_1_2 = QCOpt.get_unitary("CNot_1_2", 3) CNot_1_3 = QCOpt.get_unitary("CNot_1_3", 3) return CNot_1_3 * T_2 * T_3 * CNot_1_2 * H_3 * T_1 * Tdagger_2 * CNot_1_2 end return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 8, "elementary_gates" => ["H_3", "T_1", "T_2", "T_3", "Tdagger_1", "Tdagger_2", "Tdagger_3", "CNot_1_2", "CNot_2_3", "CNot_1_3", "Identity"], "target_gate" => target_gate(), "objective" => "minimize_depth" ) end function miller() # Reference: https://doi.org/10.1109/TCAD.2005.858352 function target_gate() CV_1_3 = QCOpt.get_unitary("CV_1_3", 3) CV_2_3 = QCOpt.get_unitary("CV_2_3", 3) CVdagger_2_3 = QCOpt.get_unitary("CVdagger_2_3", 3) CNot_1_2 = QCOpt.get_unitary("CNot_1_2", 3) CNot_3_1 = QCOpt.get_unitary("CNot_3_1", 3) CNot_3_2 = QCOpt.get_unitary("CNot_3_2", 3) return CNot_3_1 * CNot_3_2 * CV_2_3 * CNot_1_2 * CVdagger_2_3 * CV_1_3 * CNot_3_1 * CNot_1_2 end return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 8, "elementary_gates" => ["CV_1_3", "CV_2_3", "CVdagger_2_3", "CNot_1_2", "CNot_3_1", "CNot_3_2", "Identity"], "target_gate" => target_gate(), "objective" => "minimize_depth" ) end function relative_toffoli() #Reference: https://arxiv.org/pdf/1508.03273.pdf return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 9, "elementary_gates" => ["H_3", "T_3", "Tdagger_3", "CNot_1_2", "CNot_2_3", "CNot_1_3", "Identity"], "target_gate" => QCOpt.RCCXGate(), "objective" => "minimize_depth", "set_cnot_upper_bound" => 3 ) end function margolus() #Reference: https://arxiv.org/pdf/quant-ph/0312225.pdf return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 7, "elementary_gates" => ["RY_3", "CNot_1_2", "CNot_2_3", "CNot_1_3", "Identity"], "target_gate" => QCOpt.MargolusGate(), "objective" => "minimize_depth", "RY_discretization" => -π:π/4:π, # "set_cnot_lower_bound" => 3, # "set_cnot_upper_bound" => 3 ) end function CiSwap() #Reference: https://doi.org/10.1103/PhysRevResearch.2.033097 return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 12, "elementary_gates" => ["H_3", "T_3", "Tdagger_3", "CNot_3_2", "CNot_2_3", "CNot_1_3", "Identity"], "target_gate" => QCOpt.CiSwapGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", ) end function QFT3() # QFT3 circuit using Controlled-Phase gates return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 7, # "elementary_gates" => ["H_1", "H_2", "H_3", "CS_2_1", "CS_3_2", "CT_3_1", "Swap_1_3", "Identity"], "elementary_gates" => ["H_1", "H_2", "H_3", "CU3_2_1", "CU3_3_2", "CU3_3_1", "Swap_1_3", "Identity"], "CU3_θ_discretization" => [0], "CU3_ϕ_discretization" => [0], "CU3_λ_discretization" => [π/2, π/4], "target_gate" => QCOpt.QFT3Gate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", ) end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
3393
function CNot_41() # Reference: https://doi.org/10.1109/DSD.2018.00005 return Dict{String, Any}( "num_qubits" => 4, "maximum_depth" => 10, "elementary_gates" => ["H_1", "H_2", "H_3", "CNot_1_3", "CNot_4_3", "Identity"], "target_gate" => QCOpt.get_unitary("CNot_4_1", 4), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) end function quantum_fulladder() #Reference-1: https://doi.org/10.1109/DATE.2005.249 #Reference-2: https://doi.org/10.1109/TCAD.2005.858352 num_qubits = 4 function target_gate_1() CV_1_2 = QCOpt.get_unitary("CV_1_2", num_qubits); CV_4_2 = QCOpt.get_unitary("CV_4_2", num_qubits); CVdagger_1_2 = QCOpt.get_unitary("CVdagger_1_2", num_qubits); CVdagger_3_2 = QCOpt.get_unitary("CVdagger_3_2", num_qubits); CNot_3_1 = QCOpt.get_unitary("CNot_3_1", num_qubits); CNot_4_3 = QCOpt.get_unitary("CNot_4_3", num_qubits); CNot_2_4 = QCOpt.get_unitary("CNot_2_4", num_qubits); return CNot_2_4 * CV_4_2 * CVdagger_1_2 * CVdagger_3_2 * CNot_4_3 * CNot_3_1 * CV_1_2 end return Dict{String, Any}( "num_qubits" => num_qubits, "maximum_depth" => 7, "elementary_gates" => ["CV_1_2", "CV_4_2", "CV_3_2", "CVdagger_1_2", "CVdagger_4_2", "CVdagger_3_2", "CNot_3_1", "CNot_4_3", "CNot_2_4", "CNot_4_1", "Identity"], "target_gate" => target_gate_1(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) end function double_toffoli() # Reference: https://doi.org/10.1109/TCAD.2005.858352 num_qubits = 4 function target_gate() CV_3_4 = QCOpt.get_unitary("CV_3_4", num_qubits); CV_2_4 = QCOpt.get_unitary("CV_2_4", num_qubits); CVdagger_2_4 = QCOpt.get_unitary("CVdagger_2_4", num_qubits); CNot_1_3 = QCOpt.get_unitary("CNot_1_3", num_qubits); CNot_3_2 = QCOpt.get_unitary("CNot_3_2", num_qubits); return CV_2_4 * CNot_1_3 * CNot_3_2 * CV_3_4 * CVdagger_2_4 * CNot_3_2 * CNot_1_3 end return Dict{String, Any}( "num_qubits" => 4, "maximum_depth" => 7, "elementary_gates" => ["CV_1_2", "CV_2_4", "CV_3_4", "CVdagger_1_2", "CVdagger_2_4", "CVdagger_3_4", "CNot_1_3", "CNot_3_2", "CNot_2_3", "Identity"], "target_gate" => target_gate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) end function double_peres() # Reference: https://doi.org/10.1109/TCAD.2005.858352 num_qubits = 4 function target_gate() CV_1_4 = QCOpt.get_unitary("CV_1_4", num_qubits); CV_2_4 = QCOpt.get_unitary("CV_2_4", num_qubits); CV_3_4 = QCOpt.get_unitary("CV_3_4", num_qubits); CVdagger_3_4 = QCOpt.get_unitary("CVdagger_3_4", num_qubits); CNot_1_2 = QCOpt.get_unitary("CNot_1_2", num_qubits); CNot_2_3 = QCOpt.get_unitary("CNot_2_3", num_qubits); return CV_2_4 * CNot_1_2 * CV_3_4 * CV_1_4 * CNot_2_3 * CVdagger_3_4 end return Dict{String, Any}( "num_qubits" => 4, "maximum_depth" => 7, "elementary_gates" => ["CV_1_4", "CV_2_4", "CV_3_4", "CVdagger_1_4", "CVdagger_2_4", "CVdagger_3_4", "CNot_1_2", "CNot_2_3", "Identity"], "target_gate" => target_gate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
592
function RX_on_5qubits() println(">>>>> RX Gate on fourth qubit using U3Gate <<<<<") return Dict{String, Any}( "num_qubits" => 5, "maximum_depth" => 3, "elementary_gates" => ["H_1xCNot_2_3xI_4xI_5", "RX_2", "CU3_3_4", "Identity"], "target_gate" => QCOpt.kron_two_qubit_gate(5, QCOpt.CRXGate(π/4), "q3", "q4"), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "CU3_θ_discretization" => [0, π/4], "CU3_ϕ_discretization" => [0, -π/2], "CU3_λ_discretization" => [0, π/2], "RX_discretization" => [π/2], ) end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
1094
decompose_gates = [ #-- 2-qubit gates --# "hadamard", "controlled_Z", "controlled_V", "controlled_H", "controlled_H_with_R", "magic", "magic_using_CNOT_1_2", "magic_using_SHCnot", "S_using_U3", "revcnot", "revcnot_with_U", "swap", "W_using_U3", "W_using_HCnot", "GroverDiffusion_using_Clifford", "GroverDiffusion_using_U3", "iSwap", "qft2_using_HT", "RX_on_q3", "X_using_GR", "CNOT_using_GR", #-- 3-qubit gates --# "toffoli_using_2qubit_gates", "CNot_1_3", "fredkin", "toffoli_left", "toffoli_right", "miller", "relative_toffoli", "margolus", "CiSwap", # up to 1000s #-- 4-qubit gates --# "CNot_41", "double_peres", "quantum_fulladder", "double_toffoli", #-- 5-qubit gates --# "RX_on_5qubits", #-- paramterized gates --# "parametrized_hermitian_gates" ]
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
8103
#= Settings for results in the paper "QuantumCircuitOpt: An Open-source Frameworkfor Provably Optimal Quantum Circuit Design" Version of QCOpt: v0.3.0 Last updated: Oct 12, 2021 =# function controlled_Z() println(">>>>> Controlled-Z Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 4, "elementary_gates" => ["U3_1", "U3_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.CZGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -π:π/2:π, "U3_ϕ_discretization" => -π:π/2:π, "U3_λ_discretization" => -π:π/2:π,) end function controlled_V() println(">>>>> Controlled-V Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 7, "elementary_gates" => ["H_1", "H_2", "T_1", "T_2", "Tdagger_1", "Tdagger_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCOpt.CVGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal") end function controlled_H() println(">>>>> Controlled-H Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["U3_1", "U3_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCOpt.CHGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -2*π:π/4:2*π, "U3_ϕ_discretization" => [0], "U3_λ_discretization" => [0], ) end function magic_using_U3_CNot_2_1() println(">>>>> Magic basis using U3 and CNot_2_1 <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["U3_1", "U3_2", "CNot_2_1", "Identity"], "target_gate" => QCOpt.MGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -π:π/2:π, "U3_ϕ_discretization" => -π:π/2:π, "U3_λ_discretization" => -π:π/2:π, ) end function iSwapGate() println(">>>>> iSwap Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 10, "elementary_gates" => ["T_1", "T_2", "Tdagger_1", "Tdagger_2", "H_1", "H_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCOpt.iSwapGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal") end function GroverDiffusion_using_Clifford() println(">>>>> Grover's Diffusion Operator <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 6, "elementary_gates" => ["X_1", "X_2", "H_1", "H_2", "S_1", "S_2", "T_1", "T_2", "Y_1", "Y_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.GroverDiffusionGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal") end function GroverDiffusion_using_U3() println(">>>>> Grover's Diffusion Operator using U3 gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 10, "elementary_gates" => ["U3_1", "CNot_1_2", "Identity"], "target_gate" => QCOpt.GroverDiffusionGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -π:π/2:π, "U3_ϕ_discretization" => -π:π/2:π, "U3_λ_discretization" => [0]) end function magic_using_SH_CNot_1_2() println(">>>>> M gate using S, H and CNOT_1_2 Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 10, "elementary_gates" => ["S_1", "S_2", "H_1", "H_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.MGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal") end function magic_using_SH_CNot_2_1() println(">>>>> M gate using S, H and CNOT_2_1 Gate <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 10, "elementary_gates" => ["S_1", "S_2", "H_1", "H_2", "CNot_2_1", "Identity"], "target_gate" => QCOpt.MGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal") end function magic_using_U3_CNot_1_2() println(">>>>> Magic basis using U3 and CNot_1_2 <<<<<") return Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["U3_1", "U3_2", "CNot_1_2", "Identity"], "target_gate" => QCOpt.MGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -π:π/2:π, "U3_ϕ_discretization" => -π:π:π, "U3_λ_discretization" => -π:π/2:π,) end function toffoli_with_controlled_gates() # Reference: https://doi.org/10.1109/TCAD.2005.858352 println(">>>>> Toffoli gate using controlled gates <<<<<") return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 5, "elementary_gates" => ["CV_1_3", "CV_2_3", "CV_1_2", "CVdagger_1_3", "CVdagger_2_3", "CVdagger_1_2", "CNot_2_1", "CNot_1_2", "Identity"], "target_gate" => QCOpt.ToffoliGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal") end function Fredkin() println(">>>>> Fredkin gate using controlled gates <<<<<") return Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 7, # Reference: https://doi.org/10.1103/PhysRevA.53.2855 "elementary_gates" => ["CV_1_2", "CV_2_3", "CV_1_3", "CVdagger_1_2", "CVdagger_2_3", "CVdagger_1_3", "CNot_1_2", "CNot_3_2", "CNot_2_3", "CNot_1_3", "Identity"], "target_gate" => QCOpt.CSwapGate(), #also Fredkin "objective" => "minimize_depth", "decomposition_type" => "exact_optimal") end function double_toffoli() println(">>>>> Double Toffoli using controlled gates <<<<<") # Reference: https://doi.org/10.1109/TCAD.2005.858352 num_qubits = 4 function target_gate() CV_3_4 = QCOpt.get_unitary("CV_3_4", num_qubits); CV_2_4 = QCOpt.get_unitary("CV_2_4", num_qubits); CVdagger_2_4 = QCOpt.get_unitary("CVdagger_2_4", num_qubits); CNot_1_3 = QCOpt.get_unitary("CNot_1_3", num_qubits); CNot_3_2 = QCOpt.get_unitary("CNot_3_2", num_qubits); return CV_2_4 * CNot_1_3 * CNot_3_2 * CV_3_4 * CVdagger_2_4 * CNot_3_2 * CNot_1_3 end return Dict{String, Any}( "num_qubits" => 4, "maximum_depth" => 7, "elementary_gates" => ["CV_1_2", "CV_2_4", "CV_3_4", "CVdagger_1_2", "CVdagger_2_4", "CVdagger_3_4", "CNot_1_3", "CNot_3_2", "CNot_2_3", "Identity"], "target_gate" => target_gate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal") end function quantum_fulladder() #Reference-1: https://doi.org/10.1109/DATE.2005.249 #Reference-2: https://doi.org/10.1109/TCAD.2005.858352 println(">>>>> Quantum Full adder using controlled gates <<<<<") num_qubits = 4 function target_gate() CV_1_2 = QCOpt.get_unitary("CV_1_2", num_qubits); CV_4_2 = QCOpt.get_unitary("CV_4_2", num_qubits); CVdagger_1_2 = QCOpt.get_unitary("CVdagger_1_2", num_qubits); CVdagger_3_2 = QCOpt.get_unitary("CVdagger_3_2", num_qubits); CNot_3_1 = QCOpt.get_unitary("CNot_3_1", num_qubits); CNot_4_3 = QCOpt.get_unitary("CNot_4_3", num_qubits); CNot_2_4 = QCOpt.get_unitary("CNot_2_4", num_qubits); return CNot_2_4 * CV_4_2 * CVdagger_1_2 * CVdagger_3_2 * CNot_4_3 * CNot_3_1 * CV_1_2 end return Dict{String, Any}( "num_qubits" => num_qubits, "maximum_depth" => 7, "elementary_gates" => ["CV_1_2", "CV_4_2", "CV_3_2", "CVdagger_1_2", "CVdagger_4_2", "CVdagger_3_2", "CNot_3_1", "CNot_4_3", "CNot_2_4", "CNot_4_1", "Identity"], "target_gate" => target_gate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal") end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
3380
#===================================# # MIP solvers (commercial, faster) # #===================================# # https://github.com/jump-dev/Gurobi.jl function get_gurobi(; solver_log = false) return JuMP.optimizer_with_attributes(Gurobi.Optimizer, MOI.Silent() => !solver_log, # "MIPFocus" => 3, # Focus on optimality over feasibility "Presolve" => 1) end # https://github.com/jump-dev/CPLEX.jl function get_cplex(; solver_log = true) return JuMP.optimizer_with_attributes(CPLEX.Optimizer, MOI.Silent() => !solver_log, # "CPX_PARAM_EPGAP" => 1E-4, # "CPX_PARAM_MIPEMPHASIS" => 2 # Focus on optimality over feasibility "CPX_PARAM_PREIND" => 1) end #====================================# # MIP solvers (open-source, slower) # #====================================# # https://github.com/jump-dev/HiGHS.jl function get_highs(; solver_log = true) return JuMP.optimizer_with_attributes( HiGHS.Optimizer, "presolve" => "on", "log_to_console" => solver_log, ) end # https://github.com/jump-dev/Cbc.jl function get_cbc(; solver_log = true) return JuMP.optimizer_with_attributes(Cbc.Optimizer, MOI.Silent() => !solver_log) end # https://github.com/jump-dev/Glpk.jl function get_glpk(; solver_log = true) return JuMP.optimizer_with_attributes(GLPK.Optimizer, MOI.Silent() => !solver_log) end #========================================================# # Continuous nonlinear programming solver (open-source) # #========================================================# # https://github.com/jump-dev/Ipopt.jl function get_ipopt(; solver_log = true) return JuMP.optimizer_with_attributes(Ipopt.Optimizer, MOI.Silent() => !solver_log, "sb" => "yes", "max_iter" => Int(1E4)) end #=================================================================# # Local mixed-integer nonlinear programming solver (open-source) # #=================================================================# # https://github.com/lanl-ansi/Juniper.jl function get_juniper(; solver_log = true) return JuMP.optimizer_with_attributes(Juniper.Optimizer, MOI.Silent() => !solver_log, "mip_solver" => get_gurobi(), "nl_solver" => get_ipopt()) end #=================================================================# # Global mixed-integer nonlinear programming solver (open-source) # #=================================================================# # https://github.com/lanl-ansi/Alpine.jl function get_alpine() return JuMP.optimizer_with_attributes(Alpine.Optimizer, "nlp_solver" => get_ipopt(), "minlp_solver" => get_juniper(), "mip_solver" => get_gurobi() ) end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
944
function parametrized_hermitian_gates() function target_gate(num_qubits, i, j, t) A = Array{Complex{Float64},2}(zeros(2^num_qubits, 2^num_qubits)) A[i,j] = 1.0 + 0.0im A[j,i] = 1.0 + 0.0im return exp(im*A*t) end num_qubits = 2 A_i = 1 # 1 <= i,j <= num_qubits A_j = 4 # 1 <= i,j <= num_qubits t = 2.5 return Dict{String, Any}( "num_qubits" => num_qubits, "maximum_depth" => 10, "elementary_gates" => ["RX_1", "RX_2", "CRX_1_2", "CRX_2_1", "CNot_1_2", "CNot_2_1", "Identity"], # "elementary_gates" => ["RX_1", "RX_2", "RX_3", "CRX_1_2", "CRX_2_1", "CRX_2_3", "CRX_3_2", "CNot_1_2", "CNot_2_1", "CNot_2_3", "CNot_3_2", "Identity"], "target_gate" => target_gate(num_qubits, A_i, A_j, t), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "RX_discretization" => [t*2,-t*2], "CRX_discretization" => [t*2,-t*2], ) end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
3447
#= Results for the paper "QuantumCircuitOpt: An Open-source Frameworkfor Provably Optimal Quantum Circuit Design" can be reproduced by executing this file. Version of QCOpt: v0.3.0 Last updated: Oct 13, 2021 =# import QuantumCircuitOpt as QCOpt using JuMP using Gurobi include("gates_sc21.jl") # Choosing a different MIP solver other than Gurobi can slow down the run times qcm_optimizer = JuMP.optimizer_with_attributes(Gurobi.Optimizer, "Presolve" => 1) #-----------------------------# # Results of Table-I # #-----------------------------# table_I_gates = ["controlled_Z", "controlled_V", "controlled_H", "magic_using_U3_CNot_2_1", "iSwapGate", "GroverDiffusion_using_U3"] result_with_VC = Dict{String,Any}() result_without_VC = Dict{String,Any}() run_times_tab1 = zeros(length(table_I_gates),2) k = 1 for gates in table_I_gates params = getfield(Main, Symbol(gates))() model_options = Dict{Symbol, Any}(:all_valid_constraints => 0) global result_with_VC = QCOpt.run_QCModel(params, qcm_optimizer; options = model_options) run_times_tab1[k,1] = result_with_VC["solve_time"] model_options = Dict{Symbol, Any}(:all_valid_constraints => -1) global result_without_VC = QCOpt.run_QCModel(params, qcm_optimizer; options = model_options) run_times_tab1[k,2] = result_without_VC["solve_time"] global k += 1 end #--------------------------------------------# # Results of Figure 3 (Magic basis) # #--------------------------------------------# result = Dict{String,Any}() figure_3_gates = ["magic_using_SH_CNot_2_1", "magic_using_U3_CNot_2_1", "magic_using_SH_CNot_1_2", "magic_using_U3_CNot_1_2", ] run_times_fig3 = zeros(length(figure_3_gates),1) k = 1 for gates in figure_3_gates params = getfield(Main, Symbol(gates))() global result = QCOpt.run_QCModel(params, qcm_optimizer) run_times_fig3[k,1] = result["solve_time"] global k += 1 end #------------------------------------------------# # Results of Figure 4 (Grover operator) # #------------------------------------------------# result = Dict{String,Any}() figure_4_gates = ["GroverDiffusion_using_Clifford", "GroverDiffusion_using_U3"] run_times_fig4 = zeros(length(figure_4_gates),1) k = 1 for gates in figure_4_gates params = getfield(Main, Symbol(gates))() global result = QCOpt.run_QCModel(params, qcm_optimizer) run_times_fig4[k,1] = result["solve_time"] global k += 1 end #------------------------------------------------# # Results of Figure 5 (larger circuits) # #------------------------------------------------# result = Dict{String,Any}() figure_5_gates = ["toffoli_with_controlled_gates", "Fredkin", "double_toffoli", "quantum_fulladder", ] run_times_fig5 = zeros(length(figure_5_gates),1) k = 1 for gates in figure_5_gates params = getfield(Main, Symbol(gates))() global result = QCOpt.run_QCModel(params, qcm_optimizer) run_times_fig5[k,1] = result["solve_time"] global k += 1 end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
1060
import QuantumCircuitOpt as QCOpt using LinearAlgebra using JuMP using Gurobi # using CPLEX # using HiGHS include("optimizers.jl") [include("$(i)qubit_gates.jl") for i in 2:5] include("parametrized_gates.jl") include("decompose_all_gates.jl") # decompose_gates = ["iSwap"] #----------------------------------------------# # Quantum Circuit Optimization model # #----------------------------------------------# qcopt_optimizer = get_gurobi(solver_log = true) result = Dict{String,Any}() times = zeros(length(decompose_gates), 1) for gates = 1:length(decompose_gates) params = getfield(Main, Symbol(decompose_gates[gates]))() model_options = Dict{Symbol, Any}( :model_type => "compact_formulation", :convex_hull_gate_constraints => false, :idempotent_gate_constraints => false, :unitary_constraints => false, :fix_unitary_variables => true, ) global result = QCOpt.run_QCModel(params, qcopt_optimizer; options = model_options) times[gates] = result["solve_time"] end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
1426
module QuantumCircuitOpt import JuMP import LinearAlgebra import Memento import Pkg const LA = LinearAlgebra const QCO = QuantumCircuitOpt const kron_symbol = 'x' const qubit_separator = '_' # Create our module level logger (this will get precompiled) const _LOGGER = Memento.getlogger(@__MODULE__) # Register the module level logger at runtime so that folks can access the logger via `getlogger(QuantumCircuitOpt)` # NOTE: If this line is not included then the precompiled `QuantumCircuitOpt._LOGGER` won't be registered at runtime. __init__() = Memento.register(_LOGGER) "Suppresses information and warning messages output by QuantumCircuitOpt, for fine grained control use of the Memento package" function silence() Memento.info(_LOGGER, "Suppressing information and warning messages for the rest of this session. Use the Memento package for more fine-grained control of logging.") Memento.setlevel!(Memento.getlogger(QuantumCircuitOpt), "error") end "allows the user to set the logging level without the need to add Memento" function logger_config!(level) Memento.config!(Memento.getlogger("QuantumCircuitOpt"), level) end include("data.jl") include("gates.jl") include("types.jl") include("utility.jl") include("chull.jl") include("relaxations.jl") include("qc_model.jl") include("variables.jl") include("constraints.jl") include("objective.jl") include("log.jl") include("solution.jl") end # module
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
3328
""" _orientation(x::Tuple{<:Number, <:Number}, y::Tuple{<:Number, <:Number}, z::Tuple{<:Number, <:Number}) Utility function for `convex_hull`. Given an ordered triplet, this function returns if three points are collinear, oriented in clock-wise or anticlock-wise direction. """ function _orientation(x::Tuple{<:Number, <:Number}, y::Tuple{<:Number, <:Number}, z::Tuple{<:Number, <:Number}) a = ((y[2] - x[2]) * (z[1] - y[1]) - (y[1] - x[1]) * (z[2] - y[2])) if isapprox(a, 0, atol=1e-6) return 0 # collinear elseif a > 0 return 1 # clock-wise else return 2 # counterclock-wise end end """ _lt_filter(a::Tuple{<:Number, <:Number}, b::Tuple{<:Number, <:Number}) Utility function for sorting step in `convex_hull`. Given two points, `a` and `b`, this function returns true if `a` has larger polar angle (counterclock-wise direction) than `b` w.r.t. first point `chull_p1`. """ function _lt_filter(a::Tuple{<:Number, <:Number}, b::Tuple{<:Number, <:Number}) o = QCO._orientation(chull_p1, a, b) if o == 0 if LA.norm(collect(chull_p1 .- b))^2 >= LA.norm(collect(chull_p1 .- a))^2 return true else return false end elseif o == 2 return true else return false end end """ convex_hull(points::Vector{T}) where T<:Tuple{Number, Number} Graham's scan algorithm to compute the convex hull of a finite set of `n` points in a plane with time complexity `O(n*log(n))`. Given a vector of tuples of co-ordinates, this function returns a vector of tuples of co-ordinates which form the convex hull of the given set of points. Sources: https://doi.org/10.1016/0020-0190(72)90045-2 https://en.wikipedia.org/wiki/Graham_scan """ function convex_hull(points::Vector{T}) where T<:Tuple{Number, Number} num_points = size(points)[1] if num_points == 0 Memento.error(_LOGGER, "Atleast one point is necessary for evaluating the convex hull") elseif num_points <= 2 return points end min_y = points[1][2] min = 1 # Bottom-most or else the left-most point when tie for i in 2:num_points y = points[i][2] if (y < min_y) || (y == min_y && points[i][1] < points[min][1]) min_y = y min = i end end # Placing the bottom/left-most point at first position points[1], points[min] = points[min], points[1] global chull_p1 = points[1] points = Base.sort(points, lt = QCO._lt_filter) # If two or more points are collinear with chull_p1, remove all except the farthest from chull_p1 arr_size = 2 for i in 2:num_points while (i < num_points) && (QCO._orientation(chull_p1, points[i], points[i+1]) == 0) i += 1 end points[arr_size] = points[i] arr_size += 1 end if arr_size <= 3 return [] end chull = [] append!(chull, [points[1]]) append!(chull, [points[2]]) append!(chull, [points[3]]) for i in 4:(arr_size-1) while (size(chull)[1] > 1) && (QCO._orientation(chull[end - 1], chull[end], points[i]) != 2) pop!(chull) end append!(chull, [points[i]]) end return chull end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
23291
#--------------------------------------------------------# # Build all constraints of the QuantumCircuitModel here # #--------------------------------------------------------# function constraint_single_gate_per_depth(qcm::QuantumCircuitModel) num_gates = size(qcm.data["gates_real"])[3] max_depth = qcm.data["maximum_depth"] JuMP.@constraint(qcm.model, [d=1:max_depth], sum(qcm.variables[:z_bin_var][n,d] for n=1:num_gates) == 1) return end function constraint_gates_onoff_per_depth(qcm::QuantumCircuitModel) num_gates = size(qcm.data["gates_real"])[3] max_depth = qcm.data["maximum_depth"] JuMP.@constraint(qcm.model, [d=1:max_depth], qcm.variables[:G_var][:,:,d] .== sum(qcm.variables[:z_bin_var][n,d] * qcm.data["gates_real"][:,:,n] for n=1:num_gates)) return end function constraint_initial_gate_condition(qcm::QuantumCircuitModel) num_gates = size(qcm.data["gates_real"])[3] JuMP.@constraint(qcm.model, sum(qcm.variables[:V_var][:,:,n,1] for n=1:num_gates) .== qcm.data["initial_gate"]) JuMP.@constraint(qcm.model, [n=1:num_gates], qcm.variables[:V_var][:,:,n,1] .== (qcm.variables[:z_bin_var][n,1] .* qcm.data["initial_gate"])) return end function constraint_intermediate_products(qcm::QuantumCircuitModel) num_gates = size(qcm.data["gates_real"])[3] max_depth = qcm.data["maximum_depth"] JuMP.@constraint(qcm.model, [d=1:(max_depth-1)], qcm.variables[:U_var][:,:,d] .== sum(qcm.variables[:V_var][:,:,n,d] * qcm.data["gates_real"][:,:,n] for n=1:num_gates)) JuMP.@constraint(qcm.model, [d=2:max_depth], sum(qcm.variables[:V_var][:,:,n,d] for n=1:num_gates) .== qcm.variables[:U_var][:,:,(d-1)]) JuMP.@constraint(qcm.model, [d=1:(max_depth-1)], qcm.variables[:V_var][:,:,:,(d+1)] .== qcm.variables[:zU_var][:,:,:,d]) return end function constraint_target_gate_condition(qcm::QuantumCircuitModel) max_depth = qcm.data["maximum_depth"] num_gates = size(qcm.data["gates_real"])[3] decomposition_type = qcm.data["decomposition_type"] if decomposition_type in ["exact_optimal", "exact_feasible"] JuMP.@constraint(qcm.model, sum(qcm.variables[:V_var][:,:,n,max_depth] * qcm.data["gates_real"][:,:,n] for n=1:num_gates) .== qcm.data["target_gate"]) elseif decomposition_type == "approximate" JuMP.@constraint(qcm.model, sum(qcm.variables[:V_var][:,:,n,max_depth] * qcm.data["gates_real"][:,:,n] for n=1:num_gates) .== qcm.data["target_gate"][:,:] + qcm.variables[:slack_var][:,:]) end return end function constraint_complex_to_real_symmetry(qcm::QuantumCircuitModel) max_depth = qcm.data["maximum_depth"] n_r = size(qcm.data["gates_real"])[1] n_c = size(qcm.data["gates_real"])[2] for i=1:2:n_r, j=1:2:n_c, d=1:(max_depth-1) JuMP.@constraint(qcm.model, qcm.variables[:U_var][i,j,d] == qcm.variables[:U_var][i+1,j+1,d]) JuMP.@constraint(qcm.model, qcm.variables[:U_var][i,j+1,d] == -qcm.variables[:U_var][i+1,j,d]) # This seems to slow down the solution search end return end function constraint_gate_product_linearization(qcm::QuantumCircuitModel) max_depth = qcm.data["maximum_depth"] n_r = size(qcm.data["gates_real"])[1] n_c = size(qcm.data["gates_real"])[2] num_gates = size(qcm.data["gates_real"])[3] are_gates_real = qcm.data["are_gates_real"] U_var = qcm.variables[:U_var] zU_var = qcm.variables[:zU_var] z_bin_var = qcm.variables[:z_bin_var] i_val = 2 - are_gates_real U_var_bound_tol = 1E-8 for i=1:i_val:n_r, j=1:n_c, n=1:num_gates, d=1:(max_depth-1) U_var_l = JuMP.lower_bound(U_var[i,j,d]) U_var_u = JuMP.upper_bound(U_var[i,j,d]) if !(isapprox(abs(U_var_u - U_var_l), 0, atol = 2*U_var_bound_tol)) QCO.relaxation_bilinear(qcm.model, zU_var[i,j,n,d], U_var[i,j,d], z_bin_var[n,(d+1)]) else JuMP.@constraint(qcm.model, zU_var[i,j,n,d] == (U_var_l + U_var_u)/2 * z_bin_var[n,(d+1)]) end if !are_gates_real && isodd(j) JuMP.@constraint(qcm.model, zU_var[i,j,n,d] == zU_var[i+1,j+1,n,d]) JuMP.@constraint(qcm.model, zU_var[i,j+1,n,d] == -zU_var[i+1,j,n,d]) end end return end function constraint_initial_gate_condition_compact(qcm::QuantumCircuitModel) num_gates = size(qcm.data["gates_real"])[3] JuMP.@constraint(qcm.model, qcm.variables[:U_var][:,:,1] .== qcm.data["initial_gate"] * sum(qcm.variables[:z_bin_var][n,1] * qcm.data["gates_real"][:,:,n] for n=1:num_gates)) return end function constraint_intermediate_products_compact(qcm::QuantumCircuitModel) num_gates = size(qcm.data["gates_real"])[3] max_depth = qcm.data["maximum_depth"] JuMP.@constraint(qcm.model, [d=2:max_depth], qcm.variables[:U_var][:,:,d] .== sum((qcm.variables[:zU_var][:,:,n,(d-1)]) * qcm.data["gates_real"][:,:,n] for n=1:num_gates)) return end function constraint_target_gate_condition_compact(qcm::QuantumCircuitModel) max_depth = qcm.data["maximum_depth"] decomposition_type = qcm.data["decomposition_type"] U_var = qcm.variables[:U_var] if decomposition_type in ["exact_optimal", "exact_feasible"] JuMP.@constraint(qcm.model, U_var[:,:,max_depth] .== qcm.data["target_gate"][:,:]) elseif decomposition_type == "approximate" JuMP.@constraint(qcm.model, U_var[:,:,max_depth] .== qcm.data["target_gate"][:,:] + qcm.variables[:slack_var][:,:]) end return end function constraint_target_gate_condition_glphase(qcm::QuantumCircuitModel) max_depth = qcm.data["maximum_depth"] n_r = size(qcm.data["gates_real"])[1] n_c = size(qcm.data["gates_real"])[2] U_var = qcm.variables[:U_var] if qcm.data["are_gates_real"] ref_nonzero_r, ref_nonzero_c = QCO._get_nonzero_idx_of_complex_matrix(Array{Complex{Float64},2}(qcm.data["target_gate"])) for i=1:n_r, j=1:n_c if isapprox(qcm.data["target_gate"][i,j], 0, atol=1E-6) JuMP.@constraint(qcm.model, U_var[i,j,max_depth] == 0) else JuMP.@constraint(qcm.model, U_var[i,j,max_depth]*qcm.data["target_gate"][ref_nonzero_r,ref_nonzero_c] == qcm.data["target_gate"][i,j]*U_var[ref_nonzero_r,ref_nonzero_c,max_depth]) end end else ref_nonzero_r, ref_nonzero_c = QCO._get_nonzero_idx_of_complex_to_real_matrix(qcm.data["target_gate"]) for i=1:2:n_r, j=1:2:n_c if isapprox(qcm.data["target_gate"][i,j], 0, atol=1E-6) && isapprox(qcm.data["target_gate"][i,j+1], 0, atol=1E-6) JuMP.@constraint(qcm.model, U_var[i,j,max_depth] == 0.0) JuMP.@constraint(qcm.model, U_var[i,(j+1),max_depth] == 0.0) else #real parts equal JuMP.@constraint(qcm.model, U_var[i,j,max_depth]*qcm.data["target_gate"][ref_nonzero_r,ref_nonzero_c] - U_var[i,(j+1),max_depth]*qcm.data["target_gate"][ref_nonzero_r,(ref_nonzero_c+1)] == U_var[ref_nonzero_r,ref_nonzero_c,max_depth]*qcm.data["target_gate"][i,j] - U_var[ref_nonzero_r,(ref_nonzero_c+1),max_depth]*qcm.data["target_gate"][i,(j+1)]) #complex parts equal JuMP.@constraint(qcm.model, U_var[i,j,max_depth]*qcm.data["target_gate"][ref_nonzero_r,(ref_nonzero_c+1)] + U_var[i,(j+1),max_depth]*qcm.data["target_gate"][ref_nonzero_r,ref_nonzero_c] == U_var[ref_nonzero_r,ref_nonzero_c,max_depth]*qcm.data["target_gate"][i,(j+1)] + U_var[ref_nonzero_r,(ref_nonzero_c+1),max_depth]*qcm.data["target_gate"][i,j]) end end end return end function constraint_slack_var_outer_approximation(qcm::QuantumCircuitModel) slack_var = qcm.variables[:slack_var] slack_var_oa = qcm.variables[:slack_var_oa] # Number of under-estimators for the quadratic function num_points = 9 for i=1:size(slack_var)[1], j=1:size(slack_var)[2] lb = JuMP.lower_bound(slack_var[i,j]) ub = JuMP.upper_bound(slack_var[i,j]) if !(isapprox(lb, ub, atol = 1E-6)) oa_points = range(lb, ub, num_points) JuMP.@constraint(qcm.model, [k=1:length(oa_points)], slack_var_oa[i,j] >= 2*slack_var[i,j]*oa_points[k] - (oa_points[k])^2) if !(0 in oa_points) JuMP.@constraint(qcm.model, slack_var_oa[i,j] >= 0) end else mid_point = (lb+ub)/2 JuMP.@constraint(qcm.model, slack_var_oa[i,j] >= 2*slack_var[i,j]*mid_point - (mid_point)^2) end end return end function constraint_commutative_gate_pairs(qcm::QuantumCircuitModel) max_depth = qcm.data["maximum_depth"] z_bin_var = qcm.variables[:z_bin_var] commute_pairs, commute_pairs_prodIdentity = QCO.get_commutative_gate_pairs(qcm.data["gates_dict"], qcm.data["decomposition_type"]) if !isempty(commute_pairs) (length(commute_pairs) == 1) && (Memento.info(_LOGGER, "Detected $(length(commute_pairs)) input elementary gate pair which commutes")) (length(commute_pairs) > 1) && (Memento.info(_LOGGER, "Detected $(length(commute_pairs)) input elementary gate pairs which commute")) for i = 1:length(commute_pairs) JuMP.@constraint(qcm.model, [d=1:(max_depth-1)], z_bin_var[commute_pairs[i][2], d] + z_bin_var[commute_pairs[i][1], d+1] <= 1) end end if !isempty(commute_pairs_prodIdentity) (length(commute_pairs_prodIdentity) == 1) && (Memento.info(_LOGGER, "Detected $(length(commute_pairs_prodIdentity)) input elementary gate pair whose product is Identity")) (length(commute_pairs_prodIdentity) > 1) && (Memento.info(_LOGGER, "Detected $(length(commute_pairs_prodIdentity)) input elementary gate pairs whose product is Identity")) for i = 1:length(commute_pairs_prodIdentity) JuMP.@constraint(qcm.model, [d=1:(max_depth-1)], z_bin_var[commute_pairs_prodIdentity[i][2], d] + z_bin_var[commute_pairs_prodIdentity[i][1], d+1] <= 1) JuMP.@constraint(qcm.model, [d=1:(max_depth-1)], z_bin_var[commute_pairs_prodIdentity[i][1], d] + z_bin_var[commute_pairs_prodIdentity[i][2], d+1] <= 1) end end return end function constraint_involutory_gates(qcm::QuantumCircuitModel) gates_dict = qcm.data["gates_dict"] max_depth = qcm.data["maximum_depth"] z_bin_var = qcm.variables[:z_bin_var] involutory_gates = QCO.get_involutory_gates(gates_dict) if !isempty(involutory_gates) (length(involutory_gates) == 1) && (Memento.info(_LOGGER, "Detected $(length(involutory_gates)) involutory elementary gate")) (length(involutory_gates) > 1) && (Memento.info(_LOGGER, "Detected $(length(involutory_gates)) involutory elementary gates")) for i = 1:length(involutory_gates) JuMP.@constraint(qcm.model, [d=1:(max_depth-1)], z_bin_var[involutory_gates[i], d] + z_bin_var[involutory_gates[i], d+1] <= 1) end end return end function constraint_redundant_gate_product_pairs(qcm::QuantumCircuitModel) gates_dict = qcm.data["gates_dict"] max_depth = qcm.data["maximum_depth"] z_bin_var = qcm.variables[:z_bin_var] redundant_pairs = QCO.get_redundant_gate_product_pairs(gates_dict, qcm.data["decomposition_type"]) if !isempty(redundant_pairs) (length(redundant_pairs) == 1) && (Memento.info(_LOGGER, "Detected $(length(redundant_pairs)) redundant input elementary gate pair")) (length(redundant_pairs) > 1) && (Memento.info(_LOGGER, "Detected $(length(redundant_pairs)) redundant input elementary gate pairs")) for i = 1:length(redundant_pairs) JuMP.@constraint(qcm.model, [d=1:(max_depth-1)], z_bin_var[redundant_pairs[i][2], d] + z_bin_var[redundant_pairs[i][1], d+1] <= 1) end end return end function constraint_idempotent_gates(qcm::QuantumCircuitModel) gates_dict = qcm.data["gates_dict"] max_depth = qcm.data["maximum_depth"] z_bin_var = qcm.variables[:z_bin_var] idempotent_gates = QCO.get_idempotent_gates(gates_dict, qcm.data["decomposition_type"]) if !isempty(idempotent_gates) (length(idempotent_gates) == 1) && (Memento.info(_LOGGER, "Detected $(length(idempotent_gates)) idempotent elementary gate")) (length(idempotent_gates) > 1) && (Memento.info(_LOGGER, "Detected $(length(idempotent_gates)) idempotent elementary gates")) for i = 1:length(idempotent_gates) JuMP.@constraint(qcm.model, [d=1:(max_depth-1)], z_bin_var[idempotent_gates[i], d] + z_bin_var[idempotent_gates[i], d+1] <= 1) end end return end function constraint_identity_gate_symmetry(qcm::QuantumCircuitModel) gates_dict = qcm.data["gates_dict"] max_depth = qcm.data["maximum_depth"] z_bin_var = qcm.variables[:z_bin_var] identity_idx = [] for i=1:length(keys(gates_dict)) if "Identity" in gates_dict["$i"]["type"] push!(identity_idx, i) end end if !isempty(identity_idx) for i = 1:length(identity_idx) JuMP.@constraint(qcm.model, [d=1:(max_depth-1)], z_bin_var[identity_idx[i], d] <= z_bin_var[identity_idx[i], d+1]) end end return end function constraint_cnot_gate_bounds(qcm::QuantumCircuitModel) cnot_idx = qcm.data["cnot_idx"] max_depth = qcm.data["maximum_depth"] z_bin_var = qcm.variables[:z_bin_var] if !isempty(cnot_idx) if "cnot_lower_bound" in keys(qcm.data) JuMP.@constraint(qcm.model, sum(z_bin_var[n,d] for n in cnot_idx, d=1:max_depth) >= qcm.data["cnot_lower_bound"]) Memento.info(_LOGGER, "Applied CNot-gate lower bound constraint") end if "cnot_upper_bound" in keys(qcm.data) JuMP.@constraint(qcm.model, sum(z_bin_var[n,d] for n in cnot_idx, d=1:max_depth) <= qcm.data["cnot_upper_bound"]) Memento.info(_LOGGER, "Applied CNot-gate upper bound constraint") end end return end function constraint_convex_hull_complex_gates(qcm::QuantumCircuitModel) if !qcm.data["are_gates_real"] max_ex_pt = 4 # (>= 2) A parameter which can be an user input z_bin_var = qcm.variables[:z_bin_var] gates_real = qcm.data["gates_real"] gates_dict = qcm.data["gates_dict"] num_gates = size(gates_real)[3] max_depth = qcm.data["maximum_depth"] n_r = size(gates_dict["1"]["matrix"])[1] n_c = size(gates_dict["1"]["matrix"])[2] num_facets = 0 vertices_dict = Dict{Set{}, Tuple{<:Number, <:Number}}() for I=1:n_r, J=1:n_c vertices_coord_IJ = Set() for K in keys(gates_dict) re = QCO.round_real_value(real(gates_dict[K]["matrix"][I,J])) im = QCO.round_real_value(imag(gates_dict[K]["matrix"][I,J])) push!(vertices_coord_IJ, (re, im)) end if (isapprox(minimum([x[1] for x in vertices_coord_IJ]), maximum([x[1] for x in vertices_coord_IJ]), atol = 1E-6)) || (isapprox(minimum([x[2] for x in vertices_coord_IJ]), maximum([x[2] for x in vertices_coord_IJ]), atol = 1E-6)) continue else # Eliminates repeated set of extreme points vertices_dict[vertices_coord_IJ] = (I,J) end end for vertices_coord in keys(vertices_dict) I = vertices_dict[vertices_coord][1] J = vertices_dict[vertices_coord][2] vertices = Vector{Tuple{<:Number, <:Number}}() if length(vertices_coord) == 2 for l in vertices_coord push!(vertices, (l[1], l[2])) end slope, intercept = QCO._get_constraint_slope_intercept(vertices[1], vertices[2]) if !isinf(slope) if isapprox(abs(slope), 0, atol=1E-6) JuMP.@constraint(qcm.model, [d=1:max_depth], sum(gates_real[(2*I-1),(2*J), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates) - intercept == 0) else JuMP.@constraint(qcm.model, [d=1:max_depth], sum(gates_real[(2*I-1),(2*J), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates) - slope*sum(gates_real[(2*I-1),(2*J-1), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates) - intercept == 0) end elseif isinf(slope) JuMP.@constraint(qcm.model, [d=1:max_depth], sum(gates_real[(2*I-1),(2*J-1), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates) == vertices[1][1]) end num_facets += 1 elseif (length(vertices_coord) > 2) for l in vertices_coord push!(vertices, (l[1], l[2])) end vertices_convex_hull = QCO.convex_hull(vertices) num_ex_pt = size(vertices_convex_hull)[1] # Add a planar hull cut if num_ex_pt == 2 if (num_ex_pt >= 3) && (num_ex_pt <= max_ex_pt) for i=1:num_ex_pt v1 = vertices_convex_hull[i] if i == num_ex_pt v2 = vertices_convex_hull[1] else v2 = vertices_convex_hull[i+1] end # Test-vertex for half-space directionality if i == (num_ex_pt - 1) v3 = vertices_convex_hull[1] elseif i == num_ex_pt v3 = vertices_convex_hull[2] else v3 = vertices_convex_hull[i+2] end slope, intercept = QCO._get_constraint_slope_intercept(v1, v2) # Facets of the hull if !isinf(slope) if v3[2] - slope*v3[1] - intercept <= -1E-6 if isapprox(abs(slope), 0, atol=1E-6) JuMP.@constraint(qcm.model, [d=1:max_depth], sum(gates_real[(2*I-1),(2*J), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates) - intercept <= 0) else JuMP.@constraint(qcm.model, [d=1:max_depth], sum(gates_real[(2*I-1),(2*J), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates) - slope*(sum(gates_real[(2*I-1),(2*J-1), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates)) - intercept <= 0) end num_facets += 1 elseif v3[2] - slope*v3[1] - intercept >= 1E-6 if isapprox(abs(slope), 0, atol=1E-6) JuMP.@constraint(qcm.model, [d=1:max_depth], sum(gates_real[(2*I-1),(2*J), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates) - intercept >= 0) else JuMP.@constraint(qcm.model, [d=1:max_depth], sum(gates_real[(2*I-1),(2*J), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates) - slope*(sum(gates_real[(2*I-1),(2*J-1), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates)) - intercept >= 0) end num_facets += 1 else Memento.warn(_LOGGER, "Indeterminate direction for the planar-hull cut") end else isinf(slope) if v3[1] >= v1[1] + 1E-6 JuMP.@constraint(qcm.model, [d=1:max_depth], sum(gates_real[(2*I-1),(2*J-1), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates) >= v1[1]) elseif v3[1] <= v1[1] - 1E-6 JuMP.@constraint(qcm.model, [d=1:max_depth], sum(gates_real[(2*I-1),(2*J-1), n_g] * z_bin_var[n_g,d] for n_g = 1:num_gates) <= v1[1]) else Memento.warn(_LOGGER, "Indeterminate direction for the planar-hull cut") end num_facets += 1 end end end end end if num_facets > 0 Memento.info(_LOGGER, "Applied $num_facets planar-hull cuts per max_depth of the decomposition") end end return end function constraint_unitary_property(qcm::QuantumCircuitModel) max_depth = qcm.data["maximum_depth"] Z_var = qcm.variables[:Z_var] z_bin_var = qcm.variables[:z_bin_var] gates_real = qcm.data["gates_real"] num_gates = size(gates_real)[3] n_r = size(gates_real)[1] n_c = size(gates_real)[2] gates_adjoint = zeros(n_r, n_c, num_gates) for k=1:num_gates if qcm.data["are_gates_real"] gates_adjoint[:,:,k] = gates_real[:,:,k]' else gate_complex = QCO.real_to_complex_gate(gates_real[:,:,k]) gate_complex_adj = Matrix{ComplexF64}(adjoint(gate_complex)) gates_adjoint[:,:,k] = QCO.complex_to_real_gate(gate_complex_adj) end end for d = 1:max_depth for i=1:num_gates for j=i:num_gates if i == j JuMP.@constraint(qcm.model, Z_var[i,j,d] == z_bin_var[i,d]) else QCO.relaxation_bilinear(qcm.model, Z_var[i,j,d], z_bin_var[i,d], z_bin_var[j,d]) # JuMP.@constraint(qcm.model, Z_var[i,j,d] == 0) JuMP.@constraint(qcm.model, Z_var[j,i,d] == Z_var[i,j,d]) end end # RLT-type constraint JuMP.@constraint(qcm.model, sum(Z_var[i,:,d]) == z_bin_var[i,d]) end # JuMP.@constraint(qcm.model, sum(Z_var[i,i,d] for i=1:num_gates) == 1) end # Unitary constraint JuMP.@constraint(qcm.model, [d=1:max_depth], sum(Z_var[i,j,d]* QCO.round_real_value.(gates_real[:,:,i] * gates_adjoint[:,:,j] + gates_real[:,:,j] * gates_adjoint[:,:,i]) for i=1:(num_gates-1), j=(i+1):num_gates) .== zeros(n_r, n_c)) return end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
37539
import LinearAlgebra: I """ get_data(params::Dict{String, Any}; eliminate_identical_gates = true) Given the user input `params` dictionary, this function returns a dictionary of processed data which contains all the necessary information to formulate the optimization model for the circuit design problem. """ function get_data(params::Dict{String, Any}; eliminate_identical_gates = true) # Number of qubits if "num_qubits" in keys(params) if params["num_qubits"] < 2 Memento.error(_LOGGER, "Minimum of 2 qubits is necessary") end num_qubits = params["num_qubits"] else Memento.error(_LOGGER, "Number of qubits has to be specified by the user") end # Depth if "maximum_depth" in keys(params) if params["maximum_depth"] < 2 Memento.error(_LOGGER, "Minimum depth of 2 is necessary") end maximum_depth = params["maximum_depth"] else Memento.error(_LOGGER, "Maximum depth of the decomposition has to be specified by the user") end # Elementary gates if !("elementary_gates" in keys(params)) || isempty(params["elementary_gates"]) Memento.error(_LOGGER, "Specify at least two unique unitary elementary gates") end # Input Circuit if "input_circuit" in keys(params) input_circuit = params["input_circuit"] else # default value input_circuit = [] end input_circuit_dict = Dict{String,Any}() if length(input_circuit) > 0 && (length(input_circuit) <= params["maximum_depth"]) input_circuit_dict = QCO.get_input_circuit_dict(input_circuit, params) else (length(input_circuit) > 0) && (Memento.warn(_LOGGER, "Neglecting the input circuit as it's depth is greater than the allowable depth")) end # Decomposition type if "decomposition_type" in keys(params) decomposition_type = params["decomposition_type"] else decomposition_type = "exact_optimal" end if !(decomposition_type in ["exact_optimal", "exact_feasible", "optimal_global_phase", "approximate"]) Memento.error(_LOGGER, "Decomposition type not supported") end # Objective function if "objective" in keys(params) objective = params["objective"] else objective = "minimize_depth" end elementary_gates = unique(params["elementary_gates"]) if length(elementary_gates) < length(params["elementary_gates"]) Memento.warn(_LOGGER, "Eliminating non-unique gates in the input elementary gates") end gates_dict, are_elementary_gates_real = QCO.get_elementary_gates_dictionary(params, elementary_gates) target_real, is_target_real = QCO.get_target_gate(params, are_elementary_gates_real, decomposition_type) gates_dict_unique, M_real_unique, identity_idx, cnot_idx = QCO.eliminate_nonunique_gates(gates_dict, are_elementary_gates_real, eliminate_identical_gates = eliminate_identical_gates) # Initial gate if "initial_gate" in keys(params) if params["initial_gate"] == "Identity" if are_elementary_gates_real && is_target_real initial_gate = real(QCO.IGate(num_qubits)) else initial_gate = QCO.complex_to_real_gate(QCO.IGate(num_qubits)) end else Memento.error(_LOGGER, "Currently, only \"Identity\" is supported as an initial gate") # Add code here to support non-identity as an initial gate. end else if are_elementary_gates_real && is_target_real initial_gate = real(QCO.IGate(num_qubits)) else initial_gate = QCO.complex_to_real_gate(QCO.IGate(num_qubits)) end end data = Dict{String, Any}("num_qubits" => num_qubits, "maximum_depth" => maximum_depth, "gates_dict" => gates_dict_unique, "gates_real" => M_real_unique, "initial_gate" => initial_gate, "identity_idx" => identity_idx, "cnot_idx" => cnot_idx, "elementary_gates" => elementary_gates, "target_gate" => target_real, "are_gates_real" => (are_elementary_gates_real && is_target_real), "objective" => objective, "decomposition_type" => decomposition_type ) if data["are_gates_real"] Memento.info(_LOGGER, "Detected all-real elementary and target gates") end # Rotation and Universal gate angle discretizations data = QCO._populate_data_angle_discretization!(data, params) # Determinant test for input gates (data["decomposition_type"] in ["exact_optimal", "exact_feasible"]) && QCO._determinant_test_for_infeasibility(data) # Input circuit if length(keys(input_circuit_dict)) > 0 data["input_circuit"] = input_circuit_dict end # CNOT lower/upper bound data = QCO._get_cnot_bounds!(data, params) return data end """ eliminate_nonunique_gates(gates_dict::Dict{String, Any}) """ function eliminate_nonunique_gates(gates_dict::Dict{String, Any}, are_elementary_gates_real::Bool; eliminate_identical_gates = false) num_gates = length(keys(gates_dict)) # This identifies if all the elementary gates have only real entries and returns compact matrices if are_elementary_gates_real M_real = zeros(size(gates_dict["1"]["matrix"])[1], size(gates_dict["1"]["matrix"])[2], num_gates) else M_real = zeros(2*size(gates_dict["1"]["matrix"])[1], 2*size(gates_dict["1"]["matrix"])[2], num_gates) end for i=1:num_gates if are_elementary_gates_real M_real[:,:,i] = real(gates_dict["$i"]["matrix"]) else M_real[:,:,i] = QCO.complex_to_real_gate(gates_dict["$i"]["matrix"]) end end M_real_unique = M_real M_real_idx = collect(1:size(M_real)[3]) if eliminate_identical_gates M_real_unique, M_real_idx = QCO.unique_matrices(M_real) end gates_dict_unique = Dict{String, Any}() if size(M_real_unique)[3] < size(M_real)[3] Memento.info(_LOGGER, "Detected $(size(M_real)[3]-size(M_real_unique)[3]) non-unique gates (after discretization)") for i = 1:length(M_real_idx) gates_dict_unique["$i"] = gates_dict["$(M_real_idx[i])"] end else gates_dict_unique = gates_dict end identity_idx = QCO._get_identity_idx(M_real_unique) for i_id = 1:length(identity_idx) if !("Identity" in gates_dict_unique["$(identity_idx[i_id])"]["type"]) push!(gates_dict_unique["$(identity_idx[i_id])"]["type"], "Identity") end end cnot_idx = QCO._get_cnot_idx(gates_dict_unique) return gates_dict_unique, M_real_unique, identity_idx, cnot_idx end function _populate_data_angle_discretization!(data::Dict{String, Any}, params::Dict{String, Any}) one_angle_gates, two_angle_gates, three_angle_gates = QCO._get_angle_gates_idx(data["elementary_gates"]) if !isempty(union(one_angle_gates, two_angle_gates, three_angle_gates)) if length(findall(x -> (occursin("discretization", x)), collect(keys(params)))) == 0 Memento.error(_LOGGER, "Enter valid discretization angles in the imput params") end data["discretization"] = Dict{String, Any}() if !isempty(one_angle_gates) for i in one_angle_gates gate_type = QCO._parse_gate_string(data["elementary_gates"][i], type = true) data["discretization"][gate_type] = Float64.(params["$(gate_type)_discretization"]) end end if !isempty(two_angle_gates) for i in two_angle_gates gate_type = QCO._parse_gate_string(data["elementary_gates"][i], type = true) data["discretization"]["$(gate_type)_θ"] = Float64.(params["$(gate_type)_θ_discretization"]) data["discretization"]["$(gate_type)_ϕ"] = Float64.(params["$(gate_type)_ϕ_discretization"]) end end if !isempty(three_angle_gates) for i in three_angle_gates gate_type = QCO._parse_gate_string(data["elementary_gates"][i], type = true) data["discretization"]["$(gate_type)_θ"] = Float64.(params["$(gate_type)_θ_discretization"]) data["discretization"]["$(gate_type)_ϕ"] = Float64.(params["$(gate_type)_ϕ_discretization"]) data["discretization"]["$(gate_type)_λ"] = Float64.(params["$(gate_type)_λ_discretization"]) end end end return data end """ get_target_gate(params::Dict{String, Any}, are_elementary_gates_real::Bool) Given the user input `params` dictionary and a boolean if all the input elementary gates are real, this function returns the corresponding real version of the target gate. """ function get_target_gate(params::Dict{String, Any}, are_elementary_gates_real::Bool, decomposition_type::String) if !("target_gate" in keys(params)) || isempty(params["target_gate"]) Memento.error(_LOGGER, "Target gate not found in the input data") end if (size(params["target_gate"])[1] != size(params["target_gate"])[2]) || (size(params["target_gate"])[1] != 2^params["num_qubits"]) Memento.error(_LOGGER, "Dimensions of target gate do not match the input num_qubits") end # Identify if the target gate has only real entries or if it is real up to a global phase and returns a compact matrix is_target_real = QCO.is_gate_real(params["target_gate"]) if are_elementary_gates_real global_phase = 0 if (decomposition_type in ["optimal_global_phase"]) && !is_target_real ref_nonzero_r, ref_nonzero_c = QCO._get_nonzero_idx_of_complex_matrix(params["target_gate"]) global_phase = angle(params["target_gate"][ref_nonzero_r, ref_nonzero_c]) end is_target_real_up_to_phase = QCO.is_gate_real(exp(-im*global_phase)*params["target_gate"]) if is_target_real_up_to_phase return real(exp(-im*global_phase)*params["target_gate"]), is_target_real_up_to_phase else Memento.error(_LOGGER, "Infeasible decomposition: all elementary gates have zero imaginary parts and target is not real for exact decomposition or not real up to a global phase for optimal_global_phase decomposition.") end else return QCO.complex_to_real_gate(params["target_gate"]), is_target_real end end function get_elementary_gates_dictionary(params::Dict{String, Any}, elementary_gates::Array{String,1}) num_qubits = params["num_qubits"] one_angle_gates, two_angle_gates, three_angle_gates = QCO._get_angle_gates_idx(elementary_gates) one_angle_gates_dict = Dict{String,Any}() two_angle_gates_dict = Dict{String,Any}() three_angle_gates_dict = Dict{String,Any}() if !isempty(one_angle_gates) one_angle_gates_dict = QCO.get_all_one_angle_gates(params, elementary_gates, one_angle_gates) end if !isempty(two_angle_gates) two_angle_gates_dict = QCO.get_all_two_angle_gates(params, elementary_gates, two_angle_gates) end if !isempty(three_angle_gates) three_angle_gates_dict = QCO.get_all_three_angle_gates(params, elementary_gates, three_angle_gates) end all_angle_gates_dict = merge(one_angle_gates_dict, two_angle_gates_dict, three_angle_gates_dict) gates_dict = Dict{String, Any}() counter = 1 for i=1:length(elementary_gates) if i in union(one_angle_gates, two_angle_gates, three_angle_gates) M_elementary_dict = all_angle_gates_dict[elementary_gates[i]] for k in keys(M_elementary_dict) # Angle for l in keys(M_elementary_dict[k]["$(num_qubits)qubit_rep"]) # qubits (which will now be 1) gates_dict["$counter"] = Dict{String, Any}("type" => [elementary_gates[i]], "angle" => Any, "qubit_loc" => l, "matrix" => M_elementary_dict[k]["$(num_qubits)qubit_rep"][l]) if i in one_angle_gates gates_dict["$counter"]["angle"] = M_elementary_dict[k]["angle"] elseif i in two_angle_gates gates_dict["$counter"]["angle"] = Dict{String, Any}("θ" => M_elementary_dict[k]["θ"], "ϕ" => M_elementary_dict[k]["ϕ"]) elseif i in three_angle_gates gates_dict["$counter"]["angle"] = Dict{String, Any}("θ" => M_elementary_dict[k]["θ"], "ϕ" => M_elementary_dict[k]["ϕ"], "λ" => M_elementary_dict[k]["λ"],) end counter += 1 end end else M = QCO.get_unitary(elementary_gates[i], num_qubits) gates_dict["$counter"] = Dict{String, Any}("type" => [elementary_gates[i]], "matrix" => M) counter += 1 end end are_elementary_gates_real = true for i in keys(gates_dict) if !(QCO.is_gate_real(gates_dict[i]["matrix"])) are_elementary_gates_real = false continue end end return gates_dict, are_elementary_gates_real end function get_all_one_angle_gates(params::Dict{String, Any}, elementary_gates::Array{String,1}, gates_idx::Vector{Int64}) gates_complex = Dict{String, Any}() if length(gates_idx) >= 1 for i=1:length(gates_idx) input_gate = elementary_gates[gates_idx[i]] gate_name = QCO._parse_gate_string(input_gate, type=true) if isempty(params[string(gate_name,"_discretization")]) Memento.error(_LOGGER, "Empty discretization angles for $(input_gate) gate. Input a valid angle") end angle_disc = Float64.(params[string(gate_name,"_discretization")]) gates_complex[input_gate] = Dict{String, Any}() gates_complex[input_gate] = QCO.get_discretized_one_angle_gates(input_gate, gates_complex[input_gate], angle_disc, params["num_qubits"]) end end return gates_complex end function get_discretized_one_angle_gates(gate_type::String, M1::Dict{String, Any}, discretization::Array{Float64,1}, num_qubits::Int64) if length(discretization) >= 1 for i=1:length(discretization) angles = discretization[i] M1["angle_$i"] = Dict{String, Any}("angle" => angles, "$(num_qubits)qubit_rep" => Dict{String, Any}() ) qubit_loc = QCO._parse_gate_string(gate_type, qubits=true) if length(qubit_loc) == 1 qubit_loc_str = string(qubit_loc[1]) elseif length(qubit_loc) == 2 qubit_loc_str = string(qubit_loc[1], qubit_separator, qubit_loc[2]) end M1["angle_$i"]["$(num_qubits)qubit_rep"]["qubit_$(qubit_loc_str)"] = QCO.get_unitary(gate_type, num_qubits, angle = angles) end end return M1 end # This function assumes that θ and ϕ are the only angle paramters in the input gate (like QCO.RGate()) function get_all_two_angle_gates(params::Dict{String, Any}, elementary_gates::Array{String,1}, gates_idx::Vector{Int64}) gates_complex = Dict{String, Any}() if length(gates_idx) >= 1 for i=1:length(gates_idx) input_gate = elementary_gates[gates_idx[i]] gate_name = QCO._parse_gate_string(input_gate, type = true) gates_complex[input_gate] = Dict{String, Any}() for angle in ["θ", "ϕ"] if isempty(params["$(gate_name)_$(angle)_discretization"]) Memento.error(_LOGGER, "Empty $(angle) discretization angle for $input_gate gate. Input atleast one valid angle") end end θ_disc = Vector{Float64}(params["$(gate_name)_θ_discretization"]) ϕ_disc = Vector{Float64}(params["$(gate_name)_ϕ_discretization"]) gates_complex[input_gate] = QCO.get_discretized_two_angle_gates(input_gate, gates_complex[input_gate], θ_disc, ϕ_disc, params["num_qubits"]) end end return gates_complex end # This function assumes that θ and ϕ are the only angle paramters in the input gate (like QCO.RGate()) function get_discretized_two_angle_gates(gate_type::String, M2::Dict{String, Any}, θ_discretization::Array{Float64,1}, ϕ_discretization::Array{Float64,1}, num_qubits::Int64) counter = 1 for i=1:length(θ_discretization) for j=1:length(ϕ_discretization) angles = [θ_discretization[i], ϕ_discretization[j]] M2["angle_$(counter)"] = Dict{String, Any}("θ" => angles[1], "ϕ" => angles[2], "$(num_qubits)qubit_rep" => Dict{String, Any}() ) if !(gate_type in QCO.MULTI_QUBIT_GATES) qubit_loc = QCO._parse_gate_string(gate_type, qubits=true) if length(qubit_loc) == 1 qubit_loc_str = string(qubit_loc[1]) elseif length(qubit_loc) == 2 qubit_loc_str = string(qubit_loc[1], qubit_separator, qubit_loc[2]) end M2["angle_$(counter)"]["$(num_qubits)qubit_rep"]["qubit_$(qubit_loc_str)"] = QCO.get_unitary(gate_type, num_qubits, angle = angles) else M2["angle_$(counter)"]["$(num_qubits)qubit_rep"]["multi_qubits"] = QCO.get_unitary(gate_type, num_qubits, angle = angles) end counter += 1 end end return M2 end function get_all_three_angle_gates(params::Dict{String, Any}, elementary_gates::Array{String,1}, gates_idx::Vector{Int64}) gates_complex = Dict{String, Any}() if length(gates_idx) >= 1 for i=1:length(gates_idx) input_gate = elementary_gates[gates_idx[i]] gate_name = QCO._parse_gate_string(input_gate, type = true) gates_complex[input_gate] = Dict{String, Any}() for angle in ["θ", "ϕ", "λ"] if isempty(params["$(gate_name)_$(angle)_discretization"]) Memento.error(_LOGGER, "Empty $(angle) discretization angle for $input_gate gate. Input atleast one valid angle") end end θ_disc = Vector{Float64}(params["$(gate_name)_θ_discretization"]) ϕ_disc = Vector{Float64}(params["$(gate_name)_ϕ_discretization"]) λ_disc = Vector{Float64}(params["$(gate_name)_λ_discretization"]) gates_complex[input_gate] = QCO.get_discretized_three_angle_gates(input_gate, gates_complex[input_gate], θ_disc, ϕ_disc, λ_disc, params["num_qubits"]) end end return gates_complex end function get_discretized_three_angle_gates(gate_type::String, M3::Dict{String, Any}, θ_discretization::Array{Float64,1}, ϕ_discretization::Array{Float64,1}, λ_discretization::Array{Float64,1}, num_qubits::Int64) counter = 1 for i=1:length(θ_discretization) for j=1:length(ϕ_discretization) for k=1:length(λ_discretization) angles = [θ_discretization[i], ϕ_discretization[j], λ_discretization[k]] M3["angle_$(counter)"] = Dict{String, Any}("θ" => angles[1], "ϕ" => angles[2], "λ" => angles[3], "$(num_qubits)qubit_rep" => Dict{String, Any}() ) qubit_loc = QCO._parse_gate_string(gate_type, qubits=true) if length(qubit_loc) == 1 qubit_loc_str = string(qubit_loc[1]) elseif length(qubit_loc) == 2 qubit_loc_str = string(qubit_loc[1], qubit_separator, qubit_loc[2]) end M3["angle_$(counter)"]["$(num_qubits)qubit_rep"]["qubit_$(qubit_loc_str)"] = QCO.get_unitary(gate_type, num_qubits, angle = angles) counter += 1 end end end return M3 end """ get_unitary(input::String, num_qubits::Int64; angle = nothing) Given an input string representing the gate and number of qubits of the circuit, this function returns a full-sized gate with respect to the input number of qubits. For example, if `num_qubits = 3` and the input gate in `H_3` (Hadamard on third qubit), then this function returns `IGate ⨂ IGate ⨂ HGate`, where IGate and HGate are single qubit Identity and Hadamard gates, respectively. Note that `angle` vector is an optional input which is necessary when the input gate is parametrized by Euler angles. """ function get_unitary(input::String, num_qubits::Int64; angle = nothing) if num_qubits > 10 Memento.error(_LOGGER, "Greater than 10 qubits is currently not supported") end if occursin(QCO.kron_symbol, input) return QCO.get_full_sized_kron_gate(input, num_qubits) end if input == "Identity" return QCO.IGate(num_qubits) end gate_type, qubit_loc = QCO._parse_gate_string(input, type = true, qubits = true) if !(gate_type in union(QCO.ONE_QUBIT_GATES, QCO.TWO_QUBIT_GATES, QCO.MULTI_QUBIT_GATES)) Memento.error(_LOGGER, "Specified $input gate does not exist in the predefined set of gates") end QCO._catch_input_gate_errors(gate_type, qubit_loc, num_qubits, input; angle = angle) #----------------------; # One qubit gates ; #----------------------; if length(qubit_loc) == 1 if gate_type in QCO.ONE_QUBIT_GATES_CONSTANTS return QCO.kron_single_qubit_gate(num_qubits, getfield(QCO, Symbol(gate_type, "Gate"))(), "q$(qubit_loc[1])") elseif gate_type in QCO.ONE_QUBIT_GATES_ANGLE_PARAMETERS if (angle !== nothing) && (length(angle) > 0) if length(angle) == 1 return QCO.kron_single_qubit_gate(num_qubits, getfield(QCO, Symbol(gate_type, "Gate"))(angle[1]), "q$(qubit_loc[1])") elseif length(angle) == 2 return QCO.kron_single_qubit_gate(num_qubits, getfield(QCO, Symbol(gate_type, "Gate"))(angle[1], angle[2]), "q$(qubit_loc[1])") elseif length(angle) == 3 return QCO.kron_single_qubit_gate(num_qubits, getfield(QCO, Symbol(gate_type, "Gate"))(angle[1], angle[2], angle[3]), "q$(qubit_loc[1])") end else Memento.error(_LOGGER, "Enter a valid angle parameter for the input $input gate") end end #----------------------; # Two qubit gates ; #----------------------; elseif length(qubit_loc) == 2 if gate_type in QCO.TWO_QUBIT_GATES_CONSTANTS if (qubit_loc[1] < qubit_loc[2]) || (gate_type in QCO.TWO_QUBIT_GATES_CONSTANTS_SYMMETRIC) return QCO.kron_two_qubit_gate(num_qubits, getfield(QCO, Symbol(gate_type, "Gate"))(), "q$(qubit_loc[1])", "q$(qubit_loc[2])") else return QCO.kron_two_qubit_gate(num_qubits, getfield(QCO, Symbol(gate_type, "RevGate"))(), "q$(qubit_loc[1])", "q$(qubit_loc[2])") end elseif gate_type in QCO.TWO_QUBIT_GATES_ANGLE_PARAMETERS if (angle !== nothing) && (length(angle) > 0) if length(angle) == 1 if (qubit_loc[1] < qubit_loc[2]) return QCO.kron_two_qubit_gate(num_qubits, getfield(QCO, Symbol(gate_type, "Gate"))(angle[1]), "q$(qubit_loc[1])", "q$(qubit_loc[2])") else return QCO.kron_two_qubit_gate(num_qubits, getfield(QCO, Symbol(gate_type, "RevGate"))(angle[1]), "q$(qubit_loc[1])", "q$(qubit_loc[2])") end elseif length(angle) == 3 if (qubit_loc[1] < qubit_loc[2]) return QCO.kron_two_qubit_gate(num_qubits, getfield(QCO, Symbol(gate_type, "Gate"))(angle[1], angle[2], angle[3]), "q$(qubit_loc[1])", "q$(qubit_loc[2])") else return QCO.kron_two_qubit_gate(num_qubits, getfield(QCO, Symbol(gate_type, "RevGate"))(angle[1], angle[2], angle[3]), "q$(qubit_loc[1])", "q$(qubit_loc[2])") end end else Memento.error(_LOGGER, "Enter a valid angle parameter for the input $input gate") end end #-----------------------; # Multi qubit gates ; #-----------------------; elseif gate_type in QCO.MULTI_QUBIT_GATES_ANGLE_PARAMETERS if (angle !== nothing) && (length(angle) == 2) return getfield(QCO, Symbol(gate_type, "Gate"))(num_qubits, angle[1], angle[2]) else Memento.error(_LOGGER, "Enter a valid angle parameter for the input $input gate") end end end """ get_full_sized_kron_gate(input::String, num_qubits::Int64) Given an input string with kronecker symbols representing the gate and number of qubits of the circuit, this function returns a full-sized gate with respect to the input number of qubits. For example, if `num_qubits = 3` and the input gate in `I_1xT_2xH_3`, then this function returns `IGate⨂TGate⨂HGate`, where IGate, TGate and HGate are single-qubit Identity, T and Hadamard gates, respectively. Two qubit gates can also be used as one of the input gates, for ex. `I_1xCV_2_3xH_4`. Note that this function currently does not support an input gate parametrized with Euler angles. """ function get_full_sized_kron_gate(input::String, num_qubits::Int64) kron_gates = QCO._parse_gates_with_kron_symbol(input) if length(unique(kron_gates)) !== length(kron_gates) Memento.error(_LOGGER, "Specify only a single gate per qubit within kron symbol gate $input") end M = 1 gate_qubit_locs = [] for i = 1:length(kron_gates) gate_type, qubit_loc = QCO._parse_gate_string(kron_gates[i], type = true, qubits = true) if !(gate_type in union(QCO.ONE_QUBIT_GATES_CONSTANTS, QCO.TWO_QUBIT_GATES_CONSTANTS)) Memento.error(_LOGGER, "Specified $input gate is not supported in conjunction with the Kronecker product operation") end QCO._catch_input_gate_errors(gate_type, qubit_loc, num_qubits, input) if issubset(qubit_loc, gate_qubit_locs) Memento.error(_LOGGER, "Specified qubit(s) for $input gate is incorrect") else append!(gate_qubit_locs, range(qubit_loc[1], qubit_loc[end])) end # One-qubit gates if (length(qubit_loc) == 1) && (gate_type in QCO.ONE_QUBIT_GATES_CONSTANTS) if (gate_type == "I") || (gate_type == "Identity") M = kron(M, getfield(QCO, Symbol(gate_type, "Gate"))(1)) else M = kron(M, getfield(QCO, Symbol(gate_type, "Gate"))()) end # Two-qubit gates elseif (length(qubit_loc) == 2) && (gate_type in QCO.TWO_QUBIT_GATES_CONSTANTS) gate_width = abs(qubit_loc[1] - qubit_loc[2]) if gate_width == 1 if (qubit_loc[1] < qubit_loc[2]) || (gate_type in QCO.TWO_QUBIT_GATES_CONSTANTS_SYMMETRIC) M = kron(M, getfield(QCO, Symbol(gate_type, "Gate"))()) else M = kron(M, getfield(QCO, Symbol(gate_type, "RevGate"))()) end else if (qubit_loc[1] < qubit_loc[2]) || (gate_type in QCO.TWO_QUBIT_GATES_CONSTANTS_SYMMETRIC) kron_gate = QCO.get_unitary(string(gate_type, qubit_separator, 1, qubit_separator, Int(gate_width + 1)), (gate_width + 1)) else kron_gate = QCO.get_unitary(string(gate_type, qubit_separator, Int(gate_width + 1), qubit_separator, 1), (gate_width + 1)) end M = kron(M, kron_gate) end end end QCO._catch_kron_dimension_errors(num_qubits, size(M)[1]) return M end """ get_input_circuit_dict(input_circuit::Vector{Tuple{Int64,String}}, params::Dict{String,Any}) Given the user input circuit which serves as a warm-start to the optimization model, and user input params dictionary, this function outputs the post-processed dictionary of the input circuit which is used by the optimization model. """ function get_input_circuit_dict(input_circuit::Vector{Tuple{Int64,String}}, params::Dict{String,Any}) input_circuit_dict = Dict{String, Any}() status = true gate_type = [] for i = 1:length(input_circuit) if !(input_circuit[i][2] in params["elementary_gates"]) status = false gate_type = input_circuit[i][2] end end if status for i = 1:length(input_circuit) if i == input_circuit[i][1] input_circuit_dict["$i"] = Dict{String, Any}("depth" => input_circuit[i][1], "gate" => input_circuit[i][2]) # Later: add support for universal and rotation gates here else input_circuit_dict = Dict{String, Any}() Memento.warn(_LOGGER, "Neglecting the input circuit as multiple gates cannot be input at the same depth") break end end else Memento.warn(_LOGGER, "Neglecting the input circuit as gate $gate_type is not in input elementary gates") end return input_circuit_dict end """ _catch_input_gate_errors(gate_type::String, qubit_loc::Vector{Int64}, num_qubits::Int64, input_gate::String) Given an input gate string, number of qubits of the circuit and the qubit locations for the input gate, this function catches and throws any errors, should the input gate type and qubits are invalid. """ function _catch_input_gate_errors(gate_type::String, qubit_loc::Vector{Int64}, num_qubits::Int64, input_gate::String; angle = nothing) if num_qubits <= 0 Memento.error(_LOGGER, "Specified number of qubits has to be >= 1") end if (gate_type in QCO.TWO_QUBIT_GATES) && (length(qubit_loc) != 2) Memento.error(_LOGGER, "Specify two qubits for 2-qubit gate $gate_type in elementary gates") elseif (gate_type in QCO.ONE_QUBIT_GATES) && (length(qubit_loc) == 0) Memento.error(_LOGGER, "Specify a qubit for the 1-qubit gate $gate_type in elementary gates") elseif (gate_type in QCO.ONE_QUBIT_GATES) && (length(qubit_loc) >= 2) Memento.error(_LOGGER, "Specify only one qubit for the 1-qubit gate $gate_type in elementary gates") end if isempty(qubit_loc) && (gate_type !== "GR") Memento.error(_LOGGER, "Specify a valid qubit location(s) for the input $input_gate gate") elseif (gate_type == "GR") && (!isempty(qubit_loc)) Memento.error(_LOGGER, "Qubit locations are not necessary for Global-R gate as it is simultaneously applied on all qubits at a depth") elseif !issubset(qubit_loc, 1:num_qubits) Memento.error(_LOGGER, "Specified qubit(s) for $input_gate gate ∉ {1,...,$num_qubits}") elseif (length(qubit_loc) == 2) && (isapprox(qubit_loc[1], qubit_loc[2])) Memento.error(_LOGGER, "Specified $input_gate gate cannot have identical control and target qubits") elseif length(qubit_loc) > 2 Memento.error(_LOGGER, "Only 1- and 2-qubit elementary gates are currently supported") end if !(gate_type in union(QCO.ONE_QUBIT_GATES_ANGLE_PARAMETERS, QCO.TWO_QUBIT_GATES_ANGLE_PARAMETERS, QCO.MULTI_QUBIT_GATES_ANGLE_PARAMETERS)) && (angle !== nothing) Memento.warn(_LOGGER, "Neglecting the angle input for gate $(gate_type) with constant parameters") end end function _get_R_XYZ_gates_idx(elementary_gates::Array{String,1}) return findall(x -> (startswith(x, "RX") || startswith(x, "RY") || startswith(x, "RZ")) && !(occursin(kron_symbol, x)), elementary_gates) end function _get_R_gates_idx(elementary_gates::Array{String,1}) return findall(x -> startswith(x, "R") && !(startswith(x, "RX") || startswith(x, "RY") || startswith(x, "RZ")) && !(occursin(kron_symbol, x)), elementary_gates) end function _get_GR_gates_idx(elementary_gates::Array{String,1}) return findall(x -> (startswith(x, "GR")) && !(occursin(kron_symbol, x)), elementary_gates) end function _get_U3_gates_idx(elementary_gates::Array{String,1}) return findall(x -> (startswith(x, "U3")) && !(occursin(kron_symbol, x)), elementary_gates) end function _get_CR_gates_idx(elementary_gates::Array{String,1}) return findall(x -> (startswith(x, "CRX") || startswith(x, "CRY") || startswith(x, "CRZ")) && !(occursin(kron_symbol, x)), elementary_gates) end function _get_CU3_gates_idx(elementary_gates::Array{String, 1}) return findall(x -> (startswith(x, "CU3")) && !(occursin(kron_symbol, x)), elementary_gates) end function _get_Phase_gates_idx(elementary_gates::Array{String, 1}) return findall(x -> (startswith(x, "Phase")) && !(occursin(kron_symbol, x)), elementary_gates) end function _get_identity_idx(M::Array{Float64,3}) identity_idx = Int64[] for i=1:size(M)[3] if isapprox(M[:,:,i], Matrix(I, size(M)[1], size(M)[2]), atol=1E-5) push!(identity_idx, i) end end return identity_idx end function _get_cnot_idx(gates_dict::Dict{String, Any}) cnot_idx = Int64[] # Counts for both (CNot_i_j and CNot_j_i) or (CX_i_j and CX_j_i) for i in keys(gates_dict) # Input gates with kron symbols if occursin(kron_symbol, gates_dict[i]["type"][1]) gate_types = QCO._parse_gates_with_kron_symbol(gates_dict[i]["type"][1]) for j = 1:length(gate_types) gate_type = QCO._parse_gate_string(gate_types[j], type = true) if gate_type in ["CNot", "CX"] push!(cnot_idx, parse(Int64, i)) end end else # Single input gate per depth if "Identity" in gates_dict[i]["type"] continue end gate_type = QCO._parse_gate_string(gates_dict[i]["type"][1], type = true) if gate_type in ["CNot", "CX"] push!(cnot_idx, parse(Int64, i)) end end end return cnot_idx end function _get_angle_gates_idx(elementary_gates::Array{String,1}) # Update this list as new gates with angle parameters are added in gates.jl R_XYZ_gates_idx = QCO._get_R_XYZ_gates_idx(elementary_gates) R_gates_idx = QCO._get_R_gates_idx(elementary_gates) GR_gates_idx = QCO._get_GR_gates_idx(elementary_gates) Phase_gates_idx = QCO._get_Phase_gates_idx(elementary_gates) CR_gates_idx = QCO._get_CR_gates_idx(elementary_gates) U3_gates_idx = QCO._get_U3_gates_idx(elementary_gates) CU3_gates_idx = QCO._get_CU3_gates_idx(elementary_gates) one_angle_gates = union(R_XYZ_gates_idx, Phase_gates_idx, CR_gates_idx) two_angle_gates = union(R_gates_idx, GR_gates_idx) three_angle_gates = union(U3_gates_idx, CU3_gates_idx) return one_angle_gates, two_angle_gates, three_angle_gates end function _get_cnot_bounds!(data::Dict{String, Any}, params::Dict{String, Any}) cnot_lb = 0 cnot_ub = data["maximum_depth"] if "set_cnot_lower_bound" in keys(params) cnot_lb = params["set_cnot_lower_bound"] end if "set_cnot_upper_bound" in keys(params) cnot_ub = params["set_cnot_upper_bound"] end if cnot_lb > data["maximum_depth"] Memento.error(_LOGGER, "Invalid lower bound on the number of CNOT gates given the maximum depth") end if cnot_lb < cnot_ub if cnot_lb > 0 data["cnot_lower_bound"] = params["set_cnot_lower_bound"] end if cnot_ub < data["maximum_depth"] data["cnot_upper_bound"] = params["set_cnot_upper_bound"] end elseif isapprox(cnot_lb, cnot_ub, atol=1E-6) data["cnot_lower_bound"] = cnot_lb data["cnot_upper_bound"] = cnot_ub else Memento.warn(_LOGGER, "Invalid CNot-gate lower/upper bound") end return data end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
46605
#= IMPORTANT: a) Update the lists below whenever a 1 or 2 qubit gate is added to this file. b) Update QCO._get_angle_gates_idx in src/data.jl if gates with angle parameters are added to this file. =# const ONE_QUBIT_GATES_ANGLE_PARAMETERS = ["U3", "U2", "U1", "R", "RX", "RY", "RZ", "Phase"] const ONE_QUBIT_GATES_CONSTANTS = ["Identity", "I", "H", "X", "Y", "Z", "S", "Sdagger", "T", "Tdagger", "SX", "SXdagger"] const TWO_QUBIT_GATES_ANGLE_PARAMETERS = ["CRX", "CRXRev", "CRY", "CRYRev", "CRZ", "CRZRev", "CU3", "CU3Rev"] # >= 3 qubit gates const MULTI_QUBIT_GATES_ANGLE_PARAMETERS = ["GR"] # Gates invariant to qubit flip const TWO_QUBIT_GATES_CONSTANTS_SYMMETRIC = ["Swap", "SSwap", "iSwap", "Sycamore", "DCX", "W", "M", "CZ", "QFT2", "HCoin", "GroverDiffusion", "CS", "CSdagger", "CT", "CTdagger"] # Gates non-invariant to qubit flip const TWO_QUBIT_GATES_CONSTANTS_ASYMMETRIC = ["CNot", "CNotRev", "CX", "CXRev", "CY", "CYRev", "CH", "CHRev", "CV", "CVRev", "CVdagger", "CVdaggerRev", "CSX", "CSXRev"] const ONE_QUBIT_GATES = union(QCO.ONE_QUBIT_GATES_CONSTANTS, QCO.ONE_QUBIT_GATES_ANGLE_PARAMETERS) const TWO_QUBIT_GATES_CONSTANTS = union(QCO.TWO_QUBIT_GATES_CONSTANTS_SYMMETRIC, QCO.TWO_QUBIT_GATES_CONSTANTS_ASYMMETRIC) const TWO_QUBIT_GATES = union(QCO.TWO_QUBIT_GATES_CONSTANTS, QCO.TWO_QUBIT_GATES_ANGLE_PARAMETERS) # >= 3 qubit gates const MULTI_QUBIT_GATES = union(QCO.MULTI_QUBIT_GATES_ANGLE_PARAMETERS) """ _catch_gate_name_error() Helper function to ensure that the kron_symbol `x` does not appear in any of the gate names. """ function _catch_gate_name_error() all_gates = union(QCO.ONE_QUBIT_GATES, QCO.TWO_QUBIT_GATES, QCO.MULTI_QUBIT_GATES) if length(findall(x -> occursin(QCO.kron_symbol, x), all_gates)) > 0 Memento.error(_LOGGER, "Avoid the character `$(QCO.kron_symbol)` in the elemetary gate name") end end QCO._catch_gate_name_error() #-------------------------------------# # ONE QUBIT gates # #-------------------------------------# @doc raw""" IGate(num_qubits::Int64) Identity matrix for an input number of qubits. **Matrix Representation (num_qubits = 1)** ```math I = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} ``` """ function IGate(num_qubits::Int64) return Array{Complex{Float64},2}(Matrix(LA.I, 2^num_qubits, 2^num_qubits)) end @doc raw""" U3Gate(θ::Number, ϕ::Number, λ::Number) Universal single-qubit rotation gate with three Euler angles, ``\theta``, ``\phi`` and ``\lambda``. **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} U3(\theta, \phi, \lambda) = \begin{pmatrix} \cos(\th) & -e^{i\lambda}\sin(\th) \\ e^{i\phi}\sin(\th) & e^{i(\phi+\lambda)}\cos(\th) \end{pmatrix} ``` """ function U3Gate(θ::Number, ϕ::Number, λ::Number) QCO._verify_angle_bounds(θ) QCO._verify_angle_bounds(ϕ) QCO._verify_angle_bounds(λ) U3 = Array{Complex{Float64},2}([ cos(θ/2) -(cos(λ) + (sin(λ))im)*sin(θ/2) (cos(ϕ) + (sin(ϕ))im)*sin(θ/2) (cos(λ+ϕ) + (sin(λ+ϕ))im)*cos(θ/2)]) return QCO.round_complex_values(U3) end @doc raw""" U2Gate(ϕ::Number, λ::Number) Universal single-qubit rotation gate with two Euler angles, ``\phi`` and ``\lambda``. U2Gate is the special case of [U3Gate](@ref). **Matrix Representation** ```math U2(\phi, \lambda) = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & -e^{i\lambda} \\ e^{i\phi} & e^{i(\phi+\lambda)} \end{pmatrix} ``` """ function U2Gate(ϕ::Number, λ::Number) θ = π/2 U2 = QCO.U3Gate(θ, ϕ, λ) return U2 end @doc raw""" U1Gate(λ::Number) Universal single-qubit rotation gate with one Euler angle, ``\lambda``. U1Gate represents rotation about the Z axis and is the special case of [U3Gate](@ref), which also known as the [PhaseGate](@ref). Also note that ``U1(\pi) = ``[ZGate](@ref), ``U1(\pi/2) = ``[SGate](@ref) and ``U1(\pi/4) = ``[TGate](@ref). **Matrix Representation** ```math U1(\lambda) = \begin{pmatrix} 1 & 0 \\ 0 & e^{i\lambda} \end{pmatrix} ``` """ function U1Gate(λ::Number) θ = 0 ϕ = 0 U1 = QCO.U3Gate(θ, ϕ, λ) return U1 end @doc raw""" RGate(θ::Number, ϕ::Number) A single-qubit rotation gate with two Euler angles, ``\theta`` and ``\phi``, about the ``\cos(\phi)x + \sin(\phi)y`` axis. **Matrix Representation** ```math R(\theta, \phi) = e^{-i \theta \left(\cos{\phi} x + \sin{\phi} y\right)} = \begin{pmatrix} \cos{\theta} & -i e^{-i \phi} \sin{\theta} \\ -i e^{i \phi} \sin{\theta} & \cos{\theta} \end{pmatrix} ``` """ function RGate(θ::Number, ϕ::Number) R = Array{Complex{Float64},2}([cos(θ/2) -(sin(ϕ) + (cos(ϕ))im)*sin(θ/2) (sin(ϕ) - (cos(ϕ))im)*sin(θ/2) cos(θ/2)]) return QCO.round_complex_values(R) end @doc raw""" RXGate(θ::Number) A single-qubit Pauli gate which represents rotation about the X axis. **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} RX(\theta) = exp(-i \th X) = \begin{pmatrix} \cos{\th} & -i\sin{\th} \\ -i\sin{\th} & \cos{\th} \end{pmatrix} ``` """ function RXGate(θ::Number) QCO._verify_angle_bounds(θ) RX = Array{Complex{Float64},2}([cos(θ/2) -(sin(θ/2))im; -(sin(θ/2))im cos(θ/2)]) return QCO.round_complex_values(RX) end @doc raw""" RYGate(θ::Number) A single-qubit Pauli gate which represents rotation about the Y axis. **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} RY(\theta) = exp(-i \th Y) = \begin{pmatrix} \cos{\th} & -\sin{\th} \\ \sin{\th} & \cos{\th} \end{pmatrix} ``` """ function RYGate(θ::Number) QCO._verify_angle_bounds(θ) RY = Array{Complex{Float64},2}([cos(θ/2) -(sin(θ/2)); (sin(θ/2)) cos(θ/2)]) return QCO.round_complex_values(RY) end @doc raw""" RZGate(θ::Number) A single-qubit Pauli gate which represents rotation about the Z axis. This gate is also equivalent to [U1Gate](@ref) up to a phase factor, that is, ``RZ(\theta) = e^{-i{\theta}/2}U1(\theta)``. **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} RZ(\theta) = exp(-i\th Z) = \begin{pmatrix} e^{-i\th} & 0 \\ 0 & e^{i\th} \end{pmatrix} ``` """ function RZGate(θ::Number) QCO._verify_angle_bounds(θ) RZ = Array{Complex{Float64},2}([(cos(θ/2) - (sin(θ/2))im) 0; 0 (cos(θ/2) + (sin(θ/2))im)]) return QCO.round_complex_values(RZ) end @doc raw""" HGate() Single-qubit Hadamard gate, which is a ``\pi`` rotation about the X+Z axis, thus equivalent to [U3Gate](@ref)(``\frac{\pi}{2},0,\pi``) **Matrix Representation** ```math H = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix} ``` """ function HGate() return Array{Complex{Float64},2}(1/sqrt(2)*[1 1; 1 -1]) end @doc raw""" XGate() Single-qubit Pauli-X gate (``\sigma_x``), equivalent to [U3Gate](@ref)(``\pi,0,\pi``) **Matrix Representation** ```math X = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} ``` """ function XGate() return Array{Complex{Float64},2}([0 1; 1 0]) end @doc raw""" YGate() Single-qubit Pauli-Y gate (``\sigma_y``), equivalent to [U3Gate](@ref)(``\pi,\frac{\pi}{2},\frac{\pi}{2}``) **Matrix Representation** ```math Y = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix} ``` """ function YGate() return Array{Complex{Float64},2}([0 -im; im 0]) end @doc raw""" ZGate() Single-qubit Pauli-Z gate (``\sigma_z``), equivalent to [U3Gate](@ref)(``0,0,\pi``) **Matrix Representation** ```math Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} ``` """ function ZGate() return Array{Complex{Float64},2}([1 0; 0 -1]) end @doc raw""" SGate() Single-qubit S gate, equivalent to [U3Gate](@ref)(``0,0,\frac{\pi}{2}``). This gate is also referred to as a Clifford gate, P gate or a square-root of Pauli-[ZGate](@ref). Historically, this is also called as the phase gate (denoted by P), since it shifts the phase of the one state relative to the zero state. **Matrix Representation** ```math S = \begin{pmatrix} 1 & 0 \\ 0 & i \end{pmatrix} ``` """ function SGate() return Array{Complex{Float64},2}([1 0; 0 im]) end @doc raw""" SdaggerGate() Single-qubit, hermitian conjugate of the [SGate](@ref). This is also an alternative square root of the [ZGate](@ref). **Matrix Representation** ```math S = \begin{pmatrix} 1 & 0 \\ 0 & -i \end{pmatrix} ``` """ function SdaggerGate() return Array{Complex{Float64},2}([1 0; 0 -im]) end @doc raw""" TGate() Single-qubit T gate, equivalent to [U3Gate](@ref)(``0,0,\frac{\pi}{4}``). This gate is also referred to as a ``\frac{\pi}{8}`` gate or as a fourth-root of Pauli-[ZGate](@ref). **Matrix Representation** ```math T = \begin{pmatrix} 1 & 0 \\ 0 & e^{i\pi/4} \end{pmatrix} ``` """ function TGate() return Array{Complex{Float64},2}([1 0; 0 (1/sqrt(2)) + (1/sqrt(2))im]) end @doc raw""" TdaggerGate() Single-qubit, hermitian conjugate of the [TGate](@ref). This gate is equivalent to [U3Gate](@ref)(``0,0,-\frac{\pi}{4}``). This gate is also referred to as the fourth-root of Pauli-[ZGate](@ref). **Matrix Representation** ```math T^{\dagger} = \begin{pmatrix} 1 & 0 \\ 0 & e^{-i\pi/4} \end{pmatrix} ``` """ function TdaggerGate() return Array{Complex{Float64},2}([1 0; 0 (1/sqrt(2)) - (1/sqrt(2))im]) end @doc raw""" SXGate() Single-qubit square root of pauli-[XGate](@ref). **Matrix Representation** ```math \sqrt{X} = \frac{1}{2} \begin{pmatrix} 1 + i & 1 - i \\ 1 - i & 1 + i \end{pmatrix} ``` """ function SXGate() return Array{Complex{Float64},2}(1/2*[1+im 1-im; 1-im 1+im]) end @doc raw""" SXdaggerGate() Single-qubit hermitian conjugate of the square root of pauli-[XGate](@ref), or the [SXGate](@ref). **Matrix Representation** ```math \sqrt{X}^{\dagger} = \frac{1}{2} \begin{pmatrix} 1 - i & 1 + i \\ 1 + i & 1 - i \end{pmatrix} ``` """ function SXdaggerGate() return Array{Complex{Float64},2}(1/2*[1-im 1+im; 1+im 1-im]) end @doc raw""" PhaseGate(λ::Number) Single-qubit rotation gate about the Z axis. This is also equivalent to [U3Gate](@ref)(``0,0,\lambda``). This gate is also referred to as the [U1Gate](@ref). **Matrix Representation** ```math P(\lambda) = \begin{pmatrix} 1 & 0 \\ 0 & e^{i\lambda} \end{pmatrix} ``` """ function PhaseGate(λ::Number) return QCO.U1Gate(λ) end #-------------------------------------# # TWO-QUBIT GATES # #-------------------------------------# @doc raw""" CNotGate() Two-qubit controlled NOT gate with control and target on first and second qubits, respectively. This is also called the controlled X gate ([CXGate](@ref)). **Circuit Representation** ``` q_0: ──■── ┌─┴─┐ q_1: ┤ X ├ └───┘ ``` **Matrix Representation** ```math CNot = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{pmatrix} ``` """ function CNotGate() return QCO.controlled_gate(QCO.XGate(), 1) end @doc raw""" CNotRevGate() Two-qubit reverse controlled NOT gate, with target and control on first and second qubits, respectively. **Circuit Representation** ``` ┌───┐ q_0: ┤ X ├ └─┬─┘ q_1: ──■── ``` **Matrix Representation** ```math CNotRev = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \end{pmatrix} ``` """ function CNotRevGate() return QCO.controlled_gate(QCO.XGate(), 1, reverse = true) end @doc raw""" DCXGate() Two-qubit double controlled NOT gate consisting of two back-to-back [CNotGate](@ref)s with alternate controls. **Circuit Representation** ``` ┌───┐ q_0: ──■──┤ X ├ ┌─┴─┐└─┬─┘ q_1: ┤ X ├──■── └───┘ ``` **Matrix Representation** ```math DCX = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \end{pmatrix} ``` """ function DCXGate() return Array{Complex{Float64},2}([1 0 0 0; 0 0 0 1; 0 1 0 0; 0 0 1 0]) end @doc raw""" CXGate() Two-qubit controlled [XGate](@ref), which is also the same as [CNotGate](@ref). **Circuit Representation** ``` q_0: ──■── ┌─┴─┐ q_1: ┤ X ├ └───┘ ``` **Matrix Representation** ```math CX = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{pmatrix} ``` """ function CXGate() return QCO.controlled_gate(QCO.XGate(), 1) end @doc raw""" CXRevGate() Two-qubit reverse controlled-X gate, with target and control on first and second qubits, respectively. This is also the same as [CNotRevGate](@ref). **Circuit Representation** ``` ┌───┐ q_0: ┤ X ├ └─┬─┘ q_1: ──■── ``` **Matrix Representation** ```math CXRev = I \otimes |0 \rangle\langle 0| + X \otimes |1 \rangle\langle 1| = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \end{pmatrix} ``` """ function CXRevGate() return QCO.controlled_gate(QCO.XGate(), 1, reverse = true) end @doc raw""" CYGate() Two-qubit controlled [YGate](@ref). **Circuit Representation** ``` q_0: ──■── ┌─┴─┐ q_1: ┤ Y ├ └───┘ ``` **Matrix Representation** ```math CY = |0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes Y = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & -i \\ 0 & 0 & i & 0 \end{pmatrix} ``` """ function CYGate() return QCO.controlled_gate(QCO.YGate(), 1) end @doc raw""" CYRevGate() Two-qubit reverse controlled-Y gate, with target and control on first and second qubits, respectively. **Circuit Representation** ``` ┌───┐ q_0: ┤ Y ├ └─┬─┘ q_1: ──■── ``` **Matrix Representation** ```math CYRev = I \otimes |0 \rangle\langle 0| + Y \otimes |1 \rangle\langle 1| = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & -i \\ 0 & 0 & 1 & 0 \\ 0 & i & 0 & 0 \end{pmatrix} ``` """ function CYRevGate() return QCO.controlled_gate(QCO.YGate(), 1, reverse = true) end @doc raw""" CZGate() Two-qubit, symmetric, controlled [ZGate](@ref). **Circuit Representation** ``` q_0: ──■── ─■─ ┌─┴─┐ ≡ │ q_1: ┤ Z ├ ─■─ └───┘ ``` **Matrix Representation** ```math CZ = |0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes Z = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & -1 \end{pmatrix} ``` """ function CZGate() return QCO.controlled_gate(QCO.ZGate(), 1) end @doc raw""" CHGate() Two-qubit, symmetric, controlled Hadamard gate ([HGate](@ref)). **Circuit Representation** ``` q_0: ──■── ┌─┴─┐ q_1: ┤ H ├ └───┘ ``` **Matrix Representation** ```math CH = |0\rangle\langle 0| \otimes I + |1\rangle\langle 1| \otimes H = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\ 0 & 0 & \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}} \end{pmatrix} ``` """ function CHGate() return QCO.controlled_gate(QCO.HGate(), 1) end @doc raw""" CHRevGate() Two-qubit reverse controlled-H gate, with target and control on first and second qubits, respectively. **Circuit Representation** ``` ┌───┐ q_0: ┤ H ├ └─┬─┘ q_1: ──■── ``` **Matrix Representation** ```math CHRev = I \otimes |0\rangle\langle 0| + H \otimes |1\rangle\langle 1| = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \frac{1}{\sqrt{2}} & 0 & \frac{1}{\sqrt{2}} \\ 0 & 0 & 1 & 0 \\ 0 & \frac{1}{\sqrt{2}} & 0 & -\frac{1}{\sqrt{2}} \end{pmatrix} ``` """ function CHRevGate() return QCO.controlled_gate(QCO.HGate(), 1, reverse = true) end @doc raw""" CVGate() Two-qubit, controlled-V gate, which is also the same as Controlled square-root of X gate ([CSXGate](@ref)). **Circuit Representation** ``` q_0: ──■── ┌─┴─┐ q_1: ┤ V ├ └───┘ ``` **Matrix Representation** ```math CV = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0.5+0.5i & 0.5-0.5i \\ 0 & 0 & 0.5-0.5i & 0.5+0.5i \end{pmatrix} ``` """ function CVGate() return QCO.CSXGate() end @doc raw""" CVRevGate() Two-qubit reverse controlled-V gate, with target and control on first and second qubits, respectively. **Circuit Representation** ``` ┌───┐ q_0: ┤ V ├ └─┬─┘ q_1: ──■── ``` **Matrix Representation** ```math CVRev = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0.5+0.5i & 0 & 0.5-0.5i \\ 0 & 0 & 1 & 0 \\ 0 & 0.5-0.5i & 0 & 0.5+0.5i \end{pmatrix} ``` """ function CVRevGate() return Array{Complex{Float64},2}([1 0 0 0; 0 0.5+0.5im 0 0.5-0.5im; 0 0 1 0; 0 0.5-0.5im 0 0.5+0.5im]) end @doc raw""" CVdaggerGate() Two-qubit hermitian conjugate of controlled-V gate, which is also the same as hermitian conjugate Controlled square-root of X gate ([CSXGate](@ref)). **Circuit Representation** ``` q_0: ──■── ┌─┴─┐ q_1: ┤ V'├ └───┘ ``` **Matrix Representation** ```math CVdagger = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0.5-0.5i & 0.5+0.5i \\ 0 & 0 & 0.5+0.5i & 0.5-0.5i \end{pmatrix} ``` """ function CVdaggerGate() return Array{Complex{Float64},2}([1 0 0 0; 0 1 0 0; 0 0 0.5-0.5im 0.5+0.5im; 0 0 0.5+0.5im 0.5-0.5im]) end @doc raw""" CVdaggerRevGate() Two-qubit hermitian conjugate of reverse controlled-V gate, with target and control on first and second qubits, respectively. **Circuit Representation** ``` ┌───┐ q_0: ┤ V'├ └─┬─┘ q_1: ──■── ``` **Matrix Representation** ```math CVdaggerRev = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0.5-0.5i & 0 & 0.5+0.5i \\ 0 & 0 & 1 & 0 \\ 0 & 0.5+0.5i & 0 & 0.5-0.5i \end{pmatrix} ``` """ function CVdaggerRevGate() return Array{Complex{Float64},2}([1 0 0 0; 0 0.5-0.5im 0 0.5+0.5im; 0 0 1 0; 0 0.5+0.5im 0 0.5-0.5im]) end @doc raw""" CSGate() Two-qubit, controlled-S gate, which induces π/2 phase in the target qubit. This gate is invariant to the swap of control and target qubits. **Circuit Representation** ``` q_0: ──■── ┌─┴─┐ q_1: ┤ S ├ └───┘ ``` **Matrix Representation** ```math CS = |0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes S = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & i \end{pmatrix} ``` """ function CSGate() return QCO.controlled_gate(QCO.SGate(), 1) end @doc raw""" CSdaggerGate() Two-qubit hermitian conjugate of controlled-S gate. This gate is invariant to the swap of control and target qubits. **Circuit Representation** ``` q_0: ──■── ┌─┴─┐ q_1: ┤ S'├ └───┘ ``` **Matrix Representation** ```math CSdagger = |0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes S^{\dagger} = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & -i \end{pmatrix} ``` """ function CSdaggerGate() return QCO.controlled_gate(QCO.SdaggerGate(), 1) end @doc raw""" CTGate() Two-qubit, controlled-T gate, which induces a π/4 phase in the target qubit. This gate is invariant to the swap of control and target qubits. **Circuit Representation** ``` q_0: ──■── ┌─┴─┐ q_1: ┤ T ├ └───┘ ``` **Matrix Representation** ```math CT = |0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes T = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & e^{i\pi/4} \end{pmatrix} ``` """ function CTGate() return QCO.controlled_gate(QCO.TGate(), 1) end @doc raw""" CTdaggerGate() Two-qubit hermitian conjugate of controlled-T gate. This gate is invariant to the swap of control and target qubits. **Circuit Representation** ``` q_0: ──■── ┌─┴─┐ q_1: ┤ T'├ └───┘ ``` **Matrix Representation** ```math CTdagger = |0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes T^{\dagger} = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & e^{-i\pi/4} \end{pmatrix} ``` """ function CTdaggerGate() return QCO.controlled_gate(QCO.TdaggerGate(), 1) end @doc raw""" WGate() Two-qubit, W hermitian gate, typically useful to diagonlize the ([SwapGate](@ref)). **Matrix Representation** ```math W = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} & 0 \\ 0 & \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}} & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} ``` """ function WGate() return Array{Complex{Float64},2}([1 0 0 0; 0 1/sqrt(2) 1/sqrt(2) 0; 0 1/sqrt(2) -1/sqrt(2) 0; 0 0 0 1]) end @doc raw""" CRXGate(θ::Number) Two-qubit controlled [RXGate](@ref). **Circuit Representation** ``` q_0: ────■──── ┌───┴───┐ q_1: ┤ RX(ϴ) ├ └───────┘ ``` **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} CRX(\theta)\ q_1, q_0 = |0\rangle\langle0| \otimes I + |1\rangle\langle1| \otimes RX(\theta) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \cos{\th} & -i\sin{\th} \\ 0 & 0 & -i\sin{\th} & \cos{\th} \end{pmatrix} ``` """ function CRXGate(θ::Number) CRX = Array{Complex{Float64},2}([ 1 0 0 0 0 1 0 0 0 0 cos(θ/2) -(sin(θ/2))im 0 0 -(sin(θ/2))im cos(θ/2)]) return QCO.round_complex_values(CRX) end @doc raw""" CRXRevGate(θ::Number) Two-qubit controlled reverse [RXGate](@ref). **Circuit Representation** ``` ┌───────┐ q_1: ┤ RX(ϴ) ├ └───┬───┘ q_0: ────■──── ``` **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} CRXRev(\theta)\ q_1, q_0 = |0\rangle\langle0| \otimes I + |1\rangle\langle1| \otimes RX(\theta) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos{\th} & 0 & -i\sin{\th} \\ 0 & 0 & 1 & 0\\ 0 & -i\sin{\th} & 0 & \cos{\th} \end{pmatrix} ``` """ function CRXRevGate(θ::Number) CRXRev = Array{Complex{Float64},2}([1 0 0 0 0 cos(θ/2) 0 -(sin(θ/2))im 0 0 1 0 0 -(sin(θ/2))im 0 cos(θ/2)]) return QCO.round_complex_values(CRXRev) end @doc raw""" CRYGate(θ::Number) Two-qubit controlled [RYGate](@ref). **Circuit Representation** ``` q_0: ────■──── ┌───┴───┐ q_1: ┤ RY(ϴ) ├ └───────┘ ``` **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} CRY(\theta)\ q_1, q_0 = |0\rangle\langle0| \otimes I + |1\rangle\langle1| \otimes RY(\theta) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \cos{\th} & -\sin{\th} \\ 0 & 0 & \sin{\th} & \cos{\th} \end{pmatrix} ``` """ function CRYGate(θ::Number) QCO._verify_angle_bounds(θ) CRY = Array{Complex{Float64},2}([1 0 0 0 0 1 0 0 0 0 cos(θ/2) -(sin(θ/2)) 0 0 (sin(θ/2)) cos(θ/2)]) return QCO.round_complex_values(CRY) end @doc raw""" CRYRevGate(θ::Number) Two-qubit controlled reverse [RYGate](@ref). **Circuit Representation** ``` ┌───────┐ q_1: ┤ RY(ϴ) ├ └───┬───┘ q_0: ────■──── ``` **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} CRYRev(\theta)\ q_1, q_0 = |0\rangle\langle0| \otimes I + |1\rangle\langle1| \otimes RY(\theta) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos{\th} & 0 & -\sin{\th} \\ 0 & 0 & 1 & 0 \\ 0 & \sin{\th} & 0 & \cos{\th} \end{pmatrix} ``` """ function CRYRevGate(θ::Number) QCO._verify_angle_bounds(θ) CRYRev = Array{Complex{Float64},2}([ 1 0 0 0 0 cos(θ/2) 0 -(sin(θ/2)) 0 0 1 0 0 (sin(θ/2)) 0 cos(θ/2)]) return QCO.round_complex_values(CRYRev) end @doc raw""" CRZGate(θ::Number) Two-qubit controlled [RZGate](@ref). **Circuit Representation** ``` q_0: ────■──── ┌───┴───┐ q_1: ┤ RZ(ϴ) ├ └───────┘ ``` **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} CRZ(\theta)\ q_1, q_0 = |0\rangle\langle0| \otimes I + |1\rangle\langle1| \otimes RZ(\theta) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & e^{-i\th} & 0 \\ 0 & 0 & 0 & e^{i\th} \end{pmatrix} ``` """ function CRZGate(θ::Number) QCO._verify_angle_bounds(θ) CRZ = Array{Complex{Float64},2}([ 1 0 0 0 0 1 0 0 0 0 (cos(θ/2) - (sin(θ/2))im) 0 0 0 0 (cos(θ/2) + (sin(θ/2))im)]) return QCO.round_complex_values(CRZ) end @doc raw""" CRZRevGate(θ::Number) Two-qubit controlled reverse [RZGate](@ref). **Circuit Representation** ``` ┌───────┐ q_1: ┤ RZ(ϴ) ├ └───┬───┘ q_0: ────■──── ``` **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} CRZRev(\theta)\ q_1, q_0 = |0\rangle\langle0| \otimes I + |1\rangle\langle1| \otimes RZ(\theta) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & e^{-i\th} & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & e^{i\th} \end{pmatrix} ``` """ function CRZRevGate(θ::Number) QCO._verify_angle_bounds(θ) CRZRev = Array{Complex{Float64},2}([ 1 0 0 0 0 (cos(θ/2) - (sin(θ/2))im) 0 0 0 0 1 0 0 0 0 (cos(θ/2) + (sin(θ/2))im)]) return QCO.round_complex_values(CRZRev) end @doc raw""" CU3Gate(θ::Number, ϕ::Number, λ::Number) Two-qubit, controlled version of the universal rotation gate with three Euler angles ([U3Gate](@ref)). **Circuit Representation** ``` q_0: ──────■────── ┌─────┴─────┐ q_1: ┤ U3(ϴ,φ,λ) ├ └───────────┘ ``` **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} CU3(\theta, \phi, \lambda)\ q_1, q_0 = |0\rangle\langle 0| \otimes I + |1\rangle\langle 1| \otimes U3(\theta,\phi,\lambda) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \cos(\th) & -e^{i\lambda}\sin(\th) \\ 0 & 0 & e^{i\phi}\sin(\th) & e^{i(\phi+\lambda)}\cos(\th) \end{pmatrix} ``` """ function CU3Gate(θ::Number, ϕ::Number, λ::Number) QCO._verify_angle_bounds(θ) QCO._verify_angle_bounds(ϕ) QCO._verify_angle_bounds(λ) CU3 = Array{Complex{Float64},2}([ 1 0 0 0 0 1 0 0 0 0 cos(θ/2) -(cos(λ)+(sin(λ))im)*sin(θ/2) 0 0 (cos(ϕ)+(sin(ϕ))im)*sin(θ/2) (cos(λ+ϕ)+(sin(λ+ϕ))im)*cos(θ/2)]) return QCO.round_complex_values(CU3) end @doc raw""" CU3RevGate(θ::Number, ϕ::Number, λ::Number) Two-qubit, reverse controlled version of the universal rotation gate with three Euler angles ([U3Gate](@ref)). **Circuit Representation** ``` ┌────────────┐ q_1: ┤ U3(ϴ,φ,λ) ├ └──────┬─────┘ q_0: ───────■────── ``` **Matrix Representation** ```math \newcommand{\th}{\frac{\theta}{2}} CU3(\theta, \phi, \lambda)\ q_1, q_0 = |0\rangle\langle 0| \otimes I + |1\rangle\langle 1| \otimes U3(\theta,\phi,\lambda) = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos(\th) & 0 & -e^{i\lambda}\sin(\th) \\ 0 & 0 & 1 & 0 \\ 0 & e^{i\phi}\sin(\th) & 0 & e^{i(\phi+\lambda)}\cos(\th) \end{pmatrix} ``` """ function CU3RevGate(θ::Number, ϕ::Number, λ::Number) QCO._verify_angle_bounds(θ) QCO._verify_angle_bounds(ϕ) QCO._verify_angle_bounds(λ) CU3Rev = Array{Complex{Float64},2}([ 1 0 0 0 0 cos(θ/2) 0 -(cos(λ)+(sin(λ))im)*sin(θ/2) 0 0 1 0 0 (cos(ϕ)+(sin(ϕ))im)*sin(θ/2) 0 (cos(λ+ϕ)+(sin(λ+ϕ))im)*cos(θ/2)]) return QCO.round_complex_values(CU3Rev) end @doc raw""" SwapGate() Two-qubit, symmetric, SWAP gate. **Circuit Representation** ``` q_0: ─X─ │ q_1: ─X─ ``` **Matrix Representation** ```math SWAP = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} ``` """ function SwapGate() return Array{Complex{Float64},2}([1 0 0 0; 0 0 1 0; 0 1 0 0; 0 0 0 1]) end @doc raw""" SSwapGate() Two-qubit, square root version of the [SwapGate](@ref). **Circuit Representation** ``` ┌────────────┐ q_0: ┤ ├ │ sqrt(Swap) │ q_1: ┤ ├ └────────────┘ ``` **Matrix Representation** ```math SWAP = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0.5+0.5i & 0.5-0.5i & 0 \\ 0 & 0.5-0.5i & 0.5+0.5i & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} ``` """ function SSwapGate() return sqrt(QCO.SwapGate()) end @doc raw""" iSwapGate() Two-qubit, symmetric and clifford, iSWAP gate. This is an entangling swapping gate where the qubits obtain a phase of ``i`` if the state of the qubits is swapped. **Circuit Representation** ``` q_0: ─⨂─ │ q_1: ─⨂─ ``` Minimum depth representation ``` ┌───┐ ┌───┐ ┌───┐ q_0: ─┤ X ├──■──┤ S ├─┤ X ├─ └─┬─┘┌─┴─┐└───┘ └─┬─┘ q_1: ───■──┤ X ├────────■── └───┘ ``` **Matrix Representation** ```math iSWAP = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & i & 0 \\ 0 & i & 0 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} ``` """ function iSwapGate() return Array{Complex{Float64},2}([1 0 0 0; 0 0 im 0; 0 im 0 0; 0 0 0 1]) end @doc raw""" CSXGate() Two-qubit controlled version of ([SXGate](@ref)). **Circuit Representation** ``` q_0: ─────■───── ┌────┴────┐ q_1: ┤ sqrt(X) ├ └─────────┘ ``` **Matrix Representation** ```math CSXGate = |0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes SX = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0.5+0.5i & 0.5-0.5i \\ 0 & 0 & 0.5-0.5i & 0.5+0.5i \end{pmatrix} ``` """ function CSXGate() return QCO.controlled_gate(QCO.SXGate(), 1) end @doc raw""" CSXRevGate() Two-qubit controlled version of the reverse ([SXGate](@ref)). **Circuit Representation** ``` ┌─────────┐ q_1: ┤ sqrt(X) ├ └────┬────┘ q_0: ─────■──── ``` **Matrix Representation** ```math CSXRevGate = I \otimes |0\rangle\langle 0| + SX \otimes |1\rangle\langle 1| = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0.5+0.5i & 0 & 0.5-0.5i \\ 0 & 0 & 1 & 0 \\ 0 & 0.5-0.5i & 0 & 0.5+0.5i \end{pmatrix} ``` """ function CSXRevGate() return QCO.controlled_gate(QCO.SXGate(), 1, reverse = true) end @doc raw""" MGate() Two-qubit Magic gate, also known as the Ising coupling or the XX gate. Reference: [https://doi.org/10.1103/PhysRevA.69.032315](https://doi.org/10.1103/PhysRevA.69.032315) **Circuit Representation** ``` ┌───┐ ┌───┐ q_0: ─┤ X ├────────┤ S ├ └─┬─┘ └─┬─┘ │ ┌───┐ ┌─┴─┐ q_1: ───■───┤ H ├──┤ S ├ └───┘ └───┘ ``` **Matrix Representation** ```math M = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & i & 0 & 0 \\ 0 & 0 & i & 1 \\ 0 & 0 & i & -1 \\ 1 & -i & 0 & 0 \end{pmatrix} ``` """ function MGate() return Array{Complex{Float64},2}(1/sqrt(2)*[1 im 0 0; 0 0 im 1; 0 0 im -1; 1 -im 0 0]) end @doc raw""" QFT2Gate() Two-qubit Quantum Fourier Transform (QFT) gate, where the QFT operation on n-qubits is given by: ```math |j\rangle \mapsto \frac{1}{2^{n/2}} \sum_{k=0}^{2^n - 1} e^{2\pi ijk / 2^n} |k\rangle ``` **Circuit Representation** ``` ┌──────┐ q_0: ┤ ├ │ QFT2 │ q_1: ┤ ├ └──────┘ ``` **Matrix Representation** ```math M = \frac{1}{2} \begin{pmatrix} 1 & 1 & 1 & 1 \\ 1 & i & -1 & -i \\ 1 & -1 & 1 & -1 \\ 1 & -i & -1 & i \end{pmatrix} ``` """ function QFT2Gate() return Array{Complex{Float64},2}(0.5*[1 1 1 1; 1 im -1 -im; 1 -1 1 -1; 1 -im -1 im]) end @doc raw""" HCoinGate() Two-qubit, Hadamard Coin gate when implemented in tune with the quantum cellular automata. Reference: [https://doi.org/10.1007/s11128-018-1983-x](https://doi.org/10.1007/s11128-018-1983-x), [https://arxiv.org/pdf/2106.03115.pdf](https://arxiv.org/pdf/2106.03115.pdf) **Matrix Representation** ```math HCoinGate = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} & 0 \\ 0 & \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}} & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} ``` """ function HCoinGate() return Array{Complex{Float64},2}([1 0 0 0; 0 1/sqrt(2) 1/sqrt(2) 0; 0 1/sqrt(2) -1/sqrt(2) 0; 0 0 0 1]) end @doc raw""" GroverDiffusionGate() Two-qubit, Grover's diffusion operator, a key building block of the Glover's algorithm used to find a specific item (with probability > 0.5) within a randomly ordered database of N items in O(sqrt(N)) operations. Reference: [https://arxiv.org/pdf/1804.03719.pdf](https://arxiv.org/pdf/1804.03719.pdf) **Matrix Representation** ```math GroverDiffusionGate = \frac{1}{2}\begin{pmatrix} 1 & -1 & -1 & -1 \\ -1 & 1 & -1 & -1 \\ -1 & -1 & 1 & -1 \\ -1 & -1 & -1 & 1 \end{pmatrix} ``` """ function GroverDiffusionGate() return Array{Complex{Float64},2}(0.5*[1 -1 -1 -1; -1 1 -1 -1; -1 -1 1 -1; -1 -1 -1 1]) end @doc raw""" SycamoreGate() Two-qubit Sycamore Gate, native to Google's universal quantum processor. Reference: [quantumai.google/cirq/google/devices](https://quantumai.google/cirq/google/devices) **Circuit Representation** ``` ┌──────┐ q_0: ┤ ├ │ SYC │ q_1: ┤ ├ └──────┘ ``` **Matrix Representation** ```math SycamoreGate() = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & -i & 0 \\ 0 & -i & 0 & 0 \\ 0 & 0 & 0 & e^{-i \frac{\pi}{6}} \end{pmatrix} ``` """ function SycamoreGate() return Array{Complex{Float64},2}([1 0 0 0 0 0 -im 0 0 -im 0 0 0 0 0 cos(pi/6)-(sin(pi/6))im]) end #---------------------------------------# # Three-qubit gates # #---------------------------------------# @doc raw""" ToffoliGate() Three-qubit Toffoli gate, also known as the CCX (controlled-controlled-NOT) gate. **Circuit Representation** ``` q_0: ──■── │ q_1: ──■── ┌─┴─┐ q_2: ┤ X ├ └───┘ ``` **Matrix Representation** ```math Toffoli = |0 \rangle \langle 0| \otimes I \otimes I + |1 \rangle \langle 1| \otimes CXGate = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1\\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \end{pmatrix} ``` """ function ToffoliGate() return QCO.controlled_gate(QCO.XGate(), 2) end @doc raw""" CSwapGate() Three-qubit, controlled [SwapGate](@ref), also known as the [Fredkin gate](https://en.wikipedia.org/wiki/Fredkin_gate). **Circuit Representation** ``` q_0: ─■─ │ q_1: ─X─ │ q_2: ─X─ ``` **Matrix Representation** ```math CSwapGate = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ \end{pmatrix} ``` """ function CSwapGate() return QCO.controlled_gate(QCO.SwapGate(), 1) end @doc raw""" CCZGate() Three-qubit controlled-controlled Z gate. **Circuit Representation** ``` q_0: ─■─ │ q_1: ─■─ │ q_2: ─■─ ``` **Matrix Representation** ```math CCZGate = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\ \end{pmatrix} ``` """ function CCZGate() return QCO.controlled_gate(QCO.ZGate(), 2) end @doc raw""" PeresGate() Three-qubit Peres gate. This gate is equivalent to [ToffoliGate](@ref) followed by the [CNotGate](@ref) in 3 qubits. Reference: [https://doi.org/10.1103/PhysRevA.32.3266](https://doi.org/10.1103/PhysRevA.32.3266) **Circuit Representation** ``` q_0: ──■─────■── │ ┌─┴─┐ q_1: ──■───┤ X ├ ┌─┴─┐ └───┘ q_2: ┤ X ├────── └───┘ ``` **Matrix Representation** ```math PeresGate = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ \end{pmatrix} ``` """ function PeresGate() return Array{Complex{Float64},2}([1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0]) end @doc raw""" RCCXGate() Three-qubit relative (or simplified) Toffoli gate, or the CCX gate. This gate is equivalent to [ToffoliGate](@ref) upto relative phases. The advantage of this gate is that it's implementation requires only three CNot (or CX) gates. Reference: [https://arxiv.org/pdf/1508.03273.pdf](https://arxiv.org/pdf/1508.03273.pdf) **Matrix Representation** ```math RCCXGate = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & -i \\ 0 & 0 & 0 & 0 & 0 & 0 & i & 0 \\ \end{pmatrix} ``` """ function RCCXGate() return Array{Complex{Float64},2}([1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 -im 0 0 0 0 0 0 im 0]) end @doc raw""" MargolusGate() Three-qubit Margolus gate, which is a simplified [ToffoliGate](@ref) and coincides with the Toffoli gate up to a single change of sign. The advantage of this gate is that its implementation requires only three CNot (or CX) gates. Reference: [https://arxiv.org/pdf/quant-ph/0312225.pdf](https://arxiv.org/pdf/quant-ph/0312225.pdf) **Matrix Representation** ```math MargolusGate = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ \end{pmatrix} ``` """ function MargolusGate() return Array{Complex{Float64},2}([1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0]) end @doc raw""" QFT3Gate() Three-qubit Quantum Fourier Transform (QFT) gate, where the QFT operation on n-qubits is given by: ```math |j\rangle \mapsto \frac{1}{2^{n/2}} \sum_{k=0}^{2^n - 1} e^{2\pi ijk / 2^n} |k\rangle ``` **Circuit Representation** ``` ┌──────┐ q_0: ┤ ├ │ │ q_1: ┤ QFT3 ├ │ │ q_3: ┤ ├ └──────┘ ``` **Matrix Representation** ```math M = \frac{1}{2\sqrt{2}} \begin{pmatrix} 1 1 1 1 1 1 1 1 \\ 1 \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} i -\frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} -1 -\frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}} -i \frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}} \\ 1 i -1 -i 1 i -1 -i \\ 1 -\frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} -i \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} -1 \frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}} i -\frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}} \\ 1 -1 1 -1 1 -1 1 -1 \\ 1 -\frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}} i \frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}} -1 \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} -i -\frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\ 1 -i -1 i 1 -i -1 i \\ 1 \frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}} -i -\frac{1}{\sqrt{2}} - \frac{i}{\sqrt{2}} -1 -\frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} i \frac{1}{\sqrt{2}} + \frac{i}{\sqrt{2}} \\ \end{pmatrix} ``` """ function QFT3Gate() a = 1/sqrt(8) b = 1/sqrt(2) return Array{Complex{Float64},2}(a*[1+0.0im 1+0.0im 1+0.0im 1+0.0im 1+0.0im 1+0.0im 1+0.0im 1+0.0im 1+0.0im (b)+(b)im 0.0+1im -(b)+(b)im -1+0.0im -(b)-(b)im 0.0-1im (b)-(b)im 1+0.0im 0.0+1im -1+0.0im 0.0-1im 1+0.0im 0.0+1im -1+0.0im 0.0-1im 1+0.0im -(b)+(b)im 0.0-1im (b)+(b)im -1+0.0im (b)-(b)im 0.0+1im -(b)-(b)im 1+0.0im -1+0.0im 1+0.0im -1+0.0im 1+0.0im -1+0.0im 1+0.0im -1+0.0im 1+0.0im -(b)-(b)im 0.0+1im (b)-(b)im -1+0.0im (b)+(b)im 0.0-1im -(b)+(b)im 1+0.0im 0.0-1im -1+0.0im 0.0+1im 1+0.0im 0.0-1im -1+0.0im 0.0+1im 1+0.0im (b)-(b)im 0.0-1im -(b)-(b)im -1+0.0im -(b)+(b)im 0.0+1im (b)+(b)im]) end @doc raw""" CiSwapGate() Three-qubit controlled version of the [iSwapGate](@ref). Reference: [https://doi.org/10.1103/PhysRevResearch.2.033097](https://doi.org/10.1103/PhysRevResearch.2.033097) **Circuit Representation** ``` q_0: ─────■───── │ ┌───────┐ q_1: ─┤ ├─ │ iSwap │ q_2: ─┤ ├─ └───────┘ ``` **Matrix Representation** ```math CiSwapGate = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & i & 0 \\ 0 & 0 & 0 & 0 & 0 & i & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ \end{pmatrix} ``` """ function CiSwapGate() return QCO.controlled_gate(QCO.iSwapGate(), 1) end #---------------------------------------# # Multi-qubit gates # #---------------------------------------# @doc raw""" GRGate(num_qubits::Int64, θ::Number, ϕ::Number) A multi-qubit rotation gate with two Euler angles, ``\theta`` and ``\phi``, applied about the ``\cos(\phi)x + \sin(\phi)y`` axis and parametrized by the number of qubits. This gate can be applied to multiple qubits simultaneously, for a given depth. The global R gate is native to atomic systems. In the one-qubit case, this gate is equivalent to the [RGate](@ref). Reference: [Qiskit's circuit library](https://qiskit.org/documentation/stubs/qiskit.circuit.library.GR.html) **Circuit Representation (in 3 qubits)** ``` ┌──────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 GR(ϴ,φ) ├ │ │ q_2: ┤2 ├ └──────────┘ ``` **Matrix Representation (in 3 qubits)** ```math GR(\theta, \phi) = \exp \left(-i \sum_{i=1}^{3} (\cos(\phi)X_i + \sin(\phi)Y_i) \theta/2 \right) \\ = R(\theta, \phi) \otimes R(\theta, \phi) \otimes R(\theta, \phi) ``` """ function GRGate(num_qubits::Int64, θ::Number, ϕ::Number) return QCO.round_complex_values(QCO.multi_qubit_global_gate(num_qubits, QCO.RGate(θ,ϕ))) end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
12316
""" visualize_solution(results::Dict{String, Any}, data::Dict{String, Any}; gate_sequence = false) Given dictionaries of results and data, and assuming that the optimization model had a feasible solution, this function aids in visualizing the optimal circuit decomposition. """ function visualize_solution(results::Dict{String, Any}, data::Dict{String, Any}; gate_sequence = false) _header_color = :cyan _main_color = :White if !(results["primal_status"] in [MOI.FEASIBLE_POINT, MOI.NEARLY_FEASIBLE_POINT]) if results["termination_status"] == MOI.TIME_LIMIT Memento.warn(_LOGGER, "Optimizer hits time limit with an infeasible primal status. Gate decomposition may be inaccurate") else Memento.warn(_LOGGER, "Infeasible primal status. Gate decomposition may be inaccurate") end return else gates_sol, gates_sol_compressed = QCO.get_postprocessed_circuit(results, data) end if !isempty(gates_sol_compressed) printstyled("\n","=============================================================================","\n"; color = _main_color) printstyled("QuantumCircuitOpt version: ", Pkg.TOML.parse(read(string(pkgdir(QCO), "/Project.toml"), String))["version"], "\n"; color = _header_color, bold = true) printstyled("\n","Quantum Circuit Model Data"; color = _header_color, bold = true) printstyled("\n"," ","Number of qubits: ", data["num_qubits"], "\n"; color = _main_color) printstyled(" ","Total number of elementary gates (after presolve): ",size(data["gates_real"])[3],"\n"; color = _main_color) printstyled(" ","Maximum depth of decomposition: ", data["maximum_depth"],"\n"; color = _main_color) printstyled(" ","Elementary gates: ", data["elementary_gates"],"\n"; color = _main_color) if "discretization" in keys(data) for i in keys(data["discretization"]) printstyled(" ","$i discretization: ", ceil.(rad2deg.(data["discretization"][i]), digits = 1),"\n"; color = _main_color) end end printstyled(" ","Type of decomposition: ", data["decomposition_type"],"\n"; color = _main_color) printstyled(" ","MIP optimizer: ", results["optimizer"],"\n"; color = _main_color) printstyled("\n","Optimal Circuit Decomposition","\n"; color = _header_color, bold = true) print(" ") for i=1:length(gates_sol_compressed) if i != length(gates_sol_compressed) printstyled(gates_sol_compressed[i], " * "; color = _main_color) else if data["decomposition_type"] in ["exact_optimal", "exact_feasible", "optimal_global_phase"] printstyled(gates_sol_compressed[i], " = ", "Target gate","\n"; color = _main_color) elseif data["decomposition_type"] == "approximate" printstyled(gates_sol_compressed[i], " ≈ ", "Target gate","\n"; color = _main_color) end end end if data["decomposition_type"] == "approximate" printstyled(" ","||Decomposition error||₂: ", round(LA.norm(results["solution"]["slack_var"]), digits = 10),"\n"; color = _main_color) end if data["objective"] == "minimize_depth" if length(data["identity_idx"]) >= 1 && (data["decomposition_type"] !== "exact_feasible") && !(results["termination_status"] == MOI.TIME_LIMIT) printstyled(" ","Minimum optimal depth: ", length(gates_sol_compressed),"\n"; color = _main_color) else printstyled(" ","Decomposition depth: ", length(gates_sol_compressed),"\n"; color = _main_color) end elseif data["objective"] == "minimize_cnot" if !isempty(data["cnot_idx"]) if data["decomposition_type"] in ["exact_optimal", "exact_feasible", "optimal_global_phase"] printstyled(" ","Minimum number of CNOT gates: ", round(results["objective"], digits = 6),"\n"; color = _main_color) elseif data["decomposition_type"] == "approximate" printstyled(" ","Minimum number of CNOT gates: ", round((results["objective"] - results["objective_slack_penalty"]*LA.norm(results["solution"]["slack_var"])^2), digits = 6),"\n"; color = _main_color) end end end printstyled(" ","Optimizer run time: ", ceil(results["solve_time"], digits=2)," sec.","\n"; color = _main_color) if results["termination_status"] == MOI.TIME_LIMIT printstyled(" ","Termination status: TIME_LIMIT", "\n"; color = _main_color) end printstyled("=============================================================================","\n"; color = _main_color) else Memento.warn(_LOGGER, "Valid integral feasible solutions could not be found to visualize the solution") end if gate_sequence return gates_sol end end function get_postprocessed_circuit(results::Dict{String, Any}, data::Dict{String, Any}) gates_sol = Array{String,1}() id_sequence = QCO._gate_id_sequence(results["solution"]["z_bin_var"], data["maximum_depth"]) (data["decomposition_type"] in ["exact_optimal", "exact_feasible", "optimal_global_phase"]) && QCO.validate_circuit_decomposition(data, id_sequence) for d = 1:data["maximum_depth"] gate_id = data["gates_dict"]["$(id_sequence[d])"] if !("Identity" in gate_id["type"]) s1 = gate_id["type"][1] if occursin(kron_symbol, s1) push!(gates_sol, s1) elseif !(QCO._parse_gate_string(s1, type = true) in union(QCO.ONE_QUBIT_GATES_ANGLE_PARAMETERS, QCO.TWO_QUBIT_GATES_ANGLE_PARAMETERS, QCO.MULTI_QUBIT_GATES_ANGLE_PARAMETERS)) push!(gates_sol, s1) else # s2 = String[] # for i_qu = 1:data["num_qubits"] # if gate_id["qubit_loc"] == "qubit_$i_qu" # s2 = "$i_qu" # end # end if "angle" in keys(gate_id) if length(keys(gate_id["angle"])) == 1 θ = round(rad2deg(gate_id["angle"]), digits = 3) s3 = "$(θ)" push!(gates_sol, string(s1,"(", s3, ")")) elseif length(keys(gate_id["angle"])) == 2 θ = round(rad2deg(gate_id["angle"]["θ"]), digits = 3) ϕ = round(rad2deg(gate_id["angle"]["ϕ"]), digits = 3) s3 = string("(","$(θ)",",","$(ϕ)",")") push!(gates_sol, string(s1, s3)) elseif length(keys(gate_id["angle"])) == 3 θ = round(rad2deg(gate_id["angle"]["θ"]), digits = 3) ϕ = round(rad2deg(gate_id["angle"]["ϕ"]), digits = 3) λ = round(rad2deg(gate_id["angle"]["λ"]), digits = 3) s3 = string("(","$(θ)",",","$(ϕ)", ",","$(λ)",")") push!(gates_sol, string(s1, s3)) end end end end end gates_sol_compressed = QCO.get_depth_compressed_circuit(data["num_qubits"], gates_sol) return gates_sol, gates_sol_compressed end """ validate_circuit_decomposition(data::Dict{String, Any}, id_sequence::Array{Int64,1}) This function validates the circuit decomposition if it is indeed exact with respect to the specified target gate. """ function validate_circuit_decomposition(data::Dict{String, Any}, id_sequence::Array{Int64,1}; error_message = true) valid_status = false M_sol = Array{Complex{Float64},2}(Matrix(LA.I, 2^(data["num_qubits"]), 2^(data["num_qubits"]))) for i in id_sequence M_sol *= data["gates_dict"]["$i"]["matrix"] end # This tolerance is very important for the final feasiblity check if data["are_gates_real"] target_gate = real(data["target_gate"]) else target_gate = QCO.real_to_complex_gate(data["target_gate"]) end if data["decomposition_type"] in ["exact_optimal", "exact_feasible"] (QCO.isapprox(M_sol, convert(Array{Complex{Float64},2}, target_gate), atol = 1E-4)) && (valid_status = true) elseif data["decomposition_type"] in ["optimal_global_phase"] (QCO.isapprox_global_phase(M_sol, convert(Array{Complex{Float64},2}, target_gate))) && (valid_status = true) end (!(valid_status) && error_message) && Memento.error(_LOGGER, "Decomposition is not valid: Problem may be infeasible") return valid_status end """ get_depth_compressed_circuit(num_qubits::Int64, gates_sol::Array{String,1}) Given the number of qubits and the sequence of gates from the solution, this function returns a decomposition of gates after compressing adjacent pair of gates represented on two separate qubits. For example, gates H1 and H2 appearing in a sequence will be compressed to H1xH2 (kron(H1,H2)). This functionality is currently supported only for two qubit circuits and gates without angle parameters. """ function get_depth_compressed_circuit(num_qubits::Int64, gates_sol::Array{String,1}) # This part of the code may be hacky. This needs to be updated once the input format gets cleaned up for elementary gates with U and R gates. if (length(gates_sol) == 1) || (num_qubits > 2) return gates_sol end gates_sol_compressed = String[] angle_param_gate = false for i=1:length(gates_sol) if !occursin(kron_symbol, gates_sol[i]) if !occursin("GR", gates_sol[i]) gates_sol_type = QCO._parse_gate_string(gates_sol[i], type = true) else gates_sol_type = "GR" end if gates_sol_type in union(QCO.ONE_QUBIT_GATES_ANGLE_PARAMETERS, QCO.TWO_QUBIT_GATES_ANGLE_PARAMETERS, QCO.MULTI_QUBIT_GATES_ANGLE_PARAMETERS) angle_param_gate = true break end end end if !angle_param_gate status = false for i=1:(length(gates_sol)) if i <= length(gates_sol) - 1 if status status = false continue else gate_i = QCO.is_multi_qubit_gate(gates_sol[i]) gate_iplus1 = QCO.is_multi_qubit_gate(gates_sol[i+1]) if !(gate_i) && !(gate_iplus1) if (occursin('1', gates_sol[i]) && occursin('2', gates_sol[i+1])) || (occursin('2', gates_sol[i]) && occursin('1', gates_sol[i+1])) if occursin('1', gates_sol[i]) gate_string = string(gates_sol[i],"x",gates_sol[i+1]) else gate_string = string(gates_sol[i+1],"x",gates_sol[i]) end push!(gates_sol_compressed, gate_string) status = true continue else push!(gates_sol_compressed, gates_sol[i]) end else push!(gates_sol_compressed, gates_sol[i]) end end else if !status push!(gates_sol_compressed, gates_sol[i]) end end end else return gates_sol end if isempty(gates_sol_compressed) Memento.error(_LOGGER, "Compressed gates solution is empty") end return gates_sol_compressed end function _gate_id_sequence(z_val::Matrix{<:Number}, maximum_depth::Int64) id_sequence = Array{Int64,1}() for d = 1:maximum_depth id = findall(isone.(round.(abs.(z_val[:,d]), digits=3)))[1] push!(id_sequence, id) end return id_sequence end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
2530
#------------------------------------------------------------# # Build the objective function for QuantumCircuitModel here # #------------------------------------------------------------# function objective_minimize_total_depth(qcm::QuantumCircuitModel) max_depth = qcm.data["maximum_depth"] identity_idx = qcm.data["identity_idx"] num_gates = size(qcm.data["gates_real"])[3] decomposition_type = qcm.data["decomposition_type"] if !isempty(identity_idx) if decomposition_type in ["exact_optimal", "optimal_global_phase"] JuMP.@objective(qcm.model, Min, sum(qcm.variables[:z_bin_var][n,d] for n = 1:num_gates, d=1:max_depth if !(n in identity_idx))) elseif decomposition_type == "exact_feasible" QCO.objective_feasibility(qcm) elseif decomposition_type == "approximate" JuMP.@objective(qcm.model, Min, sum(qcm.variables[:z_bin_var][n,d] for n = 1:num_gates, d=1:max_depth if !(n in identity_idx)) + qcm.options.objective_slack_penalty * sum(qcm.variables[:slack_var_oa])) end else QCO.objective_feasibility(qcm) end return end function objective_feasibility(qcm::QuantumCircuitModel) decomposition_type = qcm.data["decomposition_type"] if decomposition_type in ["exact_optimal", "exact_feasible", "optimal_global_phase"] # Feasibility objective Memento.warn(_LOGGER, "Switching to a feasibility problem") elseif decomposition_type == "approximate" JuMP.@objective(qcm.model, Min, sum(qcm.variables[:slack_var_oa])) end return end function objective_minimize_cnot_gates(qcm::QuantumCircuitModel) max_depth = qcm.data["maximum_depth"] cnot_idx = qcm.data["cnot_idx"] decomposition_type = qcm.data["decomposition_type"] if !isempty(qcm.data["cnot_idx"]) if decomposition_type in ["exact_optimal", "exact_feasible", "optimal_global_phase"] JuMP.@objective(qcm.model, Min, sum(qcm.variables[:z_bin_var][n,d] for n in cnot_idx, d=1:max_depth)) elseif decomposition_type == "approximate" JuMP.@objective(qcm.model, Min, sum(qcm.variables[:z_bin_var][n,d] for n in cnot_idx, d=1:max_depth) + (qcm.options.objective_slack_penalty * sum(qcm.variables[:slack_var_oa]))) end else Memento.error(_LOGGER, "CNot (CX) gate not found in input elementary gates") end return end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
8365
#-----------------------------------------------------------# # Build optimization model for circuit decomsposition here # #-----------------------------------------------------------# import JuMP: MOI function build_QCModel(data::Dict{String, Any}; options = nothing) m_qc = QCO.QuantumCircuitModel(data) # Update defaults to user-defined options if options !== nothing for i in keys(options) QCO.set_option(m_qc, i, options[i]) end end QCO._catch_options_errors(m_qc) # convex-hull formulation per depth, but larger number of variables and constraints if m_qc.options.model_type == "balas_formulation" QCO.variable_QCModel_balas(m_qc) QCO.constraint_QCModel_balas(m_qc) # minimal variables and constraints, but not a convex-hull formulation per depth elseif m_qc.options.model_type == "compact_formulation" QCO.variable_QCModel_compact(m_qc) QCO.constraint_QCModel_compact(m_qc) end QCO.objective_QCModel(m_qc) return m_qc end function variable_QCModel_balas(qcm::QuantumCircuitModel) QCO.variable_gates_per_depth(qcm) QCO.variable_gates_onoff(qcm) QCO.variable_sequential_gate_products(qcm) QCO.variable_gate_products_copy(qcm) QCO.variable_gate_products_linearization(qcm) if qcm.data["decomposition_type"] == "approximate" QCO.variable_slack_for_feasibility(qcm) QCO.variable_slack_var_outer_approximation(qcm) end QCO.variable_QCModel_valid(qcm) return end function constraint_QCModel_balas(qcm::QuantumCircuitModel) QCO.constraint_single_gate_per_depth(qcm) QCO.constraint_gates_onoff_per_depth(qcm) QCO.constraint_initial_gate_condition(qcm) QCO.constraint_intermediate_products(qcm) QCO.constraint_gate_product_linearization(qcm) QCO.constraint_target_gate_condition(qcm) QCO.constraint_cnot_gate_bounds(qcm) (qcm.data["decomposition_type"] == "approximate") && (QCO.constraint_slack_var_outer_approximation(qcm)) (!qcm.data["are_gates_real"]) && (QCO.constraint_complex_to_real_symmetry(qcm)) QCO.constraint_QCModel_valid(qcm) return end function variable_QCModel_compact(qcm::QuantumCircuitModel) QCO.variable_gates_onoff(qcm) QCO.variable_sequential_gate_products(qcm) QCO.variable_gate_products_linearization(qcm) if qcm.data["decomposition_type"] == "approximate" QCO.variable_slack_for_feasibility(qcm) QCO.variable_slack_var_outer_approximation(qcm) end QCO.variable_QCModel_valid(qcm) return end function variable_QCModel_valid(qcm::QuantumCircuitModel) if qcm.options.all_valid_constraints != -1 if qcm.options.all_valid_constraints == 1 QCO.variable_binary_products(qcm) elseif qcm.options.all_valid_constraints == 0 qcm.options.unitary_constraints && QCO.variable_binary_products(qcm) end end return end function constraint_QCModel_compact(qcm::QuantumCircuitModel) QCO.constraint_single_gate_per_depth(qcm) QCO.constraint_initial_gate_condition_compact(qcm) QCO.constraint_intermediate_products_compact(qcm) QCO.constraint_gate_product_linearization(qcm) if qcm.data["decomposition_type"] == "optimal_global_phase" QCO.constraint_target_gate_condition_glphase(qcm) else QCO.constraint_target_gate_condition_compact(qcm) end QCO.constraint_cnot_gate_bounds(qcm) (qcm.data["decomposition_type"] == "approximate") && (QCO.constraint_slack_var_outer_approximation(qcm)) # (!qcm.data["are_gates_real"]) && (QCO.constraint_complex_to_real_symmetry(qcm)) # seems to slow down MIP run times QCO.constraint_QCModel_valid(qcm) return end function constraint_QCModel_valid(qcm::QuantumCircuitModel) if qcm.options.all_valid_constraints != -1 if qcm.options.all_valid_constraints == 1 QCO.constraint_commutative_gate_pairs(qcm) QCO.constraint_involutory_gates(qcm) QCO.constraint_redundant_gate_product_pairs(qcm) QCO.constraint_idempotent_gates(qcm) QCO.constraint_identity_gate_symmetry(qcm) QCO.constraint_convex_hull_complex_gates(qcm) QCO.constraint_unitary_property(qcm) elseif qcm.options.all_valid_constraints == 0 qcm.options.commute_gate_constraints && QCO.constraint_commutative_gate_pairs(qcm) qcm.options.involutory_gate_constraints && QCO.constraint_involutory_gates(qcm) qcm.options.redundant_gate_pair_constraints && QCO.constraint_redundant_gate_product_pairs(qcm) qcm.options.idempotent_gate_constraints && QCO.constraint_idempotent_gates(qcm) qcm.options.identity_gate_symmetry_constraints && QCO.constraint_identity_gate_symmetry(qcm) qcm.options.convex_hull_gate_constraints && QCO.constraint_convex_hull_complex_gates(qcm) qcm.options.unitary_constraints && QCO.constraint_unitary_property(qcm) end end return end function objective_QCModel(qcm::QuantumCircuitModel) if qcm.data["objective"] == "minimize_depth" QCO.objective_minimize_total_depth(qcm) elseif qcm.data["objective"] == "minimize_cnot" QCO.objective_minimize_cnot_gates(qcm) end return end "" function optimize_QCModel!(qcm::QuantumCircuitModel; optimizer=nothing) if qcm.options.relax_integrality JuMP.relax_integrality(qcm.model) end if JuMP.mode(qcm.model) != JuMP.DIRECT && optimizer !== nothing if JuMP.backend(qcm.model).optimizer === nothing JuMP.set_optimizer(qcm.model, optimizer) else Memento.warn(_LOGGER, "Model already contains optimizer, cannot use optimizer specified in `optimize_QCModel!`") end end JuMP.set_time_limit_sec(qcm.model, qcm.options.time_limit) if !qcm.options.optimizer_log JuMP.set_silent(qcm.model) end if JuMP.mode(qcm.model) != JuMP.DIRECT && JuMP.backend(qcm.model).optimizer === nothing Memento.error(_LOGGER, "No optimizer specified in `optimize_QCModel!` or the given JuMP model.") end start_time = time() _, solve_time, solve_bytes_alloc, sec_in_gc = @timed JuMP.optimize!(qcm.model) try solve_time = JuMP.solve_time(qcm.model) catch Memento.warn(_LOGGER, "The given optimizer does not provide the SolveTime() attribute, falling back on @timed. This is not a rigorous timing value."); end Memento.debug(_LOGGER, "JuMP model optimize time: $(time() - start_time)") qcm.result = QCO.build_QCModel_result(qcm, solve_time) return qcm.result end function run_QCModel(params::Dict{String, Any}, qcm_optimizer::MOI.OptimizerWithAttributes; options = nothing) data = QCO.get_data(params) model_qc = QCO.build_QCModel(data, options = options) result_qc = QCO.optimize_QCModel!(model_qc, optimizer = qcm_optimizer) if model_qc.options.relax_integrality if result_qc["primal_status"] == MOI.FEASIBLE_POINT Memento.info(_LOGGER, "Integrality-relaxed solutions can be found in the results dictionary") else Memento.info(_LOGGER, "Infeasible primal status for the integrality-relaxed problem") end else if model_qc.options.visualize_solution QCO.visualize_solution(result_qc, data) end end return result_qc end function set_option(qcm::QuantumCircuitModel, s::Symbol, val) Base.setproperty!(qcm.options, s, val) end function _catch_options_errors(qcm::QuantumCircuitModel) if !(qcm.options.model_type in ["compact_formulation", "balas_formulation"]) Memento.warn(_LOGGER, "Invalid model_type. Setting it to default value (compact_formulation).") QCO.set_option(qcm, :model_type, "compact_formulation") end if !(qcm.options.all_valid_constraints in [-1,0,1]) Memento.warn(_LOGGER, "Invalid all_valid_constraints; choose a value ∈ [-1,0,1]. Setting it to default value of 0.") QCO.set_option(qcm, :all_valid_constraints, 0) end end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
2734
""" variable_domain(var::JuMP.VariableRef) Computes the valid domain of a given JuMP variable taking into account bounds and the varaible's implicit bounds (e.g. binary). """ function variable_domain(var::JuMP.VariableRef) lb = -Inf (JuMP.has_lower_bound(var)) && (lb = JuMP.lower_bound(var)) (JuMP.is_binary(var)) && (lb = max(lb, 0.0)) ub = Inf (JuMP.has_upper_bound(var)) && (ub = JuMP.upper_bound(var)) (JuMP.is_binary(var)) && (ub = min(ub, 1.0)) return (lower_bound=lb, upper_bound=ub) end """ relaxation_bilinear(m::JuMP.Model, xy::JuMP.VariableRef, x::JuMP.VariableRef, y::JuMP.VariableRef) general relaxation of binlinear term (McCormick), which can be used to obtain specific variants in partiuclar cases of variables (like binary) ``` z >= JuMP.lower_bound(x)*y + JuMP.lower_bound(y)*x - JuMP.lower_bound(x)*JuMP.lower_bound(y) z >= JuMP.upper_bound(x)*y + JuMP.upper_bound(y)*x - JuMP.upper_bound(x)*JuMP.upper_bound(y) z <= JuMP.lower_bound(x)*y + JuMP.upper_bound(y)*x - JuMP.lower_bound(x)*JuMP.upper_bound(y) z <= JuMP.upper_bound(x)*y + JuMP.lower_bound(y)*x - JuMP.upper_bound(x)*JuMP.lower_bound(y) ``` """ function relaxation_bilinear(m::JuMP.Model, xy::JuMP.VariableRef, x::JuMP.VariableRef, y::JuMP.VariableRef) lb_x, ub_x = variable_domain(x) lb_y, ub_y = variable_domain(y) (isapprox(lb_x, 0, atol = 1E-6)) && (lb_x = 0) (isapprox(lb_y, 0, atol = 1E-6)) && (lb_y = 0) (isapprox(lb_x, 1, atol = 1E-6)) && (lb_x = 1) (isapprox(lb_y, 1, atol = 1E-6)) && (lb_y = 1) (isapprox(ub_x, 0, atol = 1E-6)) && (ub_x = 0) (isapprox(ub_y, 0, atol = 1E-6)) && (ub_y = 0) (isapprox(ub_x, 1, atol = 1E-6)) && (ub_x = 1) (isapprox(ub_y, 1, atol = 1E-6)) && (ub_y = 1) if (lb_x == 0) && (ub_x == 1) && ((lb_y != 0) || (ub_y != 1)) JuMP.@constraint(m, xy >= lb_y*x) JuMP.@constraint(m, xy >= y + ub_y*x - ub_y) JuMP.@constraint(m, xy <= ub_y*x) JuMP.@constraint(m, xy <= y + lb_y*x - lb_y) elseif (lb_y == 0) && (ub_y == 1) && ((lb_x != 0) || (ub_x != 1)) JuMP.@constraint(m, xy >= lb_x*y) JuMP.@constraint(m, xy >= ub_x*y + x - ub_x) JuMP.@constraint(m, xy <= lb_x*y + x - lb_x) JuMP.@constraint(m, xy <= ub_x*y) elseif (lb_x == 0) && (ub_x == 1) && (lb_y == 0) && (ub_y == 1) JuMP.@constraint(m, xy <= x) JuMP.@constraint(m, xy <= y) JuMP.@constraint(m, xy >= x + y - 1) else JuMP.@constraint(m, xy >= lb_x*y + lb_y*x - lb_x*lb_y) JuMP.@constraint(m, xy >= ub_x*y + ub_y*x - ub_x*ub_y) JuMP.@constraint(m, xy <= lb_x*y + ub_y*x - lb_x*ub_y) JuMP.@constraint(m, xy <= ub_x*y + lb_y*x - ub_x*lb_y) end return m end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
1907
"" function build_QCModel_result(qcm::QuantumCircuitModel, solve_time::Number) # try-catch is needed until solvers reliably support ResultCount() result_count = 1 try result_count = JuMP.result_count(qcm.model) catch Memento.warn(_LOGGER, "the given optimizer does not provide the ResultCount() attribute, assuming the solver returned a solution which may be incorrect."); end solution = Dict{String,Any}() if result_count > 0 solution = QCO.build_QCModel_solution(qcm) else Memento.warn(_LOGGER, "Quantum circuit model has no results, solution cannot be built") end result = Dict{String,Any}( "optimizer" => JuMP.solver_name(qcm.model), "termination_status" => JuMP.termination_status(qcm.model), "primal_status" => JuMP.primal_status(qcm.model), "objective" => QCO.get_objective_value(qcm.model), "objective_lb" => QCO.get_objective_bound(qcm.model), "solve_time" => solve_time, "solution" => solution, ) # Objective slack Penalty if qcm.data["decomposition_type"] == "approximate" result["objective_slack_penalty"] = qcm.options.objective_slack_penalty end return result end "" function get_objective_value(model::JuMP.Model) obj_val = NaN try obj_val = JuMP.objective_value(model) catch Memento.warn(_LOGGER, "Objective value is unbounded. Problem may be infeasible or not constrained properly"); end return obj_val end "" function get_objective_bound(model::JuMP.Model) obj_lb = -Inf try obj_lb = JuMP.objective_bound(model) catch end return obj_lb end function build_QCModel_solution(qcm::QuantumCircuitModel) solution = Dict{String,Any}() for i in keys(qcm.variables) solution[String(i)] = JuMP.value.(qcm.variables[i]) end return solution end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
4484
export QuantumCircuitModel """ QCModelOptions The composite mutable struct, `QCModelOptions`, holds various optimization model options for enhancements with defualt options set to the values provided by `get_default_options` function. """ mutable struct QCModelOptions model_type :: String all_valid_constraints :: Int64 commute_gate_constraints :: Bool involutory_gate_constraints :: Bool redundant_gate_pair_constraints :: Bool identity_gate_symmetry_constraints :: Bool fix_unitary_variables :: Bool visualize_solution :: Bool idempotent_gate_constraints :: Bool convex_hull_gate_constraints :: Bool unitary_constraints :: Bool time_limit :: Float64 relax_integrality :: Bool optimizer_log :: Bool objective_slack_penalty :: Float64 end """ get_default_options() This function returns the default options for building the struct `QCModelOptions`. """ function get_default_options() model_type = "compact_formulation" # check MODEL_TYPES in src/qc_model.jl for options all_valid_constraints = 0 # -1, 0, 1 commute_gate_constraints = true # true, false involutory_gate_constraints = true # true, false redundant_gate_pair_constraints = true # true, false identity_gate_symmetry_constraints = true # true, false fix_unitary_variables = true # true, false visualize_solution = true # true, false idempotent_gate_constraints = false # true, false convex_hull_gate_constraints = false # true, false unitary_constraints = false # true, false time_limit = 10800 # float value relax_integrality = false # true, false optimizer_log = true # true, false objective_slack_penalty = 1E3 # > 0 value return QCModelOptions(model_type, all_valid_constraints, commute_gate_constraints, involutory_gate_constraints, redundant_gate_pair_constraints, identity_gate_symmetry_constraints, fix_unitary_variables, visualize_solution, idempotent_gate_constraints, convex_hull_gate_constraints, unitary_constraints, time_limit, relax_integrality, optimizer_log, objective_slack_penalty) end """ QuantumCircuitModel The composite mutable struct, `QuantumCircuitModel`, holds dictionaries for input data, abstract JuMP model for optimization, variable references and result from solving the JuMP model. """ mutable struct QuantumCircuitModel data :: Dict{String,Any} model :: JuMP.Model options :: QCModelOptions variables :: Dict{Symbol,Any} result :: Dict{String,Any} "Constructor for struct `QuantumCircuitModel`" function QuantumCircuitModel(data::Dict{String,Any}) data = data model = JuMP.Model() options = QCO.get_default_options() variables = Dict{Symbol,Any}() result = Dict{String,Any}() qcm = new(data, model, options, variables, result) return qcm end end """ GateData The composite mutable struct, `GateData`, type of the gate, the complex matrix form of the gate, full sized real form of the gate, inverse of the gate and a boolean which states if the gate has all real entries. """ mutable struct GateData type :: String complex :: Array{Complex{Float64},2} real :: Array{Float64,2} inverse :: Array{Float64,2} isreal :: Bool "Constructor for struct `GateData`" function GateData(gate_type::String, num_qubits::Int64) type = gate_type complex = QCO.get_unitary(type, num_qubits) real = QCO.complex_to_real_gate(complex) inverse = inv(real) isreal = iszero(imag(complex)) gate = new(type, complex, real, inverse, isreal) return gate end end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
29140
""" auxiliary_variable_bounds(v::Array{JuMP.VariableRef,1}) Given a vector of JuMP variables (maximum 4 variables), this function returns the worst-case bounds, the product of these input variables can admit. """ function auxiliary_variable_bounds(v::Array{JuMP.VariableRef,1}) v_l = [JuMP.lower_bound(v[1]), JuMP.upper_bound(v[1])] v_u = [JuMP.lower_bound(v[2]), JuMP.upper_bound(v[2])] M = v_l * v_u' if length(v) == 2 # Bilinear return minimum(M), maximum(M) elseif (length(v) == 3) || (length(v) == 4) M1 = zeros(Float64, (2, 2, 2)) M1[:,:,1] = M * JuMP.lower_bound(v[3]) M1[:,:,2] = M * JuMP.upper_bound(v[3]) if length(v) == 3 # Trilinear return minimum(M1), maximum(M1) elseif length(v) == 4 # Quadrilinear M2 = zeros(Float64, (2, 2, 4)) M2[:,:,1:2] = M1 * JuMP.lower_bound(v[4]) M2[:,:,3:4] = M1 * JuMP.upper_bound(v[4]) return minimum(M2), maximum(M2) end end end """ gate_element_bounds(M::Array{Float64,3}) Given a set of elementary gates, `{G1, G2, ... ,Gn}`, this function evaluates the range of every co-ordinate of the superimposed gates, over all possible gates. """ function gate_element_bounds(M::Array{Float64,3}) M_l = zeros(size(M)[1], size(M)[2]) M_u = zeros(size(M)[1], size(M)[2]) for i = 1:size(M)[1], j = 1:size(M)[2] M_l[i,j] = minimum(M[i,j,:]) M_u[i,j] = maximum(M[i,j,:]) if M_l[i,j] > M_u[i,j] Memento.error(_LOGGER, "Lower and upper bound conflict in the elements of input elementary gates") elseif (M_l[i,j] in [-Inf, Inf]) || (M_u[i,j] in [-Inf, Inf]) Memento.error(_LOGGER, "Unbounded entry detected in the input elementary gates") end end return M_l, M_u end """ get_commutative_gate_pairs(M::Dict{String,Any}; decomposition_type::String; identity_in_pairs = true) Given a dictionary of elementary quantum gates, this function returns all pairs of commuting gates. Optional argument, `identity_pairs` can be set to `false` if identity matrix need not be part of the commuting pairs. """ function get_commutative_gate_pairs(M::Dict{String,Any}, decomposition_type::String; identity_in_pairs = true) num_gates = length(keys(M)) commute_pairs = Array{Tuple{Int64,Int64},1}() commute_pairs_prodIdentity = Array{Tuple{Int64,Int64},1}() Id = Matrix{Complex{Float64}}(Matrix(LA.I, size(M["1"]["matrix"])[1], size(M["1"]["matrix"])[2])) for i = 1:(num_gates-1), j = (i+1):num_gates M_i = M["$i"]["matrix"] M_j = M["$j"]["matrix"] if ("Identity" in M["$i"]["type"]) || ("Identity" in M["$j"]["type"]) continue end M_ij = M_i*M_j M_ji = M_j*M_i if decomposition_type in ["optimal_global_phase"] # Commuting pairs up to a global phase QCO.isapprox_global_phase(M_ij, Id) && push!(commute_pairs_prodIdentity, (i,j)) QCO.isapprox_global_phase(M_ij, M_ji) && push!(commute_pairs, (i,j)) else # Commuting pairs == Identity isapprox(M_ij, Id, atol = 1E-4) && push!(commute_pairs_prodIdentity, (i,j)) isapprox(M_ij, M_ji, atol = 1E-4) && push!(commute_pairs, (i,j)) end end if identity_in_pairs # Commuting pairs involving Identity identity_idx = [] for i in keys(M) ("Identity" in M[i]["type"]) && push!(identity_idx, parse(Int64, i)) end if length(identity_idx) > 0 for i = 1:length(identity_idx) for j = 1:num_gates (j != identity_idx[i]) && push!(commute_pairs, (j, identity_idx[i])) end end end end return commute_pairs, commute_pairs_prodIdentity end """ get_redundant_gate_product_pairs(M::Dict{String,Any}, decomposition_type::String) Given a dictionary of elementary quantum gates, this function returns all pairs of gates whose product is one of the input elementary gates. For example, let `G_basis = {G1, G2, G3}` be the elementary gates. If `G1*G2 ∈ G_basis`, then `(1,2)` is considered as a redundant pair. """ function get_redundant_gate_product_pairs(M::Dict{String,Any}, decomposition_type::String) num_gates = length(keys(M)) redundant_pairs_idx = Array{Tuple{Int64,Int64},1}() # Non-Identity redundant pairs for i = 1:(num_gates-1), j = (i+1):num_gates M_i = M["$i"]["matrix"] M_j = M["$j"]["matrix"] if ("Identity" in M["$i"]["type"]) || ("Identity" in M["$j"]["type"]) continue end for k = 1:num_gates if (k != i) && (k != j) && !("Identity" in M["$k"]["type"]) M_k = M["$k"]["matrix"] if decomposition_type in ["optimal_global_phase"] QCO.isapprox_global_phase(M_i*M_j, M_k) && push!(redundant_pairs_idx, (i,j)) QCO.isapprox_global_phase(M_j*M_i, M_k) && push!(redundant_pairs_idx, (j,i)) else isapprox(M_i*M_j, M_k, atol = 1E-4) && push!(redundant_pairs_idx, (i,j)) isapprox(M_j*M_i, M_k, atol = 1E-4) && push!(redundant_pairs_idx, (j,i)) end end end end return redundant_pairs_idx end """ get_idempotent_gates(M::Dict{String,Any}, decomposition_type::String) Given the dictionary of complex quantum gates, this function returns the indices of matrices which are self-idempotent or idempotent with other set of input gates, excluding the Identity gate. """ function get_idempotent_gates(M::Dict{String,Any}, decomposition_type::String) num_gates = length(keys(M)) idempotent_gates_idx = Vector{Int64}() # Excluding Identity gate in input for i = 1:num_gates M_i = M["$i"]["matrix"] for j = 1:num_gates M_j = M["$j"]["matrix"] if ("Identity" in M["$i"]["type"]) || ("Identity" in M["$j"]["type"]) continue end if decomposition_type in ["optimal_global_phase"] QCO.isapprox_global_phase(M_i^2, M_j) && push!(idempotent_gates_idx, i) else isapprox(M_i^2, M_j, atol=1E-4) && push!(idempotent_gates_idx, i) end end end return idempotent_gates_idx end """ get_involutory_gates(M::Dict{String,Any}) Given the dictionary of complex gates `G_1, G_2, ..., G_n`, this function returns the indices of these gates which are involutory, i.e, `G_i^2 = Identity`, excluding the Identity gate. """ function get_involutory_gates(M::Dict{String,Any}) num_gates = length(keys(M)) involutory_gates_idx = Vector{Int64}() if num_gates > 0 n_r = size(M["1"]["matrix"])[1] n_c = size(M["1"]["matrix"])[2] end Id = Matrix{ComplexF64}(LA.I, n_r, n_c) # Excluding Identity gate in input for i=1:num_gates if !("Identity" in M["$i"]["type"]) && (isapprox((M["$i"]["matrix"])^2, Id, atol=1E-5)) push!(involutory_gates_idx, i) end end return involutory_gates_idx end """ complex_to_real_gate(M::Array{Complex{Float64},2}) Given a complex-valued two-dimensional quantum gate of size NxN, this function returns a real-valued gate of dimensions 2Nx2N. """ function complex_to_real_gate(M::Array{Complex{Float64},2}) n = size(M)[1] M_real = zeros(2*n, 2*n) ii = 1; jj = 1; for i = collect(1:2:2*n) for j = collect(1:2:2*n) if isapprox(real(M[ii,jj]), 0, atol=1E-6) M_real[i,j] = 0 M_real[i+1,j+1] = 0 else M_real[i,j] = real(M[ii,jj]) M_real[i+1,j+1] = real(M[ii,jj]) end if isapprox(imag(M[ii,jj]), 0, atol=1E-6) M_real[i,j+1] = 0 M_real[i+1,j] = 0 else M_real[i,j+1] = imag(M[ii,jj]) M_real[i+1,j] = -imag(M[ii,jj]) end jj += 1 end jj = 1 ii += 1 end return M_real end """ real_to_complex_gate(M::Array{Complex{Float64},2}) Given a real-valued two-dimensional quantum gate of size 2Nx2N, this function returns a complex-valued gate of size NxN, if the input gate is in a valid complex form. """ function real_to_complex_gate(M::Array{Float64,2}) n = size(M)[1] if !iseven(n) Memento.error(_LOGGER, "Specified gate can admit only even numbered columns and rows") end M_complex = zeros(Complex{Float64}, (Int(n/2), Int(n/2))) ii = 1; jj = 1; for i = collect(1:2:n) for j = collect(1:2:n) if !isapprox(M[i,j], M[i+1, j+1], atol = 1E-5) || !isapprox(M[i+1,j], -M[i,j+1], atol = 1E-5) Memento.error(_LOGGER, "Specified real form of the complex gate is invalid") end M_re = M[i,j] M_im = M[i,j+1] (isapprox(M_re, 0, atol=1E-6)) && (M_re = 0) (isapprox(M_im, 0, atol=1E-6)) && (M_im = 0) M_complex[ii,jj] = complex(M_re, M_im) jj += 1 end jj = 1 ii += 1 end return M_complex end """ round_complex_values(M::Array{Complex{Float64},2}) Given a complex-valued matrix, this function returns a complex-valued matrix which rounds the values closest to 0, 1 and -1. This is useful to avoid numerical issues. """ function round_complex_values(M::Array{Complex{Float64},2}) if length(size(M)) == 2 n_r = size(M)[1] n_c = size(M)[2] M_round = Array{Complex{Float64},2}(zeros(n_r,n_c)) for i=1:n_r for j=1:n_c M_round[i,j] = complex(QCO.round_real_value(real(M[i,j])), QCO.round_real_value(imag(M[i,j]))) end end return M_round else return M end end """ round_real_value(x::T) where T <: Number Given a real-valued number, this function returns a real-value which rounds the values closest to 0, 1 and -1. """ function round_real_value(x::T) where T <: Number if isapprox(abs(x), 0, atol=1E-6) x = 0 elseif isapprox(x, 1, atol=1E-6) x = 1 elseif isapprox(x, -1, atol=1E-6) x = -1 end return x end """ unique_idx(x::AbstractArray{T}) This function returns the indices of unique elements in a given array of scalar or vector inputs. Overall, this function computes faster than Julia's built-in `findfirst` command. """ function unique_idx(x::AbstractArray{T}) where T uniqueset = Set{T}() ex = eachindex(x) idxs = Vector{eltype(ex)}() for i in ex xi = x[i] if !(xi in uniqueset) push!(idxs, i) push!(uniqueset, xi) end end idxs end """ unique_matrices(M::Array{Float64, 3}) This function returns the unique set of matrices and the corresponding indices of unique matrices from the given set of matrices. """ function unique_matrices(M::Array{Float64, 3}) M[isapprox.(M, 0, atol=1E-6)] .= 0 M_reshape = []; for i=1:size(M)[3] push!(M_reshape, round.(reshape(M[:,:,i], size(M)[1]*size(M)[2]), digits=5)) end idx = QCO.unique_idx(M_reshape) return M[:,:,idx], idx end """ kron_single_qubit_gate(num_qubits::Int64, M::Array{Complex{Float64},2}, qubit_loc::String) Given number of qubits of the circuit, the complex-valued one-qubit gate and the qubit location ("q1","q2',"q3",...), this function returns a full-sized gate after applying appropriate kronecker products. This function supports any number integer-valued qubits. """ function kron_single_qubit_gate(num_qubits::Int64, M::Array{Complex{Float64},2}, qubit_loc::String) if size(M)[1] != 2 Memento.error(_LOGGER, "Input should be an one-qubit gate") end qubit = parse(Int, qubit_loc[2:end]) if !(qubit in 1:num_qubits) Memento.error(_LOGGER, "Specified qubit location, $qubit, has to be ∈ [q1,...,q$num_qubits]") end I = QCO.IGate(1) M_kron = 1 for i = 1:num_qubits M_iter = I if i == qubit M_iter = M end M_kron = kron(M_kron, M_iter) end QCO._catch_kron_dimension_errors(num_qubits, size(M_kron)[1]) return QCO.round_complex_values(M_kron) end """ kron_two_qubit_gate(num_qubits::Int64, M::Array{Complex{Float64},2}, c_qubit_loc::String, t_qubit_loc::String) Given number of qubits of the circuit, the complex-valued two-qubit gate and the control and target qubit locations ("q1","q2',"q3",...), this function returns a full-sized gate after applying appropriate kronecker products. This function supports any number of integer-valued qubits. """ function kron_two_qubit_gate(num_qubits::Int64, M::Array{Complex{Float64},2}, c_qubit_loc::String, t_qubit_loc::String) if size(M)[1] != 4 Memento.error(_LOGGER, "Input should be a two-qubit gate") end c_qubit = parse(Int, c_qubit_loc[2:end]) t_qubit = parse(Int, t_qubit_loc[2:end]) if !(c_qubit in 1:num_qubits) || !(t_qubit in 1:num_qubits) Memento.error(_LOGGER, "Specified control and target qubit locations have to be ∈ [q1,...,q$num_qubits]") elseif isapprox(c_qubit, t_qubit, atol = 1E-6) Memento.error(_LOGGER, "Control and target qubits cannot be identical for a multi-qubit elementary gate") end I = QCO.IGate(1) Swap = QCO.SwapGate() # If on adjacent qubits if abs(c_qubit - t_qubit) == 1 M_kron = 1 for i = 1:(num_qubits-1) M_iter = I if (i in [c_qubit, t_qubit]) && (i+1 in [c_qubit, t_qubit]) M_iter = M end M_kron = kron(M_kron, M_iter) end # If on non-adjacent qubits # Assuming the qubit numbering starts at 1, and not 0 elseif abs(c_qubit - t_qubit) >= 2 ct = abs(c_qubit - t_qubit) M_sub_depth = 2*ct - 1 M_sub_loc = ct M_sub_swap_id = ct M_sub = Matrix{Complex{Float64}}(LA.I, 2^(ct+1),2^(ct+1)) # Idea is to represent gate_1_4 = swap_3_4 * swap_2_3 * gate_1_2 * swap_2_3 * swap_3_4 for d=1:M_sub_depth M_sub_kron = 1 swap_qubits = true for i=1:ct M_sub_iter = I if (d == M_sub_loc) && (i == 1) M_sub_iter = M elseif !(d == M_sub_loc) && (i == M_sub_swap_id) && swap_qubits M_sub_iter = Swap if (d < M_sub_loc) && (M_sub_swap_id > 2) M_sub_swap_id -= 1 elseif (d > M_sub_loc) M_sub_swap_id += 1 end swap_qubits = false end M_sub_kron = kron(M_sub_kron, M_sub_iter) end M_sub *= M_sub_kron end M_kron = 1 i = 1 while i <= num_qubits M_iter = I if (i in [c_qubit, t_qubit]) M_iter = M_sub i += (ct+1) else i += 1 end M_kron = kron(M_kron, M_iter) end end QCO._catch_kron_dimension_errors(num_qubits, size(M_kron)[1]) return QCO.round_complex_values(M_kron) end """ multi_qubit_global_gate(num_qubits::Int64, M::Array{Complex{Float64},2}) Given number of qubits of the circuit and any complex-valued one-qubit gate (`G``) in it's matrix form, this function returns a multi-qubit global gate, by applying `G` simultaneously on all the qubits. For example, given `G` and `num_qubits = 3`, this function returns `G⨂G⨂G`. """ function multi_qubit_global_gate(num_qubits::Int64, M::Array{Complex{Float64},2}) if size(M)[1] != 2 Memento.error(_LOGGER, "Input should be an one-qubit gate") end M_kron = 1 for i = 1:num_qubits M_kron = kron(M_kron, M) end QCO._catch_kron_dimension_errors(num_qubits, size(M_kron)[1]) return QCO.round_complex_values(M_kron) end """ _parse_gates_with_kron_symbol(s::String) Given a string with gates separated by kronecker symbols `x`, this function parses and returns the vector of gates. For example, if the input string is `H_1xCNot_2_3xT_4`, the output will be `Vector{String}(["H_1", "CNot_2_3", "T_4"])`. """ function _parse_gates_with_kron_symbol(s::String) gates = Vector{String}() gate_id = string() for i = 1:length(s) if s[i] != QCO.kron_symbol gate_id = gate_id * s[i] else push!(gates, gate_id) (i != length(s)) && (gate_id = string()) end if i == length(s) push!(gates, gate_id) end end return gates end """ _parse_gate_string(s::String) Given a string representing a single gate with qubit numbers separated by symbol `_`, this function parses and returns the vector of qubits on which the input gate is located. For example, if the input string is `CRX_2_3`, the output will be `Vector{Int64}([2,3])`. """ function _parse_gate_string(s::String; type=false, qubits=false) gates = Vector{String}() gate_id = string() for i = 1:length(s) if s[i] != QCO.qubit_separator gate_id = gate_id * s[i] else push!(gates, gate_id) (i != length(s)) && (gate_id = string()) end if (i == length(s)) && (s[i] != qubit_separator) push!(gates, gate_id) end end if type && qubits return gates[1], parse.(Int, gates[2:end]) # Assuming 1st element is the gate type/name elseif type return gates[1] elseif qubits return parse.(Int, gates[2:end]) end end """ is_gate_real(M::Array{Complex{Float64},2}) Given a complex-valued quantum gate, M, this function returns if M has purely real parts or not as it's elements. """ function is_gate_real(M::Array{Complex{Float64},2}) M_imag = imag(M) n_r = size(M_imag)[1] n_c = size(M_imag)[2] if sum(isapprox.(M_imag, zeros(n_r, n_c), atol=1E-6)) == n_r*n_c return true else return false end end """ _get_constraint_slope_intercept(vertex1::Vector{<:Number}, vertex2::Vector{<:Number}) Given co-ordinates of two points in a plane, this function returns the slope (m) and intercept (c) of the line joining these two points. """ function _get_constraint_slope_intercept(vertex1::Tuple{<:Number, <:Number}, vertex2::Tuple{<:Number, <:Number}) if isapprox.(vertex1, vertex2, atol=1E-6) == [true, true] Memento.warn(_LOGGER, "Invalid slope and intercept for two identical vertices") return end if isapprox(vertex1[1], vertex2[1], atol = 1E-6) return Inf, Inf else m = QCO.round_real_value((vertex2[2] - vertex1[2]) / (vertex2[1] - vertex1[1])) c = QCO.round_real_value(vertex1[2] - (m * vertex1[1])) return m,c end end """ is_multi_qubit_gate(gate::String) Given the input gate string, this function returns a boolean if the input gate is a multi qubit gate or not. For example, for a 2-qubit gate `CRZ_1_2`, output is `true`. """ function is_multi_qubit_gate(gate::String) if occursin(kron_symbol, gate) || (gate in QCO.MULTI_QUBIT_GATES) return true end qubit_loc = QCO._parse_gate_string(gate, qubits = true) if length(qubit_loc) > 1 return true elseif length(qubit_loc) == 1 return false else Memento.error(_LOGGER, "Atleast one qubit has to be specified for an input gate") end end function _verify_angle_bounds(angle::Number) if !(-2*π <= angle <= 2*π) Memento.error(_LOGGER, "Input angle is not within valid bounds in [-2π, 2π]") end end function _catch_kron_dimension_errors(num_qubits::Int64, M_dim::Int64) if M_dim !== 2^(num_qubits) Memento.error(_LOGGER, "Dimensions mismatch in evaluation of Kronecker product") end end """ _determinant_test_for_infeasibility(data::Dict{String,Any}) Given the processed data dictionary, this function performs a few simple tests based on the determinant values of elementary and target gates to detect MIP infeasibility. """ function _determinant_test_for_infeasibility(data::Dict{String,Any}) if data["are_gates_real"] det_target = LA.det(data["target_gate"]) else det_target = LA.det(QCO.real_to_complex_gate(data["target_gate"])) end if isapprox(imag(det_target), 0, atol = 1E-6) if isapprox(det_target, -1, atol=1E-6) sum_det = 0 for k = 1:length(keys(data["gates_dict"])) det_val = LA.det(data["gates_dict"]["$k"]["matrix"]) if isapprox(imag(det_val), 0, atol = 1E-6) sum_det += det_val end end if (isapprox(sum_det, length(keys(data["gates_dict"])), atol = 1E-6)) && (data["decomposition_type"] == "exact_optimal") Memento.error(_LOGGER, "Infeasible decomposition: det.(elementary_gates) = 1, while det(target_gate) = -1") end end else det_gates_real = true for k = 1:length(keys(data["gates_dict"])) if !(isapprox(imag(LA.det(data["gates_dict"]["$k"]["matrix"])), 0, atol=1E-6)) det_gates_real = false continue end end if det_gates_real && (data["decomposition_type"] == "exact_optimal") Memento.error(_LOGGER, "Infeasible decomposition: det.(elementary_gates) = real, while det(target_gate) = complex") end end end """ _get_nonzero_idx_of_complex_to_real_matrix(M::Array{Float64,2}) A helper function for global phase constraints: Given a complex to real reformulated matrix, `M`, using `QCO.complex_to_real_gate`, this function returns the first non-zero index it locates within `M`. """ function _get_nonzero_idx_of_complex_to_real_matrix(M::Array{Float64,2}) for i=1:2:size(M)[1], j=1:2:size(M)[2] if !isapprox(M[i,j], 0, atol=1E-6) || !isapprox(M[i,j+1], 0, atol=1E-6) return i,j end end end """ _get_nonzero_idx_of_complex_matrix(M::Array{Complex{Float64},2}) A helper function for global phase constraints: Given a complex matrix, `M`, this function returns the first non-zero index it locates within `M`, either in real or the complex part. """ function _get_nonzero_idx_of_complex_matrix(M::Array{Complex{Float64},2}) for i=1:size(M)[1], j=1:size(M)[2] if !isapprox(M[i,j], 0, atol=1E-6) return i,j end end end """ isapprox_global_phase(M1::Array{Complex{Float64},2}, M2::Array{Complex{Float64},2}; tol_0 = 1E-4) Given two complex matrices, `M1` and `M2`, this function returns a boolean if these matrices are equivalent up to a global phase. """ function isapprox_global_phase(M1::Array{Complex{Float64},2}, M2::Array{Complex{Float64},2}; tol_0 = 1E-4) ref_nonzero_r, ref_nonzero_c = QCO._get_nonzero_idx_of_complex_matrix(M1) global_phase = M2[ref_nonzero_r, ref_nonzero_c] / M1[ref_nonzero_r, ref_nonzero_c] # exp(-im*ϕ) return isapprox(M2, global_phase * M1, atol = tol_0) end """ _get_elementary_gates_fixed_indices(M::Array{T,3} where T <: Number) Given the set of input elementary gates in real form, this function returns a dictionary of tuples of indices wholse values are fixed in `sum_k (z_k*M[:,:,k])`. """ function _get_elementary_gates_fixed_indices(M::Array{T,3} where T <: Number) N = size(M[:,:,1])[1] M_l, M_u = QCO.gate_element_bounds(M) G_fixed_idx = Dict{Tuple{Int64, Int64}, Any}() for i=1:N, j=1:N if isapprox(M_l[i,j], M_u[i,j], atol = 1E-6) G_fixed_idx[(i,j)] = Dict{String, Any}("value" => M_l[i,j]) end end return G_fixed_idx end """ _get_unitary_variables_fixed_indices(M::Array{T,3} where T <: Number, maximum_depth::Int64) Given a 3D array of real square matrices (representing gates), and a maximum alowable depth, this function returns a dictionary of tuples of indices wholse values are fixed in the unitary matrices for every depth of the circuit. """ function _get_unitary_variables_fixed_indices(M::Array{T,3} where T <: Number, maximum_depth::Int64) N = size(M)[1] G_fixed_idx = QCO._get_elementary_gates_fixed_indices(M) U_fixed_idx = Dict{Int64, Any}() for depth = 1:(maximum_depth-1) U_fixed_idx[depth] = Dict{Tuple{Int64, Int64}, Any}() if depth == 1 # Assuming data["initial_gate"] == "Identity" U_fixed_idx[depth] = G_fixed_idx else U_fixed_idx[depth] = QCO._get_matrix_product_fixed_indices(U_fixed_idx[depth-1], G_fixed_idx, N) end end return U_fixed_idx end """ _get_matrix_product_fixed_indices(left_matrix_fixed_idx::Dict{Tuple{Int64, Int64}, Any}, right_matrix_fixed_idx::Dict{Tuple{Int64, Int64}, Any}, N::Int64) Given left and right square matrices of size `NxN`, in a dictionary format with tuples of indices whose values are fixed, this function returns a dictionary of tuples of indices wholse values are fixed in `left_matrix * right_matrix`. """ function _get_matrix_product_fixed_indices(left_matrix_fixed_idx::Dict{Tuple{Int64, Int64}, Any}, right_matrix_fixed_idx::Dict{Tuple{Int64, Int64}, Any}, N::Int64) product_fixed_idx = Dict{Tuple{Int64, Int64}, Any}() for row = 1:N left_matrix_constants_row = filter(p -> (p.first[1] == row), left_matrix_fixed_idx) left_matrix_zeros_row = filter(p -> (isapprox(p.second["value"], 0, atol = 1E-6)), left_matrix_constants_row) v_constants_row = keys(left_matrix_constants_row) |> collect .|> last v_zeros_row = keys(left_matrix_zeros_row) |> collect .|> last for col = 1:N right_matrix_constants_col = filter(p -> (p.first[2] == col), right_matrix_fixed_idx) right_matrix_zeros_col = filter(p -> (isapprox(p.second["value"], 0, atol=1E-6)), right_matrix_constants_col) v_constants_col = keys(right_matrix_constants_col) |> collect .|> first v_zeros_col = keys(right_matrix_zeros_col) |> collect .|> first all_zero_idx = union(v_zeros_row, v_zeros_col) # Keep track of zero value indices in matrix product if sort(all_zero_idx) == 1:N product_fixed_idx[(row,col)] = Dict{String, Any}("value" => 0) end # Keep track of non-zero constant value indices in matrix product if (sort(v_constants_row) == 1:N) && (sort(v_constants_col) == 1:N) value = 0 for i = 1:N value += left_matrix_constants_row[(row, i)]["value"] * right_matrix_constants_col[(i, col)]["value"] end product_fixed_idx[(row,col)] = Dict{String, Any}("value" => value) end end end return product_fixed_idx end """ controlled_gate(gate::Array{Complex{Float64},2}, num_control_qubits::Int64; reverse = false) Given a complex-valued matrix (`gate`) of `N` qubits, and number of control qubits (`NCQ`), this function returns a complex-valued controlled gate representable in `N+NCQ` qubits. The state of control qubit is applied `NCQ` times to every wire preceeding the location of the input gate. Note that this function does not account for the actual location of the controlled gate in the circuit. Here are a few examples: (a) [ToffoliGate](@ref) = controlled_gate(XGate(), 2) = controlled_gate(CNotGate(), 1) (b) CCCCCZGate = controlled_gate(ZGate(), 5) (c) TCCGate = controlled(TGate(), 2, reverse = true) """ function controlled_gate(gate::Array{Complex{Float64},2}, num_control_qubits::Int64; reverse = false) if num_control_qubits < 0 Memento.error(_LOGGER, "Number of control qubits has to be a non-negative integer") end M_0 = Array{Complex{Float64},2}([1 0; 0 0]) M_1 = Array{Complex{Float64},2}([0 0; 0 1]) ctrl_gate = gate for _ = 1:num_control_qubits num_qubits = Int(log2(size(ctrl_gate)[1])) if !reverse # |0⟩⟨0| ⊗ I control_0 = kron(M_0, QCO.IGate(num_qubits)) # |1⟩⟨1| ⊗ G control_1 = kron(M_1, ctrl_gate) else # I ⊗ |0⟩⟨0| control_0 = kron(QCO.IGate(num_qubits), M_0) # G ⊗ |1⟩⟨1| control_1 = kron(ctrl_gate, M_1) end ctrl_gate = control_0 + control_1 end return ctrl_gate end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
6605
#-----------------------------------------------------------# # Initialize all variables of the QuantumCircuitModel here # #-----------------------------------------------------------# function variable_gates_per_depth(qcm::QuantumCircuitModel) tol_0 = 1E-6 n_r = size(qcm.data["gates_real"])[1] n_c = size(qcm.data["gates_real"])[2] max_depth = qcm.data["maximum_depth"] M_l, M_u = QCO.gate_element_bounds(qcm.data["gates_real"]) qcm.variables[:G_var] = JuMP.@variable(qcm.model, M_l[i,j] <= G_var[i=1:n_r, j=1:n_c, 1:max_depth] <= M_u[i,j]) num_vars_fixed = 0 for i=1:n_r, j=1:n_c if isapprox(M_l[i,j], M_u[i,j], atol=tol_0) for d=1:max_depth JuMP.fix(G_var[i,j,d], M_l[i,j]; force=true) end num_vars_fixed += 1 end end if num_vars_fixed > 0 Memento.info(_LOGGER, "$num_vars_fixed of $(n_r * n_c) entries are constants in the given set of gates.") end return end function variable_gates_onoff(qcm::QuantumCircuitModel) num_gates = size(qcm.data["gates_real"])[3] max_depth = qcm.data["maximum_depth"] qcm.variables[:z_bin_var] = JuMP.@variable(qcm.model, z_bin_var[1:num_gates,1:max_depth], Bin) if "input_circuit" in keys(qcm.data) gates_dict = qcm.data["gates_dict"] start_value = qcm.data["input_circuit"] for d in keys(start_value) circuit_depth = start_value[d]["depth"] gate_start = start_value[d]["gate"] for n in keys(gates_dict) if gate_start in gates_dict[n]["type"] JuMP.set_start_value(z_bin_var[parse(Int64, n), circuit_depth], 1) end end end end return end function variable_sequential_gate_products(qcm::QuantumCircuitModel) max_depth = qcm.data["maximum_depth"] n_r = size(qcm.data["gates_real"])[1] n_c = size(qcm.data["gates_real"])[2] if !qcm.options.fix_unitary_variables qcm.variables[:U_var] = JuMP.@variable(qcm.model, -1 <= U_var[1:n_r, 1:n_c, 1:max_depth] <= 1) return end qcm.variables[:U_var] = JuMP.@variable(qcm.model, U_var[1:n_r, 1:n_c, 1:max_depth]) U_fixed_idx = QCO._get_unitary_variables_fixed_indices(qcm.data["gates_real"], max_depth) # U_var_bound_tol = 1E-8 for depth = 1:(max_depth-1) U_fix = U_fixed_idx[depth] for ii = 1:n_r, jj = 1:n_c if ((ii, jj) in keys(U_fix)) if isapprox(U_fix[(ii, jj)]["value"], -1, atol = 1E-6) JuMP.set_lower_bound(U_var[ii, jj, depth], -1) JuMP.set_upper_bound(U_var[ii, jj, depth], -1) elseif isapprox(U_fix[(ii, jj)]["value"], 0, atol = 1E-6) JuMP.set_lower_bound(U_var[ii, jj, depth], 0) JuMP.set_upper_bound(U_var[ii, jj, depth], 0) elseif isapprox(U_fix[(ii, jj)]["value"], 1, atol = 1E-6) JuMP.set_lower_bound(U_var[ii, jj, depth], 1) JuMP.set_upper_bound(U_var[ii, jj, depth], 1) else JuMP.set_lower_bound(U_var[ii, jj, depth], U_fix[(ii, jj)]["value"]) JuMP.set_upper_bound(U_var[ii, jj, depth], U_fix[(ii, jj)]["value"]) end else JuMP.set_lower_bound(U_var[ii, jj, depth], -1) JuMP.set_upper_bound(U_var[ii, jj, depth], 1) end end end for ii = 1:n_r, jj = 1:n_c JuMP.set_lower_bound(U_var[ii, jj, max_depth], -1) JuMP.set_upper_bound(U_var[ii, jj, max_depth], 1) end return end function variable_gate_products_copy(qcm::QuantumCircuitModel) max_depth = qcm.data["maximum_depth"] n_r = size(qcm.data["gates_real"])[1] n_c = size(qcm.data["gates_real"])[2] num_gates = size(qcm.data["gates_real"])[3] qcm.variables[:V_var] = JuMP.@variable(qcm.model, -1 <= V_var[1:n_r, 1:n_c, 1:num_gates, 1:max_depth] <= 1) return end function variable_gate_products_linearization(qcm::QuantumCircuitModel) n_r = size(qcm.data["gates_real"])[1] n_c = size(qcm.data["gates_real"])[2] max_depth = qcm.data["maximum_depth"] num_gates = size(qcm.data["gates_real"])[3] if !qcm.options.fix_unitary_variables qcm.variables[:zU_var] = JuMP.@variable(qcm.model, -1 <= zU_var[1:n_r, 1:n_c, 1:num_gates, 1:(max_depth-1)] <= 1) return end U_var = qcm.variables[:U_var] qcm.variables[:zU_var] = JuMP.@variable(qcm.model, zU_var[1:n_r, 1:n_c, 1:num_gates, 1:(max_depth-1)]) for d = 1:(max_depth-1), i = 1:n_r, j = 1:n_c, k = 1:num_gates U_var_l = JuMP.lower_bound(U_var[i,j,d]) U_var_u = JuMP.upper_bound(U_var[i,j,d]) if isapprox(U_var_l, 0, atol = 1E-6) && isapprox(U_var_u, 0, atol = 1E-6) JuMP.set_lower_bound(zU_var[i,j,k,d], 0) JuMP.set_upper_bound(zU_var[i,j,k,d], 0) else JuMP.set_lower_bound(zU_var[i,j,k,d], -1) JuMP.set_upper_bound(zU_var[i,j,k,d], 1) end end return end function variable_slack_for_feasibility(qcm::QuantumCircuitModel) n_r = size(qcm.data["gates_real"])[1] n_c = size(qcm.data["gates_real"])[2] max_depth = qcm.data["maximum_depth"] U_var = qcm.variables[:U_var] qcm.variables[:slack_var] = JuMP.@variable(qcm.model, slack_var[1:n_r, 1:n_c]) for i=1:n_r, j=1:n_c lb = JuMP.lower_bound(U_var[i,j,max_depth-1]) ub = JuMP.upper_bound(U_var[i,j,max_depth-1]) if isapprox(lb, 0, atol = 1E-6) && isapprox(ub, 0, atol = 1E-6) JuMP.set_lower_bound(slack_var[i,j], 0) JuMP.set_upper_bound(slack_var[i,j], 0) else JuMP.set_lower_bound(slack_var[i,j], -1) JuMP.set_upper_bound(slack_var[i,j], 1) end end return end function variable_slack_var_outer_approximation(qcm::QuantumCircuitModel) n_r = size(qcm.data["gates_real"])[1] n_c = size(qcm.data["gates_real"])[2] qcm.variables[:slack_var_oa] = JuMP.@variable(qcm.model, -1 <= slack_var_oa[1:n_r, 1:n_c] <= 1) return end function variable_binary_products(qcm::QuantumCircuitModel) num_gates = size(qcm.data["gates_real"])[3] max_depth = qcm.data["maximum_depth"] qcm.variables[:Z_var] = JuMP.@variable(qcm.model, 0 <= Z[1:num_gates, 1:num_gates, 1:max_depth] <= 1) return end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
802
@testset "Tests: convex_hull" begin points_1a = [(0.5, 0.0), (0.0, 0.0), (1, 0), (0,1), (-0.5, 0), (0.0, 0.5)] points_1b = [(0.0, 0.0), (1, 0), (0,1), (-0.5, 0), (0.5, 0.0), (0.0, 0.5)] points_2a = [(0.5, 0.0), (0.0, 0.0), (1, 0), (0,1), (-0.5, 0), (0.0, 0.5), (0.5, -0.5)] points_2b = [(0.5, 0.0), (0.5, -0.5), (0.0, 0.0), (0,1), (-0.5, 0), (0.0, 0.5), (1, 0)] points_3a = [(0,0)] points_3b = [(-0.5,-0.5), (0.5,0.5)] points_3c = [(-0.5, -0.5), (0.5, 0.5), (0, 0), (0.25, 0.25)] @test QCO.convex_hull(points_1a) == QCO.convex_hull(points_1b) @test QCO.convex_hull(points_2a) == QCO.convex_hull(points_2b) @test QCO.convex_hull(points_3a) == points_3a @test QCO.convex_hull(points_3b) == points_3b @test QCO.convex_hull(points_3c) == points_3b end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
5718
# Unit tests for functions in data.jl @testset "Data tests: building elementary universal gate" begin test_angle = π/3 pauli_Y = QCO.YGate() H = QCO.HGate() U3_1 = [(1/sqrt(2))+0.0im 0.0-(1/sqrt(2))im 0.0+(1/sqrt(2))im -(1/sqrt(2))+0.0im] test_U3_1 = QCO.U3Gate(π/2,π/2,π/2) @test isapprox(U3_1, test_U3_1) # @test ceil.(real(U3_1), digits=6) == ceil.(real(test_U3_1), digits=6) # @test ceil.(imag(U3_1), digits=6) == ceil.(imag(test_U3_1), digits=6) test_U3_2 = QCO.U3Gate(π,π/2,π/2) @test isapprox(test_U3_2, pauli_Y) test_U2_2 = QCO.U2Gate(0,π) @test isapprox(test_U2_2, H) test_U3_3 = QCO.U3Gate(test_angle, -π/2, π/2) @test isapprox(QCO.RXGate(test_angle), test_U3_3) test_U3_4 = QCO.U3Gate(test_angle, 0, 0) @test isapprox(QCO.RYGate(test_angle), test_U3_4) test_U1_1 = exp(-((test_angle)/2)im)*QCO.U1Gate(test_angle) @test isapprox(QCO.RZGate(test_angle), test_U1_1) end @testset "Data tests: get_full_sized_gate" begin # 2-qubit gates params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 2, "elementary_gates" => ["T_1", "T_2", "Tdagger_1", "Tdagger_2", "S_1", "S_2", "Sdagger_1", "Sdagger_2", "SX_1", "SX_2", "SXdagger_1", "SXdagger_2", "X_1", "X_2", "Y_1", "Y_2", "Z_1", "Z_2", "CZ_1_2", "CH_1_2", "CV_1_2", "Phase_1", "Phase_2", "CSX_1_2", "DCX_1_2", "Sycamore_1_2"], "Phase_discretization" => [π], "target_gate" => QCO.IGate(2), ) data = QCO.get_data(params, eliminate_identical_gates = false) @test length(keys(data["gates_dict"])) == 26 # kron gates params = Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 2, "elementary_gates" => ["I_1xH_2xT_3", "Tdagger_1xS_2xSdagger_3", "SX_1xSXdagger_2xX_3", "Y_1xCNot_2_3", "CNot_2_1xZ_3", "CV_2_1xI_3", "I_1xCV_2_3", "CVdagger_2_1xI_3", "I_1xCVdagger_2_3", "CX_2_1xI_3", "I_1xCX_2_3", "CY_2_1xI_3", "I_1xCY_2_3", "CZ_2_1xI_3", "I_1xCZ_2_3", "CH_2_1xI_3", "I_1xCH_2_3", "CSX_2_1xI_3", "I_1xCSX_2_3", "Swap_2_1xI_3", "I_1xiSwap_2_3", "DCX_2_1xI_3", "I_1xSycamore_2_3"], "target_gate" => QCO.IGate(3), ) data = QCO.get_data(params, eliminate_identical_gates = false) @test length(keys(data["gates_dict"])) == 23 # 3-qubit gates params = Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 2, "elementary_gates" => ["H_3", "T_3", "Tdagger_3", "Sdagger_3", "SX_3", "SXdagger_3", "X_3", "Y_3", "Z_3", "CNot_1_2", "CNot_2_3", "CNot_2_1", "CNot_3_2", "CNot_1_3", "CNot_3_1"], "target_gate" => QCO.IGate(3) ) # 4-qubit gates params = Dict{String, Any}( "num_qubits" => 4, "maximum_depth" => 2, "elementary_gates" => ["CU3_1_3", "CRX_3_4", "CNot_2_4", "CH_1_4"], "CRX_discretization" => [π], "CU3_θ_discretization" => [π/2], "CU3_ϕ_discretization" => [-π/2], "CU3_λ_discretization" => [π/4], "target_gate" => QCO.IGate(4) ) data = QCO.get_data(params) @test length(keys(data["gates_dict"])) == 4 #5-qubit gates params = Dict{String, Any}( "num_qubits" => 5, "maximum_depth" => 2, "elementary_gates" => ["H_1", "T_2", "Tdagger_3", "Sdagger_4", "SX_5", "CX_1_2", "CX_2_1", "CY_1_2", "CY_2_1", "CRX_2_3", "CNot_3_4", "CH_5_4", "CRY_1_3", "CRZ_2_4", "CV_3_5", "CZ_4_1", "CSX_5_1"], "CRX_discretization" => [π], "CRY_discretization" => [π], "CRZ_discretization" => [π], "target_gate" => QCO.IGate(5) ) data = QCO.get_data(params) @test length(keys(data["gates_dict"])) == 17 end @testset "Data tests: get_input_circuit_dict" begin function input_circuit_1() # [(depth, gate)] return [(1, "CNot_2_1"), (2, "S_1"), (3, "H_2"), (4, "S_2") ] end params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["S_1", "S_2", "H_1", "H_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCO.MGate(), "input_circuit" => input_circuit_1(), ) data = QCO.get_data(params) @test "input_circuit" in keys(data) @test data["input_circuit"]["1"]["depth"] == 1 @test data["input_circuit"]["1"]["gate"] == "CNot_2_1" @test data["input_circuit"]["2"]["depth"] == 2 @test data["input_circuit"]["2"]["gate"] == "S_1" @test data["input_circuit"]["3"]["depth"] == 3 @test data["input_circuit"]["3"]["gate"] == "H_2" @test data["input_circuit"]["4"]["depth"] == 4 @test data["input_circuit"]["4"]["gate"] == "S_2" function input_circuit_2() # [(depth, gate)] return [(1, "CNot_2_1"), (2, "S_1"), (3, "H_2"), (4, "T_1") ] end params["input_circuit"] = input_circuit_2() data = QCO.get_data(params) @test !("input_circuit" in keys(data)) function input_circuit_3() # [(depth, gate)] return [(1, "CNot_2_1"), (2, "S_1"), (2, "H_2"), (4, "S_2") ] end params["input_circuit"] = input_circuit_3() data = QCO.get_data(params) @test !("input_circuit" in keys(data)) function input_circuit_4() # [(depth, gate)] return [(1, "CNot_2_1"), (2, "S_1"), (3, "H_2"), (4, "S_2"), (5, "Identity"), (6, "S_1"), ] end params["input_circuit"] = input_circuit_4() data = QCO.get_data(params) @test !("input_circuit" in keys(data)) end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
10953
# Unit tests for functions in gates.jl @testset "Gates tests: elementary universal gates in gates.jl" begin @test isapprox(QCO.U2Gate(0,-π/4), QCO.U3Gate(π/2,0,-π/4), atol=tol_0) @test isapprox(QCO.U1Gate(-π/4), QCO.U3Gate(0,0,-π/4), atol=tol_0) ctrl_qbit_1 = Array{Complex{Float64},2}([1 0; 0 0]) ctrl_qbit_2 = Array{Complex{Float64},2}([0 0; 0 1]) @test isapprox(kron(ctrl_qbit_1, QCO.IGate(1)) + kron(ctrl_qbit_2, QCO.XGate()), QCO.CXGate(), atol = tol_0) @test isapprox(kron(ctrl_qbit_1, QCO.IGate(1)) + kron(ctrl_qbit_2, QCO.YGate()), QCO.CYGate(), atol = tol_0) @test isapprox(kron(ctrl_qbit_1, QCO.IGate(1)) + kron(ctrl_qbit_2, QCO.ZGate()), QCO.CZGate(), atol = tol_0) @test isapprox(kron(ctrl_qbit_1, QCO.IGate(1)) + kron(ctrl_qbit_2, QCO.HGate()), QCO.CHGate(), atol = tol_0) @test isapprox(QCO.CXGate(), QCO.CNotGate(), atol = tol_0) ϴ1 = π/3 ϴ2 = -2*π/3 @test isapprox(kron(ctrl_qbit_1, QCO.IGate(1)) + kron(ctrl_qbit_2, QCO.RXGate(ϴ1)), QCO.CRXGate(ϴ1), atol = tol_0) @test isapprox(kron(ctrl_qbit_1, QCO.IGate(1)) + kron(ctrl_qbit_2, QCO.RXGate(ϴ2)), QCO.CRXGate(ϴ2), atol = tol_0) @test isapprox(kron(ctrl_qbit_1, QCO.IGate(1)) + kron(ctrl_qbit_2, QCO.RYGate(ϴ1)), QCO.CRYGate(ϴ1), atol = tol_0) @test isapprox(kron(ctrl_qbit_1, QCO.IGate(1)) + kron(ctrl_qbit_2, QCO.RYGate(ϴ2)), QCO.CRYGate(ϴ2), atol = tol_0) @test isapprox(kron(ctrl_qbit_1, QCO.IGate(1)) + kron(ctrl_qbit_2, QCO.RZGate(ϴ1)), QCO.CRZGate(ϴ1), atol = tol_0) @test isapprox(kron(ctrl_qbit_1, QCO.IGate(1)) + kron(ctrl_qbit_2, QCO.RZGate(ϴ2)), QCO.CRZGate(ϴ2), atol = tol_0) θ = π/3 ϕ = -2*π/3 λ = π/6 @test isapprox(kron(ctrl_qbit_1, QCO.IGate(1)) + kron(ctrl_qbit_2, QCO.U3Gate(θ,ϕ,λ)), QCO.CU3Gate(θ,ϕ,λ), atol = tol_0) @test isapprox(QCO.SwapGate(), QCO.CNotGate() * QCO.CNotRevGate() * QCO.CNotGate(), atol = tol_0) @test isapprox(QCO.iSwapGate(), QCO.CNotRevGate() * QCO.CNotGate() * kron(QCO.SGate(), QCO.IGate(1)) * QCO.CNotRevGate(), atol = tol_0) @test isapprox(QCO.PhaseGate(λ), QCO.U3Gate(0,0,λ), atol = tol_0) @test isapprox(QCO.DCXGate(), QCO.CNotGate() * QCO.CNotRevGate(), atol = tol_0) S1_S2 = kron(QCO.SGate(), QCO.SGate()) H2 = kron(QCO.IGate(1), QCO.HGate()) @test isapprox(QCO.MGate(), QCO.CNotRevGate() * H2 * S1_S2) Z1 = QCO.get_unitary("Z_1", 2); Z2 = QCO.get_unitary("Z_2", 2); T2 = QCO.get_unitary("T_2", 2); Y_2 = QCO.get_unitary("Y_2", 2); CNot_1_2 = QCO.get_unitary("CNot_1_2", 2); CNot_2_1 = QCO.get_unitary("CNot_2_1", 2); Sdagger1 = QCO.get_unitary("Sdagger_1", 2); Tdagger1 = QCO.get_unitary("Tdagger_1", 2); SX1 = QCO.get_unitary("SX_1", 2); SXdagger2 = QCO.get_unitary("SXdagger_2", 2); @test isapprox(-QCO.HCoinGate(), Z2 * CNot_2_1 * SXdagger2 * Y_2 * CNot_2_1 * Tdagger1 * Z1 * T2 * Sdagger1 * CNot_1_2 * Sdagger1 * SX1 * CNot_2_1 * CNot_1_2, atol = tol_0) CV_23 = QCO.get_unitary("CV_2_3", 3); CNot_1_2 = QCO.get_unitary("CNot_1_2", 3); CVdagger_23 = QCO.get_unitary("CVdagger_2_3", 3); CV_13 = QCO.get_unitary("CV_1_3", 3); @test isapprox(QCO.ToffoliGate(), CV_23 * CNot_1_2 * CVdagger_23 * CNot_1_2 * CV_13, atol = tol_0) CVdagger_12 = QCO.get_unitary("CVdagger_1_2", 3); CVdagger_31 = QCO.get_unitary("CVdagger_3_1", 3); @test isapprox(QCO.IGate(3), CVdagger_12 * CVdagger_12 * CVdagger_12 * CVdagger_12 * CVdagger_31 * CVdagger_31 * CVdagger_31 * CVdagger_31, atol = tol_0) H_2 = QCO.get_unitary("H_2", 2); T_1 = QCO.get_unitary("T_1", 2); Tdagger2 = QCO.get_unitary("Tdagger_2", 2); @test isapprox(QCO.CVdaggerGate(), H_2 * Tdagger1 * CNot_2_1 * T_1 * Tdagger2 * CNot_2_1 * H_2, atol = tol_0) @test isapprox(QCO.CVGate(), QCO.CNotGate() * QCO.CVdaggerGate(), atol = tol_0) # Next 3 tests from: https://american-cse.org/csci2015/data/9795a059.pdf CV_31 = QCO.get_unitary("CV_3_1", 3); CNot_2_3 = QCO.get_unitary("CNot_2_3", 3); CVdagger_31 = QCO.get_unitary("CVdagger_3_1", 3); CV_21 = QCO.get_unitary("CV_2_1", 3); CVdagger_21 = QCO.get_unitary("CVdagger_2_1", 3); @test isapprox(CV_31 * CNot_2_3 * CVdagger_31 * CNot_2_3 * CV_21, CVdagger_21 * CNot_2_3 * CV_31 * CNot_2_3 * CVdagger_31, atol = tol_0) CV_12 = QCO.get_unitary("CV_1_2", 3); CV_32 = QCO.get_unitary("CV_3_2", 3); CVdagger_32 = QCO.get_unitary("CVdagger_3_2", 3); CVdagger_12 = QCO.get_unitary("CVdagger_1_2", 3); CNot_1_3 = QCO.get_unitary("CNot_1_3", 3); @test isapprox(CV_32 * CNot_1_3 * CVdagger_32 * CNot_1_3 * CV_12, CVdagger_32 * CNot_1_3 * CV_32 * CNot_1_3 * CVdagger_12, atol = tol_0) CVdagger_13 = QCO.get_unitary("CVdagger_1_3", 3); CNot_2_1 = QCO.get_unitary("CNot_2_1", 3); @test isapprox(CV_13 * CNot_2_1 * CVdagger_13 * CNot_2_1 * CV_23, CVdagger_13 * CNot_2_1 * CV_13 * CNot_2_1 * CVdagger_23, atol = tol_0) # 2-qubit Grover's diffusion operator (Ref: https://arxiv.org/pdf/1804.03719.pdf) H_1 = QCO.get_unitary("H_1", 2); X_2 = QCO.get_unitary("X_2", 2); CNot_1_2 = QCO.get_unitary("CNot_1_2", 2); @test isapprox(QCO.GroverDiffusionGate(), Y_2 * H_1 * X_2 * CNot_1_2 * H_1 * Y_2, atol=tol_0) # 2 Qubit QFT (Ref: https://www.cs.bham.ac.uk/internal/courses/intro-mqc/current/lecture06_handout.pdf) SWAP = QCO.get_unitary("Swap_1_2", 2); CU = QCO.get_unitary("CU3_2_1", 2, angle = [0, π/4, π/4]); @test isapprox(QCO.QFT2Gate(), H_1 * CU * H_2 * SWAP) # 3 Qubit QFT (Ref: Nielsen and Chuang, Quantum Computation and Quantum Information, Ch. 5.1) CS_2_1 = QCO.get_unitary("CS_2_1", 3) CS_3_2 = QCO.get_unitary("CS_3_2", 3) CT_3_1 = QCO.get_unitary("CT_3_1", 3) SWAP_1_3 = QCO.get_unitary("Swap_1_3", 3) H_1 = QCO.get_unitary("H_1", 3) H_2 = QCO.get_unitary("H_2", 3) H_3 = QCO.get_unitary("H_3", 3) @test isapprox(QCO.QFT3Gate(), H_1 * CS_2_1 * CT_3_1 * H_2 * CS_3_2 * H_3 * SWAP_1_3) # CRY Decomp (Ref: https://quantumcomputing.stackexchange.com/questions/2143/how-can-a-controlled-ry-be-made-from-cnots-and-rotations) CNOT12 = QCO.get_unitary("CNot_1_2", 2); U3_negpi = QCO.get_unitary("U3_2", 2, angle=[-pi/2, 0, 0]); U3_pi = QCO.get_unitary("U3_2", 2, angle=[pi/2, 0, 0]); @test isapprox(QCO.CRYGate(pi), CNOT12 * U3_negpi * CNOT12 * U3_pi, atol = tol_0) # Identity tests Id = QCO.IGate(2); CRXRev = QCO.get_unitary("CRX_2_1", 2, angle=pi); @test isapprox(Id, CRXRev * CRXRev * CRXRev * CRXRev, atol = tol_0) CRYRev = QCO.get_unitary("CRY_2_1", 2, angle=pi); @test isapprox(Id, CRYRev * CRYRev * CRYRev * CRYRev, atol = tol_0) CRZRev = QCO.get_unitary("CRZ_2_1", 2, angle=pi); @test isapprox(Id, CRZRev * CRZRev * CRZRev * CRZRev, atol = tol_0) # Rev gate tests for involution @test isapprox(QCO.CXRevGate(), QCO.CNotRevGate(), atol = tol_0) @test isapprox(QCO.CXGate() * QCO.SwapGate() * QCO.CXRevGate() * QCO.SwapGate(), QCO.IGate(2), atol = tol_0) @test isapprox(QCO.CYGate() * QCO.SwapGate() * QCO.CYRevGate() * QCO.SwapGate(), QCO.IGate(2), atol = tol_0) @test isapprox(QCO.CZGate() * QCO.SwapGate() * QCO.CZGate() * QCO.SwapGate(), QCO.IGate(2), atol = tol_0) @test isapprox(QCO.CHGate() * QCO.SwapGate() * QCO.CHRevGate() * QCO.SwapGate(), QCO.IGate(2), atol = tol_0) # Rev gate tests for non-involution @test isapprox(QCO.CVGate() * QCO.SwapGate() * QCO.CVRevGate() * QCO.SwapGate(), QCO.CVGate()^2, atol = tol_0) @test isapprox(QCO.CSXGate() * QCO.SwapGate() * QCO.CSXRevGate() * QCO.SwapGate(), QCO.CSXGate()^2, atol = tol_0) @test isapprox(QCO.WGate(), QCO.HCoinGate(), atol = tol_0) # Fredkin test = CSwapGate CNot_3_2 = QCO.get_unitary("CNot_3_2", 3) CV_23 = QCO.get_unitary("CV_2_3", 3) CV_13 = QCO.get_unitary("CV_1_3", 3) CNot_1_2 = QCO.get_unitary("CNot_1_2", 3) CVdagger_23 = QCO.get_unitary("CVdagger_2_3", 3) @test isapprox(QCO.CSwapGate(), CNot_3_2 * CV_23 * CV_13 * CNot_1_2 * CVdagger_23 * CNot_1_2 * CNot_3_2, atol = tol_0) # CCZGate test: CCZ is equivalent to Toffoli when the target qubit is conjugated by Hadamard gates H_3 = QCO.get_unitary("H_3", 3) @test isapprox(QCO.ToffoliGate(), H_3 * QCO.CCZGate() * H_3, atol = tol_0) # Peres test CVdagger_13 = QCO.get_unitary("CVdagger_1_3", 3) @test isapprox(QCO.PeresGate(), QCO.ToffoliGate() * CNot_1_2, atol = tol_0) @test isapprox(QCO.PeresGate(), CVdagger_13 * CVdagger_23 * CNot_1_2 * CV_23, atol = tol_0) # iSwap test @test isapprox(QCO.get_unitary("iSwap_2_1", 3), QCO.get_unitary("iSwap_1_2", 3), atol = tol_0) @test isapprox(QCO.get_unitary("iSwap_2_3", 4), QCO.get_unitary("iSwap_3_2", 4), atol = tol_0) @test isapprox(QCO.get_unitary("iSwap_3_5", 5), QCO.get_unitary("iSwap_5_3", 5), atol = tol_0) # Sycamore test @test isapprox(QCO.SycamoreGate()^12, QCO.IGate(2), atol = tol_0) # RCCX test T_3 = QCO.get_unitary("T_3", 3) Tdagger_3 = QCO.get_unitary("Tdagger_3", 3) @test isapprox(QCO.RCCXGate(), H_3 * Tdagger_3 * CNot_2_3 * T_3 * CNot_1_3 * Tdagger_3 * CNot_2_3 * T_3 * H_3, atol = tol_0) # Margolus test RY_a = QCO.get_unitary("RY_3", 3, angle = -π/4) RY_b = QCO.get_unitary("RY_3", 3, angle = π/4) @test isapprox(QCO.MargolusGate(), RY_a * CNot_2_3 * RY_a * CNot_1_3 * RY_b * CNot_2_3 * RY_b, atol = tol_0) # CiSwap test @test isapprox(QCO.CiSwapGate(), CNot_3_2 * H_3 * CNot_2_3 * T_3 * CNot_1_3 * Tdagger_3 * CNot_2_3 * T_3 * CNot_1_3 * Tdagger_3 * H_3 * CNot_3_2, atol = tol_0) # 2-angle RGate test # Ref: https://qiskit.org/documentation/stubs/qiskit.circuit.library.RGate.html#qiskit.circuit.library.RGate θ = π/3; ϕ = π/6; R1 = QCO.RGate(θ, ϕ) U3 = QCO.U3Gate(θ, ϕ, -ϕ) U3[1,2] = U3[1,2] * im; U3[2,1] = U3[2,1] * -im; @test isapprox(R1, U3; atol = tol_0) # CS, CSdagger gate test H1 = QCO.get_unitary("H_1", 2) H2 = QCO.get_unitary("H_2", 2) CS_12 = QCO.get_unitary("CS_1_2", 2) @test isapprox(H1 * CS_12 * H2 * QCO.SwapGate(), QCO.QFT2Gate(), atol = tol_0) @test isapprox(QCO.CSGate() * QCO.CSdaggerGate(), QCO.IGate(2), atol = tol_0) #SSwapGate test @test isapprox(QCO.SSwapGate()^2, QCO.SwapGate(), atol = 1E-6) # CT, CTdagger gate test @test isapprox(QCO.CTGate() * QCO.CTdaggerGate(), QCO.IGate(2), atol = tol_0) # Test for elementary gates with kron symbols M1 = QCO.get_unitary("I_1xCZ_2_4xH_5", 5) M2 = kron(kron(QCO.IGate(1), QCO.get_unitary("CZ_1_3", 3)), QCO.HGate()) @test isapprox(M1, M2, atol = tol_0) M1 = QCO.get_unitary("CV_4_1xH_5xZ_6", 6) M2 = kron(kron(QCO.get_unitary("CV_4_1", 4), QCO.HGate()), QCO.ZGate()) @test isapprox(M1, M2, atol = tol_0) end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
28422
@testset "QC_model Tests: Minimize depth for controlled-NOT gate" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["H_1", "H_2", "CNot_1_2", "Identity"], "initial_gate" => "Identity", "target_gate" => QCO.CNotRevGate(), "set_cnot_lower_bound" => 1, "set_cnot_upper_bound" => 1, "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) model_options = Dict{Symbol, Any}(:model_type => "compact_formulation_1", # Testing incorrect model_type :all_valid_constraints => 2) # Testing incorrect all_valid_constraints result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 5, atol=tol_0) @test isapprox(result_qc["solution"]["z_bin_var"][1,1], 1, atol=tol_0) || isapprox(result_qc["solution"]["z_bin_var"][2,1], 1, atol=tol_0) @test isapprox(result_qc["solution"]["z_bin_var"][1,2], 1, atol=tol_0) || isapprox(result_qc["solution"]["z_bin_var"][2,2], 1, atol=tol_0) @test isapprox(result_qc["solution"]["z_bin_var"][3,3], 1, atol=tol_0) @test isapprox(result_qc["solution"]["z_bin_var"][1,4], 1, atol=tol_0) || isapprox(result_qc["solution"]["z_bin_var"][2,4], 1, atol=tol_0) @test isapprox(result_qc["solution"]["z_bin_var"][1,5], 1, atol=tol_0) || isapprox(result_qc["solution"]["z_bin_var"][2,5], 1, atol=tol_0) end @testset "QC_model Tests: Minimum CNOT swap gate decomposition" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 4, "elementary_gates" => ["CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCO.SwapGate(), "set_cnot_lower_bound" => 2, "set_cnot_upper_bound" => 3, "objective" => "minimize_cnot", "decomposition_type" => "exact_optimal" ) model_options = Dict{Symbol, Any}(:model_type => "balas_formulation", :all_valid_constraints => 1) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 3, atol = tol_0) @test isapprox(sum(result_qc["solution"]["z_bin_var"][1:2,:]), 3, atol=tol_0) end @testset "QC_model Tests: Minimum depth U3(0,0,π/4) gate" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 2, "elementary_gates" => ["U3_1", "U3_2", "Identity"], "target_gate" => QCO.kron_single_qubit_gate(2, QCO.U3Gate(0,0,π/4), "q1"), "U3_θ_discretization" => [0, π/2], "U3_ϕ_discretization" => [0], "U3_λ_discretization" => [0, π/4], "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) result_qc = QCO.run_QCModel(params, MIP_SOLVER) data = QCO.get_data(params) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 1, atol = tol_0) @test "Identity" in data["gates_dict"]["3"]["type"] @test isapprox(sum(result_qc["solution"]["z_bin_var"][3,:]), 1, atol = tol_0) @test isapprox(sum(result_qc["solution"]["z_bin_var"][4,:]), 1, atol = tol_0) @test data["gates_dict"]["4"]["qubit_loc"] == "qubit_1" end @testset "QC_model Tests: Minimum depth CU3(0,0,π/4) gate" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 2, "elementary_gates" => ["CU3_1_2", "CU3_2_1", "Identity"], "target_gate" => QCO.CU3Gate(0, 0, π/4), "CU3_θ_discretization" => [0, π/2], "CU3_ϕ_discretization" => [0], "CU3_λ_discretization" => [0, π/4], "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) result_qc = QCO.run_QCModel(params, MIP_SOLVER) data = QCO.get_data(params) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 1, atol = tol_0) @test "Identity" in data["gates_dict"]["3"]["type"] @test isapprox(sum(result_qc["solution"]["z_bin_var"][3,:]), 1, atol = tol_0) @test isapprox(sum(result_qc["solution"]["z_bin_var"][4,:]), 1, atol = tol_0) @test data["gates_dict"]["4"]["qubit_loc"] == "qubit_1_2" end @testset "QC_model Tests: Minimum depth Rev CU3(0,0,π/4) gate" begin params = Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 2, "elementary_gates" => ["CU3_3_1", "CU3_1_3", "Identity"], "target_gate" => QCO.get_unitary("CU3_3_1", 3, angle = [0, 0, pi/4]), "CU3_θ_discretization" => [0, π/2], "CU3_ϕ_discretization" => [0], "CU3_λ_discretization" => [0, π/4], "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) result_qc = QCO.run_QCModel(params, MIP_SOLVER) data = QCO.get_data(params) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 1, atol = tol_0) @test "Identity" in data["gates_dict"]["3"]["type"] @test isapprox(sum(result_qc["solution"]["z_bin_var"][3,:]), 1, atol = tol_0) @test isapprox(sum(result_qc["solution"]["z_bin_var"][4,:]), 1, atol = tol_0) @test data["gates_dict"]["4"]["qubit_loc"] == "qubit_3_1" end @testset "QC_model Tests: Minimum depth RX, RY, RZ gate decomposition" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 3, "elementary_gates" => ["RX_1", "RY_2", "RZ_1", "Identity"], "target_gate" => QCO.kron_single_qubit_gate(2, QCO.RXGate(π/4), "q1") * QCO.kron_single_qubit_gate(2, QCO.RYGate(π/4), "q2") * QCO.kron_single_qubit_gate(2, QCO.RZGate(π/4), "q1"), "RX_discretization" => [0, π/4], "RY_discretization" => [π/4], "RZ_discretization" => [π/2, π/4], "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) model_options = Dict{Symbol, Any}(:model_type => "balas_formulation", :commute_gate_constraints => true) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 3, atol = tol_0) end @testset "QC_model Tests: Minimum depth CRX, CRY, CRZ gate decomposition" begin params = Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 3, "elementary_gates" => ["CRX_1_2", "CRY_2_3", "CRZ_3_1", "Identity"], "target_gate" => QCO.get_unitary("CRX_1_2", 3, angle = pi/4) * QCO.get_unitary("CRY_2_3", 3, angle=pi/4) * QCO.get_unitary("CRZ_3_1", 3, angle=pi/4), "CRX_discretization" => [0, π/4], "CRY_discretization" => [π/4], "CRZ_discretization" => [π/2, π/4], "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) model_options = Dict{Symbol, Any}(:model_type => "balas_formulation", :commute_gate_constraints => true) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 3, atol = tol_0) end @testset "QC_model Tests: Minimum depth Rev CRX, CRY, CRZ gate decomposition" begin params = Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 3, "elementary_gates" => ["CRX_3_1", "CRY_3_1", "CRZ_1_3", "Identity"], "target_gate" => QCO.get_unitary("CRX_3_1", 3, angle=pi/4) * QCO.get_unitary("CRY_3_1", 3, angle=pi/4) * QCO.get_unitary("CRZ_1_3", 3, angle = pi/2), "CRX_discretization" => [0, π/4], "CRY_discretization" => [π/4], "CRZ_discretization" => [π/2, π/4], "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) model_options = Dict{Symbol, Any}(:model_type => "balas_formulation", :commute_gate_constraints => true) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 3, atol = tol_0) end @testset "QC_model Tests: 3-qubit RX gate decomposition" begin params = Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 2, "elementary_gates" => ["U3_1", "U3_2", "U3_3", "Identity"], "target_gate" => QCO.kron_single_qubit_gate(3, QCO.RXGate(π/4), "q3"), "U3_θ_discretization" => [0, π/4], "U3_ϕ_discretization" => [0, -π/2], "U3_λ_discretization" => [0, π/2], "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) model_options = Dict{Symbol, Any}(:model_type => "balas_formulation") result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) data = QCO.get_data(params) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 1, atol = tol_0) if isapprox(sum(result_qc["solution"]["z_bin_var"][14,:]), 1, atol=tol_0) @test data["gates_dict"]["14"]["qubit_loc"] == "qubit_3" @test isapprox(rad2deg(data["gates_dict"]["14"]["angle"]["θ"]), 45, atol=tol_0) @test isapprox(rad2deg(data["gates_dict"]["14"]["angle"]["ϕ"]), -90, atol=tol_0) @test isapprox(rad2deg(data["gates_dict"]["14"]["angle"]["λ"]), 90, atol=tol_0) end end @testset "QC_model Tests: 3-qubit CRX gate decomposition" begin params = Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 2, "elementary_gates" => ["CU3_1_2", "CU3_2_3", "CU3_1_3", "Identity"], "target_gate" => QCO.get_unitary("CRX_1_3", 3, angle = pi/4), "CU3_θ_discretization" => [0, π/4], "CU3_ϕ_discretization" => [0, -π/2], "CU3_λ_discretization" => [0, π/2], "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) model_options = Dict{Symbol, Any}(:model_type => "balas_formulation") result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) data = QCO.get_data(params) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 1, atol = tol_0) if isapprox(sum(result_qc["solution"]["z_bin_var"][18,:]), 1, atol=tol_0) @test data["gates_dict"]["18"]["qubit_loc"] == "qubit_1_3" @test isapprox(rad2deg(data["gates_dict"]["18"]["angle"]["θ"]), 45, atol=tol_0) @test isapprox(rad2deg(data["gates_dict"]["18"]["angle"]["ϕ"]), -90, atol=tol_0) @test isapprox(rad2deg(data["gates_dict"]["18"]["angle"]["λ"]), 90, atol=tol_0) end end @testset "QC_model Tests: feasibility problem" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 3, "elementary_gates" => ["H_1", "H_2"], "target_gate" => QCO.kron_single_qubit_gate(2, QCO.HGate(), "q1"), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) model_options = Dict{Symbol, Any}(:all_valid_constraints => -1) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT data = QCO.get_data(params) for i in keys(data["gates_dict"]) if data["gates_dict"][i]["type"] == "H_1" @test isapprox(sum(result_qc["solution"]["z_bin_var"][parse(Int64, i),:]), 3 , atol = tol_0) end end end @testset "QC_model Tests: JuMP set_start_value for z_bin_var variables" begin function input_circuit() # [(depth, gate)] return [(1, "CNot_2_1"), (2, "S_1"), (3, "H_2"), (4, "S_2") ] end params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 4, "elementary_gates" => ["S_1", "S_2", "H_1", "H_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCO.MGate(), "input_circuit" => input_circuit(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) result_qc = QCO.run_QCModel(params, MIP_SOLVER) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(sum(result_qc["solution"]["z_bin_var"][6,:]), 1, atol=tol_0) @test isapprox(sum(result_qc["solution"]["z_bin_var"][5,:]), 0, atol=tol_0) end @testset "QC_model Tests: Involutory gate constraints" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 4, "elementary_gates" => ["S_1", "S_2", "H_1", "H_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCO.MGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) gates_dict = QCO.get_data(params)["gates_dict"] involutory_gates = QCO.get_involutory_gates(gates_dict) @test length(involutory_gates) == 4 #excluding Identity gate for i in keys(gates_dict) if ("S_1" in gates_dict[i]["type"]) || ("S_2" in gates_dict[i]["type"]) @test !(parse(Int, i) in involutory_gates) end if ("H_1" in gates_dict[i]["type"]) || ("H_2" in gates_dict[i]["type"]) || ("CNot_1_2" in gates_dict[i]["type"]) || ("CNot_2_1" in gates_dict[i]["type"]) @test (parse(Int, i) in involutory_gates) end end result_qc = QCO.run_QCModel(params, MIP_SOLVER) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 4, atol = tol_0) end @testset "QC_model Tests: TIME_LIMIT for building results dict and log" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["S_1", "S_2", "H_1", "H_2", "CNot_1_2", "CNot_2_1", "Identity"], "target_gate" => QCO.MGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal" ) model_options = Dict{Symbol, Any}(:time_limit => 0.2) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.TIME_LIMIT @test result_qc["primal_status"] == MOI.NO_SOLUTION end @testset "QC_model Tests: constraint_redundant_gate_product_pairs" begin function target_gate() T1 = QCO.get_unitary("U3_2", 2, angle = [0,π/2,π]) T2 = QCO.get_unitary("U3_1", 2, angle = [π/2,π/2,-π/2]) return T1*T2 end params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 2, "elementary_gates" => ["U3_1", "U3_2", "Identity"], "target_gate" => target_gate(), "U3_θ_discretization" => [0, π/2], "U3_ϕ_discretization" => [π/2], "U3_λ_discretization" => [-π/2, π], "objective" => "minimize_depth") data = QCO.get_data(params) redundant_pairs = QCO.get_redundant_gate_product_pairs(data["gates_dict"], data["decomposition_type"]) @test length(redundant_pairs) == 2 @test redundant_pairs[1] == (1,4) @test redundant_pairs[2] == (5,7) @test isapprox(data["gates_dict"]["1"]["matrix"] * data["gates_dict"]["4"]["matrix"], data["gates_dict"]["2"]["matrix"], atol = tol_0) @test isapprox(data["gates_dict"]["5"]["matrix"] * data["gates_dict"]["7"]["matrix"], data["gates_dict"]["6"]["matrix"], atol = tol_0) result_qc = QCO.run_QCModel(params, MIP_SOLVER) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 2.0, atol = tol_0) end @testset "QC_model Tests: constraint_idempotent_gates" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 3, "elementary_gates" => ["U3_1", "U3_2", "CNot_1_2", "Identity"], "target_gate" => QCO.CZGate(), "U3_θ_discretization" => [-π/2, 0, π/2], "U3_ϕ_discretization" => [0, π/2], "U3_λ_discretization" => [0, π/2]) data = QCO.get_data(params) idempotent_pairs = QCO.get_idempotent_gates(data["gates_dict"], data["decomposition_type"]) @test length(idempotent_pairs) == 2 model_options = Dict{Symbol, Any}(:idempotent_gate_constraints => true) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 3.0, atol = tol_0) for i in keys(data["gates_dict"]) if "Identity" in data["gates_dict"][i]["type"] @test isapprox(sum(result_qc["solution"]["z_bin_var"][parse(Int64, i),:]), 0, atol = tol_0) end end end @testset "QC_model Tests: constraint_convex_hull_complex_gates" begin function target_gate() num_qubits = 4 CV_1_4 = QCO.get_unitary("CV_1_4", num_qubits); CV_2_4 = QCO.get_unitary("CV_2_4", num_qubits); CV_3_4 = QCO.get_unitary("CV_3_4", num_qubits); CVdagger_3_4 = QCO.get_unitary("CVdagger_3_4", num_qubits); CNot_1_2 = QCO.get_unitary("CNot_1_2", num_qubits); CNot_2_3 = QCO.get_unitary("CNot_2_3", num_qubits); return CV_2_4 * CNot_1_2 * CV_3_4 * CV_1_4 * CNot_2_3 * CVdagger_3_4 end params = Dict{String, Any}( "num_qubits" => 4, "maximum_depth" => 6, "elementary_gates" => ["CV_1_4", "CV_2_4", "CV_3_4", "CVdagger_3_4", "CNot_1_2", "CNot_2_3", "Identity"], "target_gate" => target_gate() ) model_options = Dict{Symbol, Any}(:relax_integrality => true, :convex_hull_gate_constraints => true, :fix_unitary_variables => true, :optimizer_log => false, ) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 0.6, atol = tol_0) end @testset "QC_model Tests: RGate decomposition" begin num_qubits = 2 GR1 = QCO.GRGate(num_qubits, π/6, π/3) CNot_1_2 = QCO.get_unitary("CNot_1_2", 2) T = QCO.round_complex_values(GR1 * CNot_1_2) params = Dict{String, Any}( "num_qubits" => num_qubits, "maximum_depth" => 3, "elementary_gates" => ["R_1", "R_2", "CNot_1_2", "Identity"], "R_θ_discretization" => [π/3, π/6], "R_ϕ_discretization" => [π/3, π/6], "target_gate" => T, "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", ) model_options = Dict{Symbol, Any}(:optimizer_log => false, :fix_unitary_variables => false) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 3.0, atol = tol_0) z_sol = result_qc["solution"]["z_bin_var"] @test isapprox(sum(z_sol[1:8, :]), 2, atol = tol_0) @test isapprox(sum(z_sol[9, :]), 1, atol = tol_0) end @testset "QC_model Tests: GRGate decomposition for Pauli-X gate, and unitary constraints" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["GR", "RZ_2", "CZ_1_2", "Identity"], "target_gate" => QCO.get_unitary("X_1", 2), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "GR_θ_discretization" => [-π/2, π/2], "GR_ϕ_discretization" => [0], "RZ_discretization" => [π], ) model_options = Dict{Symbol, Any}(:optimizer_log => false, :unitary_constraints => true) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 5.0, atol = tol_0) z_sol = result_qc["solution"]["z_bin_var"] @test isapprox(sum(z_sol[4, :]), 2, atol = tol_0) # test for number of CZ gates end @testset "QC_model Tests: Decomposition using exact_feasible option" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["CH_1_2", "CNot_2_1", "CNot_1_2", "Identity"], "target_gate" => QCO.WGate(), "objective" => "minimize_depth", "decomposition_type" => "exact_feasible", ) model_options = Dict{Symbol, Any}(:optimizer_log => false) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 0.0, atol = tol_0) z_sol = result_qc["solution"]["z_bin_var"] @test isapprox(sum(z_sol[2:4, :]), 4, atol = tol_0) end @testset "QC_model Tests: Approximate decomposition using outer approximation" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["H_1", "H_2", "CNot_1_2", "Identity"], "target_gate" => QCO.CNotRevGate(), "objective" => "minimize_depth", "decomposition_type" => "approximate", ) model_options = Dict{Symbol, Any}(:optimizer_log => false) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 5.0, atol = tol_0) end @testset "QC_model Tests: Approximate decomposition using outer approximation" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["H_1", "H_2", "CNot_1_2", "Identity"], "target_gate" => QCO.CNotRevGate(), "objective" => "minimize_depth", "decomposition_type" => "approximate", ) model_options = Dict{Symbol, Any}(:optimizer_log => false) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 5.0, atol = tol_0) # Testing approximate decomposition for balas_formulation model_options = Dict{Symbol, Any}(:optimizer_log => false, :model_type => "balas_formulation") result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 5.0, atol = tol_0) # Testing approximate decomposition for feasibility case params["elementary_gates"] = ["H_1", "H_2", "CNot_1_2"] model_options = Dict{Symbol, Any}(:optimizer_log => false) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 0.0, atol = tol_0) # Testing approximate decomposition for minimizing CNOT gates params["elementary_gates"] = ["H_1", "H_2", "CNot_1_2", "Identity"] params["objective"] = "minimize_cnot" model_options = Dict{Symbol, Any}(:optimizer_log => false) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 1.0, atol = tol_0) # Testing approximate decomposition for case when slack_var-s are fixed based on U_var-s params = Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 7, "elementary_gates" => ["CV_1_2", "CV_2_3", "CV_1_3", "CVdagger_1_2", "CVdagger_2_3", "CVdagger_1_3", "CNot_1_2", "CNot_3_2", "CNot_2_3", "CNot_1_3", "Identity"], "target_gate" => QCO.CSwapGate(), #also Fredkin "objective" => "minimize_depth", "decomposition_type" => "approximate" ) model_options = Dict{Symbol, Any}(:optimizer_log => false, :relax_integrality => true, :fix_unitary_variables => true) result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 0.38281250, atol = tol_0) end @testset "QC_model Tests: Global phase constraints" begin #Real elementary gates - Target is real but with a minus sign params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["H_1", "H_2", "CNot_1_2", "Identity"], "target_gate" => - QCO.CNotRevGate(), "objective" => "minimize_depth", ) model_options = Dict{Symbol, Any}(:optimizer_log => false) # Without global phase constraints params["decomposition_type"] = "exact_optimal" result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.INFEASIBLE @test result_qc["primal_status"] == MOI.NO_SOLUTION # With global phase constraints params["decomposition_type"] = "optimal_global_phase" result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 5.0, atol = tol_0) # Real elementary gates - Target is complex, but real in a global phase sence params["target_gate"] = exp(im*pi*0.3) * QCO.CNotRevGate() # Without global phase constraints # This is an infeasible decomposition: all elementary gates have zero imaginary parts and # target is not real for exact decomposition or not real up to a global phase for # `optimal_global_phase` decomposition. # With global phase constraints params["decomposition_type"] = "optimal_global_phase" result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 5.0, atol = tol_0) # Using complex-valued elementary gates params["elementary_gates"] = ["T_1", "H_1", "H_2", "CNot_1_2", "Identity"] # Without global phase constraints params["decomposition_type"] = "exact_optimal" result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.INFEASIBLE @test result_qc["primal_status"] == MOI.NO_SOLUTION # Using global phase constraints params["decomposition_type"] = "optimal_global_phase" result_qc = QCO.run_QCModel(params, MIP_SOLVER; options = model_options) @test result_qc["termination_status"] == MOI.OPTIMAL @test result_qc["primal_status"] == MOI.FEASIBLE_POINT @test isapprox(result_qc["objective"], 5.0, atol = tol_0) end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
1175
@testset "Relaxation tests: relaxation_bilinear" begin QCO.silence() m = JuMP.Model(MIP_SOLVER) LB = [-1, -2.5, 0, -3, 0] UB = [2.5, 0, 1, 3.2, 1] JuMP.@variable(m, LB[i] <= x[i=1:5] <= UB[i]) JuMP.@variable(m, z[1:6]) QCO.relaxation_bilinear(m, z[1], x[1], x[2]) QCO.relaxation_bilinear(m, z[2], x[1], x[4]) QCO.relaxation_bilinear(m, z[3], x[2], x[3]) QCO.relaxation_bilinear(m, z[4], x[3], x[4]) QCO.relaxation_bilinear(m, z[5], x[3], x[5]) QCO.relaxation_bilinear(m, z[6], x[4], x[5]) JuMP.@constraint(m, sum(x) >= 3.3) JuMP.@constraint(m, sum(x) <= 3.8) coefficients = [0.4852, -0.7795, 0.1788, 0.7778, 0.3418, -0.3407] JuMP.set_objective_function(m, sum(coefficients[i] * z[i] for i=1:length(z))) obj_vals = Vector{Float64}() for obj_sense in [MOI.MIN_SENSE, MOI.MAX_SENSE] JuMP.set_objective_sense(m, obj_sense) JuMP.optimize!(m) @test JuMP.termination_status(m) == MOI.OPTIMAL push!(obj_vals, JuMP.objective_value(m)) end @test obj_vals[1] <= -9.922644 # global optimum value @test obj_vals[2] >= 4.908516 # global optimum value end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
598
using JuMP using Test import QuantumCircuitOpt as QCO import Memento import LinearAlgebra as LA import HiGHS # Suppress warnings during testing QCO.logger_config!("error") const HIGHS = MOI.OptimizerWithAttributes( HiGHS.Optimizer, "presolve" => "on", "log_to_console" => false, ) const MIP_SOLVER = HIGHS tol_0 = 1E-6 @testset "QuantumCircuitOpt" begin include("utility_tests.jl") include("chull_tests.jl") include("gates_tests.jl") include("types_tests.jl") include("data_tests.jl") include("qc_model_tests.jl") include("relaxations_tests.jl") end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
189
@testset "Tests: types" begin gate = QCO.GateData("H_1", 2) @test gate.isreal gate = QCO.GateData("S_3", 3) @test !gate.isreal # Add more tests for U3 and R gates. end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
code
8490
# Unit tests for functions in utility.jl M_c = [complex(1,0) complex(0,-1) complex(-0.5,0.5) complex(0,0)] M_r = [1.0 0.0 0.0 -1.0 0.0 1.0 1.0 0.0 -0.5 0.5 0.0 0.0 -0.5 -0.5 0.0 0.0] # Variable bounds to test auxiliary_variable_bounds function l = [-2, -1, 0, 2] u = [-1, 2, 3, 2] @testset "Tests: complex to real matrix function" begin test_M_r = QCO.complex_to_real_gate(M_c) @test test_M_r == M_r end @testset "Tests: real to complex matrix function" begin test_M_c = QCO.real_to_complex_gate(M_r) @test test_M_c == M_c end @testset "Tests: auxiliary variable product bounds" begin m = Model() @variable(m, l[i] <= x[i=1:length(l)] <= u[i]) # x1*x2 @test QCO.auxiliary_variable_bounds([x[1], x[2]]) == (-4, 2) # x1*x3 @test QCO.auxiliary_variable_bounds([x[1], x[3]]) == (-6, 0) # x1*x4 @test QCO.auxiliary_variable_bounds([x[1], x[4]]) == (-4, -2) # x4*x4 @test QCO.auxiliary_variable_bounds([x[4], x[4]]) == (4, 4) # x1*x2*x3 @test QCO.auxiliary_variable_bounds([x[1], x[2], x[3]]) == (-12, 6) @test QCO.auxiliary_variable_bounds([x[3], x[1], x[2]]) == (-12, 6) @test QCO.auxiliary_variable_bounds([x[2], x[1], x[3]]) == (-12, 6) # x1*x2*x3*x4 @test QCO.auxiliary_variable_bounds([x[1], x[2], x[3], x[4]]) == (-24, 12) @test QCO.auxiliary_variable_bounds([x[4], x[1], x[3], x[2]]) == (-24, 12) @test QCO.auxiliary_variable_bounds([x[4], x[3], x[2], x[1]]) == (-24, 12) end @testset "Tests: unique_matrices and unique_idx" begin D = zeros(3,3,4) D[:,:,1] = Matrix(LA.I,3,3) D[:,:,2] = rand(3,3) D[:,:,3] = Matrix(LA.I,3,3) D[:,:,4] = rand(3,3) D[1,1,3] = 1 + 2*tol_0 D[3,3,3] = 1 - tol_0 D[1,2,3] = 0 - tol_0 D[1,3,3] = 0 + tol_0 D[isapprox.(D, 0, atol=tol_0)] .= 0 D_unique, D_unique_idx = QCO.unique_matrices(D) @test D_unique_idx == [1,2,4] @test D_unique[:,:,1] == D[:,:,1] @test D_unique[:,:,2] == D[:,:,2] @test D_unique[:,:,3] == D[:,:,4] end @testset "Tests: commuting matrices" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 5, "elementary_gates" => ["H_1", "H_2", "CNot_1_2", "Identity"], "target_gate" => QCO.CNotRevGate() ) data = QCO.get_data(params) C2,C2_Identity = QCO.get_commutative_gate_pairs(data["gates_dict"], data["decomposition_type"]) @test length(C2) == 4 @test length(C2_Identity) == 0 @test isapprox(data["gates_real"][:,:,C2[1][1]] * data["gates_real"][:,:,C2[1][2]], data["gates_real"][:,:,C2[1][2]] * data["gates_real"][:,:,C2[1][1]], atol=tol_0) # With global phase equivalence params["decomposition_type"] = "optimal_global_phase" params["elementary_gates"] = ["Y_1", "H_1", "H_2", "CNot_1_2", "Identity"] data = QCO.get_data(params) C2,C2_Identity = QCO.get_commutative_gate_pairs(data["gates_dict"], data["decomposition_type"]) @test length(C2) == 7 end @testset "Tests: kron_single_qubit_gate" begin I1 = QCO.kron_single_qubit_gate(4, QCO.IGate(1), "q1") I2 = QCO.kron_single_qubit_gate(4, QCO.IGate(1), "q2") I3 = QCO.kron_single_qubit_gate(4, QCO.IGate(1), "q3") I4 = QCO.kron_single_qubit_gate(4, QCO.IGate(1), "q4") @test I1 == I2 == I3 == I4 end @testset "Tests: get_redundant_gate_product_pairs" begin params = Dict{String, Any}( "num_qubits" => 3, "maximum_depth" => 15, "elementary_gates" => ["T_1", "T_2", "T_3", "H_3", "CNot_1_2", "CNot_1_3", "CNot_2_3", "Tdagger_2", "Tdagger_3", "Identity"], "target_gate" => QCO.ToffoliGate() ) data = QCO.get_data(params) redundant_pairs = QCO.get_redundant_gate_product_pairs(data["gates_dict"], data["decomposition_type"]) @test length(redundant_pairs) == 0 # With global phase equivalence params["decomposition_type"] = "optimal_global_phase" data = QCO.get_data(params) redundant_pairs = QCO.get_redundant_gate_product_pairs(data["gates_dict"], data["decomposition_type"]) @test length(redundant_pairs) == 0 end @testset "Tests: get_idempotent_gates" begin params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 14, "elementary_gates" => ["Y_1", "Y_2", "Z_1", "Z_2", "T_2", "Tdagger_1", "Sdagger_1", "SX_1", "SXdagger_2", "CNot_2_1", "CNot_1_2", "Identity"], "target_gate" => -QCO.HCoinGate()) data = QCO.get_data(params) idempotent_gates = QCO.get_idempotent_gates(data["gates_dict"], data["decomposition_type"]) @test idempotent_gates[1] == 6 @test idempotent_gates[2] == 7 @test "Tdagger_1" in data["gates_dict"]["$(idempotent_gates[1])"]["type"] @test "Sdagger_1" in data["gates_dict"]["$(idempotent_gates[2])"]["type"] @test "Z_1" in data["gates_dict"]["3"]["type"] M1 = data["gates_dict"]["$(idempotent_gates[1])"]["matrix"] M2 = data["gates_dict"]["$(idempotent_gates[2])"]["matrix"] @test isapprox(M1^2, data["gates_dict"]["7"]["matrix"], atol = tol_0) @test isapprox(M2^2, data["gates_dict"]["3"]["matrix"], atol = tol_0) # With global phase equivalence params["decomposition_type"] = "optimal_global_phase" data = QCO.get_data(params) idempotent_gates = QCO.get_idempotent_gates(data["gates_dict"], data["decomposition_type"]) @test length(idempotent_gates) == 2 end @testset "Tests: _parse_gate_string" begin v1 = QCO._parse_gate_string("RX_1", qubits=true) @test v1[1] == 1 v2 = QCO._parse_gate_string("CU3_51", qubits=true) @test v2[1] == 51 v3 = QCO._parse_gate_string("CRZ_9_1", qubits=true) @test length(v3) == 2 @test v3[1] == 9 @test v3[2] == 1 end @testset "Tests: is_gate_real" begin M_test = [0 1E-7im -1E-7im; 1E-10im 0 0; -1E-8im -1E-10im 0] @test QCO.is_gate_real(M_test) M_test = [0 1E-7im -1E-7im; 1E-10im 0 0; -1E-8im -1E-5im 0] @test !QCO.is_gate_real(M_test) end @testset "Tests: _get_constraint_slope_intercept" begin v1 = (0.0, 0.0) v2 = (1.0, 1.0) m,c = QCO._get_constraint_slope_intercept(v1, v2) @test m == 1 @test c == 0 m,c = QCO._get_constraint_slope_intercept(v2, v1) @test m == 1 @test c == 0 v2 = (0, 0.5) m,c = QCO._get_constraint_slope_intercept(v1, v2) @test !isfinite(m) @test !isfinite(c) v1 = (1.0, 2.0) v2 = (-3.0, 4.0) m,c = QCO._get_constraint_slope_intercept(v1, v2) @test m == -0.5 @test c == 2.5 QCO._get_constraint_slope_intercept(v1, v1) end @testset "Tests: U_var fixed indices" begin num_qubits = 2 maximum_depth = 3 # Input gates H1 = QCO.complex_to_real_gate(QCO.get_unitary("H_1", num_qubits)) CNot_1_2 = QCO.complex_to_real_gate(QCO.get_unitary("CNot_1_2", num_qubits)) Id = QCO.complex_to_real_gate(QCO.IGate(num_qubits)) # Assuming only H1 in elementary gates n_r = size(H1)[1] gates = zeros(n_r,n_r,1) gates[:,:,1] = H1 U_fixed_idx = QCO._get_unitary_variables_fixed_indices(gates, maximum_depth) # Depth = 1 for idx in keys(U_fixed_idx[1]) @test isapprox(U_fixed_idx[1][idx]["value"], gates[idx[1],idx[2],1], atol = tol_0) end # Depth = 2 (product of H1 is an identity matrix) @test length(keys(U_fixed_idx[2])) == n_r * n_r for idx in keys(U_fixed_idx[2]) @test isapprox(U_fixed_idx[2][idx]["value"], Id[idx[1], idx[2]], atol = tol_0) end # Assuming H1 and CNot_1_2 in elementary gates gates = zeros(n_r,n_r,2) gates[:,:,1] = H1 gates[:,:,2] = CNot_1_2 U_fixed_idx = QCO._get_unitary_variables_fixed_indices(gates, maximum_depth) # Depth = 1 sum_mat = abs.(gates[:,:,1]) + abs.(gates[:,:,2]) for idx in keys(U_fixed_idx[1]) if isapprox(U_fixed_idx[1][idx]["value"], 0, atol = tol_0) @test isapprox(U_fixed_idx[1][idx]["value"], sum_mat[idx[1], idx[2]], atol = tol_0) end end # Depth = 2 prod_mat_1 = gates[:,:,1] * gates[:,:,2] prod_mat_2 = gates[:,:,2] * gates[:,:,1] for idx in keys(U_fixed_idx[2]) if isapprox(U_fixed_idx[2][idx]["value"], 0, atol = tol_0) @test isapprox(U_fixed_idx[2][idx]["value"], prod_mat_1[idx[1], idx[2]], atol = tol_0) @test isapprox(U_fixed_idx[2][idx]["value"], prod_mat_2[idx[1], idx[2]], atol = tol_0) end end end
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
docs
13841
QuantumCircuitOpt.jl Change Log =============================== ### v0.5.9 - Catch error in `data.jl` if `set_cnot_lower_bound` > `maximum_depth` - Feasibility switching warning moved to the correct condition in objective.jl - Renamed function `get_full_sized_gate` -> `get_unitary` - Added 3-qubit `QFT3Gate` to gates.jl - Added `QFT3` circuit using controlled-phase gates in examples - Updated docs and unit tests to reflect above changes ### v0.5.8 - Readme update for dark/light theme logo display - Fixed Docs compile issue - Updated arXiv link for SC22 paper ### v0.5.7 - Clean up in log.jl to validate circuit decomposition upto global phase - Added `parametrized_hermitian_gates` in examples ### v0.5.6 - Video link to SC22 presentation added ### v0.5.5 - `optimal_global_phase` now recognizes commuting elementary gate pairs that commute, are redundant and idempotent up to a global phase - Docs updated with the SC22 (IEEE) paper link - Added `isapprox_global_phase` utility to evaluate equivalences of any two complex gates up to a global phase - Updated docs and unit tests to reflect above changes - Removed compatability on Pkg ### v0.5.4 - Added a generalized function to obtain controlled gates (`controlled_gate()`) in any number of qubits - Cleaned-up controlled gates in `src/gates.jl` - Updated docs to reflect above changes ### v0.5.3 - Minor update: SC22 publication added in docs - README banner update ### v0.5.2 - Added dependency on `Pkg` package for logging purposes - Renamed gates in `src/examples` folder ### v0.5.1 - New feature: Added support for compiling optimal circuits upto a global phase using linear constraints (`optimal_global_phase`) - Deactivated determinant feasiblity check for global phase model - Bug fix in evaluation of kron-symboled elementary gates (#63) - `get_full_sized_gate` function now supports gates with kronecker operations - Updated docs and unit tests to reflect above changes ### v0.5.0 - Minor: Fixed result `primal_status` issue in `log.jl` - Added helper functions for obtaining fixed indices of `U_var` unitary variables to zeros or constant values. Dropped linearization constraints for fixed `U_var` variables - Dropped support for `unit_magnitude_constraints` - Reformulated quadratic objective function of `slack_var` variables into a linear outer-approximation - increases code coverage due to MILP reformulation - Fixed `slack_var` based on fixed `U_var` variables - Minor updates in error messages for kron symboled gates - Changed Cbc test dependency to HiGHS (MIP) solver - Updated docs and unit tests to reflect above changes ### v0.4.1 - Added support for returning exact feasible decomposition (without optimality certificate) using `exact_feasible` - Added support for unitary constraints using binary linearizations (speeds up feasiblity problems) - Added `W_using_HSTCnot` in examples - Added `CNOT_using_GR` in examples (for Rydberg atom array-based simulators) - Added support for `CSGate`, `CSdaggerGate`, `CTGate`, `CTdaggerGate` and `SSwapGate` (sqrt(`SwapGate`)) - Dropped support for `CZRevGate` as it is invariant to qubit flip - Updated README and docs with the Youtube link for the JuliaCon's presentation - Updated `decomposition_type` to `exact_optimal` from `exact` - Updated docs and unit tests to reflect above changes ### v0.4.0 - Added support for two angle param gates througout data and log - Added support for Rotation gate (`RGate`) with two angle params - Added support for multi-qubit gates with angle params - Added support for Global R gate (`GRGate`) with two angle params - Clean-up in `data.jl` and `utility.jl` to handle multi-qubit gates - Decomposition of Pauli-X using global rotation added in 2-qubit examples - Updated planar-hull cuts evaluation to account for repeated sets of extreme points (improved run times) - Clean-up of `constraint_convex_hull_complex_gates` - Updated docs and unit tests to reflect above changes ### v0.3.6 - DOI link for publication added - Added support for JuMP v1.0 ### v0.3.5 - Dropped support for redundant `constraint_complex_to_real_symmetry_compact` function - Added unit magnitude (outer-approximation) constraints for unitary variables - Updated docs and unit tests to reflect above changes - Updated README.md and docs with the Youtube link for the SC21 presentation - Added support for JuMP v0.22+ - Dropped explicit support for MathOptInterface ### v0.3.4 - Updated error messages in `src/data.jl` to better represent one and two qubit gates - More determinant-based tests (to handle complex det values) to detect infeasibility - Updated unit tests to cover CNOT gate bound constraints ### v0.3.3 - Added determinant-based test to detect infeasibility in the pre-processing step - Added support for 3-qubit RCCXGate (relative Toffoli) - Added support for 3-qubit MargolusGate (simplified Toffoli) - #46 - Added support for 3-qubit CiSwapGate (controlled iSwap) - Updated docs and unit tests to reflect above changes ### v0.3.2 - Moved all the model options (including valid constraints) from `qc_model.jl` to `types.jl` into `QCModelOptions`, a struct form - Streamlined default options for `QCModelOptions` - Moved `relax_integrality`, `time_limit`, `objective_slack_penalty` and `optimizer_log` options from `data.jl` to `QCModelOptions` - Removed `identify_real_gates`, `optimizer` and `optimizer_presolve` options from `params` and updated `solvers.jl` - Default recognition of real elementary and target gates, and implements a compact MIP - Updated docs and unit tests to reflect above changes ### v0.3.1 - Added decomposition of the QFT2 gate using H, T and CNOT gates to `2qubits_gates.jl` - Added CITATION.bib - Added QCOpt's framework to quick start guide in docs - Minor updates in README ### v0.3.0 - Enabling support for convex hull evaluation (Graham's algorithm) within QCOpt (`QCO.convex_hull()`) - Dropping dependency on QHull.jl - Added decomposition of quantum full-adder, double-toffoli and double-peres gates to `4qubit_gates.jl` - Added decomposition of toffoli gate using controlled gates and miller gate to `3qubit_gates.jl` - Added decomposition of QFT2 gates using R gates to `2qubits_gates.jl` - Issue #37 fixed and more meaningful messages for input gate parsing - Updated unit tests to cover `convex_hull` function - Bug fix in `_get_cnot_idx` to account for gates with kronecker symbols - Inculded `CXGate` for evaluation of `_get_cnot_idx` in `data.jl` - Separate files added in the `examples` folder for SC21 paper's results - Options to add lower and upper bounds on number of CNOT gates in user-defined `params` - User-specified "depth" changed to "maximum_depth" - Updated docs and unit tests to reflect above changes ### v0.2.5 - Major updates in input gate convention for two qubit gates. For example, `CNot_12` becomes `CNot_1_2`. This update now makes the package flexible to be able to compute on any number of qubit circuits. `CNot_2_10` is a valid input for a 10 qubit circuit - Major clean up in `data.jl` including generalized parsing in `get_full_sized_gate` and `get_full_sized_kron_gate` functions - Clean up of `log.jl` to make it generic and consistent with above changes - Enabling support for convex hull-based cuts on complex variables at every depth (improved run times in CPLEX, default = turned off) - Added `constraint_convex_hull_complex_gates` function in support with depndency of QHull.jl - Added `round_real_value` function and cleaned up `round_complex_values` in `utility.jl` - Added toffoli-left block and toffoli-right block decompositions to `3qubit_gates.jl` - Update `is_multi_qubit_gate` function to make it generic to any gate type ### v0.2.4 - Enabling support for 2-qubit Sycamore gate, native to Google's quantum processor - Citation for the SC21 paper (accepted) - Clean-up in real to complex matrix conversion and vice-versa in `src/utility.jl` - Better rounding in `relaxation_bilinear` function - Updated docs with more function references to reflect the above changes ### v0.2.3 - Enabling support for Identity-gate symmetry-breaking constraints - improved run times - Enabling support for `identify_real_gates` which applies a compact MIP formulation (turned-off default) - Updated unit tests and docs to reflect the above changes - Minor bug fix in `is_multi_qubit_gate` function to handle gates with kron symbols ### v0.2.2 - Bug fix in `is_multi_qubit_gate` function in `src/log.jl` to handle any 2 qubit gates - Decomposition for 4-qubit CNot_41 added in `examples/4qubit_gates.jl` - Moved involutory gate evaluation from `data.jl` to a `get_involutory_gates` function in `utility.jl` (to be consistent with other similar functions). `constraint_involutory_gates` function is updated accordingly to reflect these changes - Meaningful error messages in `data.jl` for input gates with missing continuous angle parameters - Updated unit tests on involutory gates ### v0.2.1 - Framework updates which support upto *nine* qubit circuit decompositions - Generalizing and condensing `kron_single_qubit_gate` function to handle any number of integer-valued qubits in `src/utility.jl` - Generalizing and condensing `kron_two_qubit_gate` function to handle any number of integer-valued qubits without explicit enumeration in `src/utility.jl`. Also, computes slightly faster with lesser memory on larger qubits than the previous version - Docs updates for missing inputs options - Enabling support for PhaseGate with discretizations in `src/data.jl` - Enabling support for DCXGate in `src/data.jl` - Minor clean ups and removal of redundant functions in `src/data.jl` ### v0.2.0 - MAJOR framework updates which support gates upto *five* qubit gates. Framework is now flexible to generalize it to even larger qubit circuits, by updating functions `kron_single_qubit_gate` and `kron_two_qubit_gate` - Bug fixes and major re-factoring of `src/data.jl` to support any permutation of gates on qubits - Enabling Controlled-R (CRX, CRY, CRZ) and Controlled-U3 (CU3) gates - Adding functions to data.jl that are the equivalent of the single-qubit ones (e.g. get_all_CR_gates) - Enabling this functionality in the log.jl - Kron symbol updated from `⊗` to `x` - Enabling functionality to take elementary gates with kronecker symbols over all qubits. For example, `"H_1xCNot_23xI_4xI_5"`, `H_1xH_2xT_3`, `I_1xSX_2xTdagger_3`. This functionality only supports one and 2 qubit gates without angle parameters (excluded controlled R and U3 gates) - Adding various new 2 qubit gates (including controlled R and U3) in `src/gates.jl` - Expanding the elementary gates set with cleaner and flexible framework for any `num_qubits` in functions, `get_full_sized_gate` and `get_full_sized_kron_gate` - Adding new functions: `_parse_gates_with_kron_symbol`, `kron_two_qubit_gate` - Updating Docs and adding new unit tests to reflect above changes ### v0.1.9 - Updated toffoli input circuit to make it feasible for the commuting gate constraints - Added support for 3-qubit Toffoli using Rotation gates, Fredkin gate and `CNot_13` (in `src/examples`) - Infeasibility bug fix in commuting gate constraints (for `T_2` expressed as `U3_2(0,0,π/4)`) ### v0.1.8 - Added support for specificity of qubits in U3 and Rotation (RX, RY, RZ) gates (Major change). Example: U3_1, RX_2, RZ_3, etc - Added support for kronecker product gates (`X_1⊗X_2`, `S_1⊗S_2`, etc) and bug fix to handle this change in `get_compressed_decomposition` in `src/log.jl` - Added `is_multi_qubit_gate` function in `src/log.jl` - Docs and tests updated to reflect above changes ### v0.1.7 - Added support for a few controlled versions of V gates in 2 & 3 qubits - Added support for Grover's diffusion operator - Naming convention updated from NameQubit to Name_Qubit for 1 qubit gates (consistent with 2 qubit gates) - `cnot_ij` updated to `CNot_ij` to be consistent with naming convention in `src/gates.jl` - Docs and tests updated to reflect above changes ### v0.1.6 - Added support for obtaining idempotent matrices and adding corresponding valid constraints - Updated `all_valid_constraints` from `Bool` to values in `[-1,0,1]` - `qc_model.jl` clean-up - Updated unit tests to reflect above changes ### v0.1.5 - Added support for pair-wise commuting products with Identity, (AB=BA=I) - Bug fix to remove redundant pairs in `get_commutative_gate_pairs` when corresponding product is an Identity gate - Added support for eliminating redundant pairs whose product matches an input elementary gate (`get_redundant_gate_product_pairs` in utility) - improved run times - Added support to turn on/off all valid constraints (`all_valid_constraints`) - Updated docs to reflect the improved run times ### v0.1.4 - Optimizer time limit option added for early termination of solvers - `log.jl` updates to support optimizer hitting time limits - Revamping of commuting gate valid constraints (dropped support for triplets) - Revamping data.jl to fix default values of user inputs - Updated unit tests for the above changes ### v0.1.3 - Update to minimize_depth from maximizing IGate to minimizing non-IGates, which also improved run times. - Clean-up and update to unit tests to reflect the above change - Fixed Gurobi solver bug in `examples/solver.jl` - Involutory gate constraints added and corresponding unit tests ### v0.1.2 - Update to warm start with an initial circuit (without U3 and R gates) - Update to unit tests to reflect the above changes - Update to docs to reflect the above changes - Bug fixes in error/warn messages ### v0.1.1 - docs/make.jl updates for sidebar name - Updated docs logo to handle dark theme ### v0.1.0 - Initial function-based working implementation - Support for 2- and 3-qubit decompositions - Added preliminary documentation - Added preliminary unit tests - Github Actions set-up
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
docs
7504
<h1 align="center" margin=0px> <!-- <img src="https://github.com/harshangrjn/QuantumCircuitOpt.jl/blob/master/docs/src/assets/logo_header_light.png#gh-light-mode-only" width=90%> <img src="https://github.com/harshangrjn/QuantumCircuitOpt.jl/blob/master/docs/src/assets/logo_header_dark.png#gh-dark-mode-only" width=90%> <br> --> <a href="https://github.com#gh-light-mode-only"> <img src="https://github.com/harshangrjn/QuantumCircuitOpt.jl/blob/master/docs/src/assets/logo_header_light.png#gh-light-mode-only" width=90%> </a> <a href="https://github.com#gh-dark-mode-only"> <img src="https://github.com/harshangrjn/QuantumCircuitOpt.jl/blob/master/docs/src/assets/logo_header_dark.png#gh-dark-mode-only" width=90%> </a> <br> A Julia Package for Optimal Quantum Circuit Design </h1> Status: [![CI](https://github.com/harshangrjn/QuantumCircuitOpt.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/harshangrjn/QuantumCircuitOpt.jl/actions/workflows/ci.yml) [![codecov](https://codecov.io/gh/harshangrjn/QuantumCircuitOpt.jl/branch/master/graph/badge.svg?token=KGJWIV6QF4)](https://codecov.io/gh/harshangrjn/QuantumCircuitOpt.jl) [![version](https://juliahub.com/docs/QuantumCircuitOpt/version.svg)](https://juliahub.com/ui/Packages/QuantumCircuitOpt/dwSy1) <!-- Stable version: [![Documentation](https://github.com/harshangrjn/QuantumCircuitOpt.jl/actions/workflows/documentation.yml/badge.svg)](https://harshangrjn.github.io/QuantumCircuitOpt.jl/stable/) --> Dev version: [![Documentation](https://github.com/harshangrjn/QuantumCircuitOpt.jl/actions/workflows/documentation.yml/badge.svg)](https://harshangrjn.github.io/QuantumCircuitOpt.jl/dev/) <!-- # QuantumCircuitOpt.jl --> **QuantumCircuitOpt** is a Julia package which implements discrete optimization-based methods for provably optimal synthesis of an architecture for quantum circuits. While programming quantum computers, a primary goal is to build useful and less-noisy quantum circuits from the basic building blocks, also termed as elementary gates which arise due to hardware constraints. Thus, given a desired quantum computation, as a target gate, and a set of elemental one- and two-qubit gates, this package provides a _provably optimal, exact_ (up to global phase and machine precision) or an approximate decomposition with minimum number of elemental gates and CNOT gates. Now, this package also supports multi-qubit gates in the elementary gates set, such as the [global rotation](https://harshangrjn.github.io/QuantumCircuitOpt.jl/dev/multi_qubit_gates/#GRGate) gate. _Note that QuantumCircuitOpt currently supports only decompositions of circuits up to ten qubits_. Overall, QuantumCircuitOpt can be a useful tool for researchers and developers working on quantum algorithms or quantum computing applications, as it can help to reduce the resource requirements of quantum computations, making them more practical and efficient. ## Installation QuantumCircuitOpt is a registered package and can be installed by entering the following in the Julia REPL-mode: ```julia import Pkg Pkg.add("QuantumCircuitOpt") ``` ## Usage - Clone the repository. - Open a terminal in the repo folder and run `julia --project=.`. - Hit `]` to open the project environment and run `test` to run unit tests. If you see an error because of missing packages, run `resolve`. On how to use this package, check the Documentation's [quick start guide](https://harshangrjn.github.io/QuantumCircuitOpt.jl/dev/quickguide/#Sample-circuit-decomposition) and the [examples](https://github.com/harshangrjn/QuantumCircuitOpt.jl/tree/master/examples) folder for several important circuit decompositions. ## Video Links For more technical details about the package, check out these video links: - November 2022: Presentation [link](https://vimeo.com/771366943/01810daa4e) from the [Third Quantum Computing Software Workshop](https://sc22.supercomputing.org/session/?sess=sess423), held in conjunction with the International Conference on Super Computing ([SC22](https://sc22.supercomputing.org)). - July 2022: Presentation [link](https://www.youtube.com/watch?v=OeONXwD4JJY) from the [JuliaCon 2022](https://pretalx.com/juliacon-2022/talk/KJTGC3/) conference. - November 2021: Presentation [link](https://www.youtube.com/watch?v=sf1HJW5Vmio) from the [Second Quantum Computing Software Workshop](https://sc21.supercomputing.org/session/?sess=sess345), held in conjunction with the International Conference on Super Computing ([SC21](https://sc21.supercomputing.org)). ## Sample Circuit Synthesis Here is a sample usage of QuantumCircuitOpt to optimally decompose a 2-qubit controlled-Z gate ([CZGate](https://harshangrjn.github.io/QuantumCircuitOpt.jl/dev/2_qubit_gates/#CZGate)) using the entangling [CNOT](https://harshangrjn.github.io/QuantumCircuitOpt.jl/dev/2_qubit_gates/#CNotGate) gate and an one-qubit universal rotation gate ([U3Gate](https://harshangrjn.github.io/QuantumCircuitOpt.jl/dev/1_qubit_gates/#U3Gate)) with three discretized Euler angles (θ,ϕ,λ): ```julia import QuantumCircuitOpt as QCOpt using JuMP using Gurobi # Target: CZGate function target_gate() return Array{Complex{Float64},2}([1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 -1]) end params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 4, "elementary_gates" => ["U3_1", "U3_2", "CNot_1_2", "Identity"], "target_gate" => target_gate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -π:π/2:π, "U3_ϕ_discretization" => -π:π/2:π, "U3_λ_discretization" => -π:π/2:π, ) qcm_optimizer = JuMP.optimizer_with_attributes(Gurobi.Optimizer, "presolve" => 1) QCOpt.run_QCModel(params, qcm_optimizer) ``` If you prefer to decompose a target gate of your choice, update the `target_gate()` function and the set of `elementary_gates` accordingly in the above sample code. ## Bug reports and Contributing Please report any issues via the Github **[issue tracker](https://github.com/harshangrjn/QuantumCircuitOpt.jl/issues)**. All types of issues are welcome and encouraged; this includes bug reports, documentation typos, feature requests, etc. QuantumCircuitOpt is being actively developed and suggestions or other forms of contributions are encouraged. ## Acknowledgement This work was supported by Los Alamos National Laboratory's LDRD Early Career Research award. The primary developer of this package is [Harsha Nagarajan](http://harshanagarajan.com) ([@harshangrjn](https://github.com/harshangrjn)). ## Citing QuantumCircuitOpt If you find QuantumCircuitOpt useful in your work, we request you to cite the following paper ([IEEE link](https://doi.org/10.1109/QCS54837.2021.00010), [arXiv link](https://arxiv.org/abs/2111.11674)): ```bibtex @inproceedings{QCOpt_SC2021, title={{QuantumCircuitOpt}: An Open-source Framework for Provably Optimal Quantum Circuit Design}, author={Nagarajan, Harsha and Lockwood, Owen and Coffrin, Carleton}, booktitle={SC21: The International Conference for High Performance Computing, Networking, Storage, and Analysis}, series={Second Workshop on Quantum Computing Software}, pages={55--63}, year={2021}, doi={10.1109/QCS54837.2021.00010}, organization={IEEE Computer Society} } ``` Another publication which explores the potential of non-linear programming formulations in QuantumCircuitOpt is the following: [IEEE link](https://doi.org/10.1109/QCS56647.2022.00009), [arXiv link](https://arxiv.org/abs/2310.18281).
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
docs
484
# Documentation for QuantumCircuitOpt ## Installation QuantumCircuitOpt's documentation is generated using [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl). To install it, run the following command in a Julia session: ```julia Pkg.add("Documenter") Pkg.add("DocumenterTools") ``` ## Building the Docs To preview the `html` output of the documents, run the following command: ```julia julia --color=yes make.jl ``` You can then view the documents in `build/index.html`.
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
docs
688
# Quantum Circuits Library: Single-qubit gates ```@meta CurrentModule = QuantumCircuitOpt ``` ## IGate ```@docs IGate ``` ## U3Gate ```@docs U3Gate ``` ## U2Gate ```@docs U2Gate ``` ## U1Gate ```@docs U1Gate ``` ## RGate ```@docs RGate ``` ## RXGate ```@docs RXGate ``` ## RYGate ```@docs RYGate ``` ## RZGate ```@docs RZGate ``` ## HGate ```@docs HGate ``` ## XGate ```@docs XGate ``` ## YGate ```@docs YGate ``` ## ZGate ```@docs ZGate ``` ## SGate ```@docs SGate ``` ## SdaggerGate ```@docs SdaggerGate ``` ## TGate ```@docs TGate ``` ## TdaggerGate ```@docs TdaggerGate ``` ## SXGate ```@docs SXGate ``` ## SXdaggerGate ```@docs SXdaggerGate ``` ## PhaseGate ```@docs PhaseGate ```
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
docs
1408
# Quantum Circuits Library: Two-qubit gates ```@meta CurrentModule = QuantumCircuitOpt ``` ## CNotGate ```@docs CNotGate ``` ## CNotRevGate ```@docs CNotRevGate ``` ## DCXGate ```@docs DCXGate ``` ## CXGate ```@docs CXGate ``` ## CXRevGate ```@docs CXRevGate ``` ## CYGate ```@docs CYGate ``` ## CYRevGate ```@docs CYRevGate ``` ## CZGate ```@docs CZGate ``` ## CHGate ```@docs CHGate ``` ## CHRevGate ```@docs CHRevGate ``` ## CVGate ```@docs CVGate ``` ## CVRevGate ```@docs CVRevGate ``` ## CVdaggerGate ```@docs CVdaggerGate ``` ## CVdaggerRevGate ```@docs CVdaggerRevGate ``` ## WGate ```@docs WGate ``` ## CRXGate ```@docs CRXGate ``` ## CRXRevGate ```@docs CRXRevGate ``` ## CRYGate ```@docs CRYGate ``` ## CRYRevGate ```@docs CRYRevGate ``` ## CRZGate ```@docs CRZGate ``` ## CRZRevGate ```@docs CRZRevGate ``` ## CSGate ```@docs CSGate ``` ## CSdaggerGate ```@docs CSdaggerGate ``` ## CTGate ```@docs CTGate ``` ## CTdaggerGate ```@docs CTdaggerGate ``` ## CU3Gate ```@docs CU3Gate ``` ## CU3RevGate ```@docs CU3RevGate ``` ## SwapGate ```@docs SwapGate ``` ## SSwapGate ```@docs SSwapGate ``` ## iSwapGate ```@docs iSwapGate ``` ## CSXGate ```@docs CSXGate ``` ## CSXRevGate ```@docs CSXRevGate ``` ## MGate ```@docs MGate ``` ## QFT2Gate ```@docs QFT2Gate ``` ## HCoinGate ```@docs HCoinGate ``` ## GroverDiffusionGate ```@docs GroverDiffusionGate ``` ## SycamoreGate ```@docs SycamoreGate ```
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
docs
353
# Quantum Circuits Library: Three-qubit gates ```@meta CurrentModule = QuantumCircuitOpt ``` ## ToffoliGate ```@docs ToffoliGate ``` ## CSwapGate ```@docs CSwapGate ``` ## CCZGate ```@docs CCZGate ``` ## PeresGate ```@docs PeresGate ``` ## RCCXGate ```@docs RCCXGate ``` ## MargolusGate ```@docs MargolusGate ``` ## CiSwapGate ```@docs CiSwapGate ```
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
docs
87
# QuantumCircuitOpt Function References ```@autodocs Modules = [QuantumCircuitOpt] ```
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
docs
4561
```@raw html <align="center"/> <img width="790px" class="display-light-only" src="assets/docs_header.png" alt="assets/docs_header.png"/> <img width="790px" class="display-dark-only" src="assets/docs_header_dark.png" alt="assets/docs_header.png"/> ``` # Documentation ```@meta CurrentModule = QuantumCircuitOpt ``` ## Overview **[QuantumCircuitOpt](https://github.com/harshangrjn/QuantumCircuitOpt.jl)** is a Julia package which implements discrete optimization-based methods for provably optimal synthesis of an architecture for Quantum circuits. While programming Quantum Computers, a primary goal is to build useful and less-noisy quantum circuits from the basic building blocks, also termed as elementary gates which arise due to hardware constraints. Thus, given a desired quantum computation, as a target gate, and a set of elemental one- and two-qubit gates, this package provides a _provably optimal, exact_ (up to global phase and machine precision) or an approximate decomposition with minimum number of elemental gates and CNOT gates. Now, this package also supports multi-qubit gates in the elementary gates set, such as the [global rotation](https://harshangrjn.github.io/QuantumCircuitOpt.jl/dev/multi_qubit_gates/#GRGate) gate which is native to trapped ion quantum computers. _Note that QuantumCircuitOpt currently supports only decompositions of circuits up to ten qubits_. Overall, QuantumCircuitOpt can be a useful tool for researchers and developers working on quantum algorithms or quantum computing applications, as it can help to reduce the resource requirements of quantum computations, making them more practical and efficient. ## Installation To use QuantumCircuitOpt, first [download and install](https://julialang.org/downloads/) Julia. Note that the current version of QuantumCircuitOpt is compatible with Julia 1.0 and later. The latest stable release of QuantumCircuitOpt can be installed by entering the following in the Julia REPL-mode: ```julia import Pkg Pkg.add("QuantumCircuitOpt") ``` At least one mixed-integer programming (MIP) solver is required for running QuantumCircuitOpt. The well-known [Gurobi](https://github.com/jump-dev/Gurobi.jl) or IBM's [CPLEX](https://github.com/jump-dev/CPLEX.jl) solver is highly recommended, as it is fast, scaleable and can be used to solve on fairly large-scale circuits. However, the open-source MIP solver [HiGHS](https://github.com/jump-dev/HiGHS.jl) is also compatible with QuantumCircuitOpt. Gurobi (or any other MIP solver) can be installed via the package manager with ```julia import Pkg Pkg.add("Gurobi") ``` ## Unit Tests To run the tests in the package, run the following command after installing the QuantumCircuitOpt package. ```julia import Pkg Pkg.test("QuantumCircuitOpt") ``` ## Acknowledgement This work was supported by Los Alamos National Laboratory's LDRD Early Career Research award. The primary developer of this package is [Harsha Nagarajan](http://harshanagarajan.com) ([@harshangrjn](https://github.com/harshangrjn)). ## Citing QuantumCircuitOpt If you find QuantumCircuitOpt useful in your work, we request you to cite the following publication ([IEEE link](https://doi.org/10.1109/QCS54837.2021.00010), [arXiv link](https://arxiv.org/abs/2111.11674)): ```bibtex @inproceedings{NagarajanLockwoodCoffrin2021, title={{QuantumCircuitOpt}: An Open-source Framework for Provably Optimal Quantum Circuit Design}, author={Nagarajan, Harsha and Lockwood, Owen and Coffrin, Carleton}, booktitle={SC21: The International Conference for High Performance Computing, Networking, Storage, and Analysis}, series={Second Workshop on Quantum Computing Software}, pages={55--63}, year={2021}, doi={10.1109/QCS54837.2021.00010}, organization={IEEE Computer Society} } ``` Another publication which explores the potential of non-linear programming formulations in the QuantumCircuitOpt package is the following ([IEEE link](https://doi.org/10.1109/QCS56647.2022.00009), [arXiv link](https://arxiv.org/abs/2310.18281)): ```bibtex @inproceedings{HendersonNagarajanCoffrin2022, title={Exploring Non-linear Programming Formulations in {QuantumCircuitOpt} for Optimal Circuit Design}, author={Henderson. R, Elena and Nagarajan, Harsha and Coffrin, Carleton}, booktitle={SC22: The International Conference for High Performance Computing, Networking, Storage, and Analysis}, series={Third Workshop on Quantum Computing Software}, pages={36--42}, year={2022}, doi={10.1109/QCS56647.2022.00009}, organization={IEEE Computer Society} } ```
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
docs
124
# Quantum Circuits Library: Multi-qubit gates ```@meta CurrentModule = QuantumCircuitOpt ``` ## GRGate ```@docs GRGate ```
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
docs
16285
# Quick Start Guide ## Framework Building on the recent success of [Julia](https://julialang.org), [JuMP](https://github.com/jump-dev/JuMP.jl) and mixed-integer programming (MIP) solvers, [QuantumCircuitOpt](https://github.com/harshangrjn/QuantumCircuitOpt.jl) (or QCOpt), is an open-source toolkit for optimal quantum circuit design. As illustrated in the figure below, QCOpt is written in Julia, a relatively new and fast dynamic programming language used for technical computing with support for extensible type system and meta-programming. At a high level, QCOpt provides an abstraction layer to achieve two primary goals: 1. To capture user-specified inputs, such as a desired quantum computation and the available hardware gates, and build a JuMP model of an MIP formulation, and 2. To extract, analyze and post-process the solution from the JuMP model to provide exact and approximate circuit decompositions, up to a global phase and machine precision. ```@raw html <align="center"/> <img width="550px" class="display-light-only" src="../assets/QCOpt_framework.png" alt="../assets/QCOpt_framework.png"/> <img width="550px" class="display-dark-only" src="../assets/QCOpt_framework_dark.png" alt="../assets/QCOpt_framework.png"/> ``` ## Video tutorials - November 2022: Presentation [link](https://vimeo.com/771366943/01810daa4e) from the [Third Quantum Computing Software Workshop](https://sc22.supercomputing.org/session/?sess=sess423), held in conjunction with the International Conference on Super Computing ([SC22](https://sc22.supercomputing.org)). This video will introduce the importance of nonlinear programming formulations for optimal quantum circuit design. More technical details can be found in this [paper](https://doi.org/10.1109/QCS56647.2022.00009). - July 2022: Presentation at the [JuliaCon 2022](https://pretalx.com/juliacon-2022/talk/KJTGC3/) introduces the package in greater depth and how to use it's various features. ```@raw html <align="center"/> <a href="https://www.youtube.com/watch?v=OeONXwD4JJY"> <img alt="Youtube-link" src="../assets/video_img_2.png" width=500" height="350"> </a> ``` - November 2021: Presentation from the [2nd Quantum Computing Software Workshop](https://sc21.supercomputing.org/session/?sess=sess345), held in conjunction with the International Conference on Super Computing ([SC21](https://sc21.supercomputing.org)), will introduce the technicalities underlying the package, which can also be found in this [paper](https://doi.org/10.1109/QCS54837.2021.00010). ```@raw html <align="center"/> <a href="https://www.youtube.com/watch?v=sf1HJW5Vmio"> <img alt="Youtube-link" src="../assets/video_img_1.png" width=500" height="350"> </a> ``` ## Getting started To get started, install [QCOpt](https://github.com/harshangrjn/QuantumCircuitOpt.jl) and [JuMP](https://github.com/jump-dev/JuMP.jl), a modeling language layer for optimization. QCOpt also needs a MIP solver such as [Gurobi](https://github.com/jump-dev/Gurobi.jl) or IBM's [CPLEX](https://github.com/jump-dev/CPLEX.jl). If you prefer an open-source MIP solver, install [HiGHS](https://github.com/jump-dev/HiGHS.jl) from the Julia package manager, though be warned that the run times of QCOpt can be substantially slower using any of the open-source MIP solvers. # User inputs QCOpt takes two types of user-defined input specifications. The first type of input contains all the necessary circuit specifications. This is given by a dictionary in Julia, which is a collection of key-value pairs, where every key is of the type `String`, which admits values of various types. Below is the list of allowable keys for the dictionary, given in column 1, and it's respective values with descriptions, given in column 2. This input dictionary is represented as `params` in all the [example](https://github.com/harshangrjn/QuantumCircuitOpt.jl/tree/master/examples) circuit decompositions. | Mandatory circuit specifications | Description | | -----------: | :----------- | | `num_qubits` | Number of qubits of the circuit (≥ 2). | | `maximum_depth` | Maximum allowable depth for decomposition of the circuit (≥ 2). | | `elementary_gates` | Vector of all one and two qubit elementary gates. The menagerie of quantum gates currently supported in QCOpt can be found in [gates.jl](https://github.com/harshangrjn/QuantumCircuitOpt.jl/blob/master/src/gates.jl). | | `target_gate` | Target unitary gate which you wish to decompose using the above-mentioned `elementary_gates`.| | `objective` | Choose one of the following: (a) `minimize_depth`, which minimizes the total number of one- and two-qubit gates. For this option, include `Identity` matrix in the above-mentioned `elementary_gates`, (b) `minimize_cnot`, which minimizes the number of CNOT gates in the decomposition. (default: `minimize_depth`) | | `decomposition_type` | Choose one of the following: (a) `exact_optimal`, which finds an exact, provably optimal, decomposition if it exists, (b) `exact_feasible`, which finds any feasible exact decomposition, but not necessarily an optimal one if it exists, (c) `optimal_global_phase`, which finds an optimal (best) circuit decomposition if it exists, up to a global phase (d) `approximate`, which finds an approximate decomposition if an exact one does not exist; otherwise it will return an exact decomposition (default: `exact_optimal`)| If the above-specified `elementary_gates` contain gates with continuous angle parameters, then the following mandarotry input angle discretizations have to be specified in addition to the above inputs: | Mandatory angle discretizations | Description | | -----------: | :----------- | | `RX_discretization` | Vector of discretization angles (in radians) for `RXGate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `RY_discretization` | Vector of discretization angles (in radians) for `RYGate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `RZ_discretization` | Vector of discretization angles (in radians) for `RZGate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `Phase_discretization` | Vector of discretization angles (in radians) for `PhaseGate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `U3_θ_discretization` | Vector of discretization angles (in radians) for θ parameter in `U3Gate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `U3_ϕ_discretization` | Vector of discretization angles (in radians) for ϕ parameter in `U3Gate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `U3_λ_discretization` | Vector of discretization angles (in radians) for λ parameter in `U3Gate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `CRX_discretization` | Vector of discretization angles (in radians) for `CRXGate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `CRY_discretization` | Vector of discretization angles (in radians) for `CRYGate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `CRZ_discretization` | Vector of discretization angles (in radians) for `CRZGate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `CU3_θ_discretization` | Vector of discretization angles (in radians) for θ parameter in `CU3Gate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `CU3_ϕ_discretization` | Vector of discretization angles (in radians) for ϕ parameter in `CU3Gate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| | `CU3_λ_discretization` | Vector of discretization angles (in radians) for λ parameter in `CU3Gate`. Input this only if this gate is part of the above-mentioned `elementary_gates`.| In addition, here is a list of *optional* circuit specifications, which can be added to the above set of inputs, to accelerate the performance of the QCOpt package: | Optional circuit specifications | Description | | -----------: | :----------- | | `initial_gate` | Intitial-condition gate to the decomposition (gate at 0th depth) (default: `Identity`). | | `set_cnot_lower_bound` | This option sets a lower bound on the total number of CNot or CX gates which an optimal decomposition can admit. | | `set_cnot_upper_bound` | This option sets an upper bound on the total number of CNot/CX gates which an optimal decomposition can admit. Note that both `set_cnot_lower_bound` and `set_cnot_upper_bound` can also be set to an identitcal value to fix the number of CNot/CX gates in the optimal decomposition.| | `input_circuit` | Input circuit representing an ensemble of elementary gates which decomposes the given target gate. This input circuit, which serves as a warm-start, can accelerate the MIP solver's search for the incumbent solution. (default: empty circuit). | # Optimization model inputs The second set of inputs for QCOpt contains all the optional specifications for the underlying optimization models. This is given by a dictionary in Julia, which is a collection of key-value pairs, where every key is of the type `Symbol`, which admits values of various types. Below is the list of allowable keys for this dictionary, given in column 1, and it's respective values with descriptions, given in column 2. This input dictionary is an optional one, as it's default values are already set in [`types.jl`](https://github.com/harshangrjn/QuantumCircuitOpt.jl/blob/master/src/types.jl) correspnding to an optimal performance of the QCOpt package. Further, this dictionary is an optional argument while executing functions, `build_QCModel` and `run_QCModel` only. | Optional model inputs | Description | | -----------: | :----------- | |`model_type`| The type of implemented MIP model to optimize in QCOpt (default: `compact_formulation`). | |`commute_gate_constraints`| This option activates the valid constraints to eliminate pairs of commuting gates in the elementary (native) gates set (default: `true`)| |`involutory_gate_constraints`| This option activates the valid constraints to eliminate pairs of involutory gates in the elementary (native) gates set (default: `true`)| |`redundant_gate_pair_constraints`| This option activates the valid constraints to eliminate redundant pairs of gates in the elementary (native) gates set (default: `true`)| |`identity_gate_symmetry_constraints`| This option activates the valid constraints to eliminate symmetry in the Identity gate in the decomposition (default: `true`)| |`idempotent_gate_constraints`| This option activates the valid constraints to eliminate idempotent gates in the elementary (native) gates set (default: `false`)| |`convex_hull_gate_constraints`| This option activates the valid constraints to apply convex hull of complex entries in the elementary (native) gates set (default: `false`)| |`fix_unitary_variables`| This option evaluates all the fixed-valued indices of unitary matrix varaibles (`U_var`) at every depth, and appropriately builds the optimization model (default: `true`)| |`visualize_solution`| This option activates the visualization of the optimal circuit decomposition (default: `true`)| | `relax_integrality` | This option transforms integer variables into continuous variables (default: `false`). | | `optimizer_log` | This option enables or disables console logging for the `optimizer` (default: `true`).| | `objective_slack_penalty` | This option sets the penalty for minimizing the slack term in the objective, when `decomposition_type` is set to `approximate` (default: `1E3`). | | `time_limit` | This option allows sets the maximum time limit for the optimizer in seconds (default: `10,800`). | # Sample circuit synthesis Using the above-described mandatory and optional user inputs, here is a sample circuit decomposition to minimize the total depth for implementing a 2-qubit controlled-Z gate ([CZGate](https://harshangrjn.github.io/QuantumCircuitOpt.jl/dev/2_qubit_gates/#CZGate)), with entangling [CNOT](https://harshangrjn.github.io/QuantumCircuitOpt.jl/dev/2_qubit_gates/#CNotGate) gate and the one-qubit, universal rotation gate ([U3Gate](https://harshangrjn.github.io/QuantumCircuitOpt.jl/dev/1_qubit_gates/#U3Gate)) with three discretized Euler angles (θ,ϕ,λ): ```julia import QuantumCircuitOpt as QCOpt using JuMP using Gurobi # Target: CZGate function target_gate() return Array{Complex{Float64},2}([1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 -1]) end # Circuit specifications (mandatory) params = Dict{String, Any}( "num_qubits" => 2, "maximum_depth" => 4, "elementary_gates" => ["U3_1", "U3_2", "CNot_1_2", "Identity"], "target_gate" => target_gate(), "objective" => "minimize_depth", "decomposition_type" => "exact_optimal", "U3_θ_discretization" => -π:π/2:π, "U3_ϕ_discretization" => -π:π/2:π, "U3_λ_discretization" => -π:π/2:π, ) # Optimization model inputs (optional) model_options = Dict{Symbol, Any}(:model_type => "compact_formulation", :visualize_solution => true) qcm_optimizer = JuMP.optimizer_with_attributes(Gurobi.Optimizer, "presolve" => 1) QCOpt.run_QCModel(params, qcm_optimizer; options = model_options) ``` If you prefer to decompose a target gate of your choice, update the `target_gate()` function and the set of `elementary_gates` accordingly in the above sample code. For more such circuit decompositions, with various types of elementary gates, refer to [examples](https://github.com/harshangrjn/QuantumCircuitOpt.jl/tree/master/examples) folder. !!! warning Note that [QCOpt](https://github.com/harshangrjn/QuantumCircuitOpt.jl) tries to find the global minima of a specified objective function for a given set of input one- and two-qubit gates, target gate and the total depth of the decomposition. This combinatiorial optimization problem is known to be NP-hard to compute in the size of `num_qubits`, `maximum_depth` and `elementary_gates`. !!! tip Run times of [QCOpt](https://github.com/harshangrjn/QuantumCircuitOpt.jl)'s mathematical optimization models are significantly faster using [Gurobi](https://www.gurobi.com) as the underlying mixed-integer programming (MIP) solver. Note that this solver's individual-usage license is available [free](https://www.gurobi.com/academia/academic-program-and-licenses/) for academic purposes. # Extracting results The run commands (for example, `run_QCModel`) in QCOpt return detailed results in the form of a dictionary. This dictionary can be saved for further processing as follows, ```julia results = QCOpt.run_QCModel(params, qcm_optimizer) ``` For example, for decomposing the above controlled-Z gate, the QCOpt's runtime and the optimal objective value (minimum depth) can be accessed using, ```julia results["solve_time"] results["objective"] ``` Also, `results["solution"]` contains detailed information about the solution produced by the optimization model, which can be utilized for further analysis. # Visualizing results QCOpt currently supports the visualization of optimal circuit decompositions obtained from the results dictionary (from above), which can be executed using, ```julia data = QCOpt.get_data(params) QCOpt.visualize_solution(results, data) ``` For example, for the above controlled-Z gate decomposition, the processed output of QCOpt is as follows: ``` ============================================================================= QuantumCircuitOpt version: v0.5.1 Quantum Circuit Model Data Number of qubits: 2 Total number of elementary gates (after presolve): 72 Maximum depth of decomposition: 4 Elementary gates: ["U3_1", "U3_2", "CNot_1_2", "Identity"] U3_θ discretization: [-180.0, -90.0, 0.0, 90.0, 180.0] U3_ϕ discretization: [-180.0, -90.0, 0.0, 90.0, 180.0] U3_λ discretization: [-180.0, -90.0, 0.0, 90.0, 180.0] Type of decomposition: exact_optimal MIP optimizer: Gurobi Optimal Circuit Decomposition U3_2(-90.0,0.0,0.0) * CNot_1_2 * U3_2(90.0,0.0,0.0) = Target gate Minimum optimal depth: 3 Optimizer run time: 3.01 sec. ============================================================================= ```
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "BSD-3-Clause" ]
0.5.9
d695ea89a34e0acecae211a3c6cc0d6254411507
docs
296
# Examples for QuantumCircuitOpt `run_examples.jl` file contains the main driver file which can be executed to decompose a target gate into sequence of elementary gates of your choice. Multiple such gate implementations can be found inside files such as `2qubit_gates.jl`, `3qubit_gates.jl`, etc.
QuantumCircuitOpt
https://github.com/harshangrjn/QuantumCircuitOpt.jl.git
[ "MIT" ]
0.2.1
b40f10bde9569c0c900489f89a5882a0a90c2cf4
code
5265
module BioFetch using FASTX using GenomicAnnotations using BioServices.EUtils using BioServices.EBIProteins export fetchseq, SeqFormat, fasta, gb @enum SeqFormat fasta gb """ fetchseq(ids::AbstractString::AbstractVector{<:AbstractString}, range::Union{Nothing, AbstractRange} = nothing, revstrand = false; format::SeqFormat = fasta) Fetches sequence data from a database by accession number in either FASTA format or GenBank flatfile format. Nucleotide and protein records may be mixed. Results will be returned in the order provided. Supports NCBI, Ensembl, and UniProt accession numbers. GenBank format may not work right now. ```julia fetchseq("AH002844") # retrive one FASTA NCBI nucleotide record fetchseq(["CAA41295.1", "NP_000176"]) # retrieve two FASTA NCBI protein records fetchseq("NC_036893.1", 81_775_230 .+ (1:1_000_000)) # retrive a 1 Mb segment of a FASTA NCBI genomic record fetchseq("NC_036893.1", 81000000:81999999, true) # retrive a 1 Mb segment of a FASTA NCBI genomic record on the reverse strand ``` `range` and `revstrand` are only valid for nucleotide queries """ function fetchseq(ids::AbstractVector{<:AbstractString}, range::Union{Nothing, AbstractRange} = nothing, revstrand = false; format::SeqFormat = fasta) ncbinucleotides = String[] ncbiproteins = String[] ebiuniprots = String[] ebiensembls = String[] order = IdDict(ncbinucleotides => [], ncbiproteins => [], ebiuniprots => [], ebiensembls => []) for (i, id) ∈ enumerate(ids) ebiensembl = startswith(id, r"ENS[A-Z][0-9]{11}") ncbiprotein = startswith(id, r"[NX]P_|[A-Z]{3}[0-9]") ncbinucleotide = startswith(id, r"[NX][CGRTMW]_|[A-Z]{2}[0-9]|[A-Z]{4,6}[0-9]") && !ebiensembl ebiuniprot = startswith(id, r"[A-Z][0-9][A-Z0-9]{4}") ncbiprotein || ncbinucleotide || ebiuniprot || ebiensembl || throw("could not infer database for $id") array = ncbinucleotide ? ncbinucleotides : ncbiprotein ? ncbiproteins : ebiuniprot ? ebiuniprots : ebiensembl ? ebiensembls : error() push!(array, id) push!(order[array], i) end results = [fetchseq_ncbi(ncbinucleotides, "nuccore"; format, range, revstrand); fetchseq_ncbi(ncbiproteins, "protein"; format); fetchseq_uniprot(ebiuniprots; format); fetchseq_ensembl(ebiensembls; format)] order = [order[ncbinucleotides]; order[ncbiproteins]; order[ebiuniprots]; order[ebiensembls]] return results[order] end function fetchseq(id::AbstractString, range::Union{Nothing, AbstractRange} = nothing, revstrand = false; format::SeqFormat = fasta) ebiensembl = startswith(id, r"ENS[A-Z][0-9]{11}") ncbiprotein = startswith(id, r"[NX]P_|[A-Z]{3}[0-9]") ncbinucleotide = startswith(id, r"[NX][CGRTMW]_|[A-Z]{2}[0-9]|[A-Z]{4,6}[0-9]") && !ebiensembl ebiuniprot = startswith(id, r"[A-Z][0-9][A-Z0-9]{4}") result = ncbinucleotide ? fetchseq_ncbi(id, "nuccore"; format, range, revstrand) : ncbiprotein ? fetchseq_ncbi(id, "protein"; format) : ebiuniprot ? fetchseq_uniprot([id]; format) : ebiensembl ? fetchseq_ensembl([id]; format) : error("could not infer database for $id") return result end function fetchseq_ncbi(ids, db::AbstractString; format::SeqFormat = fasta, range::Union{Nothing, AbstractRange} = nothing, revstrand = false) isempty(ids) && return [] if isnothing(range) response = efetch(; db, id = ids, rettype = String(Symbol(format)), retmode="text", strand = revstrand ? 2 : 1) else response = efetch(; db, id = ids, rettype = String(Symbol(format)), retmode="text", seq_start = first(range), seq_stop = last(range), strand = revstrand ? 2 : 1) end body = IOBuffer(response.body) reader = format == fasta ? FASTA.Reader(body) : format == gb ? GenBank.Reader(body) : nothing records = [record for record ∈ reader] return records end function fetchseq_uniprot(ids::AbstractVector; format::SeqFormat = fasta) isempty(ids) && return [] records = [] contenttype = format == fasta ? "text/x-fasta" : format == gb ? "text/flatfile" : error("unknown format") for id ∈ ids response = ebiproteins(; accession = id, contenttype) body = IOBuffer(response.body) reader = format == fasta ? FASTA.Reader(body) : format == gb ? GenBank.Reader(body) : nothing records = [record for record ∈ reader] append!(records, records) end return records end function fetchseq_ensembl(ids::AbstractVector; format::SeqFormat = fasta) isempty(ids) && return [] records = [] contenttype = format == fasta ? "text/x-fasta" : format == gb ? "text/flatfile" : error("unknown format") for id ∈ ids response = ebiproteins(; dbtype = "Ensembl", dbid = id, contenttype) body = IOBuffer(response.body) reader = format == fasta ? FASTA.Reader(body) : format == gb ? GenBank.Reader(body) : nothing records = [record for record ∈ reader] append!(records, records) end return records end end
BioFetch
https://github.com/BioJulia/BioFetch.jl.git
[ "MIT" ]
0.2.1
b40f10bde9569c0c900489f89a5882a0a90c2cf4
code
894
using BioFetch, FASTX, GenomicAnnotations, Test nr002726 = fetchseq("NR_002726.2") @test length(nr002726) == 1 @test typeof(nr002726[1]) == FASTA.Record nr002726gb = fetchseq("NR_002726.2", format = gb) @test length(nr002726gb) == 1 @test typeof(nr002726gb[1]) == GenomicAnnotations.Record{Gene} seqs = fetchseq(["CAA41295.1", "NP_000176"], format = fasta) @test length(seqs) == 2 @test typeof(seqs[1]) == FASTA.Record nr002726 = fetchseq("NR_002726.2", 10:20) nr002726rev = fetchseq("NR_002726.2", 10:20, true) @test length(nr002726) == 1 @test typeof(nr002726[1]) == FASTA.Record @test length(FASTX.sequence(nr002726[1])) == 11 @test length(FASTX.sequence(nr002726rev[1])) == 11 @test map(x -> x == 'G' ? 'C' : x == 'C' ? 'G' : x == 'T' ? 'A' : x == 'A' ? 'T' : x, FASTX.sequence(nr002726[1])) |> reverse == FASTX.sequence(nr002726rev[1]) @test length(fetchseq("ENSG00000141510")) == 42
BioFetch
https://github.com/BioJulia/BioFetch.jl.git
[ "MIT" ]
0.2.1
b40f10bde9569c0c900489f89a5882a0a90c2cf4
docs
1011
# BioFetch.jl Easily fetch biological sequences from online sources BioFetch provides a higher-level interface to retrieve data from sequence databases and provide them in a readily manipulatable form via FASTX.jl and GenomeAnnotations.jl. Currently supports Entrez (NCBI) Nucleotide and Protein databases, as well as UniProt and Ensembl. Examples: ```julia fetchseq("AH002844") # retrive one NCBI nucleotide record as FASTA fetchseq("CAA41295.1", "NP_000176", format = gb) # retrieve two NCBI protein records as GenBank Flat File fetchseq("Q00987") # retrieve one UniProt protein record as FASTA fetchseq("ENSG00000141510") # retrieve one Ensembl gene record's proteins as FASTA fetchseq("NC_036893.1", 81_775_230 .+ (1:1_000_000)) # retrive a 1 Mb segment of a FASTA NCBI genomic record fetchseq("NC_036893.1", 81000000:81999999, true) # retrive a 1 Mb segment of a FASTA NCBI genomic record on the reverse strand ```
BioFetch
https://github.com/BioJulia/BioFetch.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
181
using Documenter, ITensorMPOCompression, ITensors makedocs(; sitename="ITensorMPOCompression", format=Documenter.HTML(; prettyurls=false), modules=[ITensorMPOCompression], )
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
3014
#' # ITensorMPOCompression #' #' A package to enable block respecting compression of Matrix Product Operators (MPOs) for use with ITensors.jl. #' #' Reference: *Daniel E. Parker, Xiangyu Cao, and Michael P. Zaletel Phys. Rev. B 102, 035147* #' #' ITensors has built in support for generating MPOs from local operators. This framework is called `AutoMPO`. MPOs #' generated by `AutoMPO` are already compressed, so you only need this package #' if you: #' #' 1. Are using MPOs that are created by hand, outside the `AutoMPO` framework. #' 2. Want your MPO to be in orthogonal/canonical form. #' 3. Need to see the bond spectrums throughout the lattice. #' #' Support for compression of infinite lattice MPOs (iMPOs) is in the ITensorInfiniteMPS package #' which can be found [here](https://github.com/ITensor/ITensorInfiniteMPS.jl). #' #' Technical notes on what this package does can be founs [here](https://github.com/JanReimers/ITensorMPOCompression.jl/blob/main/docs/TechnicalDetails.pdf) #' #' ## Installation #' #' You can install this package through the Julia package manager: #' ```julia #' julia> ] add ITensorMPOCompression #' ``` #' ## Examples #' #' Here are is an example of orthogonalizing an hand generated (not using AutoMPO) MPO #+ term=true using ITensors using ITensorMPOCompression include("../test/hamiltonians/hamiltonians.jl"); N = 10; #10 sites NNN = 7; #Include up to 7th nearest neighbour interactions sites = siteinds("S=1/2", N); H = transIsing_MPO(sites, NNN); is_regular_form(H,lower) == true @show get_Dw(H); #Show bond dimensions pprint(H[2]) #schematic view of operators at site #2 orthogonalize!(H,left); #Orthogonalize into left canonical form. Also does rank reduction. orthogonalize!(H,right); #Orthogonalize into right canoncial form. pprint(H[2]) #Show vastly reduced matrix of operators at site #2 @show get_Dw(H); #Show reduced bond dimensions is_regular_form(H,lower) == true isortho(H, right) == true #looks at cached ortho center limits check_ortho(H,right) == true #Does the more expensive V*V_dagger==Id contraction and test pprint(H) #High level view of what is in the MPO. #' Here are is an example of truncating an hand generated (not using AutoMPO) MPO #+ term=true using ITensors using ITensorMPOCompression include("../test/hamiltonians/hamiltonians.jl"); N = 10; #10 sites NNN = 7; #Include up to 7th nearest neighbour interactions sites = siteinds("S=1/2", N); H = transIsing_MPO(sites, NNN); is_regular_form(H,lower) == true spectrums = truncate!(H,left); pprint(H[5]) @show get_Dw(H); @show spectrums; is_regular_form(H,lower) == true isortho(H, left) == true check_ortho(H, left) == true #' ## Generating this README #' This file was generated with [weave.jl](https://github.com/JunoLab/Weave.jl) with the following commands: #+ eval=false using ITensorMPOCompression, Weave weave( joinpath(pkgdir(ITensorMPOCompression), "examples", "README.jl"); doctype="github", out_path=pkgdir(ITensorMPOCompression), )
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
1552
# Define the nearest neighbor term `S⋅S` for the Heisenberg model using ITensors using ITensorMPOCompression using Printf Base.show(io::IO, f::Float64) = @printf(io, "%1.3f", f) import ITensorMPOCompression: insert_Q, reg_form_Op function two_site_gate(s,n::Int64) U = ITensors.randomU(Float64, s[n], s[n+1]) U = prime(U; plev=1) Udag = dag(prime(U)) return U,Udag end function apply(U::ITensor,WL::reg_form_Op,WR::reg_form_Op,Udag::ITensor) WbL=extract_blocks(WL,left;Ac=true) WbR=extract_blocks(WR,right;Ac=true) WbR.𝐀̂𝐜̂=replaceind(WbR.𝐀̂𝐜̂,WbR.irAc,WbL.icAc) #@show inds(WbL.𝐀̂𝐜̂) inds(WbR.𝐀̂𝐜̂) Phi = prime(((WbL.𝐀̂𝐜̂ * WbR.𝐀̂𝐜̂) * U) * Udag, -2; tags="Site") #@show inds(Phi) @assert order(Phi)==6 is=siteinds(WL) U, ss, V, spec, iu, iv = svd(Phi, WbL.irAc, is...; utags=tags(WL.iright),vtags=tags(WR.ileft), cutoff=1e-15) WL⎖,iqpl=insert_Q(WL,U,iu,left) WR⎖,iqpr=insert_Q(WR,ss*V,iv,right) WR⎖=replaceind(WR⎖,iqpr,iqpl) check(WL⎖) check(WR⎖) @assert is_regular_form(WL⎖) @assert is_regular_form(WR⎖) return WL⎖,WR⎖ end function gate_sweep!(H::reg_form_MPO) N=length(H) for n in 1:N-1 U,Udag=two_site_gate(s,n) H[n],H[n+1]=apply(U,H[n],H[n+1],Udag) end end N,NNN = 5,2 s = siteinds("S=1/2", N) H = reg_form_MPO(Heisenberg_AutoMPO(s, NNN)) @assert is_gauge_fixed(H) orthogonalize!(H,right) @assert is_gauge_fixed(H) gate_sweep!(H) # U,Udag=two_site_gate(s,2) # H[2],H[3]=apply(U,H[2],H[3],Udag) # #@assert check_ortho(H[2],left) pprint(H) orthogonalize!(H,right) pprint(H) nothing
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
730
using ITensors, ITensorMPOCompression include("../test/hamiltonians/hamiltonians.jl") N = 10 sites = siteinds("S=1/2", N; conserve_qns=true) state = [isodd(n) ? "Up" : "Dn" for n in 1:length(sites)] psi = randomMPS(sites, state) println("Show QN directions. Arrows should point *away* from ortho centers") println("MPS as constructed") show_directions(psi) println("MPS with ortho center on site 5") orthogonalize!(psi, 5) show_directions(psi) H = transIsing_AutoMPO(sites, 1); println("MPO as constructed from AutoMPO") show_directions(H) println("MPO ortho=left (orth center on site 10)") orthogonalize!(H,left) show_directions(H) println("MPO ortho=right (orth center on site 1)") orthogonalize!(H,right) show_directions(H)
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
516
using ITensors using ITensorMPOCompression include("../test/hamiltonians/hamiltonians.jl") N = 10; #10 sites NNN = 7; #Include up to 7th nearest neighbour interactions sites = siteinds("S=1/2", N); H = transIsing_MPO(sites, NNN); is_regular_form(H,lower) == true pprint(H[2]) orthogonalize!(H,1) pprint(H[2]) get_Dw(H) is_regular_form(H,lower) == true isortho(H, right) == true #looks at cached ortho center limits check_ortho(H,right) == true #Does the more expensive V*V_dagger==Id contraction and test pprint(H)
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
313
using ITensors using ITensorMPOCompression include("../test/hamiltonians/hamiltonians.jl") N = 10; #10 sites NNN = 7; #Include up to 7th nearest neighbour interactions sites = siteinds("S=1/2", N); H = transIsing_MPO(sites, NNN); pprint(H) bond_spectrum = truncate!(H,left) pprint(H) @show bond_spectrum nothing
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
1207
using ITensors using ITensorMPOCompression using Printf Base.show(io::IO, f::Float64) = @printf(io, "%1.3f", f) function Heisenberg_2D_AutoMPO(sites, Nx::Int64, Ny::Int64, hz::Float64=0.0, J::Float64=1.0) N = length(sites) @mpoc_assert N == Nx * Ny ampo = OpSum() for j in 1:N add!(ampo, hz, "Sz", j) end lattice = square_lattice(Nx, Ny; yperiodic=false) # Define the Heisenberg spin Hamiltonian on this lattice ampo = OpSum() for b in lattice ampo .+= 0.5 * J, "S+", b.s1, "S-", b.s2 ampo .+= 0.5 * J, "S-", b.s1, "S+", b.s2 ampo .+= J, "Sz", b.s1, "Sz", b.s2 end return MPO(ampo, sites) end Nx = 10 Ny = 6 N = Nx * Ny; #10 sites sites = siteinds("S=1/2", N); H = Heisenberg_2D_AutoMPO(sites, Nx, Ny) Dw_auto = get_Dw(H) bond_spectrum = truncate!(H,left) #if you look at the SV spectrum we min(sv)=0.25 so there is nothing small to truncate. Dw_trunc = get_Dw(H) if Dw_auto == Dw_trunc println("It is very hard to beat autoMPO!!!!") println(" And here is why:") println(" For a pseudo 2D MPOs there are no small singular values to truncate") else println("Wa-hoo truncate did something useful :)") @show Dw_auto Dw_trunc end @show bond_spectrum nothing
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
3666
using ITensors using ITensorMPOCompression using Test # using Printf # Base.show(io::IO, f::Float64) = @printf(io, "%1.3e", f) #dumb way to control float output include("../test/hamiltonians/hamiltonians.jl") @testset "Investigate suprise effects of the inital sweep direction" begin ul = lower initstate(n) = "↑" verbose = false @printf(" max(Dw) dumb-summed \n") @printf(" N NNN Raw L1 L2 R1 R2\n") for NNN in [1, 5, 8, 12, 14, 20, 25] # N needs to be big enough that there is block in the middle of lattice which # exhibits no edge effects. N = 2 * NNN + 4 sites = siteinds("S=1/2", N) HdumbL = two_body_MPO(sites, NNN; Jprime=1.0, presummed=false) HdumbR = deepcopy(HdumbL) Dw_raw=maxlinkdim(HdumbL) orthogonalize!(HdumbL, left; verbose=verbose, atol=1e-14) orthogonalize!(HdumbR, right; verbose=verbose, atol=1e-14) Dw1_L, Dw1_R = maxlinkdim(HdumbL), maxlinkdim(HdumbR) orthogonalize!(HdumbL, right; verbose=verbose, atol=1e-14) orthogonalize!(HdumbR, left; verbose=verbose, atol=1e-14) Dw2_L, Dw2_R = maxlinkdim(HdumbL), maxlinkdim(HdumbR) @printf("%4i %4i %4i %4i %4i %4i %4i \n", N, NNN, Dw_raw, Dw1_L, Dw2_L, Dw1_R, Dw2_R) end end @testset "Tabulate MPO Dw reduction for 2 body NNN interactions" begin ul=lower initstate(n) = "↑" @printf(" |--------------------------max(Dw)-------------------------|\n") @printf(" AutoMPO pre-summed dumb-summed \n") @printf(" Finite Finite finite \n") @printf(" N NNN raw orth trunc raw orth trunc raw orth trunc\n") for NNN in 1:15 # N needs to be big enough that there is block in the middle of lattice which # exhibits no edge effects. N=2*NNN+4 #Nmid=div(N,2) #NNNd= NNN>15 ? 1 : NNN #don't bother with the dumb version for largeish NNN sites = siteinds("S=1/2",N;conserve_qns=false); Hpres=two_body_MPO(sites,NNN;presummed=true) Hdumb=two_body_MPO(sites,NNN;presummed=false) Hauto=two_body_AutoMPO(sites,NNN;nexp=4) Dw_ps_raw,Dw_ds_raw,Dw_auto_raw=maxlinkdim(Hpres),maxlinkdim(Hdumb),maxlinkdim(Hauto) orthogonalize!(Hpres,left;atol=1e-15) orthogonalize!(Hpres,right;atol=1e-15) orthogonalize!(Hdumb,left;atol=1e-15) orthogonalize!(Hdumb,right;atol=1e-15) orthogonalize!(Hauto,left;atol=1e-15) orthogonalize!(Hauto,right;atol=1e-15) Dw_ps_orth,Dw_ds_orth,Dw_auto_orth=maxlinkdim(Hpres),maxlinkdim(Hdumb),maxlinkdim(Hauto) ss_pres=truncate!(Hpres,left;cutoff=1e-15) ss_dumb=truncate!(Hdumb,left;cutoff=1e-15) ss_auto=truncate!(Hauto,left;cutoff=1e-15) Dw_ps_trunc,Dw_ds_trunc,Dw_auto_trunc=maxlinkdim(Hpres),maxlinkdim(Hdumb),maxlinkdim(Hauto) @printf("%3i %3i %3i %3i %3i %3i %3i %3i %3i %3i %3i\n", N,NNN, Dw_auto_raw,Dw_auto_orth,Dw_auto_trunc, Dw_ps_raw,Dw_ps_orth,Dw_ps_trunc, Dw_ds_raw,Dw_ds_orth,Dw_ds_trunc, ) # # Make sure the bond spectrum for auto, presummed amd dum summed hamiltonians # are all identical to machine precision. # @test length(ss_pres)==length(ss_auto) @test length(ss_dumb)==length(ss_auto) for nb in 1:length(ss_pres) ss_p=eigs(ss_pres[nb]) ss_d=eigs(ss_dumb[nb]) ss_a=eigs(ss_auto[nb]) if !isnothing(ss_d) pd=.√(ss_p)-.√(ss_d) pa=.√(ss_p)-.√(ss_a) #@show sqrt(sum(pa.^2))/N @test sqrt(sum(pd.^2))/N ≈ 0.0 atol = 1e-14*N @test sqrt(sum(pa.^2))/N ≈ 0.0 atol = 4e-12*N end end end end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
2720
using ITensors using ITensorMPOCompression using Test # using Printf # Base.show(io::IO, f::Float64) = @printf(io, "%1.3e", f) #dumb way to control float output include("../test/hamiltonians/hamiltonians.jl") maxlinkdim(H::MPO)=maximum(get_Dw(H)) maxlinkdim(H::reg_form_MPO)=maximum(get_Dw(MPO(H))) @testset "Investigate suprise effects of the inital sweep direction for 3 body Hamiltonian" begin ul = lower initstate(n) = "↑" verbose = false @printf(" max(Dw) dumb-summed \n") @printf(" N Raw autoMPO L1 L2 R1 R2 \n") for N in 3:15 # N needs to be big enough that there is block in the middle of lattice which # exhibits no edge effects. sites = siteinds("S=1/2", N) HhandL = reg_form_MPO(three_body_MPO(sites, N)) HhandR = reg_form_MPO(three_body_MPO(sites, N)) Hauto = three_body_AutoMPO(sites) Dw_raw, Dw_auto = maxlinkdim(HhandL), maxlinkdim(Hauto) orthogonalize!(HhandL,left; verbose=verbose, atol=1e-14) orthogonalize!(HhandR,right; verbose=verbose, atol=1e-14) Dw1_L, Dw1_R = maxlinkdim(HhandL), maxlinkdim(HhandR) orthogonalize!(HhandL,right; verbose=verbose, atol=1e-14) orthogonalize!(HhandR,left; verbose=verbose, atol=1e-14) Dw2_L, Dw2_R = maxlinkdim(HhandL), maxlinkdim(HhandR) @printf( "%4i %4i %4i %4i %4i %4i %4i \n", N, Dw_raw, Dw_auto, Dw1_L, Dw2_L, Dw1_R, Dw2_R, ) end end @testset "Tabulate MPO Dw reduction for 3 body Hamiltonian" begin ul = lower initstate(n) = "↑" @printf(" |--------max(Dw)-----------|\n") @printf(" AutoMPO hand built\n") @printf(" N raw trunc raw trunc \n") for N in 3:15 sites = siteinds("S=1/2", N) Hhand = reg_form_MPO(three_body_MPO(sites, N)) Hauto = reg_form_MPO(three_body_AutoMPO(sites)) Dw_hand_raw, Dw_auto_raw = maxlinkdim(Hhand), maxlinkdim(Hauto) ss_hand = truncate!(Hhand,left; cutoff=1e-15, atol=1e-15) ss_auto = truncate!(Hauto,left; cutoff=1e-15, atol=1e-15) Dw_hand_trunc1, Dw_auto_trunc = maxlinkdim(Hhand), maxlinkdim(Hauto) @printf( "%3i %3i %3i %3i %3i \n", N, Dw_auto_raw, Dw_auto_trunc, Dw_hand_raw, Dw_hand_trunc1, ) # # Make sure the bond spectrum for auto, presummed amd dum summed hamiltonians # are all identical to machine precision. # @test length(ss_hand) == length(ss_auto) for nb in 1:length(ss_hand) ss_h = eigs(ss_hand[nb]) ss_a = eigs(ss_auto[nb]) ha = .√(ss_h) - .√(ss_a) #@show sqrt(sum(ha.^2))/N @test sqrt(sum(ha .^ 2)) / N ≈ 0.0 atol = 3e-12 end end end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
549
using ITensors using ITensorMPOCompression include("../test/hamiltonians/hamiltonians.jl") # using Printf # Base.show(io::IO, f::Float64) = @printf(io, "%1.3f", f) #dumb way to control float output N = 10; #10 sites NNN = 7; #Include up to 7th nearest neighbour interactions sites = siteinds("S=1/2", N); H = transIsing_MPO(sites, NNN); is_regular_form(H,lower) == true @show get_Dw(H) spectrums = truncate!(H,left) pprint(H[5]) @show get_Dw(H) @show spectrums is_regular_form(H,lower) == true isortho(H, left) == true check_ortho(H, left) == true
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
738
using ITensors function two_component_BH(N::Int64;U=1.0,U12=-0.5,t1=0.5,t2=0.25,kwargs...) sites = siteinds("Boson",N;conserve_qns=true,conserve_number=false) op = OpSum() for i in 1:2:N-3 op += -U/2, "N", i op += U/2, "N", i,"N",i op += -t1, "a", i, "a†", i + 2 op += -t1, "a†", i, "a", i + 2 end op += -U/2, "N", N-1 op += U/2, "N", N-1,"N",N-1 for i in 2:2:N-2 op += -U/2, "N", i op += U/2, "N", i,"N",i op += -t2, "a", i, "a†", i + 2 op += -t2, "a†", i, "a", i + 2 end op += -U/2, "N", N op += U/2, "N", N,"N",N for i in 1:2:N-1 op +=U12, "N", i,"N",i+1 end MPO(op,sites;kwargs...) end two_component_BH(6)
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
6486
module ITensorMPOCompression using ITensors using NDTensors import ITensors: addqns, isortho, orthocenter, setinds , linkind, data, permute, checkflux import ITensors: dim, dims, trivial_space, eachindval, eachval, getindex, setindex! import ITensors: truncate!, truncate, orthogonalize, orthogonalize! import ITensors: QNIndex, QNBlocks, Indices, AbstractMPS, DenseTensor, BlockSparseTensor,DiagTensor, tensor import NDTensors: getperm, BlockDim, blockstart, blockend import Base: similar, reverse, transpose # reg_form and orth_type values and functions export upper, lower, left, right, mirror, flip # lots of characterization functions export is_regular_form, isortho, check_ortho, detect_regular_form # MPO bond dimensions and bond spectrum export get_Dw, min, max export bond_spectrums # primary operations #export orthogonalize!, truncate, truncate! # Display helpers export @pprint, pprint, show_directions # Wrapped MPO types export reg_form_MPO macro mpoc_assert(ex) esc(:($Base.@assert $ex)) end function mpoc_checkflux(::Union{DenseTensor,DiagTensor}) # No-op end function mpoc_checkflux(T::Union{BlockSparseTensor,DiagBlockSparseTensor}) return checkflux(T) end macro checkflux(T) return esc(:(mpoc_checkflux(tensor($T)))) end default_eps = 1e-14 #for characterization routines, floats abs()<default_eps are considered to be zero. @doc """ @enum reg_form upper lower Indicates that an MPO or operator-valued matrix has either an `upper` or `lower` regular form. This becomes non-trival for rectangular matrices. See also [`detect_regular_form`](@ref) and related functions """ @enum reg_form upper lower @doc """ @enum orth_type left right Indicates that an MPO matrix satisfies the conditions for `left` or `right` canonical form """ @enum orth_type left right # """ # mirror(lr::orth_type)::orth_type # returns this mirror of lr. `left`->`right` and `right`->`left` # """ function mirror(lr::orth_type)::orth_type if lr == left ret = right else #must be right ret = left end return ret end mirror(ul::reg_form) = ul == lower ? upper : lower bond_spectrums = Vector{Spectrum} function Base.max(s::Spectrum)::Float64 return sqrt(eigs(s)[1]) end function Base.min(s::Spectrum)::Float64 return sqrt(eigs(s)[end]) end function Base.max(ss::bond_spectrums)::Float64 ret = max(ss[1]) for n in 2:length(ss) ms = max(ss[n]) if ms > ret ret = ms end end return ret end function Base.min(ss::bond_spectrums)::Float64 ret = min(ss[1]) for n in 2:length(ss) ms = min(ss[n]) if ms < ret ret = ms end end return ret end function slice(A::ITensor, iv::IndexVal...)::ITensor iv_dagger = [dag(x.first) => x.second for x in iv] return A * onehot(iv_dagger...) end """ assign!(W::ITensor,i1::IndexVal,i2::IndexVal,op::ITensor) Assign an operator to an element of the operator valued matrix W W[i1,i2]=op """ function assign!(W::ITensor, op::ITensor, ivs::IndexVal...) return assign!(W, tensor(op), ivs...) end function assign!(W::ITensor, op::DenseTensor, ivs::IndexVal...) iss = inds(op) for s in eachindval(iss) s2 = [x.second for x in s] W[ivs..., s...] = op[s2...] end end function assign!(W::ITensor, op::BlockSparseTensor, ivs::IndexVal...) iss = inds(op) for b in eachnzblock(op) isv = [iss[i] => b[i] for i in 1:length(b)] W[ivs..., isv...] = op[b][1] #not sure why we need [1] here end end """ function redim(i::Index,Dw::Int64)::Index Create an index with the same tags ans plev, but different dimension(s) and and id """ # # Build and increased QN space with padding at the begining and end. # Use the sample qns argument get the correct blocks for padding. # Ability to split blocks is not needed, therefore not supported. # function redim(iq::QNIndex, pad1::Int64, pad2::Int64, qns::QNBlocks) @assert pad1 == blockdim(qns[1]) #Splitting blocks not supported @assert pad2 == blockdim(qns[end]) #Splitting blocks not supported qnsp = [qns[1], space(iq)..., qns[end]] #creat the new space return Index(qnsp; tags=tags(iq), plev=plev(iq), dir=dir(iq)) #create new index. end function redim(i::Index, pad1::Int64, pad2::Int64, ::Int64) #@assert dim(i) + pad1 + pad2 <= Dw return Index(dim(i) + pad1 + pad2; tags=tags(i), plev=plev(i), dir=dir(i)) #create new index. end # # Build a reduced QN space from offset->Dw+offset, possibly splitting QNBlocks at the # begining and end of the space. # function redim(iq::QNIndex, Dw::Int64, offset::Int64) # println("---------------------") # @show iq Dw offset @assert dim(iq) - offset >= Dw qns=copy(space(iq)) qns1=QNBlocks() is=1 for i in 0:length(qns) #starting at 0 quickly dispenses with the offset==0 case. _Dw=dim(qns[1:i]) if _Dw==offset is=i+1 break elseif _Dw>offset excess = _Dw-offset if excess==blockdim(qns[i]) is=i #no need to split the block. Add this block below. else #we need to split this block and add it here. qn_split=qn(qns[i])=>excess #push!(qns1,qn_split) qns[i]=qn_split is=i end break end end # @show qns1 is for i in is:length(qns) _Dw=dim(qns[is:i]) if _Dw==Dw #no need to split .. and we are done. push!(qns1,qns[i]) break; elseif _Dw>Dw #Need to split excess = _Dw-Dw #How much space to leave bdim=blockdim(qns[i]) qn_split=qn(qns[i])=>bdim-excess push!(qns1,qn_split) break else push!(qns1,qns[i]) end end # @show qns1 @mpoc_assert Dw==dim(qns1) return Index(qns1; tags=tags(iq), plev=plev(iq), dir=dir(iq)) #create new index. end function redim(i::Index, Dw::Int64, ::Int64) return Index(Dw; tags=tags(i), plev=plev(i)) #create new index. end function Base.reverse(i::QNIndex) return Index(Base.reverse(space(i)); dir=dir(i), tags=tags(i), plev=plev(i)) end function Base.reverse(i::Index) return Index(space(i); tags=tags(i), plev=plev(i)) end function G_transpose(i::Index, iu::Index) D = dim(i) @mpoc_assert D == dim(iu) G = ITensor(0.0, dag(i), iu) for n in 1:D G[i => n, iu => D + 1 - n] = 1.0 end return G end include("subtensor.jl") include("reg_form_Op.jl") include("blocking.jl") include("reg_form_MPO.jl") include("util.jl") include("gauge_fix.jl") include("qx.jl") include("characterization.jl") include("orthogonalize.jl") include("truncate.jl") end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
9128
#------------------------------------------------------------------------------- # # Blocking functions # # # Decisions: 1) Use ilf,ilb==forward,backward or ir,ic=row,column ? # 2) extract_blocks gets everything. Should it defer to get_bc_block for b and c? # may best to define W as # ul=lower ul=upper # 1 0 0 1 b d # lr=left b A 0 0 A c # d c I 0 0 I # # 1 0 0 1 c d # lr=right c A 0 0 A b # d b I 0 0 I # # Use kwargs in extract_blocks so caller can choose what they need. Default is c only # mutable struct regform_blocks 𝕀::Union{ITensor,Nothing} 𝐀̂::Union{ITensor,Nothing} 𝐀̂𝐜̂::Union{ITensor,Nothing} 𝐕̂::Union{ITensor,Nothing} 𝐛̂::Union{ITensor,Nothing} 𝐜̂::Union{ITensor,Nothing} 𝐝̂::Union{ITensor,Nothing} irA::Union{Index,Nothing} icA::Union{Index,Nothing} irAc::Union{Index,Nothing} icAc::Union{Index,Nothing} irV::Union{Index,Nothing} icV::Union{Index,Nothing} irb::Union{Index,Nothing} icb::Union{Index,Nothing} irc::Union{Index,Nothing} icc::Union{Index,Nothing} ird::Union{Index,Nothing} icd::Union{Index,Nothing} function regform_blocks() return new( nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing, ) end end d(Wb::regform_blocks)::Float64 = scalar(Wb.𝕀 * dag(Wb.𝕀)) b0(Wb::regform_blocks)::ITensor = Wb.𝐛̂ * dag(Wb.𝕀) / d(Wb) c0(Wb::regform_blocks)::ITensor = Wb.𝐜̂ * dag(Wb.𝕀) / d(Wb) A0(Wb::regform_blocks)::ITensor = Wb.𝐀̂ * dag(Wb.𝕀) / d(Wb) # # Transpose inds for upper, no-op for lower # function swap_ul(ileft::Index, iright::Index, ul::reg_form) return if ul == lower (ileft, iright, dim(ileft), dim(iright)) else (iright, ileft, dim(iright), dim(ileft)) end end function swap_ul(Wrf::reg_form_Op) return if Wrf.ul == lower (Wrf.ileft, Wrf.iright, dim(Wrf.ileft), dim(Wrf.iright)) else (Wrf.iright, Wrf.ileft, dim(Wrf.iright), dim(Wrf.ileft)) end end # lower left or upper right llur(ul::reg_form, lr::orth_type) = lr == left && ul == lower || lr == right && ul == upper llur(W::reg_form_Op, lr::orth_type) = llur(W.ul, lr) # Use recognizably distinct UTF symbols for operators, and op valued vectors and matrices: # 𝐀̂ 𝐛̂ 𝐜̂ 𝐝̂ 𝐕̂ function extract_blocks( Wrf::reg_form_Op, lr::orth_type; all=false, c=false, b=false, d=false, A=false, Ac=false, V=false, I=true, fix_inds=false, swap_bc=true, )::regform_blocks check(Wrf) @assert plev(Wrf.ileft) == 0 @assert plev(Wrf.iright) == 0 W = Wrf.W ir, ic = linkinds(Wrf) if Wrf.ul == upper ir, ic = ic, ir #transpose end nr, nc = dim(ir), dim(ic) @assert nr > 1 || nc > 1 if all || fix_inds #does not include Ac A = b = c = d = I = true end if !llur(Wrf, lr) && swap_bc #not lower-left or upper-right b, c = c, b #swap flags end A = A && (nr > 1 && nc > 1) b = b && nr > 1 c = c && nc > 1 Wb = regform_blocks() I && (Wb.𝕀 = nr > 1 ? slice(W, ir => 1, ic => 1) : slice(W, ir => 1, ic => nc)) if A Wb.𝐀̂ = W[ir => 2:(nr - 1), ic => 2:(nc - 1)] Wb.irA, = inds(Wb.𝐀̂; tags=tags(ir)) Wb.icA, = inds(Wb.𝐀̂; tags=tags(ic)) end if Ac if llur(Wrf, lr) Wb.𝐀̂𝐜̂ = nr > 1 ? W[ir => 2:nr, ic => 2:(nc - 1)] : W[ir => 1:1, ic => 2:(nc - 1)] else Wb.𝐀̂𝐜̂ = nc > 1 ? W[ir => 2:(nr - 1), ic => 1:(nc - 1)] : W[ir => 2:(nr - 1), ic => 1:1] end Wb.irAc, = inds(Wb.𝐀̂𝐜̂; tags=tags(ir)) Wb.icAc, = inds(Wb.𝐀̂𝐜̂; tags=tags(ic)) end if V i1, i2, n1, n2 = swap_ul(Wrf) if llur(Wrf, lr) #lower left/upper right min1 = Base.min(n1, 2) min2 = Base.min(n2, 2) Wb.𝐕̂ = W[i1 => min1:n1, i2 => min2:n2] #Bottom right corner else #lower right/upper left max1 = Base.max(n1 - 1, 1) max2 = Base.max(n2 - 1, 1) Wb.𝐕̂ = W[i1 => 1:max1, i2 => 1:max2] #top left corner end Wb.irV, = inds(Wb.𝐕̂; tags=tags(ir)) Wb.icV, = inds(Wb.𝐕̂; tags=tags(ic)) end if b Wb.𝐛̂ = W[ir => 2:(nr - 1), ic => 1:1] Wb.irb, = inds(Wb.𝐛̂; tags=tags(ir)) Wb.icb, = inds(Wb.𝐛̂; tags=tags(ic)) end if c Wb.𝐜̂ = W[ir => nr:nr, ic => 2:(nc - 1)] Wb.irc, = inds(Wb.𝐜̂; tags=tags(ir)) Wb.icc, = inds(Wb.𝐜̂; tags=tags(ic)) end if d Wb.𝐝̂ = nr > 1 ? W[ir => nr:nr, ic => 1:1] : W[ir => 1:1, ic => 1:1] Wb.ird, = inds(Wb.𝐝̂; tags=tags(ir)) Wb.icd, = inds(Wb.𝐝̂; tags=tags(ic)) end if fix_inds if !isnothing(Wb.𝐜̂) Wb.𝐜̂ = replaceind(Wb.𝐜̂, Wb.irc, Wb.ird) Wb.irc = Wb.ird end if !isnothing(Wb.𝐛̂) Wb.𝐛̂ = replaceind(Wb.𝐛̂, Wb.icb, Wb.icd) Wb.icb = Wb.icd end if !isnothing(Wb.𝐀̂) Wb.𝐀̂ = replaceinds(Wb.𝐀̂, [Wb.irA, Wb.icA], [Wb.irb, Wb.icc]) Wb.irA, Wb.icA = Wb.irb, Wb.icc end end if !llur(Wrf, lr) && swap_bc #not lower-left or upper-right Wb.𝐛̂, Wb.𝐜̂ = Wb.𝐜̂, Wb.𝐛̂ Wb.irb, Wb.irc = Wb.irc, Wb.irb Wb.icb, Wb.icc = Wb.icc, Wb.icb end if !isnothing(Wb.𝐀̂) @assert hasinds(Wb.𝐀̂, Wb.irA, Wb.icA) end return Wb end function set_𝐛̂_block!(Wrf::reg_form_Op, 𝐛̂::ITensor) check(Wrf) i1, i2, n1, n2 = swap_ul(Wrf) return Wrf.W[i1 => 2:(n1 - 1), i2 => 1:1] = 𝐛̂ end function set_𝐜̂_block!(Wrf::reg_form_Op, 𝐜̂::ITensor) check(Wrf) i1, i2, n1, n2 = swap_ul(Wrf) return Wrf.W[i1 => n1:n1, i2 => 2:(n2 - 1)] = 𝐜̂ end function set_𝐛̂𝐜̂_block!(Wrf::reg_form_Op, 𝐛̂𝐜̂::ITensor, lr::orth_type) @mpoc_assert Wrf.ul==lower if lr==left set_𝐛̂_block!(Wrf, 𝐛̂𝐜̂) else set_𝐜̂_block!(Wrf, 𝐛̂𝐜̂) end end function set_𝐝̂_block!(Wrf::reg_form_Op, 𝐝̂::ITensor) check(Wrf) i1, i2, n1, n2 = swap_ul(Wrf) return Wrf.W[i1 => n1:n1, i2 => 1:1] = 𝐝̂ end function set_𝕀_block!(Wrf::reg_form_Op, 𝕀::ITensor) check(Wrf) i1, i2, n1, n2 = swap_ul(Wrf) n1 > 1 && assign!(Wrf.W, 𝕀, i1 => 1, i2 => 1) return n2 > 1 && assign!(Wrf.W, 𝕀, i1 => n1, i2 => n2) end function set_𝐀̂𝐜̂_block(Wrf::reg_form_Op, 𝐀̂𝐜̂::ITensor, lr::orth_type) @mpoc_assert Wrf.ul==lower check(Wrf) i1, i2, n1, n2 = swap_ul(Wrf) if lr==left #lower left/upper right min1 = Base.min(n1, 2) Wrf.W[i1 => min1:n1, i2 => 2:(n2 - 1)] = 𝐀̂𝐜̂ else #lower right/upper left max2 = Base.max(n2 - 1, 1) Wrf.W[i1 => 2:(n1 - 1), i2 => 1:max2] = 𝐀̂𝐜̂ end end # noop versions for when b/c are empty. Happens in edge ops of H. function set_𝐛̂𝐜̂_block!(::reg_form_Op, ::Nothing, ::orth_type) end function set_𝐛̂_block!(::reg_form_Op, ::Nothing) end function set_𝐜̂_block!(::reg_form_Op, ::Nothing) end # # Given R, build R⎖ such that lr=left R=M*R⎖, lr=right R=R⎖*M # function build_R⎖(R::ITensor, iqx::Index, ilf::Index)::Tuple{ITensor,Index} @mpoc_assert order(R) == 2 @mpoc_assert hasinds(R, iqx, ilf) @mpoc_assert dim(iqx) == dim(ilf) #make sure RL is square @checkflux(R) im = Index(space(iqx); tags=tags(iqx), dir=dir(iqx), plev=1) #new common index between M and R⎖ R⎖ = ITensor(0.0, im, ilf) #R⎖+=δ(im,ilf) #set diagonal ... blocksparse + diag is not supported yet. So we do it manually below. Dw = dim(im) for j1 in 2:(Dw - 1) R⎖[im => j1, ilf => j1] = 1.0 # Fill in the interior diagonal end # # Copy over the perimeter of RL. # R⎖[im => Dw:Dw, ilf => 2:Dw] = R[iqx => Dw:Dw, ilf => 2:Dw] #last row R⎖[im => 1:Dw, ilf => 1:1] = R[iqx => 1:Dw, ilf => 1:1] #first col @checkflux(R⎖) # # Fix up index tags and primes. # im = noprime(settags(im, "Link,m")) RL_prime = noprime(replacetags(R⎖, tags(iqx), tags(im); plev=1)) return RL_prime, dag(im) end function my_similar(::DenseTensor, inds...) return ITensor(inds...) end function my_similar(::BlockSparseTensor, inds...) return ITensor(inds...) end function my_similar(::DiagTensor, inds...) return diagITensor(inds...) end function my_similar(::DiagBlockSparseTensor, inds...) return diagITensor(inds...) end function my_similar(T::ITensor, inds...) return my_similar(tensor(T), inds...) end function warn_space(A::ITensor, ig::Index) ia, = inds(A; tags=tags(ig), plev=plev(ig)) @mpoc_assert dim(ia) + 2 == dim(ig) if hasqns(A) sa, sg = space(ia), space(ig) if dir(ia) != dir(ig) sa = -sa end if sa != sg[2:(nblocks(ig) - 1)] @warn "Mismatched spaces:" @show sa sg[2:(nblocks(ig) - 1)] dir(ia) dir(ig) #@assert false end end end # |1 0 0| # given A, spit out G=|0 A 0| , indices of G are provided. # |0 0 1| function grow(A::ITensor, ig1::Index, ig2::Index) @checkflux(A) @mpoc_assert order(A) == 2 warn_space(A, ig1) warn_space(A, ig2) Dw1, Dw2 = dim(ig1), dim(ig2) G = my_similar(A, ig1, ig2) G[ig1 => 1, ig2 => 1] = 1.0 @checkflux(G) G[ig1 => Dw1, ig2 => Dw2] = 1.0 @checkflux(G) G[ig1 => 2:(Dw1 - 1), ig2 => 2:(Dw2 - 1)] = A @checkflux(G) return G end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
7781
# # Functions for characterizing operator tensors # # # Figure out the site number, and left and indicies of an MPS or MPO ITensor # assumes: # 1) link indices all have a "Link" tag # 2) the "Link" tag is the first tag for each link index # 3) one other tag has the form "l=$n" where n is the link number # 4) the site number is the largest of the link numbers, i.e. left link is l=n-1 # # Obviously a lot of things could go wrong with all these assumptions. # # returns forward,reverse relatvie to sweep direction indexes # if lr=left, then the sweep direction is o the right, and i_right is the forward index. function parse_links(A::ITensor, lr::orth_type)::Tuple{Index,Index} i_left, i_right = parse_links(A) return lr == left ? (i_right, i_left) : (i_left, i_right) end function parse_links(A::ITensor)::Tuple{Index,Index} # # find any site index and try and extract the site number # d, nsite, space = parse_site(A) # # Now process the link tags # ils = filterinds(inds(A); tags="Link") if length(ils) == 2 n1, c1 = parse_link(ils[1]) n2, c2 = parse_link(ils[2]) #find the "l=$n" tags. -1 if not such tag n1, n2 = infer_site_numbers(n1, n2, nsite) #handle qx links with no l=$n tags. if c1 > c2 return ils[2], ils[1] elseif c2 > c1 return ils[1], ils[2] elseif n1 > n2 return ils[2], ils[1] elseif n2 > n1 return ils[1], ils[2] else @mpoc_assert false #no way to dermine order of links end elseif length(ils) == 1 n, c = parse_link(ils[1]) if n == Nothing return Index(1), ils[1] #probably a qx link, don't know if row or col elseif nsite == 1 return Index(1), ils[1] #row vector else return ils[1], Index(1) #col vector end else @show ils @mpoc_assert false end end undef_int = -99999 function parse_site(W::ITensor) is = inds(W; tags="Site")[1] return parse_site(is) end function parse_site(is::Index) @mpoc_assert hastags(is, "Site") nsite = undef_int #sentenal value for t in tags(is) ts = String(t) if ts[1:2] == "n=" nsite::Int64 = tryparse(Int64, ts[3:end]) end if length(ts) >= 4 && ts[1:4] == "Spin" space = ts end if ts[1:2] == "S=" space = ts[3:end] end end @mpoc_assert nsite >= 0 return dim(is), nsite, space end function parse_link(il::Index)::Tuple{Int64,Int64} @mpoc_assert hastags(il, "Link") nsite = ncell = undef_int #sentinel values for t in tags(il) ts = String(t) if ts[1:2] == "l=" || ts[1:2] == "n=" nsite::Int64 = tryparse(Int64, ts[3:end]) end if ts[1:2] == "c=" ncell::Int64 = tryparse(Int64, ts[3:end]) end end return nsite, ncell end # # if one ot links is "Link,qx" then we don't get any site info from it. # All this messy logic below tries to infer the site # of qx link from site index # and link number of other index. # function infer_site_numbers(n1::Int64, n2::Int64, nsite::Int64)::Tuple{Int64,Int64} if n1 == undef_int && n2 == undef_int @mpoc_assert false end if n1 == undef_int if n2 == nsite n1 = nsite - 1 elseif n2 == nsite - 1 n1 = nsite else @mpoc_assert false end end if n2 == undef_int if n1 == nsite n2 = nsite - 1 elseif n1 == nsite - 1 n2 = nsite else @mpoc_assert false end end return n1, n2 end # # Handles direction and leaving out the last element in the sweep. # function sweep(H::AbstractMPS, lr::orth_type)::StepRange{Int64,Int64} N = length(H) return lr == left ? (1:1:(N - 1)) : (N:-1:2) end #---------------------------------------------------------------------------- # # Detection of canonical (orthogonal) forms # @doc """ isortho(H,lr)::Bool Test if anMPO is in `lr` orthogonal (canonical) form by checking the cached orthogonality center. # Arguments - `H:MPO` : MPO to be characterized. - `lr::orth_type` : choose `left` or `right` orthogonality condition to test for. Returns `true` if the MPO is in `lr` orthogonal (canonical) form. This is a fast operation and should be safe to use in time critical production code. The one exception is for iMPO with Ncell=1, where currently the ortho center does not distinguis between left/right or un-orthognal states. """ function ITensors.isortho(H::AbstractMPS, lr::orth_type)::Bool io = false # if length(H)==1 # io=check_ortho(H,lr) #Expensive!! # else if isortho(H) if lr == left io = orthocenter(H) == length(H) else io = orthocenter(H) == 1 end end #end return io end #---------------------------------------------------------------------------- # # Detection of upper and lower regular forms # # # This test is complicated by two things # 1) It is not clear to me (JR) that the A block of an MPO matrix must be upper or lower triangular for # block respecting compression to work properly. Parker et al. make no definitive statement about this. # It is my intention to test this empirically using auto MPO generated Hamiltonians # which tend to be non-triangular. # 2) As a consequence of 1, we cannot decide in advance whether to test for upper or lower regular forms. # We must therefore test for both and return true if either one is true. # @doc """ detect_regular_form(H)::Tuple{Bool,Bool} Inspect the structure of an MPO `H` to see if it satisfies the regular form conditions. # Arguments - `H::MPO` : MPO to be characterized. # Keywords - `eps::Float64 = 1e-14` : operators inside `W` with norm(W[i,j])<eps are assumed to be zero. # Returns a Tuple containing - `reg_lower::Bool` Indicates all sites in `H` are in lower regular form. - `reg_upper::Bool` Indicates all sites in `H` are in upper regular form. The function returns two Bools in order to handle cases where `H` is not regular form, returning (`false`,`false`) and `H` is in a special pseudo-diagonal regular form, returning (`true`,`true`). """ function detect_regular_form(H::AbstractMPS;kwargs...)::Tuple{Bool,Bool} return is_regular_form(H, lower;kwargs...), is_regular_form(H, upper;kwargs...) end @doc """ is_regular_form(H::MPO,ul::reg_form)::Bool Inspect the structure of an MPO `H` to see if it satisfies the `lower/upper` regular form conditions. # Arguments - `H::MPO` : MPO to be characterized. - `ul::reg_form` : Select whether to test for `lower` or `upper` regular form. # Keywords - `eps::Float64 = 1e-14` : operators inside `W` with norm(W[i,j])<eps are assumed to be zero. # Returns - `regular::Bool` Indicates all sites in `H` are in `ul` regular form. """ function is_regular_form(H::AbstractMPS, ul::reg_form;kwargs...)::Bool il = dag(linkind(H, 1)) for n in 2:(length(H) - 1) ir = linkind(H, n) #@show il ir inds(H[n]) Wrf = reg_form_Op(H[n], il, ir, ul) !is_regular_form(Wrf;kwargs...) && return false il = dag(ir) end return true end function get_Dw(H::MPO)::Vector{Int64} N = length(H) Dws = Vector{Int64}(undef, N - 1) for n in 1:(N - 1) l = commonind(H[n], H[n + 1]) Dws[n] = dim(l) end return Dws end function get_traits(W::reg_form_Op, eps::Float64) r, c = W.ileft, W.iright d, n, space = parse_site(W.W) Dw1, Dw2 = dim(r), dim(c) bl, bu = detect_regular_form(W;eps=eps) l = bl ? 'L' : ' ' u = bu ? 'U' : ' ' if bl && bu l = 'D' u = ' ' elseif !(bl || bu) l = 'N' u = 'o' end tri = bl ? lower : upper is__left = check_ortho(W, left; eps=eps) is_right = check_ortho(W, right; eps=eps) if is__left && is_right lr = 'B' elseif is__left && !is_right lr = 'L' elseif !is__left && is_right lr = 'R' else lr = 'M' end return Dw1, Dw2, d, l, u, lr end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
2279
# # Find the first dim==1 index and remove it, then return a Vector. # function vector_o2(T::ITensor) @assert order(T) == 2 i1 = inds(T)[findfirst(d -> d == 1, dims(T))] return vector(T * dag(onehot(i1 => 1))) end function is_gauge_fixed(Wrf::reg_form_Op; eps=1e-14, b=true, c=true, kwargs...)::Bool Wb = extract_blocks(Wrf, left; c=c, b=b) nr, nc = dims(Wrf) if b && nr > 1 !(norm(b0(Wb)) < eps) && return false end if c && nc > 1 !(norm(c0(Wb)) < eps) && return false end return true end function is_gauge_fixed(Hrf::AbstractMPS; kwargs...)::Bool for W in Hrf !is_gauge_fixed(W; kwargs...) && return false end return true end function gauge_fix!(H::reg_form_MPO;kwargs...) if !is_gauge_fixed(H;kwargs) tₙ = Vector{Float64}(undef, 1) for W in H tₙ = gauge_fix!(W, tₙ, left) @assert is_regular_form(W) end #tₙ=Vector{Float64}(undef,1) end of sweep above already returns this. for W in reverse(H) tₙ = gauge_fix!(W, tₙ, right) @assert is_regular_form(W) end end end function gauge_fix!(W::reg_form_Op, tₙ₋₁::Vector{Float64}, lr::orth_type) @assert W.ul==lower @assert is_regular_form(W) Wb = extract_blocks(W, lr; all=true, fix_inds=true) 𝕀, 𝐀̂, 𝐛̂, 𝐜̂, 𝐝̂ = Wb.𝕀, Wb.𝐀̂, Wb.𝐛̂, Wb.𝐜̂, Wb.𝐝̂ #for readability below. nr, nc = dims(W) nb, nf = lr == left ? (nr, nc) : (nc, nr) # # Make in ITensor with suitable indices from the 𝒕ₙ₋₁ vector. # if nb > 1 ibd, ibb =lr==left ? (Wb.ird, Wb.irb) : (Wb.icd, Wb.icb) 𝒕ₙ₋₁ = ITensor(tₙ₋₁, dag(ibb), ibd) end 𝐜̂⎖ = nothing # # First two if blocks are special handling for row and column vector at the edges of the MPO # if nb == 1 #col/row at start of sweep. 𝒕ₙ = c0(Wb) 𝐜̂⎖ = 𝐜̂ - 𝕀 * 𝒕ₙ 𝐝̂⎖ = 𝐝̂ elseif nf == 1 ##col/row at the end of the sweep 𝐝̂⎖ = 𝐝̂ + 𝒕ₙ₋₁ * 𝐛̂ 𝒕ₙ = ITensor(1.0, Index(1), Index(1)) #Not used, but required for the return statement. else 𝒕ₙ = 𝒕ₙ₋₁ * A0(Wb) + c0(Wb) 𝐜̂⎖ = 𝐜̂ + 𝒕ₙ₋₁ * 𝐀̂ - 𝒕ₙ * 𝕀 𝐝̂⎖ = 𝐝̂ + 𝒕ₙ₋₁ * 𝐛̂ end set_𝐝̂_block!(W, 𝐝̂⎖) set_𝐛̂𝐜̂_block!(W, 𝐜̂⎖,mirror(lr)) @assert is_regular_form(W) # 𝒕ₙ is always a 1xN tensor so we need to remove that dim==1 index in order for vector(𝒕ₙ) to work. return vector_o2(𝒕ₙ) end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
4444
#----------------------------------------------------------------- # # Ac block respecting orthogonalization. # @doc """ orthogonalize!(H::MPO,lr::orth_type) Bring an MPO into left or right canonical form using block respecting QR decomposition. # Arguments - `H::MPO` : Matrix Product Operator to be orthogonalized - `lr::orth_type` : Choose `left` or `right` orthgonal/canoncial form for the output. # Keywords - `atol::Float64 = 1e-14` : Absolute cutoff for rank revealing QR which removes zero pivot rows. - `rtol::Float64 = -1.0` : Relative cutoff for rank revealing QR which removes zero pivot rows. - `verbose::Bool = false` : Show some details of the orthogonalization process. atol=`-1.0 and rtol=`-1.0 indicates no rank reduction. # Examples ```julia julia> using ITensors julia> using ITensorMPOCompression include("../test/hamiltonians/hamiltonians.jl"); julia> N=10; #10 sites julia> NNN=7; #Include up to 7th nearest neighbour interactions julia> sites = siteinds("S=1/2",N); julia> H=transIsing_MPO(sites,NNN); # # Make sure we have a regular form or orhtogonalize! won't work. # julia> is_regular_form(H,lower)==true true # # Let's see what the second site for the MPO looks like. # I = unit operator, and S = any other operator # julia> pprint(H[2]) I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . . . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 S 0 S 0 0 S 0 0 0 S 0 0 0 0 S 0 0 0 0 0 S 0 0 0 0 0 0 S I # # Now we can orthogonalize or bring it into canonical form. # Defaults are left orthogonal with rank reduction. # julia> orthogonalize!(H,left); # # Wahoo .. rank reduction knocked the size of H way down, and we haven't # tried compressing yet! # julia> pprint(H[2]) I 0 0 0 S I 0 0 0 0 S I # # What do all the bond dimensions of H look like? # julia> @show get_Dw(H); get_Dw(H) = [3, 4, 5, 6, 7, 8, 9, 9, 9] # # wrap up with two more checks on the structure of H # julia> is_lower_regular_form(H)==true true julia> isortho(H,left)==true true ``` """ function ITensors.orthogonalize!(H::MPO, lr::orth_type; kwargs...) Hrf = reg_form_MPO(H) orthogonalize!(Hrf, lr; kwargs) copy!(H,Hrf) end @doc """ orthogonalize!(H::MPO,j::Int64) Bring an MPO into mixed canonical form with the orthogonality center on site `j`. # Arguments - `H::MPO` : Matrix Product Operator to be orthogonalized - `j::Int64` : Site index for the orthogonality centre. # Keywords - `atol::Float64 = 1e-14` : Absolute cutoff for rank revealing QR which removes zero pivot rows. - `rtol::Float64 = -1.0` : Relative cutoff for rank revealing QR which removes zero pivot rows. - `verbose::Bool = false` : Show some details of the orthogonalization process. atol=`-1.0 and rtol=`-1.0 indicates no rank reduction. # Examples ```julia julia> using ITensors julia> using ITensorMPOCompression include("../test/hamiltonians/hamiltonians.jl"); julia> N=10; #10 sites julia> NNN=7; #Include up to 7th nearest neighbour interactions julia> sites = siteinds("S=1/2",N); julia> H=transIsing_MPO(sites,NNN); julia> orthogonalize!(H,5); julia> pprint(H) n Dw1 Dw2 d Reg. Orth. Form Form 1 1 3 2 L B 2 3 4 2 L L 3 4 5 2 L L 4 5 6 2 L L 5 6 7 2 L M 6 7 6 2 L R 7 6 5 2 L R 8 5 4 2 L R 9 4 3 2 L R 10 3 1 2 L B ``` """ function ITensors.orthogonalize!(H::MPO, j::Int64; kwargs...) Hrf = reg_form_MPO(H) orthogonalize!(Hrf, j; kwargs...) copy!(H,Hrf) end function ITensors.orthogonalize!(H::reg_form_MPO, lr::orth_type; kwargs...) gauge_fix!(H;kwargs...) rng = sweep(H, lr) for n in rng nn = n + rng.step H[n], R, iqp = ac_qx(H[n], lr;kwargs...) H[nn] *= R check(H[n]) check(H[nn]) end H.rlim = rng.stop + rng.step + 1 H.llim = rng.stop + rng.step - 1 return end function ITensors.orthogonalize!(H::reg_form_MPO, j::Int64; kwargs...) if !isortho(H) orthogonalize!(H,right;kwargs...) end oc=orthocenter(H) rng= oc<=j ? (oc:1:j-1) : (oc-1:-1:j) for n in rng nn = n + rng.step H[n], R, iqp = ac_qx(H[n], left;kwargs...) H[nn] *= R check(H[n]) check(H[nn]) end H.rlim = j + 1 H.llim = j - 1 return end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
5363
using LinearAlgebra @doc """ `block_qx(W::ITensor,ul::reg_form)::Tuple{ITensor,ITensor,Index}` Perform a block respecting QX decomposition of the operator valued matrix `W`. The appropriate decomposition, QR, RQ, QL, LQ is selected based on the `reg_form` `ul` and the `orth` keyword argument. The new internal `Index` between Q and R/L is modified so that the tags are "Link,qx" instead "Link,qr" etc. returned by the qr/rq/ql/lq routines. Q and R/L are also gauge fixed so that the corner element of R/L is 1.0 and Q⁺Q=d𝕀 where d is the dimensionality of the local Hilbert space. # Arguments - `W` Operator valued matrix for decomposition. - `ul` upper/lower regular form of `W`. We can auto detect here, but is more efficient if this is done by the higher level calling routines. # Keywords - `orth::orth_type = right` : choose `left` or `right` orthogonal (canonical) form - `rr_cutoff::Float64 = -1.0` : cutoff for rank revealing QX which removes zero pivot rows and columns. All rows with max(abs(R[r,:]))<rr_cutoff are considered zero and removed. rr_cutoff==-1.0 indicates no rank reduction. # Returns a Tuple containing - `Q` with orthonormal columns or rows depending on orth=left/right, dimensions: (χ+1)x(χq+1) - `R` or `L` depending on `ul` with dimensions: (χq+2)x(χ\'+2) - `iq` the new internal link index between `Q` and `R`/`L` with dimensions χq+2 and tags="Link,qx" # Example ```julia julia>using ITensors julia>using ITensorMPOCompression julia>N=5; #5 sites julia>NNN=2; #Include 2nd nearest neighbour interactions julia>sites = siteinds("S=1/2",N); # # Make a Hamiltonian directly, i.e. not using autoMPO # julia>H=transIsing_MPO(sites,NNN); # # Use pprint to see the structure for site #2. I = unit operator and S = any # other operator # julia>pprint(H[2]) #H[1] is a row vector, so let's see what H[2] looks like I 0 0 0 0 S 0 0 0 0 S 0 0 0 0 0 0 I 0 0 0 S 0 S I # # Now do a block respecting QX decomposition. QL decomposition is chosen because # H[2] is in lower regular form and the default ortho direction is left. # julia>Q,L,iq=block_qx(H[2];rr_cutoff=1e-14); #Block respecting QL # # The first column of Q is unchanged because it is outside the V-block. # Also one column was removed because set rr_cutoff to enable rank revealing QX. # julia>pprint(Q) I 0 0 0 S 0 0 0 S 0 0 0 0 I 0 0 0 0 S I # # Similarly L is missing one row due to the rank revealing QX algorithm # julia>pprint(L,iq) #we need to tell pprint the iq is the row index. I 0 0 0 0 0 0 I 0 0 0 S 0 S 0 0 0 0 0 I ``` """ function equal_edge_blocks(i1::QNIndex, i2::QNIndex)::Bool qns1, qns2 = space(i1), space(i2) qn11, qn1n = qns1[1], qns1[nblocks(qns1)] qn21, qn2n = qns2[1], qns2[nblocks(qns2)] return ITensors.have_same_qns(qn(qn11), qn(qn21)) && ITensors.have_same_qns(qn(qn1n), qn(qn2n)) end function equal_edge_blocks(::Index, ::Index)::Bool return true end function insert_Q(Ŵrf::reg_form_Op, Q̂::ITensor, iq::Index, lr::orth_type) @mpoc_assert Ŵrf.ul==lower # # Create new index by growing iq. # ilb, ilf = linkinds(Ŵrf, lr) #Backward and forward indices. iq⎖ = redim(iq, 1, 1, space(ilf)) #pad with 1 at the start and 1 and the end: iqp =(1,iq,1). ileft, iright = lr == left ? (ilb, iq⎖) : (iq⎖, ilb) # # Create a new reg form tensor # Ŵrf⎖ = reg_form_Op(eltype(Ŵrf), ileft, iright,siteinds(Ŵrf)) # # Preserve b,c,d blocks and insert Q # Wb = extract_blocks(Ŵrf, lr; b=true, c=false, d=true) # we don't need c here? set_𝐛̂𝐜̂_block!(Ŵrf⎖, Wb.𝐛̂, lr) #preserve b or c block from old W set_𝐝̂_block!(Ŵrf⎖, Wb.𝐝̂) #preserve d block from old W set_𝕀_block!(Ŵrf⎖, Wb.𝕀) #init I blocks from old W set_𝐀̂𝐜̂_block(Ŵrf⎖, Q̂, lr) #Insert new Qs form QR decomp return Ŵrf⎖, iq⎖ end function ac_qx(Ŵrf::reg_form_Op, lr::orth_type; qprime=false, verbose=false, cutoff=1e-14, kwargs...) @mpoc_assert Ŵrf.ul==lower @checkflux(Ŵrf.W) Wb = extract_blocks(Ŵrf, lr; Ac=true) ilf_Ac = lr==left ? Wb.icAc : Wb.irAc ilf = forward(Ŵrf, lr) #Backward and forward indices. @checkflux(Wb.𝐀̂𝐜̂) if lr == left Qinds = noncommoninds(Wb.𝐀̂𝐜̂, ilf_Ac) Q̂, R, iq, p = qr( Wb.𝐀̂𝐜̂, Qinds; verbose=verbose, positive=true, atol=cutoff, tags=tags(ilf) ) else Rinds = ilf_Ac R, Q̂, iq, p = lq( Wb.𝐀̂𝐜̂, Rinds; verbose=verbose, positive=true, atol=cutoff, tags=tags(ilf) ) end @checkflux(Q̂) @checkflux(R) # Re-scale dh = d(Wb) #dimension of local Hilbert space. @assert abs(dh - round(dh)) == 0.0 #better be an integer! Q̂ *= sqrt(dh) R /= sqrt(dh) Ŵrf⎖, iq⎖ = insert_Q(Ŵrf, Q̂, iq, lr) #create a new W with Q. The size may change. @assert equal_edge_blocks(ilf, iq⎖) #both inds or R have the same tags, so we prime one of them so the grow function can distinguish. R⎖ = grow(prime(R, iq), dag(iq⎖)', ilf) p = add_edges(p) #grow p so we can apply it to Rp. if qprime iq⎖ = prime(iq⎖) else R⎖ = noprime(R⎖) end return Ŵrf⎖, R⎖, iq⎖, p end function add_edges(p::Vector{Int64}) Dw = length(p) + 2 return [1, (p .+ 1)..., Dw] end # # This assumes the edge D=1 blocks appear first in the block list # If this fails we need to return a dict{Block,Vector{Int64}} so we can # associate block with perm vectors # function add_edges(p::Vector{Vector{Int64}}) return [[1], [1], p...] end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
5083
#----------------------------------------------------------------------- # # Finite lattice with open BCs, of regulat form Tensos: l*W1*W2...*WN*r # Edge tensors have dim=1 dummy indices (order(W)==4) so generic code can work the same # on all tensors. # mutable struct reg_form_MPO <: AbstractMPS data::Vector{reg_form_Op} llim::Int # orthocenter-1 rlim::Int # orthocenter+1 d0::ITensor # onehot tensor used to create the l=0 dummy index. dN::ITensor # onehot tensor used to create the l=N dummy index. ul::reg_form #upper or lower function reg_form_MPO( Ws::Vector{reg_form_Op}, llim::Int64, rlim::Int64, d0::ITensor, dN::ITensor, ul::reg_form, ) return new(Ws, llim, rlim, d0, dN, ul) end end function reg_form_MPO( H::MPO, ils::Indices, irs::Indices, d0::ITensor, dN::ITensor, ul::reg_form ) N = length(H) @assert length(ils) == N @assert length(irs) == N data = Vector{reg_form_Op}(undef, N) for n in eachindex(H) data[n] = reg_form_Op(H[n], ils[n], irs[n], ul) end return reg_form_MPO(data, H.llim, H.rlim, d0, dN, ul) end function add_edge_links!(H::MPO) N = length(H) irs = map(n -> linkind(H, n), 1:(N - 1)) #right facing index, which can be thought of as a column index ils = dag.(irs) #left facing index, or row index. ts = trivial_space(irs[1]) T = eltype(H[1]) il0 = Index(ts; tags="Link,l=0", dir=dir(dag(irs[1]))) ilN = Index(ts; tags="Link,l=$N", dir=dir(irs[1])) d0 = onehot(T, il0 => 1) dN = onehot(T, ilN => 1) H[1] *= d0 H[N] *= dN ils, irs = [il0, ils...], [irs..., ilN] for n in 1:N il, ir, W = ils[n], irs[n], H[n] #@show il ir inds(W,tags="Link") @assert !hasqns(il) || dir(W, il) == dir(il) @assert !hasqns(ir) || dir(W, ir) == dir(ir) end return ils, irs, d0, dN end function reg_form_MPO(H::MPO;honour_upper=false, kwargs...) (bl, bu) = detect_regular_form(H;kwargs...) if !(bl || bu) throw(ErrorException("MPO++(H::MPO), H must be in either lower or upper regular form")) end if (bl && bu) # @pprint(H[1]) @assert false end ul::reg_form = bl ? lower : upper #if both bl and bu are true then something is seriously wrong ils, irs, d0, dN = add_edge_links!(H) Hrf=reg_form_MPO(H, ils, irs, d0, dN, ul) # flip to lower regular form by default. if ul==upper && !honour_upper Hrf=transpose(Hrf) end check(Hrf) return Hrf end function check(Hrf::reg_form_MPO) check.(Hrf) end function ITensors.MPO(Hrf::reg_form_MPO)::MPO N = length(Hrf) H = MPO(Ws(Hrf)) H[1] *= dag(Hrf.d0) H[N] *= dag(Hrf.dN) H.llim,H.rlim=Hrf.llim,Hrf.rlim return H end function copy!(H::MPO,Hrf::reg_form_MPO) for n in eachindex(H) H[n]=Hrf[n].W end N = length(Hrf) H[1]*=dag(Hrf.d0) H[N]*=dag(Hrf.dN) H.llim,H.rlim=Hrf.llim,Hrf.rlim end data(H::reg_form_MPO) = H.data function Ws(H::reg_form_MPO) return map(n -> H[n].W, 1:length(H)) end Base.length(H::reg_form_MPO) = length(H.data) function Base.reverse(H::reg_form_MPO) return reg_form_MPO(Base.reverse(H.data), H.llim, H.rlim, H.d0, H.dN, H.ul) end Base.iterate(H::reg_form_MPO, args...) = iterate(H.data, args...) Base.getindex(H::reg_form_MPO, args...) = getindex(H.data, args...) Base.setindex!(H::reg_form_MPO, args...) = setindex!(H.data, args...) function get_Dw(H::reg_form_MPO) return get_Dw(MPO(H)) end function is_regular_form(H::reg_form_MPO;kwargs...)::Bool for W in H !is_regular_form(W;kwargs...) && return false end return true end @doc """ check_ortho(H,lr)::Bool Test if all sites in an MPO statisfty the condition for `lr` orthogonal (canonical) form. # Arguments - `H:MPO` : MPO to be characterized. - `lr::orth_type` : choose `left` or `right` orthogonality condition to test for. # Keywrds - `eps::Float64 = 1e-14` : operators inside H with norm(W[i,j])<eps are assumed to be zero. Returns `true` if the MPO is in `lr` orthogonal (canonical) form. This is an expensive operation which scales as N*Dw^3 which should mostly be used only for unit testing code or in debug mode. In production code use isortho which looks at the cached ortho state. """ check_ortho(H::MPO, lr::orth_type;kwargs...)=check_ortho(reg_form_MPO(copy(H)), lr;kwargs...) function check_ortho(H::reg_form_MPO, lr::orth_type;kwargs...)::Bool for n in sweep(H, lr) #skip the edge row/col opertors !check_ortho(H[n], lr;kwargs...) && return false end return true end function Base.transpose(Hrf::reg_form_MPO)::reg_form_MPO Ws=copy(data(Hrf)) N=length(Hrf) ul1=mirror(Hrf.ul) for n in 1:N-1 ir=Ws[n].iright G = G_transpose(ir, reverse(ir)) Ws[n]*=G Ws[n+1]*=dag(G) Ws[n].ul=ul1 end Ws[N].ul=ul1 return reg_form_MPO(Ws,Hrf.llim, Hrf.rlim,Hrf. d0, Hrf.dN, ul1) end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
7630
#--------------------------------------------------------------------------------- # # Manage an MPO/iMPO tensor and track the left and right facing indices. This # seems to be easiest way to avoid tag hunting. # Also track lower or upper regular form in ul member. # mutable struct reg_form_Op W::ITensor ileft::Index iright::Index ul::reg_form function reg_form_Op(W::ITensor, ileft::Index, iright::Index, ul::reg_form) if !hasinds(W, ileft, iright) @show inds(W, tags="Link") ileft iright end @assert hasinds(W, ileft, iright) return new(W, ileft, iright, ul) end function reg_form_Op(W::ITensor, ul::reg_form) return new(W, Index(1), Index(1), ul) end end # # Internal consistency checks # function check(Wrf::reg_form_Op) @mpoc_assert order(Wrf.W) == 4 @mpoc_assert tags(Wrf.ileft) != tags(Wrf.iright) || plev(Wrf.ileft) != plev(Wrf.iright) @mpoc_assert hasinds(Wrf.W, Wrf.ileft) @mpoc_assert hasinds(Wrf.W, Wrf.iright) if hasqns(Wrf.W) @mpoc_assert dir(Wrf.W, Wrf.ileft) == dir(Wrf.ileft) @mpoc_assert dir(Wrf.W, Wrf.iright) == dir(Wrf.iright) @checkflux(Wrf.W) end end function reg_form_Op(ElT::Type{<:Number},il::Index,ir::Index,is) Ŵ = ITensor(ElT(0.0), il, ir, is) return reg_form_Op(Ŵ, il, ir, lower) end # Extract a subtensor function Base.getindex(Wrf::reg_form_Op, rleft::UnitRange, rright::UnitRange) return Wrf.W[Wrf.ileft => rleft, Wrf.iright => rright] end # # Support some ITensors/Base functions # Base.eltype(Wrf::reg_form_Op)=eltype(Wrf.W) ITensors.dims(Wrf::reg_form_Op) = dim(Wrf.ileft), dim(Wrf.iright) Base.getindex(Wrf::reg_form_Op, lr::orth_type) = lr == left ? Wrf.ileft : Wrf.iright function Base.setindex!(Wrf::reg_form_Op, il::Index, lr::orth_type) if lr == left Wrf.ileft = il else Wrf.iright = il end end function Base.show(io::IO, Wrf::reg_form_Op) print(io," ileft=$(Wrf.ileft)\n, iright=$(Wrf.iright)\n, ul=$(Wrf.ul)\n\n") return show(io, Wrf.W) end ITensors.order(Wrf::reg_form_Op) = order(Wrf.W) ITensors.inds(Wrf::reg_form_Op;kwargs...) = inds(Wrf.W;kwargs...) ITensors.siteinds(Wrf::reg_form_Op) = noncommoninds(Wrf.W, Wrf.ileft, Wrf.iright) ITensors.linkinds(Wrf::reg_form_Op) = Wrf.ileft, Wrf.iright ITensors.linkinds(Wrf::reg_form_Op, lr::orth_type) = backward(Wrf, lr), forward(Wrf, lr) function ITensors.replacetags(Wrf::reg_form_Op, tsold, tsnew) Wrf.W = replacetags(Wrf.W, tsold, tsnew) Wrf.ileft = replacetags(Wrf.ileft, tsold, tsnew) Wrf.iright = replacetags(Wrf.iright, tsold, tsnew) return Wrf end function ITensors.replaceind(Wrf::reg_form_Op, iold::Index, inew::Index) W= replaceind(Wrf.W, iold, inew) if Wrf.ileft==iold ileft=inew iright=Wrf.iright elseif Wrf.iright==iold ileft=Wrf.ileft iright=inew else @assert false end return reg_form_Op(W,ileft,iright,Wrf.ul) end function ITensors.noprime(Wrf::reg_form_Op) Wrf.W = noprime(Wrf.W) Wrf.ileft = noprime(Wrf.ileft) Wrf.iright = noprime(Wrf.iright) return Wrf end # # Backward and forward indices for a given ortho direction. Sweep direction is opposite # to the ortho direction. Hence the mirror in forward case. # forward(Wrf::reg_form_Op, lr::orth_type) = Wrf[mirror(lr)] backward(Wrf::reg_form_Op, lr::orth_type) = Wrf[lr] # # Detection of upper/lower regular form # @doc """ detect_regular_form(W[,eps])::Tuple{Bool,Bool} Inspect the structure of an operator-valued matrix W to see if it satisfies the regular form conditions as specified in Section III, definition 3 of > *Daniel E. Parker, Xiangyu Cao, and Michael P. Zaletel Phys. Rev. B 102, 035147* # Arguments - `W::ITensor` : operator-valued matrix to be characterized. W is expected to have 2 "Site" indices and 1 or 2 "Link" indices @ Keywords - `eps::Float64 = 1e-14` : operators inside W with norm(W[i,j])<eps are assumed to be zero. # Returns a Tuple containing - `reg_lower::Bool` Indicates W is in lower regular form. - `reg_upper::Bool` Indicates W is in upper regular form. The function returns two Bools in order to handle cases where W is not in regular form, returning (false,false) and W is in a special pseudo diagonal regular form, returning (true,true). """ detect_regular_form(Wrf::reg_form_Op;kwargs...)::Tuple{Bool,Bool} = is_regular_form(Wrf, lower;kwargs...), is_regular_form(Wrf, upper;kwargs...) is_regular_form(Wrf::reg_form_Op;kwargs...)::Bool = is_regular_form(Wrf, Wrf.ul;kwargs...) function is_regular_form(Wrf::reg_form_Op, ul::reg_form;eps=default_eps,verbose=false)::Bool ul_cache = Wrf.ul Wrf.ul = mirror(ul) Wb = extract_blocks(Wrf, left; b=true, c=true, d=true) is = siteinds(Wrf) 𝕀 = delta(is) #We need to make our own, can't trust Wb.𝕀 is ul is wrong. dh = dim(is[1]) nr, nc = dims(Wrf) if (nc == 1 && ul == lower) || (nr == 1 && ul == upper) i1 = abs(scalar(dag(𝕀) * slice(Wrf.W, Wrf.ileft => 1, Wrf.iright => 1)) - dh) < eps iN = bz = cz = dz = true end if (nr == 1 && ul == lower) || (nc == 1 && ul == upper) iN = abs(scalar(dag(𝕀) * slice(Wrf.W, Wrf.ileft => nr, Wrf.iright => nc)) - dh) < eps i1 = bz = cz = dz = true end if nr > 1 && nc > 1 i1 = abs(scalar(dag(Wb.𝕀) * slice(Wrf.W, Wrf.ileft => 1, Wrf.iright => 1)) - dh) < eps iN = abs(scalar(dag(Wb.𝕀) * slice(Wrf.W, Wrf.ileft => nr, Wrf.iright => nc)) - dh) < eps bz = isnothing(Wb.𝐛̂) ? true : norm(Wb.𝐛̂) < eps cz = isnothing(Wb.𝐜̂) ? true : norm(Wb.𝐜̂) < eps dz = norm(Wb.𝐝̂) < eps end Wrf.ul = ul_cache if !(i1 && iN && bz && cz && dz) && verbose @warn "Non regular form tensor encountered." pprint(Wrf.W) @show ul nr nc i1 iN bz cz dz @show dh scalar(dag(𝕀) * slice(Wrf.W,Wrf.ileft=>1,Wrf.iright=>1)) Wb.𝕀 𝕀 end return i1 && iN && bz && cz && dz end # # Contract V blocks to test orthogonality. # function check_ortho(W::ITensor, lr::orth_type, ul::reg_form;kwargs...) il,ir=parse_links(W) if order(W)==3 T=eltype(W) if dim(il)==1 W*=onehot(T, il => 1) else W*=onehot(T, ir => 1) end end return check_ortho(reg_form_Op(W,il,ir,ul),lr;kwargs...) end function check_ortho(Wrf::reg_form_Op, lr::orth_type; eps=default_eps, verbose=false)::Bool Wb = extract_blocks(Wrf, lr; V=true) DwDw = dim(Wb.irV) * dim(Wb.icV) ilf = llur(Wrf, lr) ? Wb.icV : Wb.irV Id = Wb.𝐕̂ * prime(dag(Wb.𝐕̂), ilf) / d(Wb) if order(Id) == 2 is_can = norm(dense(Id) - delta(ilf, dag(ilf'))) / sqrt(DwDw) < eps if !is_can && verbose @show Id end elseif order(Id) == 0 is_can = abs(scalar(Id) - d(Wb)) < eps end return is_can end # # Overload * tensor contraction operators. Detect which link index ileft/iright is common with B # and replace it with the correct remaining link from B # function product(Wrf::reg_form_Op, B::ITensor)::reg_form_Op WB = Wrf.W * B ic = commonind(Wrf.W, B) @assert hastags(ic, "Link") new_index = noncommonind(B, ic, siteinds(Wrf)) if ic == Wrf.iright return reg_form_Op(WB, Wrf.ileft, new_index, Wrf.ul) elseif ic == Wrf.ileft return reg_form_Op(WB, new_index, Wrf.iright, Wrf.ul) else @assert false end end Base.:*(Wrf::reg_form_Op, B::ITensor)::reg_form_Op = product(Wrf, B) Base.:*(A::ITensor, Wrf::reg_form_Op)::reg_form_Op = product(Wrf, A)
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
10860
using StaticArrays import Base.range struct IndexRange index::Index range::UnitRange{Int64} function IndexRange(i::Index, r::UnitRange) return new(i, r) end end irPair{T} = Pair{<:Index{T},UnitRange{Int64}} where {T} irPairU{T} = Union{irPair{T},IndexRange} where {T} IndexRange(ir::irPair{T}) where {T} = IndexRange(ir.first, ir.second) IndexRange(ir::IndexRange) = IndexRange(ir.index, ir.range) start(ir::IndexRange) = range(ir).start starts(irs::Tuple{Vararg{UnitRange{Int64}}}) = map((ir) -> ir.start, irs) stops(irs::Tuple{Vararg{UnitRange{Int64}}}) = map((ir) -> ir.stop, irs) starts(irs::SVector{N,UnitRange{Int64}}) where {N} = map((ir) -> ir.start, irs) stops(irs::SVector{N,UnitRange{Int64}}) where {N} = map((ir) -> ir.stop, irs) range(ir::IndexRange) = ir.range range(i::Index) = 1:dim(i) ranges(irs::Tuple) = ntuple(i -> range(irs[i]), Val(length(irs))) ranges(starts::SVector{N,Int64},stops::SVector{N,Int64}) where {N} = map(i -> starts[i]:stops[i], 1:N) indices(irs::Tuple{Vararg{IndexRange}}) = map((ir) -> ir.index, irs) indranges(ips::Tuple{Vararg{irPairU}}) = map((ip) -> IndexRange(ip), ips) dim(ir::IndexRange) = dim(range(ir)) dim(r::UnitRange{Int64}) = r.stop - r.start + 1 dims(irs::Tuple{Vararg{IndexRange}}) = map((ir) -> dim(ir), irs) redim(ip::irPair) = redim(IndexRange(ip)) redim(ir::IndexRange) = redim(ir.index, dim(ir), start(ir) - 1) redim(irs::Tuple{Vararg{IndexRange}}) = map((ir) -> redim(ir), irs) eachval(ir::IndexRange) = range(ir) eachval(irs::Tuple{Vararg{IndexRange}}) = CartesianIndices(ranges(irs)) function eachindval(irs::Tuple{Vararg{IndexRange}}) return (indices(irs) .=> Tuple(ns) for ns in eachval(irs)) end #-------------------------------------------------------------------------------------- # # NDTensor level code which distinguishes between Dense and BlockSparse storage # function in_range( block_start::NTuple{N,Int64}, block_end::NTuple{N,Int64}, rs::UnitRange{Int64}... ) where {N} for i in eachindex(rs) (block_start[i] > rs[i].stop || block_end[i] < rs[i].start) && return false end return true end function fix_ranges( dest_block_start::SVector{N,Int64}, dest_block_end::SVector{N,Int64}, rs::SVector{N,UnitRange{Int64}} ) where {N} return ranges(max.(0,starts(rs)-dest_block_start).+1,min.(dest_block_end,stops(rs))-dest_block_start.+1) end function get_subtensor( T::BlockSparseTensor{ElT,N}, new_inds, rs::UnitRange{Int64}... ) where {ElT,N} Ds = Vector{DenseTensor{ElT,N}}() bs = Vector{Block{N}}() for b in eachnzblock(T) blockT = blockview(T, b) if in_range(blockstart(T,b),blockend(T,b),rs...)# && !isnothing(blockT) rs1=fix_ranges(SVector(blockstart(T,b)),SVector(blockend(T,b)),SVector(rs)) _,tb1=blockindex(T,starts(rs)...) tb1=CartesianIndex(ntuple(i->tb1[i]-1,N)) push!(Ds,blockT[rs1...]) push!(bs,CartesianIndex(b)-tb1) end end if length(Ds) == 0 return BlockSparseTensor(new_inds) end T_sub = BlockSparseTensor(ElT, undef, bs, new_inds) for ib in eachindex(Ds) blockT_sub = bs[ib] blockview(T_sub, blockT_sub) .= Ds[ib] end return T_sub end # # The code for diag and non-diag is the same. Use Union to capture this. # Not sure how to trap cross assignemnts like: DiagBlockSparseTensor[] = BlockSparseTensor[] # function set_subtensor( T::Union{BlockSparseTensor{ElT,N},DiagBlockSparseTensor{ElT,N}}, A::Union{BlockSparseTensor{ElT,N},DiagBlockSparseTensor{ElT,N}}, rs::UnitRange{Int64}... ) where {ElT,N} for ab in eachnzblock(A) blockA = blockview(A, ab) iT=SVector(blockstart(A, ab))+SVector(starts(rs)).-1 index_within_Tblock, tb = blockindex(T, iT...) # # Get a blockView. Insert a new block if we have to. # blockT = blockview(T, tb) if isnothing(blockT) insertblock!(T, tb) blockT = blockview(T, tb) end siwb=SVector(index_within_Tblock) dA=SVector(dims(blockA)) dT=SVector(blockend(T, tb))-siwb.+1 if all(dA.<=dT) #All of blockA fits inside blockT rs1=ranges(siwb,siwb+dA.-1) blockT[rs1...] = blockA #Dense assignment for each block else # rsa = ntuple(i -> 1:dim(inds(A)[i]), N) # rs1=ranges(siwb,siwb+min.(dA,dT).-1) # rsa1 = ntuple(i -> (rsa[i].start):(rsa[i].start + Base.min(dA[i], dT[i]) - 1), N) # blockT[rs1...] = blockA[rsa1...] #partial block Dense assignment for each block @error "Subtensor assign, Incomplete bloc transfer is not supported." @assert false end end # for for ab in eachnzblock(A) end function set_subtensor( T::DiagTensor{ElT}, A::DiagTensor{ElT}, rs::UnitRange{Int64}... ) where {ElT} if !all(y -> y == rs[1], rs) @error("set_subtensor(DiagTensor): All ranges must be the same, rs=$(rs).") end N = length(rs) #only assign along the diagonal. for i in rs[1] is = ntuple(i1 -> i, N) js = ntuple(j1 -> i - rs[1].start + 1, N) T[is...] = A[js...] end end function setindex!( T::BlockSparseTensor{ElT,N}, A::BlockSparseTensor{ElT,N}, irs::Vararg{UnitRange{Int64},N} ) where {ElT,N} return set_subtensor(T, A, irs...) end function setindex!( T::DiagTensor{ElT,N}, A::DiagTensor{ElT,N}, irs::Vararg{UnitRange{Int64},N} ) where {ElT,N} return set_subtensor(T, A, irs...) end function setindex!( T::DiagBlockSparseTensor{ElT,N}, A::DiagBlockSparseTensor{ElT,N}, irs::Vararg{UnitRange{Int64},N}, ) where {ElT,N} return set_subtensor(T, A, irs...) end #------------------------------------------------------------------------------------ # # ITensor level wrappers which allows us to handle the indices in a different manner # depending on dense/block-sparse # function get_subtensor_wrapper( T::DenseTensor{ElT,N}, new_inds, rs::UnitRange{Int64}... ) where {ElT,N} return ITensor(T[rs...], new_inds) end function get_subtensor_wrapper( T::BlockSparseTensor{ElT,N}, new_inds, rs::UnitRange{Int64}... ) where {ElT,N} return ITensor(get_subtensor(T, new_inds, rs...)) end function ITensors.permute(indsT::T, irs::IndexRange...) where {T<:(Tuple{Vararg{T,N}} where {N,T})} ispec = indices(irs) #indices caller specified ranges for inot = Tuple(noncommoninds(indsT, ispec)) #indices not specified by caller isort = ispec..., inot... #all indices sorted so user specified ones are first. isort_sub = redim(irs)..., inot... #all indices for subtensor p = getperm(indsT, ntuple(n -> isort[n], length(isort))) if !isperm(p) @show p ispec inot indsT isort end return NDTensors.permute(isort_sub, p), NDTensors.permute((ranges(irs)..., ranges(inot)...), p) end # # Use NDTensors T[3:4,1:3,1:6...] syntax to extract the subtensor. # function get_subtensor_ND(T::ITensor, irs::IndexRange...) isub, rsub = permute(inds(T), irs...) #get indices and ranges for the subtensor return get_subtensor_wrapper(tensor(T), isub, rsub...) #virtual dispatch based on Dense or BlockSparse end function match_tagplev(i1::Index, i2s::Index...) for i in eachindex(i2s) #@show i tags(i1) tags(i2s[i]) plev(i1) plev(i2s[i]) if tags(i1) == tags(i2s[i]) && plev(i1) == plev(i2s[i]) return i end end @error("match_tagplev: unable to find tag/plev for $i1 in Index set $i2s.") return nothing end function getperm_tagplev(s1, s2) N = length(s1) r = Vector{Int}(undef, N) return map!(i -> match_tagplev(s1[i], s2...), r, 1:length(s1)) end # # # Permute is1 to be in the order of is2. # BUT: match based on tags and plevs instread of IDs # function permute_tagplev(is1, is2) length(is1) != length(is2) && throw( ArgumentError( "length of first index set, $(length(is1)) does not match length of second index set, $(length(is2))", ), ) perm = getperm_tagplev(is1, is2) #@show perm is1 is2 return is1[invperm(perm)] end # This operation is non trivial because we need to # 1) Establish that the non-requested (not in irs) indices are identical (same ID) between T & A # 2) Establish that requested (in irs) indices have the same tags and # prime levels (dims are different so they cannot possibly have the same IDs) # 3) Use a combination of tags/primes (for irs indices) or IDs (for non irs indices) to permut # the indices of A prior to conversion to a Tensor. # function set_subtensor_ND(T::ITensor, A::ITensor, irs::IndexRange...) ireqT = indices(irs) #indices caller requested ranges for inotT = Tuple(noncommoninds(inds(T), ireqT)) #indices not requested by caller ireqA = Tuple(noncommoninds(inds(A), inotT)) #Get the requested indices for a inotA = Tuple(noncommoninds(inds(A), ireqA)) p=getperm(inotA,ntuple(n -> inotT[n], length(inotT))) inotA_sorted=NDTensors.permute(inotA,p) if length(ireqT) != length(ireqA) || inotA_sorted != inotT @show inotA inotT ireqT ireqA inotA != inotT length(ireqT) length(ireqA) @error( "subtensor assign, incompatable indices\ndestination inds=$(inds(T)),\n source inds=$(inds(A))." ) @assert(false) end isortT = ireqT..., inotT... #all indices sorted so user specified ones are first. p = getperm(inds(T), ntuple(n -> isortT[n], length(isortT))) # find p such that isort[p]==inds(T) rsortT = NDTensors.permute((ranges(irs)..., ranges(inotT)...), p) #sorted ranges for T ireqAp = permute_tagplev(ireqA, ireqT) #match based on tags & plev, NOT IDs since dims are different. isortA = NDTensors.permute((ireqAp..., inotA...), p) #inotA is the same inotT, using inotA here for a less confusing read. Ap = permute(A, isortA...; allow_alias=true) return tensor(T)[rsortT...] = tensor(Ap) end # function set_subtensor_ND(T::ITensor, v::Number, irs::IndexRange...) # ireqT = indices(irs) #indices caller requested ranges for # inotT = Tuple(noncommoninds(inds(T), ireqT)) #indices not requested by caller # isortT = ireqT..., inotT... #all indices sorted so user specified ones are first. # p = getperm(inds(T), ntuple(n -> isortT[n], length(isortT))) # find p such that isort[p]==inds(T) # rsortT = permute((ranges(irs)..., ranges(inotT)...), p) #sorted ranges for T # return tensor(T)[rsortT...] .= v # end getindex(T::ITensor, irs::Vararg{IndexRange,N}) where {N} = get_subtensor_ND(T, irs...) function getindex(T::ITensor, irs::Vararg{irPairU,N}) where {N} return get_subtensor_ND(T, indranges(irs)...) end function setindex!(T::ITensor, A::ITensor, irs::Vararg{IndexRange,N}) where {N} return set_subtensor_ND(T, A, irs...) end function setindex!(T::ITensor, A::ITensor, irs::Vararg{irPairU,N}) where {N} return set_subtensor_ND(T, A, indranges(irs)...) end # function setindex!(T::ITensor, v::Number, irs::Vararg{IndexRange,N}) where {N} # return set_subtensor_ND(T, v, irs...) # end # function setindex!(T::ITensor, v::Number, irs::Vararg{irPairU,N}) where {N} # return set_subtensor_ND(T, v, indranges(irs)...) # end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
4791
@doc """ truncate!(H::MPO,lr::orth_type) Compress an MPO using block respecting SVD techniques as described in > *Daniel E. Parker, Xiangyu Cao, and Michael P. Zaletel Phys. Rev. B 102, 035147* # Arguments - `H::MPO` : Matrix Product Operator to be truncated. If `H` is not already in the correct canonical form for compression, it will automatically be put into the correct form prior to compression. - `lr::orth_type` : Choose `left` or `right` orthgonal/canoncial form for the output. # Keywords - `cutoff::Float64 = 1e-15` : The `cutoff` allows the SVD algorithm to truncate as many states as possible while still ensuring a certain accuracy. # Returns - `Vector{Spectrum}`, one `Spectrum' for each bond on the lattice. # Example ```julia julia> using ITensors julia> using ITensorMPOCompression include("../test/hamiltonians/hamiltonians.jl") julia> N=10; #10 sites julia> NNN=7; #Include up to 7th nearest neighbour interactions julia> sites = siteinds("S=1/2",N); julia> H=transIsing_MPO(sites,NNN); # # Make sure we have a regular form or truncate! won't work. # julia> is_lower_regular_form(H)==true true julia> @show get_Dw(H) get_Dw(H) = [30, 30, 30, 30, 30, 30, 30, 30, 30] # # truncate! returns the spectrum of singular values at each bond. The largest # singular values are remaining well under control. i.e. no sign of divergences. # julia> @show truncate!(H,left); spectrums = Bond Ns max(s) min(s) Entropy Tr. Error 1 1 0.30739 3.07e-01 0.22292 0.00e+00 2 2 0.35392 3.49e-02 0.26838 0.00e+00 3 3 0.37473 2.06e-02 0.29133 0.00e+00 4 4 0.38473 1.77e-02 0.30255 0.00e+00 5 5 0.38773 7.25e-04 0.30588 0.00e+00 6 4 0.38473 1.77e-02 0.30255 0.00e+00 7 3 0.37473 2.06e-02 0.29133 0.00e+00 8 2 0.35392 3.49e-02 0.26838 0.00e+00 9 1 0.30739 3.07e-01 0.22292 0.00e+00 julia> pprint(H[2]) I 0 0 0 S S S 0 0 S S I # # We can see that bond dimensions have been drastically reduced. # julia> get_Dw(H) 9-element Vector{Int64}: 3 4 5 6 7 6 5 4 3 julia> is_lower_regular_form(H)==true true julia> isortho(H,left)==true true ``` """ function truncate!(H::MPO, lr::orth_type; kwargs...)::bond_spectrums Hrf = reg_form_MPO(H) ss=truncate!(Hrf, lr; kwargs...) copy!(H,Hrf) return ss end function truncate( Ŵrf::reg_form_Op, lr::orth_type; kwargs... )::Tuple{reg_form_Op,ITensor,Spectrum} @mpoc_assert Ŵrf.ul==lower ilf = forward(Ŵrf, lr) # l=n-1 l=n l=n-1 l=n l=n # ------W---- --> -----Q-----R----- # ilf iqx ilf Q̂, R, iqx = ac_qx(Ŵrf, lr; qprime=true, kwargs...) #left Q[r,qx], R[qx,c] - right R[r,qx] Q[qx,c] @checkflux(Q̂.W) @checkflux(R) if dim(ilf)>dim(iqx) @warn "Truncate bail out, dim(ilf)=$(dim(ilf)), dim(iqx)=$(dim(iqx))" return noprime(Q̂), noprime(R), Spectrum(nothing,0.0) end @mpoc_assert dim(ilf) == dim(iqx) #Rectanuglar not allowed # # Factor RL=M*L' (left/lower) = L'*M (right/lower) = M*R' (left/upper) = R'*M (right/upper) # M will be returned as a Dw-2 X Dw-2 interior matrix. M_sans in the Parker paper. # Dw = dim(iqx) M = R[dag(iqx) => 2:(Dw - 1), ilf => 2:(Dw - 1)] M = replacetags(M, tags(ilf), "Link,m"; plev=0) # l=n' l=n l=n' m l=n # ------R---- ---> -----M------R'---- # iqx' ilf iqx' im ilf R⎖, im = build_R⎖(R, iqx, ilf) #left M[lq,im] RL_prime[im,c] - right RL_prime[r,im] M[im,lq] # # svd decomp M. # isvd = inds(M; tags=tags(iqx))[1] #decide the backward index for svd. Works for both sweep directions. U, s, V, spectrum, iu, iv = svd(M, isvd; kwargs...) # ns sing. values survive compression #@show diag(array(s)) # # Now recontrsuct R, and W in the truncated space. # iup = redim(iu, 1, 1, space(iqx)) R = grow(s * V, iup, im) * R⎖ #RL[l=n,u] dim ns+2 x Dw2 Uplus = grow(U, dag(iqx), dag(iup)) Uplus = noprime(Uplus, iqx) Ŵrf = Q̂ * Uplus #W[l=n-1,u] R = replacetags(R, "Link,u", tags(ilf)) #RL[l=n,l=n] sames tags, different id's and possibly diff dimensions. Ŵrf = replacetags(Ŵrf, "Link,u", tags(ilf)) #W[l=n-1,l=n] check(Ŵrf) return Ŵrf, R, spectrum end function truncate!(H::reg_form_MPO, lr::orth_type; kwargs...)::bond_spectrums #Two sweeps are essential for avoiding rectangular R in site truncate. if !isortho(H) orthogonalize!(H, lr; kwargs...) orthogonalize!(H, mirror(lr); kwargs...) end gauge_fix!(H) ss = bond_spectrums(undef, 0) rng = sweep(H, lr) for n in rng nn = n + rng.step H[n], R, s = truncate(H[n], lr; kwargs...) H[nn] *= R push!(ss, s) end H.rlim = rng.stop + rng.step + 1 H.llim = rng.stop + rng.step - 1 return ss end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
6878
using Printf function is_unit(O::ITensor, eps::Float64)::Bool s = inds(O) ITensors.@debug_check begin @mpoc_assert(length(s) == 2) end Id = delta(s[1], s[2]) if hasqns(s) nm = 0.0 for b in eachnzblock(Id) isv = [s[i] => b[i] for i in 1:length(b)] nm += abs(O[isv...] - Id[isv...]) end return nm < eps else return norm(O - Id) < eps end end function to_char(O::ITensor, eps::Float64)::Char c = '0' if is_unit(O, eps) c = 'I' elseif norm(O) > eps c = 'S' end return c end function to_char(O::Float64, eps::Float64)::Char c = '0' if abs(O - 1.0) < eps c = 'I' elseif abs(O) > eps c = 'S' end return c end @doc """ pprint(W[,eps]) Show (pretty print) a schematic view of an operator-valued matrix. In order to display any `ITensor` as a matrix one must decide which index to use as the row index, and similarly for the column index. `pprint` does this by inspecting the indices with "Site" tags to get the site number, and uses the "Link" indices `l=\$n` as the column and `l=\$(n-1)` as the row. The output symbols I,0,S have the obvious interpretations and S just means any (non zero) operator that is not I. This function can obviously be enhanced to recognize and display other symbols like X,Y,Z ... instead of just S. # Arguments - `W::ITensor` : Operator-valued matrix for display. - `eps::Float64 = 1e-14` : operators inside W with norm(W[i,j])<eps are assumed to be zero. # Examples ```julia julia> pprint(W) I 0 0 0 0 S 0 0 0 0 S 0 0 0 0 0 0 I 0 0 0 S 0 S I ``` """ function pprint(W::ITensor, eps::Float64=default_eps) r, c = parse_links(W) return pprint(r, W, c, eps) end function pprint(W::ITensor, c::Index, eps::Float64=default_eps) r, = noncommoninds(W, c; tags="Link") @mpoc_assert length(c) == 1 return pprint(r, W, c, eps) end function pprint(r::Index, W::ITensor, eps::Float64=default_eps) c, = noncommoninds(W, r; tags="Link") @mpoc_assert length(c) == 1 return pprint(r, W, c, eps) end macro pprint(W) quote println($(string(W)), " = ") pprint($(esc(W))) end end function Base.show(io::IO, ss::bond_spectrums) N = length(ss) print(io, "\nBond Ns max(s) min(s) Entropy Tr. Error\n") for n in 1:N s = ss[n] if length(s.eigs) > 0 @printf( io, "%4i %4i %1.5f %1.2e %1.5f %1.2e\n", n, length(s.eigs), max(s), min(s), entropy(s), truncerror(s) ) else @printf( io, "%4i %4i ------- -------- ------- %1.2e\n", n, length(s.eigs), truncerror(s) ) end end end function pprint(r::Index, W::ITensor, c::Index, eps::Float64=default_eps) # @mpoc_assert hasind(W,r) can't assume this becuse parse_links could return a Dw=1 dummy index. # @mpoc_assert hasind(W,c) isl = filterinds(W; tags="Link") ord = order(W) if length(isl) == 2 for ir in eachindval(r) for ic in eachindval(c) if ord == 4 Oij = slice(W, ir, ic) else @mpoc_assert ord == 2 Oij = abs(W[ir, ic]) end Base.print(to_char(Oij, eps)) Base.print(" ") end Base.print("\n") end elseif length(isl) == 1 for i in eachindval(isl[1]) Oij = slice(W, i) Base.print(to_char(Oij, eps)) Base.print(" ") end Base.print("\n") end return Base.print("\n") end pprint(Wrf::reg_form_Op)=pprint(Wrf.ileft,Wrf.W,Wrf.iright) @doc """ pprint(H[,eps]) Display the structure of an MPO, one line for each lattice site. For each site the table lists - n : lattice site number - Dw1 : dimension of the row index (left link index) - Dw2 : dimension of the column index (right link index) - d : dimension of the local Hilbert space - Reg. Form : U=upper, L=lower, D=diagonal, No = Not reg. form. - Orth. Form : L=left, R=right, M=not orthogonal, B=both left and right. Be careful when reading the L symbols. L stands for Left in the Orth. column but is stands for Lower in the other two columns. # Arguments - `H::MPO` : MPO for display. - `eps::Float64 = 1e-14` : operators inside H with norm(W[i,j])<eps are assumed to be zero. # Examples ```julia julia> using ITensors julia> using ITensorMPOCompression julia> N=10; #10 sites julia> NNN=7; #Include up to 7th nearest neighbour interactions julia> sites = siteinds("S=1/2",N); julia> H=transIsing_MPO(sites,NNN); julia> pprint(H) n Dw1 Dw2 d Reg. Orth. Tri. Form Form Form 1 1 30 2 L M R 2 30 30 2 L M L 3 30 30 2 L M L 4 30 30 2 L M L 5 30 30 2 L M L 6 30 30 2 L M L 7 30 30 2 L M L 8 30 30 2 L M L 9 30 30 2 L M L 10 30 1 2 L M C julia> orthogonalize!(H,orth=right) julia> pprint(H) n Dw1 Dw2 d Reg. Orth. Tri. Form Form Form 1 1 3 2 L M R 2 3 4 2 L R L 3 4 5 2 L R L 4 5 6 2 L R L 5 6 7 2 L R L 6 7 6 2 L R L 7 6 5 2 L R L 8 5 4 2 L R L 9 4 3 2 L R L 10 3 1 2 L R C julia> truncate!(H,orth=left) julia> pprint(H) n Dw1 Dw2 d Reg. Orth. Tri. Form Form Form 1 1 3 2 L L R 2 3 4 2 L L L 3 4 5 2 L L F 4 5 6 2 L L F 5 6 7 2 L L F 6 7 6 2 L L F 7 6 5 2 L L F 8 5 4 2 L L F 9 4 3 2 L L L 10 3 1 2 L M C ``` """ function pprint(H::MPO, eps::Float64=default_eps) pprint(reg_form_MPO(copy(H)),eps) end function pprint(H::reg_form_MPO, eps::Float64=default_eps) N = length(H) println(" n Dw1 Dw2 d Reg. Orth.") println(" Form Form ") for n in 1:N Dw1, Dw2, d, l, u, lr = get_traits(H[n], eps) #println(" $n $Dw1 $Dw2 $d $l$u $lr $lt$ut") @printf "%4i %4i %4i %4i %s%s %s\n" n Dw1 Dw2 d l u lr end end function get_directions(psi::AbstractMPS) return map(n -> dir(inds(psi[n]; tags="Link,l=$n")[1]), 1:(length(psi) - 1)) end function show_directions(psi::AbstractMPS) dirs = get_directions(psi) n = 1 for d in dirs print(" $n ") if d == ITensors.In print("<--") elseif d == ITensors.Out print("-->") elseif d == ITensors.Neither print("???") else @assert(false) end n += 1 end return print(" $n \n") end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
5665
using ITensors using ITensorMPOCompression using Test using Revise, Printf include("hamiltonians/hamiltonians.jl") Base.show(io::IO, f::Float64) = @printf(io, "%1.3f", f) #dumb way to control float output import ITensorMPOCompression: extract_blocks, regform_blocks @testset "Extract blocks qns=$qns, ul=$ul" for qns in [false, true], ul in [lower, upper] eps = 1e-15 N = 5 #5 sites NNN = 2 #Include 2nd nearest neighbour interactions sites = siteinds("Electron", N; conserve_qns=qns) d = dim(inds(sites[1])[1]) H = reg_form_MPO(Hubbard_AutoMPO(sites, NNN; ul=ul);honour_upper=true) lr = ul == lower ? left : right Wrf = H[1] nr, nc = dims(Wrf) #pprint(Wrf.W) Wb = extract_blocks(Wrf, lr; all=true, V=true) @test norm(matrix(Wb.𝕀) - 1.0 * Matrix(LinearAlgebra.I, d, d)) < eps @test isnothing(Wb.𝐀̂) if ul == lower @test isnothing(Wb.𝐛̂) @test norm(array(Wb.𝐝̂) - array(Wrf[nr:nr, 1:1])) < eps @test norm(array(Wb.𝐜̂) - array(Wrf[nr:nr, 2:(nc - 1)])) < eps else @test isnothing(Wb.𝐜̂) @test norm(array(Wb.𝐝̂) - array(Wrf[1:1, nc:nc])) < eps @test norm(array(Wb.𝐛̂) - array(Wrf[1:1, 2:(nc - 1)])) < eps end @test norm(array(Wb.𝐕̂) - array(Wrf[1:1, 2:nc])) < eps Wrf = H[N] nr, nc = dims(Wrf) Wb = extract_blocks(Wrf, lr; all=true, V=true, fix_inds=true) @test norm(matrix(Wb.𝕀) - 1.0 * Matrix(LinearAlgebra.I, d, d)) < eps @test isnothing(Wb.𝐀̂) if ul == lower @test isnothing(Wb.𝐜̂) @test norm(array(Wb.𝐝̂) - array(Wrf[nr:nr, 1:1])) < eps @test norm(array(Wb.𝐛̂) - array(Wrf[2:(nr - 1), 1:1])) < eps else @test isnothing(Wb.𝐛̂) @test norm(array(Wb.𝐝̂) - array(Wrf[1:1, nc:nc])) < eps @test norm(array(Wb.𝐜̂) - array(Wrf[2:(nr - 1), nc:nc])) < eps end @test norm(array(Wb.𝐕̂) - array(Wrf[2:nr, 1:1])) < eps Wrf = H[2] nr, nc = dims(Wrf) Wb = extract_blocks(Wrf, lr; all=true, V=true, fix_inds=true, Ac=true) if ul == lower @test norm(matrix(Wb.𝕀) - 1.0 * Matrix(LinearAlgebra.I, d, d)) < eps @test norm(array(Wb.𝐝̂) - array(Wrf[nr:nr, 1:1])) < eps @test norm(array(Wb.𝐛̂) - array(Wrf[2:(nr - 1), 1:1])) < eps @test norm(array(Wb.𝐜̂) - array(Wrf[nr:nr, 2:(nc - 1)])) < eps @test norm(array(Wb.𝐀̂) - array(Wrf[2:(nr - 1), 2:(nc - 1)])) < eps @test norm(array(Wb.𝐀̂𝐜̂) - array(Wrf[2:nr, 2:(nc - 1)])) < eps else @test norm(matrix(Wb.𝕀) - 1.0 * Matrix(LinearAlgebra.I, d, d)) < eps @test norm(array(Wb.𝐝̂) - array(Wrf[1:1, nc:nc])) < eps @test norm(array(Wb.𝐛̂) - array(Wrf[1:1, 2:(nc - 1)])) < eps @test norm(array(Wb.𝐜̂) - array(Wrf[2:(nr - 1), nc:nc])) < eps @test norm(array(Wb.𝐀̂) - array(Wrf[2:(nr - 1), 2:(nc - 1)])) < eps @test norm(array(Wb.𝐀̂𝐜̂) - array(Wrf[2:(nr - 1), 2:nc])) < eps end @test norm(array(Wb.𝐕̂) - array(Wrf[2:nr, 2:nc])) < eps end @testset "Extract blocks MPO with fix_inds=true ul=$ul" for ul in [lower, upper] N = 5 #5 sites NNN = 2 #Include 2nd nearest neighbour interactions sites = siteinds("Electron", N; conserve_qns=false) d = dim(inds(sites[1])[1]) H = reg_form_MPO(Hubbard_AutoMPO(sites, NNN; ul=ul);honour_upper=true) lr = ul == lower ? left : right Wrf = H[1] Wb = extract_blocks(Wrf, lr; fix_inds=true) if lr==left @test hasinds(Wb.𝐜̂,Wb.irc,Wb.icc) @test hasinds(Wb.𝐝̂,Wb.ird,Wb.icd) @test Wb.ird==Wb.irc else @test hasinds(Wb.𝐛̂,Wb.irb,Wb.icb) @test hasinds(Wb.𝐝̂,Wb.ird,Wb.icd) @test Wb.icd==Wb.icb end Wrf = H[N] Wb = extract_blocks(Wrf, lr; fix_inds=true) if lr==right @test hasinds(Wb.𝐜̂,Wb.irc,Wb.icc) @test hasinds(Wb.𝐝̂,Wb.ird,Wb.icd) @test Wb.ird==Wb.irc else @test hasinds(Wb.𝐛̂,Wb.irb,Wb.icb) @test hasinds(Wb.𝐝̂,Wb.ird,Wb.icd) @test Wb.icd==Wb.icb end Wrf = H[2] Wb = extract_blocks(Wrf, lr; fix_inds=true) @test hasinds(Wb.𝐀̂,Wb.irA,Wb.icA) @test hasinds(Wb.𝐛̂,Wb.irb,Wb.icb) @test hasinds(Wb.𝐜̂,Wb.irc,Wb.icc) @test hasinds(Wb.𝐝̂,Wb.ird,Wb.icd) @test Wb.ird==Wb.irc @test Wb.icd==Wb.icb @test Wb.irA==Wb.irb end @testset "Detect regular form qns=$qns, ul=$ul" for qns in [false, true], ul in [lower, upper] eps = 1e-15 N = 5 #5 sites NNN = 2 #Include 2nd nearest neighbour interactions sites = siteinds("Electron", N; conserve_qns=qns) H = reg_form_MPO(Hubbard_AutoMPO(sites, NNN; ul=ul);honour_upper=true) for W in H @test is_regular_form(W, ul;eps=eps) @test dim(W.ileft) == 1 || dim(W.iright) == 1 || !is_regular_form(W, mirror(ul);eps=eps) end end @testset "Sub tensor assign for block sparse matrices with compatable QN spaces" begin qns=[QN("Sz",0)=>1,QN("Sz",0)=>3,QN("Sz",0)=>2] i,j=Index(qns,"i"),Index(qns,"j") A=randomITensor(i,j) nr,nc=dims(A) B=copy(A) for dr in 0:nr-1 for dc in 0:nc-1 #@show dr dc nr-dr nc-dc B[i=>1:nr-dr,j=>1:nc-dc]=A[i=>1:nr-dr,j=>1:nc-dc] @test norm(B-A)==0 B[i=>1+dr:nr,j=>1:nc-dc]=A[i=>1+dr:nr,j=>1:nc-dc] @test norm(B-A)==0 end end end # # This is a tough nut to crack. But it is not needed for MPO compression. # # @testset "Sub tensor assign for block sparse matrices with in-compatable QN spaces" begin # qns=[QN("Sz",0)=>1,QN("Sz",0)=>3,QN("Sz",0)=>2] # qnsC=[QN("Sz",0)=>2,QN("Sz",0)=>2,QN("Sz",0)=>2] #purposely miss allgined. # i,j=Index(qns,"i"),Index(qns,"j") # A=randomITensor(i,j) # nr,nc=dims(A) # ic,jc=Index(qnsC,"i"),Index(qnsC,"j") # C=randomITensor(ic,jc) # @show dense(A) dense(C) # C[ic=>1:nr,jc=>1:nc]=A[i=>1:nr,j=>1:nc] # @show matrix(A)-matrix(C) # @test norm(matrix(A)-matrix(C))==0 # end nothing
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
1223
using ITensors using ITensorMPOCompression using Test using Revise, Printf, SparseArrays include("hamiltonians/hamiltonians.jl") import ITensorMPOCompression: gauge_fix!, is_gauge_fixed Base.show(io::IO, f::Float64) = @printf(io, "%1.3f", f) #dumb way to control float output models = [ [transIsing_MPO, "S=1/2", true], [transIsing_AutoMPO, "S=1/2", true], [Heisenberg_AutoMPO, "S=1/2", true], [Heisenberg_AutoMPO, "S=1", true], [Hubbard_AutoMPO, "Electron", false], ] @testset "Gauge fix finite $(model[1]), qns=$qns, ul=$ul" for model in models, qns in [false, true], ul in [lower, upper] eps = 1e-14 N = 10 #5 sites NNN = 4 #Include 2nd nearest neighbour interactions sites = siteinds(model[2], N; conserve_qns=qns) Hrf = reg_form_MPO(model[1](sites, NNN; ul=ul)) pre_fixed = model[3] #Hamiltonian starts gauge fixed state = [isodd(n) ? "Up" : "Dn" for n in 1:N] H = MPO(Hrf) psi = randomMPS(sites, state) E0 = inner(psi', H, psi) @test is_regular_form(Hrf) @test pre_fixed == is_gauge_fixed(Hrf; eps=eps) gauge_fix!(Hrf) @test is_regular_form(Hrf) @test is_gauge_fixed(Hrf; eps=eps) He = MPO(Hrf) E1 = inner(psi', He, psi) @test E0 ≈ E1 atol = eps end nothing
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
6266
using ITensors using ITensorMPOCompression using Revise using Test include("hamiltonians/hamiltonians.jl") import ITensorMPOCompression: transpose, orthogonalize!, redim # using Printf # Base.show(io::IO, f::Float64) = @printf(io, "%1.3e", f) function random_qindex(d::Int64, nq::Int64)::Index qns = Pair{QN,Int64}[] for n in 1:nq append!(qns, [QN() => rand(1:d)]) end return Index(qns, "Link,l=1") end @testset verbose = true "Hamiltonians" begin NNEs = [ (1, -1.5066685458330529), (2, -1.4524087749432490), (3, -1.4516941302867301), (4, -1.4481111362390489), ] @testset "MPOs hand coded versus autoMPO give same GS energies" for nne in NNEs N = 5 model_kwargs = (hx=0.5,) eps = 4e-14 #this is right at the lower limit for passing the tests. NNN = nne[1] Eexpected = nne[2] sites = siteinds("SpinHalf", N; conserve_qns=false) ITensors.ITensors.disable_debug_checks() #dmrg crashes when this in. # # Use autoMPO to make H # Hauto = transIsing_AutoMPO(sites, NNN; model_kwargs...) Eauto, psi = fast_GS(Hauto, sites) @test Eauto ≈ Eexpected atol = eps Eauto1 = inner(psi', Hauto, psi) @test Eauto1 ≈ Eexpected atol = eps # # Make H directly ... should be lower triangular # Hdirect = transIsing_MPO(sites, NNN; model_kwargs...) #defaults to lower reg form #@show Hauto[1] Hdirect[1] @test order(Hdirect[1]) == 3 @test inner(psi', Hdirect, psi) ≈ Eexpected atol = eps Edirect, psidirect = fast_GS(Hdirect, sites) @test Edirect ≈ Eexpected atol = eps overlap = abs(inner(psi, psidirect)) @test overlap ≈ 1.0 atol = eps end @testset "Redim function with non-trivial QN spaces" begin for offset in 0:2 for d in 1:5 for nq in 1:5 il = random_qindex(d, nq) Dw = dim(il) if Dw > 1 + offset ilr = redim(il, Dw - offset - 1, offset) @test dim(ilr) == Dw - offset - 1 end end #for nq end #for d end #for offset end #@testset makeHs = [transIsing_AutoMPO, transIsing_MPO, Heisenberg_AutoMPO] @testset "Auto MPO Ising Ham with Sz blocking" for makeH in makeHs N = 5 eps = 4e-14 #this is right at the lower limit for passing the tests. NNN = 2 sites = siteinds("SpinHalf", N; conserve_qns=true) H = makeH(sites, NNN; ul=lower) il = filterinds(inds(H[2]); tags="Link") for i in 1:2 for start_offset in 0:2 for end_offset in 0:2 Dw = dim(il[i]) Dw_new = Dw - start_offset - start_offset if Dw_new > 0 ilr = redim(il[i], Dw_new, start_offset) @test dim(ilr) == Dw_new end #if end #for end_offset end #for start_offset end #for i end #@testset @testset "hand coded versus autoMPO with conserve_qns=true have the same index directions" begin N = 5 hx = 0.0 #Hx!=0 breaks symmetry. eps = 4e-14 #this is right at the lower limit for passing the tests. NNN = 2 sites = siteinds("SpinHalf", N; conserve_qns=true) Hauto = transIsing_AutoMPO(sites, NNN) Hhand = transIsing_MPO(sites, NNN) for (Wauto, Whand) in zip(Hauto, Hhand) for ia in inds(Wauto) ih = filterinds(Whand; tags=tags(ia), plev=plev(ia))[1] @test dir(ia) == dir(ih) end end end @testset "Parker eq. 34 3-body Hamiltonian" begin N = 15 sites = siteinds("SpinHalf", N; conserve_qns=false) Hnot = three_body_AutoMPO(sites; cutoff=-1.0) #No truncation inside autoMPO H = three_body_AutoMPO(sites; cutoff=1e-15) #Truncated by autoMPO psi = randomMPS(sites) Enot = inner(psi', Hnot, psi) E = inner(psi', H, psi) #@show E-Enot get_Dw(Hnot) get_Dw(H) @test E ≈ Enot atol = 3e-9 end function verify_links(H::MPO) N = length(H) @test order(H[1]) == 3 @test hastags(H[1], "Link,l=1") @test hastags(H[1], "Site,n=1") for n in 2:(N - 1) @test order(H[n]) == 4 @test hastags(H[n], "Link,l=$(n-1)") @test hastags(H[n], "Link,l=$n") @test hastags(H[n], "Site,n=$n") il, = inds(H[n - 1]; tags="Link,l=$(n-1)") ir, = inds(H[n]; tags="Link,l=$(n-1)") @test id(il) == id(ir) end @test order(H[N]) == 3 @test hastags(H[N], "Link,l=$(N-1)") @test hastags(H[N], "Site,n=$N") il, = inds(H[N - 1]; tags="Link,l=$(N-1)") ir, = inds(H[N]; tags="Link,l=$(N-1)") @test id(il) == id(ir) end makeHs = [ (transIsing_MPO, "S=1/2"), (transIsing_AutoMPO, "S=1/2"), (Heisenberg_AutoMPO, "S=1/2"), (Hubbard_AutoMPO, "Electron"), ] @testset "Reg for H=$(makeH[1]), ul=$ul, qns=$qns" for makeH in makeHs, qns in [false, true], ul in [lower, upper] N = 5 sites = siteinds(makeH[2], N; conserve_qns=qns) H = makeH[1](sites, 2; ul=ul) @test is_regular_form(H, ul) @test hasqns(H[1]) == qns verify_links(H) end models = [ (transIsing_MPO, "S=1/2", true), (transIsing_AutoMPO, "S=1/2", true), (Heisenberg_AutoMPO, "S=1/2", true), (Heisenberg_AutoMPO, "S=1", true), (Hubbard_AutoMPO, "Electron", false), ] @testset "Convert upper MPO to lower, H=$(model[1]), qns=$qns" for model in models, qns in [false,true] N,NNN=5,2 sites = siteinds(model[2], N; conserve_qns=qns) Hu = reg_form_MPO(model[1](sites, NNN;ul=upper);honour_upper=true) @test is_regular_form(Hu) @test Hu.ul==upper Hl = transpose(Hu) @test Hu.ul==upper @test is_regular_form(Hu) @test Hl.ul==lower @test is_regular_form(Hl) @test !check_ortho(Hu,left) @test !check_ortho(Hl,left) @test !check_ortho(Hu,right) @test !check_ortho(Hl,right) Hl1=MPO(Hl) @test order(Hl1[1])==3 @test order(Hl1[N])==3 orthogonalize!(Hl,left) @test Hu.ul==upper @test is_regular_form(Hu) @test Hl.ul==lower @test is_regular_form(Hl) @test check_ortho(Hl,left) @test !check_ortho(Hu,left) @test !check_ortho(Hu,right) Hu1=transpose(Hl) #@test check_ortho(Hu1,right) @test check_ortho(Hu1,left) Hl1=MPO(Hl) @test order(Hl1[1])==3 @test order(Hl1[N])==3 end end #Hamiltonians testset nothing
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
3817
using ITensors using ITensorMPOCompression using Revise using Test using Printf include("hamiltonians/hamiltonians.jl") import ITensorMPOCompression: gauge_fix!, is_gauge_fixed Base.show(io::IO, f::Float64) = @printf(io, "%1.3f", f) #dumb way to control float output verbose = false #verbose at the outer test level verbose1 = false #verbose inside orth algos @testset verbose = verbose "Orthogonalize" begin models = [ [transIsing_MPO, "S=1/2", true], [transIsing_AutoMPO, "S=1/2", true], [Heisenberg_AutoMPO, "S=1/2", true], [Heisenberg_AutoMPO, "S=1", true], [Hubbard_AutoMPO, "Electron", false], ] @testset "Ac/Ab block respecting decomposition $(model[1]), qns=$qns, ul=$ul" for model in models, qns in [false, true], ul in [lower, upper] eps = 1e-14 pre_fixed = model[3] #Hamiltonian starts gauge fixed N = 10 #5 sites NNN = 4 #Include 6nd nearest neighbour interactions sites = siteinds(model[2], N; conserve_qns=qns) Hrf = reg_form_MPO(model[1](sites, NNN; ul=ul)) state = [isodd(n) ? "Up" : "Dn" for n in 1:N] psi = randomMPS(sites, state) E0 = inner(psi', MPO(Hrf), psi) @test is_regular_form(Hrf) # # Left->right sweep # lr = left @test pre_fixed == is_gauge_fixed(Hrf) NNN >= 7 && orthogonalize!(Hrf, right) orthogonalize!(Hrf, left) @test is_regular_form(Hrf) @test check_ortho(Hrf, left) @test isortho(Hrf, left) NNN < 7 && @test is_gauge_fixed(Hrf) #Now everything should be fixed, unless NNN is big # # Expectation value check. # E1 = inner(psi', MPO(Hrf), psi) @test E0 ≈ E1 atol = eps # # Right->left sweep # orthogonalize!(Hrf, right) @test is_regular_form(Hrf) @test check_ortho(Hrf, right) @test isortho(Hrf, right) @test is_gauge_fixed(Hrf) #Should still be gauge fixed # # # Expectation value check. # # E2 = inner(psi', MPO(Hrf), psi) @test E0 ≈ E2 atol = eps end @testset "Ortho center options" for N = 10 #5 sites NNN = 4 #Include 4th nearest neighbour interactions sites = siteinds("Electron", N; conserve_qns=false) H=Hubbard_AutoMPO(sites, NNN) for j=1:N Hj=copy(H) @test !check_ortho(Hj,left) @test !check_ortho(Hj,right) @test !isortho(Hj,left) @test !isortho(Hj,right) orthogonalize!(Hj,j) for j1 in 1:j-1 @test check_ortho(Hj[j1],left,lower) @test !check_ortho(Hj[j1],right,lower) end for j1 in j+1:N @test !check_ortho(Hj[j1],left,lower) @test check_ortho(Hj[j1],right,lower) end end orthogonalize!(H,left) for j=1:N Hj=copy(H) @test check_ortho(Hj,left) @test !check_ortho(Hj,right) @test isortho(Hj,left) @test !isortho(Hj,right) orthogonalize!(Hj,j) for j1 in 1:j-1 @test check_ortho(Hj[j1],left,lower) @test !check_ortho(Hj[j1],right,lower) end for j1 in j+1:N @test !check_ortho(Hj[j1],left,lower) @test check_ortho(Hj[j1],right,lower) end end end @testset "Compare Dws for Ac orthogonalized hand built MPO, vs Auto MPO, NNN=$NNN, ul=$ul, qns=$qns" for NNN in [ 1, 5, 8, 12 ], ul in [lower, upper], qns in [false, true] N = 2 * NNN + 4 sites = siteinds("S=1/2", N; conserve_qns=qns) Hhand = reg_form_MPO(transIsing_MPO(sites, NNN; ul=ul)) Hauto = transIsing_AutoMPO(sites, NNN; ul=ul) orthogonalize!(Hhand, right) orthogonalize!(Hhand, left) @test get_Dw(Hhand) == get_Dw(Hauto) end end nothing
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
2356
using ITensors using ITensorMPOCompression using Test using Printf include("hamiltonians/hamiltonians.jl") import ITensorMPOCompression: sweep, ac_qx #using Printf #Base.show(io::IO, f::Float64) = @printf(io, "%1.3f", f) #println("-----------Start--------------") models = [ [transIsing_MPO, "S=1/2", true], [transIsing_AutoMPO, "S=1/2", true], [Heisenberg_AutoMPO, "S=1/2", true], [Heisenberg_AutoMPO, "S=1", true], [Hubbard_AutoMPO, "Electron", false], ] @testset "Ac Block respecting QX decomposition $(model[1]), qns=$qns, ul=$ul, lr=$lr" for model in models, qns in [false, true], ul in [lower, upper], lr in [right, left] N = 6 NNN = 4 model_kwargs = (hx=0.5, ul=ul) eps = 1e-15 sites = siteinds(model[2], N) pre_fixed = model[3] #Hamiltonian starts gauge fixed # # test lower triangular MPO # H = reg_form_MPO(model[1](sites, NNN)) rng = sweep(H, lr) for n in rng W = H[n] @test is_regular_form(W) W1, X, lq = ac_qx(W, lr; cutoff=1e-14) @test pre_fixed == check_ortho(W1, lr;eps=eps) end end @testset "QR,QL,LQ,RQ decomposition with rank revealing" begin N = 10 NNN = 6 model_kwargs = (hx=0.5, ul=lower) eps = 2e-15 rr_cutoff = 1e-15 sites = siteinds("SpinHalf", N) # # use lower tri MPO to get some zero pivots for QL and RQ. # H = transIsing_MPO(sites, NNN; model_kwargs...) W = H[2] r, c = parse_links(W) Lind = noncommoninds(inds(W), c) Rind = noncommoninds(inds(W), r) @assert dim(c) == dim(r) # # use upper tri MPO to get some zero pivots for LQ and QR. # model_kwargs = (hx=0.5, ul=upper) H = transIsing_MPO(sites, NNN; model_kwargs...) W = H[2] r, c = parse_links(W) Lind = noncommoninds(inds(W), c) Rind = noncommoninds(inds(W), r) @assert dim(c) == dim(r) # # QR decomp # Q, R, iq = qr(W, Rind; positive=true, atol=rr_cutoff) @test dim(c) - dim(iq) == 5 #make sure rank reduction worked. @test Q * prime(Q, iq) ≈ δ(Float64, iq, iq') atol = eps @test W ≈ R * Q atol = eps # # LQ decomp # L, Q, iq = lq(W, r; positive=true, atol=rr_cutoff) @test dim(c) - dim(iq) == 5 #make sure rank reduction worked. @test Q * prime(Q, iq) ≈ δ(Float64, iq, iq') atol = eps @test W ≈ L * Q atol = eps end nothing
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
400
using ITensors using ITensorMPOCompression using Test using Revise @testset "ITensorMPOCompression.jl" begin @testset verbose = true "$filename" for filename in [ "blocking.jl", "gauge_fix.jl", "qx_unittests.jl", "hamiltonians.jl", "orthogonalize.jl", "truncate.jl", ] print("$filename: ") @time include(filename) end end nothing #suppress messy dump from Test
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
12009
using ITensors using ITensorMPOCompression using Revise using Test using Printf using Profile include("hamiltonians/hamiltonians.jl") using NDTensors: Diag, BlockSparse, tensor #brute force method to control the default float display format. Base.show(io::IO, f::Float64) = @printf(io, "%1.1e", f) # # We need consistent output from randomMPS in order to avoid flakey unit testset # So we just pick any seed so that randomMPS (hopefull) gives us the same # pseudo-random output for each test run. # using Random Random.Random.seed!(12345); ITensors.ITensors.disable_debug_checks() verbose = false #verbose at the outer test level verbose1 = false #verbose inside orth algos @testset verbose = verbose "Truncate/Compress" begin models = [ [transIsing_MPO, "S=1/2", true], [transIsing_AutoMPO, "S=1/2", true], [Heisenberg_AutoMPO, "S=1/2", true], [Heisenberg_AutoMPO, "S=1", true], [Hubbard_AutoMPO, "Electron", false], ] @testset "Truncate/Compress MPO $(model[1]), qns=$qns, ul=$ul, lr=$lr" for model in models, qns in [false, true], ul in [lower, upper], lr in [left, right] eps = 1e-14 pre_fixed = model[3] #Hamiltonian starts gauge fixed N = 10 #5 sites NNN = 4 #Include 6nd nearest neighbour interactions sites = siteinds(model[2], N; conserve_qns=qns) Hrf = reg_form_MPO(model[1](sites, NNN; ul=ul)) state = [isodd(n) ? "Up" : "Dn" for n in 1:N] psi = randomMPS(sites, state) E0 = inner(psi', MPO(Hrf), psi) bs = truncate!(Hrf, lr) @test is_regular_form(Hrf) @test check_ortho(Hrf, lr) @test is_gauge_fixed(Hrf) #Now everything should be fixed, unless NNN is big # # Expectation value check. # E1 = inner(psi', MPO(Hrf), psi) @test E0 ≈ E1 atol = eps end # @testset "Test ground states" for qns in [false,true] # eps=3e-13 # N=10 # NNN=5 # hx= qns ? 0.0 : 0.5 # sites = siteinds("SpinHalf", N;conserve_qns=qns) # H=transIsing_MPO(sites,NNN;hx=hx) # E0,psi0=fast_GS(H,sites) # truncate!(H;verbose=verbose1,orth=left) # E1,psi1=fast_GS(H,sites) # overlap=abs(inner(psi0,psi1)) # RE=abs((E0-E1)/E0) # if verbose # @printf "Trans. Ising E0/N=%1.15f E1/N=%1.15f rel. error=%.1e overlap-1.0=%.1e \n" E0/(N-1) E1/(N-1) RE overlap-1.0 # end # @test E0 ≈ E1 atol = eps # @test overlap ≈ 1.0 atol = eps # hx=0.0 # H=Heisenberg_AutoMPO(sites,NNN;hx=hx) # E0,psi0=fast_GS(H,sites) # truncate!(H;verbose=verbose1,orth=right) # E1,psi1=fast_GS(H,sites) # overlap=abs(inner(psi0,psi1)) # RE=abs((E0-E1)/E0) # if verbose # @printf "Heisenberg E0/N=%1.15f E1/N=%1.15f rel. error=%.1e overlap-1.0=%.1e \n" E0/(N-1) E1/(N-1) RE overlap-1.0 # end # @test E0 ≈ E1 atol = eps # @test overlap ≈ 1.0 atol = eps # end # @testset "Look at bond singular values for large lattices" begin # NNN=5 # if verbose # @printf " |------ max(sv) ----| min(sv)\n" # @printf " N Dw left mid right mid\n" # end # for N in [6,8,10,12,18,20,40,80] # sites = siteinds("SpinHalf", N) # H=transIsing_MPO(sites,NNN;hx=0.5) # specs=truncate!(H;verbose=verbose1,cutoff=1e-10) # imid::Int64=div(N,2) # max_1 =specs[1 ].eigs[1] # max_mid=specs[imid].eigs[1] # max_N =specs[N-1 ].eigs[1] # min_mid=specs[imid].eigs[end] # Dw=maximum(get_Dw(H)) # if verbose # @printf "%4i %4i %1.5f %1.5f %1.5f %1.5f\n" N Dw max_1 max_mid max_N min_mid # end # @test (max_1-max_N)<1e-10 # @test max_mid<1.0 # end # end # @testset "Try a lattice with alternating S=1/2 and S=1 sites. MPO. Qns=$qns" for qns in [false,true] # N=10 # NNN=4 # eps=1e-14 # sites = siteinds(n->isodd(n) ? "S=1/2" : "S=1",N; conserve_qns=qns) # Ha=transIsing_AutoMPO(sites,NNN) # H=transIsing_MPO(sites,NNN) # #@show get_Dw(H) # state=[isodd(n) ? "Up" : "Dn" for n=1:N] # psi=randomMPS(sites,state) # Ea=inner(psi',Ha,psi) # E0=inner(psi',H,psi) # @test E0 ≈ Ea atol = eps # Ho=copy(H) # orthogonalize!(Ho;verbose=verbose1,rr_cutoff=1e-12) # #@show get_Dw(Ho) # Eo=inner(psi',Ho,psi) # @test E0 ≈ Eo atol = eps # Ht=copy(H) # ss=truncate!(Ht) # #@show get_Dw(Ht) # #@show ss # Et=inner(psi',Ht,psi) # #@show E0 Ea Eo Et E0-Eo E0-Et # @test E0 ≈ Et atol = eps # # # # Run some GS calculations # # # #E0,psi0=fast_GS(H,sites) unreliable # # All of these use and emperically determined number of sweeps to get full convergence # # This model can easily get stuck in a false minimum. # Ea,psia=fast_GS(Ha,sites,6) # Eo,psio=fast_GS(Ho,sites,8) # Et,psit=fast_GS(Ht,sites,7) # #@show Ea Eo Et Ea-Eo Ea-Et # E2a=inner(Ha,psia,Ha,psia) # E2o=inner(Ho,psio,Ho,psio) # E2t=inner(Ht,psit,Ht,psit) # #@show E2a-Ea^2 E2o-Eo^2 E2t-Et^2 # @test E2a-Ea^2 ≈ 0.0 atol = eps # @test E2o-Eo^2 ≈ 0.0 atol = eps # @test E2t-Et^2 ≈ 0.0 atol = eps # @test Ea ≈ Eo atol = eps # @test Ea ≈ Et atol = eps # end # @testset "Try a lattice with alternating S=1/2 and S=1 sites. iMPO. Qns=$qns" for qns in [false,true] # initstate(n) = isodd(n) ? "Dn" : "Up" # ul=lower # if verbose # @printf " Dw Dw Dw \n" # @printf " Ncell NNN uncomp. left right \n" # end # # # # This one is tricky to set for QNs=true up due to QN flux constraints. # # An Ncell=3 with S={1/2,1,1/2} seems to work. # # # for NNN in [2,4,6], N in [3] # # si = infsiteinds(n->isodd(n) ? "S=1" : "S=1/2",N; initstate, conserve_qns=qns) # H0=transIsing_iMPO(si,NNN;ul=ul) # @test is_regular_form(H0) # Dw0=Base.max(get_Dw(H0)...) # # # # Do truncate outputting left ortho Hamiltonian # # # HL=copy(H0) # Ss,ss,HR=truncate!(HL;verbose=verbose1,orth=left) # #@test typeof(storage(Ss[1])) == (qns ? BlockSparse{Float64, Vector{Float64}, 2} : Diag{Float64, Vector{Float64}}) # DwL=Base.max(get_Dw(HL)...) # @test is_regular_form(HL) # @test isortho(HL,left) # @test check_ortho(HL,left) # # # # Now test guage relations using the diagonal singular value matrices # # as the gauge transforms. # # # for n in 1:N # @test norm(Ss[n-1]*HR[n]-HL[n]*Ss[n]) ≈ 0.0 atol = 1e-14 # end # # # # Do truncate from H0 outputting right ortho Hamiltonian # # # HR=copy(H0) # Ss,ss,HL=truncate!(HR;verbose=verbose1,orth=right) # #@test typeof(storage(Ss[1])) == (qns ? BlockSparse{Float64, Vector{Float64}, 2} : Diag{Float64, Vector{Float64}}) # DwR=Base.max(get_Dw(HR)...) # @test is_regular_form(HR) # @test isortho(HR,right) # @test check_ortho(HR,right) # for n in 1:N # @test norm(Ss[n-1]*HR[n]-HL[n]*Ss[n]) ≈ 0.0 atol = 1e-14 # end # if verbose # @printf " %4i %4i %4i %4i %4i \n" N NNN Dw0 DwL DwR # end # end # end # @testset "Orthogonalize/truncate verify gauge invariace of <ψ|H|ψ>, ul=$ul, qbs=$qns" for ul in [lower,upper], qns in [false,true] # initstate(n) = "↑" # for N in [1], NNN in [2,4] #3 site unit cell fails for qns=true. # svd_cutoff=1e-15 #Same as autoMPO uses. # si = infsiteinds("S=1/2", N; initstate, conserve_szparity=qns) # ψ = InfMPS(si, initstate) # for n in 1:N # ψ[n] = randomITensor(inds(ψ[n])) # end # H0=transIsing_iMPO(si,NNN;ul=ul) # H0.llim=-1 # H0.rlim=1 # Hsum0=InfiniteSum{MPO}(H0,NNN) # E0=expect(ψ,Hsum0) # HL=copy(H0) # orthogonalize!(HL;verbose=verbose1,orth=left) # HsumL=InfiniteSum{MPO}(HL,NNN) # EL=expect(ψ,HsumL) # @test EL ≈ E0 atol = 1e-14 # HR=copy(HL) # orthogonalize!(HR;verbose=verbose1,orth=right) # HsumR=InfiniteSum{MPO}(HR,NNN) # ER=expect(ψ,HsumR) # @test ER ≈ E0 atol = 1e-14 # HL=copy(H0) # truncate!(HL;verbose=verbose1,orth=left) # HsumL=InfiniteSum{MPO}(HL,NNN) # EL=expect(ψ,HsumL) # @test EL ≈ E0 atol = 1e-14 # HR=copy(H0) # truncate!(HR;verbose=verbose1,orth=right) # HsumR=InfiniteSum{MPO}(HR,NNN) # ER=expect(ψ,HsumR) # @test ER ≈ E0 atol = 1e-14 # H=copy(H0) # truncate!(H;verbose=verbose1) # Hsum=InfiniteSum{MPO}(HR,NNN) # E=expect(ψ,Hsum) # @test E ≈ E0 atol = 1e-14 # #@show get_Dw(H0) get_Dw(HL) get_Dw(HR) # end # end # Slow test, turn off if you are making big changes. # @testset "Head to Head autoMPO with 2-body Hamiltonian ul=$ul, QNs=$qns" for ul in [lower,upper],qns in [false,true] # for N in 3:15 # NNN=N-1#div(N,2) # sites = siteinds("SpinHalf", N;conserve_qns=qns) # Hauto=transIsing_AutoMPO(sites,NNN;ul=ul) # Dw_auto=get_Dw(Hauto) # Hr=transIsing_MPO(sites,NNN;ul=ul) # truncate!(Hr;verbose=verbose1) #sweep left to right # delta_Dw=sum(get_Dw(Hr)-Dw_auto) # @test delta_Dw<=0 # if verbose && delta_Dw<0 # println("Compression beat AutoMPO by deltaDw=$delta_Dw for N=$N, NNN=$NNN,lr=right,ul=$ul,QNs=$qns") # end # if verbose && delta_Dw>0 # println("AutoMPO beat Compression by deltaDw=$delta_Dw for N=$N, NNN=$NNN,lr=right,ul=$ul,QNs=$qns") # end # end # end # Slow test, turn off if you are making big changes. # @testset "Head to Head autoMPO with 3-body Hamiltonian" begin # if verbose # @printf "+-----+---------+--------------------+--------------------+\n" # @printf "| |autoMPO | 1 truncation | 2 truncations |\n" # @printf "| N | dE | dE RE Dw | dE RE Dw |\n" # end # eps=1e-15 # for N in [6,10,16,20,24] # sites = siteinds("SpinHalf", N;conserve_qns=false) # Hnot=three_body_AutoMPO(sites;cutoff=-1.0) #No truncation inside autoMPO # H=three_body_AutoMPO(sites) #Truncated by autoMPO # #@show get_Dw(Hnot) # Dw_auto = get_Dw(H) # psi=randomMPS(sites) # Enot=inner(psi',Hnot,psi) # E=inner(psi',H,psi) # @test E ≈ Enot atol = sqrt(eps) # truncate!(Hnot;verbose=verbose1,max_sweeps=1) # Dw_1=get_Dw(Hnot) # delta_Dw_1=sum(Dw_auto-Dw_1) # Enott1=inner(psi',Hnot,psi) # @test E ≈ Enott1 atol = sqrt(eps) # RE1=abs(E-Enott1)/sqrt(eps) # truncate!(Hnot;verbose=verbose1) # Dw_2=get_Dw(Hnot) # delta_Dw_2=sum(Dw_auto-Dw_2) # Enott2=inner(psi',Hnot,psi) # @test E ≈ Enott2 atol = sqrt(eps) # RE2=abs(E-Enott2)/sqrt(eps) # if verbose # @printf "| %3i | %1.1e | %1.1e %1.3f %4i | %1.1e %1.3f %4i | \n" N abs(E-Enot) abs(E-Enott1) RE1 delta_Dw_1 abs(E-Enott2) RE2 delta_Dw_2 # end # end # end end #@testset "Truncate/Compress" nothing
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
12915
import ITensorMPOCompression: parse_links, parse_site, G_transpose, @mpoc_assert, reg_form, assign!, slice, redim @doc """ transIsing_MPO(sites,NNN;kwargs...) Directly coded build up of a transverse Ising model Hamiltonian with up to `NNN` neighbour 2-body interactions. The interactions are hard coded to decay like `J/(i-j)`. between sites `i` and `j`. # Arguments - `sites` : Site set defining the lattice of sites. - `NNN::Int64=1` : Number of neighbouring 2-body interactions to include in `H` # Keywords - `hx::Float64=0.0` : External magnetic field in `x` direction. - `ul::reg_form=lower` : build H with `lower` or `upper` regular form. - `J::Float64=1.0` : Nearest neighbour interaction strength. Further neighbours decay like `J/(i-j)`.. """ function transIsing_MPO(sites, NNN::Int64;ul=lower,J=1.0,hx=0.0,pbc=false, kwargs...)::MPO N = length(sites) Dw::Int64 = transIsing_Dw(NNN) use_qn::Bool = hasqns(sites[1]) mpo = MPO(N) io = ul == lower ? ITensors.Out : ITensors.In if pbc prev_link = Ising_index(Dw, "Link,c=0,l=$(N)", use_qn, io) else prev_link = Ising_index(Dw, "Link,l=0", use_qn, io) end for n in 1:N mpo[n] = transIsing_op(sites[n], prev_link, NNN, J, hx, ul, pbc) prev_link = filterinds(mpo[n]; tags="Link,l=$n")[1] end if pbc i0 = filterinds(mpo[1]; tags="Link,c=0,l=$(N)")[1] i0 = replacetags(i0, "c=0", "c=1") in = filterinds(mpo[N]; tags="Link,c=1,l=$(N)")[1] mpo[N] = replaceind(mpo[N], in, i0) end if !pbc mpo = to_openbc(mpo) #contract with l* and *r at the edges. end return mpo end # It turns out that the trans-Ising model # Dw = 2+Sum(i,i=1..NNN) =2 + NNN*(NNN+1)/2 # function transIsing_Dw(NNN::Int64)::Int64 return 2 + NNN * (NNN + 1) / 2 end function Ising_index(Dw::Int64, tags::String, use_qn::Bool, dir) if (use_qn) if tags[1:4] == "Link" qns = fill(QN("Sz", 0) => 1, Dw) ind = Index(qns; dir=dir, tags=tags) else @mpoc_assert tags[1:4] == "Site" ind = Index(QN("Sz", 1) => Dw; dir=dir, tags=tags) end else ind = Index(Dw, tags) end return ind end # NNN = Number of Neighbours, for example # NNN=1 corresponds to nearest neighbour # NNN=2 corresponds to nearest and next nearest neighbour function transIsing_op( site::Index, prev_link::Index, NNN::Int64, J::Float64, hx::Float64=0.0, ul::reg_form=lower, pbc::Bool=false, )::ITensor @mpoc_assert NNN >= 1 do_field = hx != 0.0 Dw::Int64 = transIsing_Dw(NNN) d, n, space = parse_site(site) use_qn = hasqns(site) r = dag(prev_link) c = Ising_index(Dw, "Link,l=$n", use_qn, dir(prev_link)) if pbc c = addtags(c, "c=1") end is = dag(site) #site seem to have the wrong direction! W = ITensor(r, c, is, dag(is')) Id = op(is, "Id") Sz = op(is, "Sz") if do_field Sx = op(is, "Sx") end assign!(W, Id, r => 1, c => 1) assign!(W, Id, r => Dw, c => Dw) iblock = 1 if ul == lower if do_field assign!(W, hx * Sx, r => Dw, c => 1) #add field term end #very hard to explain this without a diagram. for iNN in 1:NNN assign!(W, Sz, r => iblock + 1, c => 1) for jNN in 1:(iNN - 1) assign!(W, Id, r => iblock + 1 + jNN, c => iblock + jNN) end Jn = J / (iNN) #interactions need to decay with distance in order for H to extensive assign!(W, Jn * Sz, r => Dw, c => iblock + iNN) iblock += iNN end else if do_field assign!(W, hx * Sx, r => 1, c => Dw) #add field term end #very hard to explain this without a diagram. for iNN in 1:NNN assign!(W, Sz, r => 1, c => iblock + 1) for jNN in 1:(iNN - 1) assign!(W, Id, r => iblock + jNN, c => iblock + 1 + jNN) end Jn = J / (iNN) #interactions need to decay with distance in order for H to extensive assign!(W, Jn * Sz, r => iblock + iNN, c => Dw) iblock += iNN end end return W end # # implement eq. E3 from the Parker paper. # # | I c1 c2 d1+d2 | # W1+W2 = | 0 A1 0 b1 | # | 0 0 A2 b2 | # | 0 0 0 I | # or # # | I 0 0 0 | # W1+W2 = | b1 A1 0 0 | # | b2 0 A2 0 | # | d1+d2 c1 c2 I | # χ # function add_ops(i1::ITensors.QNIndex,i2::ITensors.QNIndex) qns=[space(i1)[1:end-1]...,space(i2)[2:end]...] return Index(qns,tags=tags(l1),plev=plev(i1),dir=dir(i1)) end function add_ops(i1::Index,i2::Index) return Index(space(i1)+space(i2)-2,tags=tags(i1),plev=plev(i1),dir=dir(i1)) end function add_ops(W1::ITensor, W2::ITensor)::ITensor #@pprint(W1) #@pprint(W2) is1 = inds(W1; tags="Site", plev=0)[1] is2 = inds(W2; tags="Site", plev=0)[1] @mpoc_assert is1 == is2 l1, r1 = parse_links(W1) l2, r2 = parse_links(W2) @mpoc_assert tags(l1) == tags(l2) @mpoc_assert tags(r1) == tags(r2) χl1, χr1 = dim(l1) - 2, dim(r1) - 2 χl2, χr2 = dim(l2) - 2, dim(r2) - 2 χl, χr = χl1 + χl2, χr1 + χr2 l, r = add_ops(l1,l2), add_ops(r1,r2) W = ITensor(0.0, l, r, is1, is1') Id = slice(W1, l1 => 1, r1 => 1) assign!(W, Id, l => 1, r => 1) assign!(W, Id, l => χl + 2, r => χr + 2) # d1+d2 block d1 = slice(W1, l1 => χl1 + 2, r1 => 1) d2 = slice(W2, l2 => χl2 + 2, r2 => 1) assign!(W, d1 + d2, l => χl + 2, r => 1) W[l => 2:(χl1 + 1), r => 1:1] = W1[l1 => 2:(χl1 + 1), r1 => 1:1] # b1 block W[l => (χl1 + 2):(χl1 + χl2 + 1), r => 1:1] = W2[l2 => 2:(χl2 + 1), r2 => 1:1] # b2 block W[l => (χl + 2):(χl + 2), r => 2:(χr1 + 1)] = W1[ l1 => (χl1 + 2):(χl1 + 2), r1 => 2:(χr1 + 1) ] # c1 block W[l => (χl + 2):(χl + 2), r => (χr1 + 2):(χr1 + χr2 + 1)] = W2[ l2 => (χl2 + 2):(χl2 + 2), r2 => 2:(χr2 + 1) ] # c2 block W[l => 2:(χl1 + 1), r => 2:(χr1 + 1)] = W1[l1 => 2:(χl1 + 1), r1 => 2:(χr1 + 1)] # A1 block W[l => (χl1 + 2):(χl1 + χl2 + 1), r => (χr1 + 2):(χr1 + χr2 + 1)] = W2[ l2 => 2:(χl2 + 1), r2 => 2:(χr2 + 1) ] # A2 block return W end function daisychain_links!(H::MPO; pbc=false) N = length(H) for n in 2:N if pbc ln = inds(H[n]; tags="c=0")[1] replacetags!(H[n], "c=1", "c=$n") else ln = inds(H[n]; tags="l=0")[1] replacetags!(H[n], "l=1", "l=$n") end l1, r1 = parse_links(H[n - 1]) #@show l1 r1 ln #@show inds(H[n]) replaceind!(H[n], ln, r1) #@show inds(H[n]) end if pbc i0 = filterinds(H[1]; tags="Link,c=0,l=$(N)")[1] i0 = replacetags(i0, "c=0", "c=1") in = filterinds(H[N]; tags="Link,c=1,l=$(N)")[1] H[N] = replaceind(H[N], in, i0) end if !pbc H = to_openbc(H) #contract with l* and *r at the edges. end end # Add the W operator to each site and fix up all tags accordingly. function addW!(sites, H, W) N = length(sites) H[1] = add_ops(H[1], W) for n in 2:N #@show inds(H[n]) iw1, iw2 = inds(W; tags="Link") ih1, ih2 = inds(H[n]; tags="Link") replacetags!(W, tags(iw2), tags(ih2)) replacetags!(W, tags(iw1), tags(ih1)) is = sites[n] replaceinds!(W, inds(W; tags="Site"), (is, dag(is)')) H[n] = add_ops(H[n], W) end end function two_body_MPO(sites, NNN::Int64; pbc=false, Jprime=1.0, presummed=true, kwargs...) N = length(sites) H = MPO(N) if pbc l, r = Index(1, "Link,c=0,l=1"), Index(1, "Link,c=1,l=1") else l, r = Index(1, "Link,l=0"), Index(1, "Link,l=1") end ul = lower H[1] = one_body_op(sites[1], l, r, ul; kwargs...) for n in 2:N H[n] = one_body_op(sites[n], l, r, ul; kwargs...) end W = H[1] if Jprime != 0.0 if presummed W = add_ops(W, two_body_sum(sites[1], l, r, NNN, ul; kwargs...)) else for n in 1:NNN W = add_ops(W, two_body_op(sites[1], l, r, n, ul; kwargs...)) end end end addW!(sites, H, W) daisychain_links!(H; kwargs...) return H end function three_body_MPO(sites, NNN::Int64; pbc=false, Jprime=1.0, presummed=true, J=1.0, kwargs...) N = length(sites) H = MPO(N) if pbc l, r = Index(1, "Link,c=0,l=1"), Index(1, "Link,c=1,l=1") else l, r = Index(1, "Link,l=0"), Index(1, "Link,l=1") end ul = lower H[1] = one_body_op(sites[1], l, r, ul; kwargs...) for n in 2:N H[n] = one_body_op(sites[n], l, r, ul; kwargs...) end W = H[1] if Jprime != 0.0 if presummed W = add_ops(W, two_body_sum(sites[1], l, r, NNN, ul; kwargs...)) else for m in 1:NNN W = add_ops(W, two_body_op(sites[1], l, r, m, ul; kwargs...)) end end end if J != 0.0 for n in 2:NNN for m in (n + 1):NNN W = add_ops(W, three_body_op(sites[1], l, r, n, m, ul; kwargs...)) end end end addW!(sites, H, W) daisychain_links!(H; pbc=pbc) H.llim,H.rlim=-1,1 return H end # # d-block = Hx*Sx # function one_body_op(site::Index, r1::Index, c1::Index, ul::reg_form; hx=0.0, kwargs...)::ITensor Dw::Int64 = 2 #d,n,space=parse_site(site) #use_qn=hasqns(site) r, c = redim(r1, Dw,0), redim(c1, Dw,0) is = dag(site) #site seem to have the wrong direction! W = ITensor(0.0, r, c, is, dag(is')) Id = op(is, "Id") assign!(W, Id, r => 1, c => 1) assign!(W, Id, r => Dw, c => Dw) if hx != 0.0 Sx = op(is, "Sx") #This will crash if Sz is a good QN assign!(W, hx * Sx, r => Dw, c => 1) end return W end # # J_1n * Z_1*Z_n # function two_body_op( site::Index, r1::Index, c1::Index, n::Int64, ul::reg_form; Jprime=1.0, kwargs... )::ITensor @mpoc_assert n >= 1 Dw::Int64 = 2 + n #d,n,space=parse_site(site) #use_qn=hasqns(site) r, c = redim(r1, Dw,0), redim(c1, Dw,0) is = dag(site) #site seem to have the wrong direction! W = ITensor(0.0, r, c, is, dag(is')) Id = op(is, "Id") Sz = op(is, "Sz") assign!(W, Id, r => 1, c => 1) assign!(W, Id, r => Dw, c => Dw) Jn = Jprime / n^4 #interactions need to decay with distance in order for H to extensive if ul == lower assign!(W, Sz, r => 2, c => 1) for j in 1:(n - 1) assign!(W, Id, r => 2 + j, c => 1 + j) end assign!(W, Jn * Sz, r => Dw, c => Dw - 1) else assign!(W, Sz, r => 1, c => 2) for j in 1:(n - 1) assign!(W, Id, r => 1 + j, c => 2 + j) end assign!(W, Jn * Sz, r => Dw - 1, c => Dw) end return W end function two_body_sum( site::Index, r1::Index, c1::Index, NNN::Int64, ul::reg_form;Jprime=1.0, kwargs... )::ITensor @mpoc_assert NNN >= 1 Dw::Int64 = 2 + NNN #d,n,space=parse_site(site) #use_qn=hasqns(site) r, c = redim(r1, Dw,0), redim(c1, Dw,0) is = dag(site) #site seem to have the wrong direction! W = ITensor(0.0, r, c, is, dag(is')) Id = op(is, "Id") Sz = op(is, "Sz") assign!(W, Id, r => 1, c => 1) assign!(W, Id, r => Dw, c => Dw) if ul == lower assign!(W, Sz, r => Dw, c => Dw - 1) else assign!(W, Sz, r => Dw - 1, c => Dw) end for n in 1:NNN Jn = Jprime / n^4 #interactions need to decay with distance in order for H to extensive if ul == lower assign!(W, Id, r => Dw - n, c => Dw - 1 - n) assign!(W, Jn * Sz, r => Dw - n, c => 1) else assign!(W, Id, r => Dw - 1 - n, c => Dw - n) assign!(W, Jn * Sz, r => 1, c => Dw - n) end end return W end # # J1n*Jnm * Z_1*Z_n*Z_m # function three_body_op( site::Index, r1::Index, c1::Index, n::Int64, m::Int64, ul::reg_form; J=1.0, kwargs... )::ITensor @mpoc_assert n >= 1 @mpoc_assert m > n W = two_body_op(site, r1, c1, m - 1, ul) #@pprint(W) r, c = inds(W; tags="Link") Dw = dim(r) Sz = op(dag(site), "Sz") k = 1 Jkn = J / (n - k)^2 Jnm = J / (m - n)^2 #@show k,n,m,Jkn,Jnm if ul == lower assign!(W, Sz, r => 2 + n - k, c => 1 + n - k) assign!(W, Jkn * Jnm * Sz, r => Dw, c => Dw - 1) else assign!(W, Sz, r => 1 + n - k, c => 2 + n - k) assign!(W, Jkn * Jnm * Sz, r => Dw - 1, c => Dw) end return W end function to_openbc(mpo::MPO)::MPO N = length(mpo) l, r = get_lr(mpo) mpo[1] = l * mpo[1] mpo[N] = mpo[N] * r @mpoc_assert length(filterinds(inds(mpo[1]); tags="Link")) == 1 @mpoc_assert length(filterinds(inds(mpo[N]); tags="Link")) == 1 return mpo end function get_lr(mpo::MPO)::Tuple{ITensor,ITensor} ul::reg_form = is_regular_form(mpo, lower) ? lower : upper N = length(mpo) W1 = mpo[1] llink = filterinds(inds(W1); tags="l=0")[1] l = ITensor(0.0, dag(llink)) WN = mpo[N] rlink = filterinds(inds(WN); tags="l=$N")[1] r = ITensor(0.0, dag(rlink)) if ul == lower l[llink => dim(llink)] = 1.0 r[rlink => 1] = 1.0 else l[llink => 1] = 1.0 r[rlink => dim(rlink)] = 1.0 end return l, r end function fast_GS(H::MPO, sites, nsweeps::Int64=5)::Tuple{Float64,MPS} state = [isodd(n) ? "Up" : "Dn" for n in 1:length(sites)] psi0 = randomMPS(sites, state) sweeps = Sweeps(nsweeps) setmaxdim!(sweeps, 2, 4, 8, 16, 32) setcutoff!(sweeps, 1E-10) #setnoise!(sweeps, 1e-6, 1e-7, 1e-8, 0.0) E, psi = dmrg(H, psi0, sweeps; outputlevel=0) return E, psi end include("hamiltonians_AutoMPO.jl")
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
code
4764
@doc """ three_body_AutoMPO(sites;kwargs...) Use `ITensor.autoMPO` to reproduce the 3 body Hamiltonian defined in eq. 34 of the Parker paper. The MPO is returned in lower regular form. # Arguments - `sites` : Site set defining the lattice of sites. # Keywords - `hx::Float64 = 0.0` : External magnetic field in `x` direction. """ function three_body_AutoMPO(sites;hx=0.0, kwargs...) N = length(sites) os = OpSum() if hx != 0 os = one_body(os, N, hx) end os = two_body(os, N; kwargs...) os = three_body(os, N; kwargs...) return MPO(os, sites; kwargs...) end function one_body(os::OpSum, N::Int64, hx::Float64=0.0)::OpSum for n in 1:N add!(os, hx, "Sx", n) end return os end function two_body(os::OpSum, N::Int64;Jprime=1.0, kwargs...)::OpSum if Jprime != 0.0 for n in 1:N for m in (n + 1):N Jnm = Jprime / abs(n - m)^4 add!(os, Jnm, "Sz", n, "Sz", m) # if heis # add!(os, Jnm*0.5,"S+", n, "S-", m) # add!(os, Jnm*0.5,"S-", n, "S+", m) # end end end end return os end function three_body(os::OpSum, N::Int64; J=1.0, kwargs...)::OpSum if J != 0.0 for k in 1:N for n in (k + 1):N Jkn = J / abs(n - k)^2 for m in (n + 1):N Jnm = J / abs(m - n)^2 # if k==1 # @show k,n,m,Jkn,Jnm # end add!(os, Jnm * Jkn, "Sz", k, "Sz", n, "Sz", m) end end end end return os end function to_upper!(H::ITensors.AbstractMPS) N = length(H) l, r = parse_links(H[1]) G = G_transpose(r, reverse(r)) H[1] = H[1] * G for n in 2:(N - 1) H[n] = dag(G) * H[n] l, r = parse_links(H[n]) G = G_transpose(r, reverse(r)) H[n] = H[n] * G end return H[N] = dag(G) * H[N] end @doc """ transIsing_AutoMPO(sites,NNN;kwargs...) Use `ITensor.autoMPO` to build up a transverse Ising model Hamiltonian with up to `NNN` neighbour 2-body interactions. The interactions are hard coded to decay like `J/(i-j)`. between sites `i` and `j`. The MPO is returned in lower regular form. # Arguments - `sites` : Site set defining the lattice of sites. - `NNN::Int64` : Number of neighbouring 2-body interactions to include in `H` # Keywords - `hx::Float64 = 0.0` : External magnetic field in `x` direction. - `J::Float64 = 1.0` : Nearest neighbour interaction strength. Further neighbours decay like `J/(i-j)`.. """ function transIsing_AutoMPO(sites, NNN::Int64; ul=lower, J=1.0, hx=0.0, nexp=1,kwargs...)::MPO do_field = hx != 0.0 N = length(sites) ampo = OpSum() if do_field for j in 1:N add!(ampo, hx, "Sx", j) end end for dj in 1:NNN f = J / dj^nexp for j in 1:(N - dj) add!(ampo, f, "Sz", j, "Sz", j + dj) end end H = MPO(ampo, sites; kwargs...) if ul == upper to_upper!(H) end H.llim,H.rlim=-1,1 return H end function two_body_AutoMPO(sites, NNN::Int64; kwargs...) return transIsing_AutoMPO(sites, NNN; kwargs...) end @doc """ Heisenberg_AutoMPO(sites,NNN;kwargs...) Use `ITensor.autoMPO` to build up a Heisenberg model Hamiltonian with up to `NNN` neighbour 2-body interactions. The interactions are hard coded to decay like `J/(i-j)`. between sites `i` and `j`. The MPO is returned in lower regular form. # Arguments - `sites` : Site set defining the lattice of sites. - `NNN::Int64` : Number of neighbouring 2-body interactions to include in `H` # Keywords - `hz::Float64 = 0.0` : External magnetic field in `z` direction. - `J::Float64 = 1.0` : Nearest neighbour interaction strength. Further neighbours decay like `J/(i-j)`. """ function Heisenberg_AutoMPO(sites, NNN::Int64;ul=lower,hz=0.0,J=1.0, kwargs...)::MPO N = length(sites) @mpoc_assert(N >= NNN) @mpoc_assert(J!=0.0) ampo = OpSum() for j in 1:N add!(ampo, hz, "Sz", j) end for dj in 1:NNN f = J / dj for j in 1:(N - dj) add!(ampo, f, "Sz", j, "Sz", j + dj) add!(ampo, f * 0.5, "S+", j, "S-", j + dj) add!(ampo, f * 0.5, "S-", j, "S+", j + dj) end end H = MPO(ampo, sites; kwargs...) if ul == upper to_upper!(H) end H.llim,H.rlim=-1,1 return H end function Hubbard_AutoMPO(sites, NNN::Int64; ul=lower, U=1.0,t=1.0,V=0.5, kwargs...)::MPO N = length(sites) @mpoc_assert(N >= NNN) os = OpSum() for i in 1:N os += (U, "Nupdn", i) end for dn in 1:NNN tj, Vj = t / dn, V / dn for n in 1:(N - dn) os += -tj, "Cdagup", n, "Cup", n + dn os += -tj, "Cdagup", n + dn, "Cup", n os += -tj, "Cdagdn", n, "Cdn", n + dn os += -tj, "Cdagdn", n + dn, "Cdn", n os += Vj, "Ntot", n, "Ntot", n + dn end end H = MPO(os, sites; kwargs...) if ul == upper to_upper!(H) end H.llim,H.rlim=-1,1 return H end
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
docs
6215
# ITensorMPOCompression A package to enable block respecting compression of Matrix Product Operators (MPOs) for use with ITensors.jl. Reference: *Daniel E. Parker, Xiangyu Cao, and Michael P. Zaletel Phys. Rev. B 102, 035147* ITensors has built in support for generating MPOs from local operators. This framework is called `AutoMPO`. MPOs generated by `AutoMPO` are already compressed, so you only need this package if you: 1. Are using MPOs that are created by hand, outside the `AutoMPO` framework. 2. Want your MPO to be in orthogonal/canonical form. 3. Need to see the bond spectrums throughout the lattice. Support for compression of infinite lattice MPOs (iMPOs) is in the ITensorInfiniteMPS package which can be found [here](https://github.com/ITensor/ITensorInfiniteMPS.jl). Technical notes on what this package does can be founs [here](https://github.com/JanReimers/ITensorMPOCompression.jl/blob/main/docs/TechnicalDetails.pdf) ## Installation You can install this package through the Julia package manager: ```julia julia> ] add ITensorMPOCompression ``` ## Examples Here are is an example of orthogonalizing an hand generated (not using AutoMPO) MPO ```julia julia> using ITensors julia> using ITensorMPOCompression julia> include("../test/hamiltonians/hamiltonians.jl"); julia> N = 10; #10 sites julia> NNN = 7; #Include up to 7th nearest neighbour interactions julia> sites = siteinds("S=1/2", N); julia> H = transIsing_MPO(sites, NNN); julia> is_regular_form(H,lower) == true true julia> @show get_Dw(H); #Show bond dimensions get_Dw(H) = [30, 30, 30, 30, 30, 30, 30, 30, 30] julia> pprint(H[2]) #schematic view of operators at site #2 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0 0 0 S 0 S 0 0 S 0 0 0 S 0 0 0 0 S 0 0 0 0 0 S 0 0 0 0 0 0 S I julia> orthogonalize!(H,left); #Orthogonalize into left canonical form. Also does rank reduction. julia> orthogonalize!(H,right); #Orthogonalize into right canoncial form. julia> pprint(H[2]) #Show vastly reduced matrix of operators at site #2 I 0 0 0 S S S 0 0 S 0 I julia> @show get_Dw(H); #Show reduced bond dimensions get_Dw(H) = [3, 4, 5, 6, 7, 6, 5, 4, 3] julia> is_regular_form(H,lower) == true true julia> isortho(H, right) == true #looks at cached ortho center limits true julia> check_ortho(H,right) == true #Does the more expensive V*V_dagger==Id contraction and test true julia> pprint(H) #High level view of what is in the MPO. n Dw1 Dw2 d Reg. Orth. Form Form 1 1 3 2 L M 2 3 4 2 L R 3 4 5 2 L R 4 5 6 2 L R 5 6 7 2 L R 6 7 6 2 L R 7 6 5 2 L R 8 5 4 2 L R 9 4 3 2 L R 10 3 1 2 L B ``` Here are is an example of truncating an hand generated (not using AutoMPO) MPO ```julia julia> using ITensors julia> using ITensorMPOCompression julia> include("../test/hamiltonians/hamiltonians.jl"); julia> N = 10; #10 sites julia> NNN = 7; #Include up to 7th nearest neighbour interactions julia> sites = siteinds("S=1/2", N); julia> H = transIsing_MPO(sites, NNN); julia> is_regular_form(H,lower) == true true julia> spectrums = truncate!(H,left); julia> pprint(H[5]) I 0 0 0 0 0 0 S S S S S S 0 S S S S S S 0 S S S S S S 0 S S S S S S 0 0 S S S S S I julia> @show get_Dw(H); get_Dw(H) = [3, 4, 5, 6, 7, 6, 5, 4, 3] julia> @show spectrums; spectrums = Bond Ns max(s) min(s) Entropy Tr. Error 1 1 0.30739 3.07e-01 0.22292 0.00e+00 2 2 0.35392 3.49e-02 0.26838 0.00e+00 3 3 0.37473 2.06e-02 0.29133 0.00e+00 4 4 0.38473 1.77e-02 0.30255 0.00e+00 5 5 0.38773 7.25e-04 0.30588 0.00e+00 6 4 0.38473 1.77e-02 0.30255 0.00e+00 7 3 0.37473 2.06e-02 0.29133 0.00e+00 8 2 0.35392 3.49e-02 0.26838 0.00e+00 9 1 0.30739 3.07e-01 0.22292 0.00e+00 julia> is_regular_form(H,lower) == true true julia> isortho(H, left) == true true julia> check_ortho(H, left) == true true ``` ## Generating this README This file was generated with [weave.jl](https://github.com/JunoLab/Weave.jl) with the following commands: ```julia using ITensorMPOCompression, Weave weave( joinpath(pkgdir(ITensorMPOCompression), "examples", "README.jl"); doctype="github", out_path=pkgdir(ITensorMPOCompression), ) ```
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
0.3.1
58346ee4fd66739b207c9e69d4bd736b04a9c20e
docs
5568
# ITensorMPOCompression ITensorMPOCompression is a Julia language module based in the [ITensors](https://itensor.org/) library. In general, compression of Hamiltonian MPOs must be treated differently than standard MPS compression. The root of the problem can be traced to the combination of both extensive and intensive degrees of freedom in Hamiltonian operators. If conventional compression methods are applied to Hamiltonian MPOs, one finds that two of the singular values will diverge as the lattice size increases, resulting in severe numerical instabilities. The recent paper > *Local Matrix Product Operators:Canonical Form, Compression, and Control Theory* Daniel E. Parker, Xiangyu Cao, and Michael P. Zaletel **Phys. Rev. B** 102, 035147 contains a number of important insights for the handling of finite and infinite lattice MPOs. They show that the intensive degrees of freedom can be isolated from the extensive ones. If one only compresses the intensive portions of the Hamiltonian then the divergent singular values are removed from the problem. This module attempts to implement the algorithms described in the *Parker et. al.* paper. The techincal details are presented in a document provided with this module: [TechnicalDetails.pdf](../TechnicalDetails.pdf). A brief summary of the key functions of this module follows. ## Block respecting QX decomposition ### Finite MPO A finite lattice MPO with *N* sites can expressed as ```math \hat{H}=\hat{W}^{1}\hat{W}^{2}\hat{W}^{3}\cdots\hat{W}^{N-1}\hat{W}^{N} ``` where each ``\\\hat{W}^{n}`` is an operator-valued matrix on site *n* ### Regular Forms MPOs must be in the so called regular form in order for orthogonalization and compression to succeed. These forms are defined as follows: ```math \hat{W}_{upper}=\begin{bmatrix}\hat{\mathbb{I}} & \hat{\boldsymbol{c}} & \hat{d}\\ 0 & \hat{\boldsymbol{A}} & \hat{\boldsymbol{b}}\\ 0 & 0 & \hat{\mathbb{I}} \end{bmatrix} ``` ```math \hat{W}_{lower}=\begin{bmatrix}\hat{\mathbb{I}} & 0 & 0\\ \hat{\boldsymbol{b}} & \hat{\boldsymbol{A}} & 0\\ \hat{d} & \hat{\boldsymbol{c}} & \hat{\mathbb{I}} \end{bmatrix} ``` Where: ``\\\hat{\boldsymbol{b}}\quad and\quad\hat{\boldsymbol{c}}`` are operator-valued vectors and ``\\\hat{\boldsymbol{A}}`` is an operator-valued matrix which is *not nessecarily triangular*. # Truncation (SVD compression) Truncation (or compression) of an MPO starts with 2 orthogonalization sweeps using column pivoting, rank reducing QR decomposoitions. These sweeps will significantly reduce the bond dimensions of the MPO. A final sweep using SVD decomposition and compression of the internal degrees of freedom will then yield a bond spectrum at each bond site. The users can control the rank reduction and SVD compression using parameters described below. ```@docs ITensorMPOCompression.truncate! ``` # Orthogonalization (Canonical forms) Most users will not need to deal directly with orthogonalization, as the truncation routine will do this automaticlly. This is achieved by simply sweeping through the lattice and carrying out block respecting *QX* steps described in the technical notes. For left canoncical form one starts at the left and sweeps right, and the converse applies for right canonical form. ```@docs ITensorMPOCompression.orthogonalize! ``` # Characterizations The module has a number of functions for viewing and characterization of MPOs and operator-valued matrices. ## Regular forms Regular forms are defined above in section [Regular Forms](@ref) ```@docs ITensorMPOCompression.reg_form detect_regular_form is_regular_form ``` ## Orthogonal forms The definition of orthogonal forms for MPOs or operator-valued matrices are more complicated than those for MPSs. First we must define the inner product of two operator-valued matrices. For the case of orthogonal columns this looks like: ```math \sum_{a}\left\langle \hat{W}_{ab}^{\dagger},\hat{W}_{ac}\right\rangle =\frac{\sum_{a}^{}Tr\left[\hat{W}_{ab}\hat{W}_{ac}\right]}{Tr\left[\hat{\mathbb{I}}\right]}=\delta_{bc} ``` Where the summation limits depend on where the V-block is for `left`/`right` and `lower`/`upper`. The specifics for all four cases are shown in table 6 in the [Technical Notes](../TechnicalDetails.pdf) ```@docs ITensorMPOCompression.orth_type ITensors.isortho ITensorMPOCompression.check_ortho ``` # Some utility functions One of the difficult aspects of working with operator-valued matrices is that they have four indices and if one just does a naive @show W to see what's in there, you see a voluminous output that is hard to read because of the default slicing selected by the @show overload. The pprint(W) (pretty print) function attempts to solve this problem by simply showing you where the zero, unit and other operators reside. ```@docs pprint ``` # Test Hamiltonians For development and demo purposes it is useful to have a quick way to make Hamiltonian MPOs for various models. Right now we have four Hamiltonians available 1. Direct transverse Ising model with arbitrary neighbour 2-body interactions 2. autoMPO transverse Ising model with arbitrary neighbour 2-body interactions 3. autoMPO Heisenberg model with arbitrary neighbour 2-body interactions 4. The 3-body model in eq. 34 of the Parker paper, built with autoMPO. The autoMPO MPOs come pre-truncated so they are not as useful for testing truncation. The automated truncation in AutoMPO can **partially** disabled by providing the the keyword argument `cutoff=-1.0` which gets passed down in the svd/truncate call used when building the MPO
ITensorMPOCompression
https://github.com/JanReimers/ITensorMPOCompression.jl.git
[ "MIT" ]
1.3.1
b6eb90a8a48763177796cb6944fec798ba482239
code
18920
module MultiQuad using QuadGK, Cuba, HCubature, Unitful, FastGaussQuadrature, LinearAlgebra, LRUCache, Base.Threads, ProgressMeter export quad, dblquad, tplquad function _quadgk_wrapper_1D(arg::Function, x1, x2; kwargs...) return quadgk(arg, x1, x2; kwargs...) end function _cuba_wrapper_1D(arg::Function, x1, x2; method::Symbol, kwargs...) if method == :suave integrate = suave elseif method == :vegas integrate = vegas else ex = ErrorException("Integration method $method is not supported!") throw(ex) end units = unit(arg(x1)) * unit(x1) arg2(a) = ustrip(units, (x2 - x1) * arg((x2 - x1) * a + x1)) function integrand(x, f) f[1] = arg2(x[1]) end result, err = integrate(integrand, 1, 1; kwargs...) if units == Unitful.NoUnits return result[1], err[1] else return (result[1], err[1]) .* units end end #order, method, optional function get_weights_fastgaussquadrature(order::Int, method::Symbol, optional::Real=NaN) if method == :gausslegendre xw = gausslegendre return xw(order) elseif method == :gausshermite xw = gausshermite return xw(order) elseif method == :gausslaguerre xw = gausslaguerre if isnan(optional) return xw(order) else α = optional return xw(order, α) end elseif method == :gausschebyshev xw = gausschebyshev if isnan(optional) return xw(order) else kind = optional return xw(order, kind) end # elseif method == :gaussjacobi # xw = gaussjacobi # return xw(order) elseif method == :gaussradau xw = gaussradau return xw(order) elseif method == :gausslobatto xw = gausslobatto return xw(order) else ex = ErrorException("Integration method $method is not supported!") throw(ex) end end const lru_xw_fastgaussquadrature = LRU{ Tuple{Int,Symbol,Real}, Tuple{Vector{Float64},Vector{Float64}}, }(maxsize=Int(1e5)) function get_weights_fastgaussquadrature_cached(order::Int, method::Symbol, optional::Real=NaN) get!(lru_xw_fastgaussquadrature, (order, method, optional)) do get_weights_fastgaussquadrature(order, method, optional) end end function _fastgaussquadrature_wrapper_1D(arg::Function, x1, x2; method::Symbol, order::Int, multithreading::Bool=true, verbose::Bool=false, kwargs...) if !(method in [:gausslegendre, :gausschebyshev, :gaussradau, :gausslobatto]) ex = ErrorException("Integration method $method is not supported!") throw(ex) end if haskey(kwargs, :α) optional = kwargs[:α] elseif haskey(kwargs, :kind) optional = kwargs[:kind] else optional = NaN end x, w = get_weights_fastgaussquadrature_cached(order, method, optional) b = x2 a = x1 b_a_2 = (b - a) / 2 a_plus_b_2 = (a + b) / 2 arg_gauss(x) = arg(b_a_2 * x + a_plus_b_2) if verbose p = Progress(order) end if multithreading && order - 1 > nthreads() && nthreads() > 1 tmp = arg_gauss(x[1]) knots = zeros(order) * unit(tmp) knots[1] = tmp if verbose next!(p) @threads for i in 2:order knots[i] = arg_gauss(x[i]) next!(p) end else @threads for i in 2:order knots[i] = arg_gauss(x[i]) end end else knots = arg_gauss.(x) end integral = b_a_2 * dot(w, knots) return integral, NaN end function _fastgaussquadrature_wrapper_1D(arg::Function; method::Symbol, order::Int, multithreading::Bool=true, verbose::Bool=false, kwargs...) if !(method in [:gausshermite, :gausslaguerre]) ex = ErrorException("Integration method $method is not supported!") throw(ex) end if haskey(kwargs, :α) optional = kwargs[:α] elseif haskey(kwargs, :kind) optional = kwargs[:kind] else optional = NaN end x, w = get_weights_fastgaussquadrature_cached(order, method, optional) if verbose p = Progress(order) end if multithreading && order - 1 > nthreads() && nthreads() > 1 tmp = arg(x[1]) knots = zeros(order) * unit(tmp) knots[1] = tmp if verbose next!(p) @threads for i in 2:order knots[i] = arg(x[i]) next!(p) end else @threads for i in 2:order knots[i] = arg(x[i]) end end else knots = arg.(x) end integral = dot(w, knots) return integral, NaN end @doc raw""" quad(arg::Function, x1, x2[; method = :quadgk, oder=1000, multithreading=true, kwargs...]) Performs the integral ``\int_{x1}^{x2}f(x)dx`` Available integration methods: - `:suave` - `:vegas` - `:quadgk` There are several fixed order quadrature methods available based on [`FastGaussQuadrature`](https://github.com/JuliaApproximation/FastGaussQuadrature.jl) - `:gausslegendre` - `:gausshermite` - `:gausslaguerre` - `:gausschebyshev` - `:gaussradau` - `:gausslobatto` If a specific integration routine is not needed, it is suggested to use `:quadgk` (the default option). For highly oscillating integrals, it is advised to use `:gausslegendre`with a high order (~10000). Please note that `:gausshermite` and `:gausslaguerre` are used to specific kind of integrals with infinite bounds. For more informations on these integration techniques, please follow the official documentation [here](https://juliaapproximation.github.io/FastGaussQuadrature.jl/stable/gaussquadrature/). See [QuadGK](https://github.com/JuliaMath/QuadGK.jl) and [Cuba.jl](https://giordano.github.io/Cuba.jl/stable/) for all the available keyword arguments. # Examples ```jldoctest using MultiQuad func(x) = x^2*exp(-x) quad(func, 0, 4) # equivalent to quad(func, 0, 4, method=:quadgk) quad(func, 0, 4, method=:gausslegendre, order=1000) # for certain kinds of integrals with infinite bounds, it may be possible to use a specific integration routine func(x) = x^2*exp(-x) quad(func, 0, Inf, method=:quadgk)[1] # gausslaguerre computes the integral of f(x)*exp(-x) from 0 to infinity quad(x -> x^4, method=:gausslaguerre, order=10000)[1] ``` `quad` can handle units of measurement through the [`Unitful`](https://github.com/PainterQubits/Unitful.jl) package: ```jldoctest using Unitful func(x) = x^2 integral, error = quad(func, 1u"m", 5u"m") ``` """ function quad(arg::Function, x1, x2; method::Symbol=:quadgk, order::Int=1000, multithreading::Bool=true, verbose::Bool=false, kwargs...) if method in [:suave, :vegas] return _cuba_wrapper_1D(arg, x1, x2; method=method) elseif method == :quadgk return _quadgk_wrapper_1D(arg, x1, x2; kwargs...) elseif method in [:gausslegendre, :gausschebyshev, :gaussradau, :gausslobatto] return _fastgaussquadrature_wrapper_1D(arg, x1, x2; method=method, order=order, multithreading=multithreading, verbose=verbose, kwargs...) else ex = ErrorException("Integration method $method is not supported!") throw(ex) end end @doc raw""" quad(arg::Function; method[, oder=1000, kwargs...]) """ function quad(arg::Function; method::Symbol, order::Int=1000, multithreading::Bool=true, verbose::Bool=false, kwargs...) if method in [:gausshermite, :gausslaguerre] return _fastgaussquadrature_wrapper_1D(arg; method=method, order=order, multithreading=multithreading, verbose=verbose, kwargs...) else ex = ErrorException("Integration method $method is not supported!") throw(ex) end end function _cuba_wrapper_2D(arg::Function, x1, x2, y1::Function, y2::Function; method::Symbol, kwargs...) if method == :cuhre integrate = cuhre elseif method == :divonne integrate = divonne elseif method == :suave integrate = suave elseif method == :vegas integrate = vegas else ex = ErrorException("Integration method $method is not supported!") throw(ex) end units = unit(arg(y1(x1), x1)) * unit(x1) * unit(y1(x1)) arg1(a, x) = (y2(x) - y1(x)) * arg((y2(x) - y1(x)) * a + y1(x), x) arg2(a, b) = ustrip(units, (x2 - x1) * arg1(a, (x2 - x1) * b + x1)) function integrand2(x, f) f[1] = arg2(x[1], x[2]) end result, err = integrate(integrand2, 2, 1; kwargs...) if units == Unitful.NoUnits return result[1], err[1] else return (result[1], err[1]) .* units end end function _cuba_wrapper_2D(arg::Function, x1, x2, y1, y2; method::Symbol, kwargs...) if method == :cuhre integrate = cuhre elseif method == :divonne integrate = divonne elseif method == :suave integrate = suave elseif method == :vegas integrate = vegas else ex = ErrorException("Integration method $method is not supported!") throw(ex) end units = unit(arg(y1, x1)) * unit(x1) * unit(y1) arg1(a, x) = (y2 - y1) * arg((y2 - y1) * a + y1, x) arg2(a, b) = ustrip(units, (x2 - x1) * arg1(a, (x2 - x1) * b + x1)) function integrand2(x, f) f[1] = arg2(x[1], x[2]) end result, err = integrate(integrand2, 2, 1; kwargs...) if units == Unitful.NoUnits return result[1], err[1] else return (result[1], err[1]) .* units end end function _hcubature_wrapper_2D(arg::Function, x1, x2, y1::Function, y2::Function; kwargs...) units = unit(arg(y1(x1), x1)) * unit(x1) * unit(y1(x1)) arg1(a, x) = (y2(x) - y1(x)) * arg((y2(x) - y1(x)) * a + y1(x), x) arg2(a, b) = ustrip(units, (x2 - x1) * arg1(a, (x2 - x1) * b + x1)) function integrand(arr) return arg2(arr[1], arr[2]) end min_arr = [0, 0] max_arr = [1, 1] result, err = hcubature(integrand, min_arr, max_arr; kwargs...) if units == Unitful.NoUnits return result[1], err[1] else return (result[1], err[1]) .* units end end function _hcubature_wrapper_2D(arg::Function, x1, x2, y1, y2; kwargs...) units = unit(arg(y1, x1)) * unit(x1) * unit(y1) arg1(a, x) = (y2 - y1) * arg((y2 - y1) * a + y1, x) arg2(a, b) = ustrip(units, (x2 - x1) * arg1(a, (x2 - x1) * b + x1)) function integrand(arr) return arg2(arr[1], arr[2]) end min_arr = [0, 0] max_arr = [1, 1] result, err = hcubature(integrand, min_arr, max_arr; kwargs...) if units == Unitful.NoUnits return result[1], err[1] else return (result[1], err[1]) .* units end end @doc raw""" dblquad(arg::Function, x1, x2, y1::Function, y2::Function; method = :cuhre, kwargs...) Performs the integral ``\int_{x1}^{x2}\int_{y1(x)}^{y2(x)}f(y,x)dydx`` Available integration methods: - `:cuhre` - `:divonne` - `:suave` - `:vegas` - `:hcubature` See [Cuba.jl](https://giordano.github.io/Cuba.jl/stable/) for all the available keyword arguments fro the `:cuhre`, `:divonne`, `:suave` and `:vegas` methods. See [HCubature](https://github.com/stevengj/HCubature.jl) for all the available keywords for the `:hcubature` method. # Examples ```jldoctest func(y,x) = sin(x)*y^2 integral, error = dblquad(func, 1, 2, x->0, x->x^2, rtol=1e-9) ``` `dblquad` can handle units of measurement through the [`Unitful`](https://github.com/PainterQubits/Unitful.jl) package: ```jldoctest using Unitful func(y,x) = x*y^2 integral, error = dblquad(func, 1u"m", 2u"m", x->0u"m^2", x->x^2, rtol=1e-9) ``` """ function dblquad( arg::Function, x1, x2, y1::Function, y2::Function; method=:hcubature, kwargs... ) if method in [:cuhre, :divonne, :suave, :vegas] return _cuba_wrapper_2D(arg, x1, x2, y1, y2; method=method) elseif method == :hcubature return _hcubature_wrapper_2D(arg, x1, x2, y1, y2; kwargs...) else ex = ErrorException("Integration method $method is not supported!") throw(ex) end end function dblquad( arg::Function, x1, x2, y1, y2; method=:hcubature, kwargs... ) if method in [:cuhre, :divonne, :suave, :vegas] return _cuba_wrapper_2D(arg, x1, x2, y1, y2; method=method) elseif method == :hcubature return _hcubature_wrapper_2D(arg, x1, x2, y1, y2; kwargs...) else ex = ErrorException("Integration method $method is not supported!") throw(ex) end end function _cuba_wrapper_3D(arg::Function, x1, x2, y1::Function, y2::Function, z1::Function, z2::Function; method::Symbol, kwargs...) if method == :cuhre integrate = cuhre elseif method == :divonne integrate = divonne elseif method == :suave integrate = suave elseif method == :vegas integrate = vegas else ex = ErrorException("Integration method $method is not supported!") throw(ex) end units = unit(arg(z1(x1, y1(x1)), y1(x1), x1)) * unit(x1) * unit(y1(x1)) * unit(z1(y1(x1), x1)) arg0(a, y, x) = (z2(x, y) - z1(x, y)) * arg((z2(x, y) - z1(x, y)) * a + z1(x, y), y, x) arg1(a, b, x) = (y2(x) - y1(x)) * arg0(a, (y2(x) - y1(x)) * b + y1(x), x) arg2(a, b, c) = ustrip(units, (x2 - x1) * arg1(a, b, (x2 - x1) * c + x1)) function integrand2(x, f) f[1] = arg2(x[1], x[2], x[3]) end result, err = integrate(integrand2, 3, 1; kwargs...) if units == Unitful.NoUnits return result[1], err[1] else return (result[1], err[1]) .* units end end function _cuba_wrapper_3D(arg::Function, x1, x2, y1, y2, z1, z2; method::Symbol, kwargs...) if method == :cuhre integrate = cuhre elseif method == :divonne integrate = divonne elseif method == :suave integrate = suave elseif method == :vegas integrate = vegas else ex = ErrorException("Integration method $method is not supported!") throw(ex) end units = unit(arg(z1, y1, x1)) * unit(x1) * unit(y1) * unit(z1) arg0(a, y, x) = (z2 - z1) * arg((z2 - z1) * a + z1, y, x) arg1(a, b, x) = (y2 - y1) * arg0(a, (y2 - y1) * b + y1, x) arg2(a, b, c) = ustrip(units, (x2 - x1) * arg1(a, b, (x2 - x1) * c + x1)) function integrand2(x, f) f[1] = arg2(x[1], x[2], x[3]) end result, err = integrate(integrand2, 3, 1; kwargs...) if units == Unitful.NoUnits return result[1], err[1] else return (result[1], err[1]) .* units end end function _hcubature_wrapper_3D(arg::Function, x1, x2, y1::Function, y2::Function, z1::Function, z2::Function; kwargs...) units = unit(arg(z1(x1, y1(x1)), y1(x1), x1)) * unit(x1) * unit(y1(x1)) * unit(z1(y1(x1), x1)) arg0(a, y, x) = (z2(x, y) - z1(x, y)) * arg((z2(x, y) - z1(x, y)) * a + z1(x, y), y, x) arg1(a, b, x) = (y2(x) - y1(x)) * arg0(a, (y2(x) - y1(x)) * b + y1(x), x) arg2(a, b, c) = ustrip(units, (x2 - x1) * arg1(a, b, (x2 - x1) * c + x1)) function integrand(arr) return arg2(arr[1], arr[2], arr[3]) end min_arr = [0, 0, 0] max_arr = [1, 1, 1] result, err = hcubature(integrand, min_arr, max_arr; kwargs...) if units == Unitful.NoUnits return result[1], err[1] else return (result[1], err[1]) .* units end end function _hcubature_wrapper_3D(arg::Function, x1, x2, y1, y2, z1, z2; kwargs...) units = unit(arg(z1, y1, x1)) * unit(x1) * unit(y1) * unit(z1) arg0(a, y, x) = (z2 - z1) * arg((z2 - z1) * a + z1, y, x) arg1(a, b, x) = (y2 - y1) * arg0(a, (y2 - y1) * b + y1, x) arg2(a, b, c) = ustrip(units, (x2 - x1) * arg1(a, b, (x2 - x1) * c + x1)) function integrand(arr) return arg2(arr[1], arr[2], arr[3]) end min_arr = [0, 0, 0] max_arr = [1, 1, 1] result, err = hcubature(integrand, min_arr, max_arr; kwargs...) if units == Unitful.NoUnits return result[1], err[1] else return (result[1], err[1]) .* units end end @doc raw""" tplquad(arg::Function, x1, x2, y1::Function, y2::Function, z1::Function, z2::Function; method = :cuhre, kwargs...) Performs the integral ``\int_{x1}^{x2}\int_{y1(x)}^{y2(x)}\int_{z1(x,y)}^{z2(x,y)}f(z,y,x)dzdydx`` Available integration methods: - `:cuhre` - `:divonne` - `:suave` - `:vegas` - `:hcubature` See [Cuba.jl](https://giordano.github.io/Cuba.jl/stable/) for all the available keyword arguments fro the `:cuhre`, `:divonne`, `:suave` and `:vegas` methods. See [HCubature](https://github.com/stevengj/HCubature.jl) for all the available keywords for the `:hcubature` method. # Examples ```jldoctest func(z,y,x) = sin(z)*y*x integral, error = tplquad(func, 0, 4, x->x, x->x^2, (x,y)->2, (x,y)->3*x) ``` `tplquad` can handle units of measurement through the [`Unitful`](https://github.com/PainterQubits/Unitful.jl) package: ```jldoctest using Unitful func(z,y,x) = sin(z)*y*x integral, error = tplquad(func, 0u"m", 4u"m", x->0u"m^2", x->x^2, (x,y)->0, (x,y)->3) ``` """ function tplquad( arg::Function, x1, x2, y1::Function, y2::Function, z1::Function, z2::Function; method=:hcubature, kwargs... ) if method in [:cuhre, :divonne, :suave, :vegas] return _cuba_wrapper_3D(arg, x1, x2, y1, y2, z1, z2; method=method, kwargs...) elseif method == :hcubature return _hcubature_wrapper_3D(arg, x1, x2, y1, y2, z1, z2; kwargs...) else ex = ErrorException("Integration method $method is not supported!") throw(ex) end end function tplquad( arg::Function, x1, x2, y1, y2, z1, z2; method=:hcubature, kwargs... ) if method in [:cuhre, :divonne, :suave, :vegas] return _cuba_wrapper_3D(arg, x1, x2, y1, y2, z1, z2; method=method, kwargs...) elseif method == :hcubature return _hcubature_wrapper_3D(arg, x1, x2, y1, y2, z1, z2; kwargs...) else ex = ErrorException("Integration method $method is not supported!") throw(ex) end end end # module
MultiQuad
https://github.com/aurelio-amerio/MultiQuad.jl.git
[ "MIT" ]
1.3.1
b6eb90a8a48763177796cb6944fec798ba482239
code
7562
using MultiQuad, Test, Unitful @testset "quad" begin rtol = 1e-10 xmin = 0 xmax = 4 func1(x) = x^2 * exp(-x) res = 2 - 26 / exp(4) int, err = quad(func1, xmin, xmax, rtol = rtol) @test isapprox(int, res, atol = err) @test typeof(quad( func1, xmin, xmax, rtol = rtol, method = :vegas, )[1]) == Float64 @test typeof(quad( func1, xmin, xmax, rtol = rtol, method = :suave, )[1]) == Float64 xmin2 = 0 * u"m" xmax2 = 4 * u"m" func2(x) = x^2 res2 = 64 / 3 int2, err2 = quad(func2, xmin2, xmax2, rtol = rtol) @test isapprox(int2, res2 * u"m^3", atol = err2) @test typeof(quad( func2, xmin2, xmax2, rtol = rtol, method = :vegas, )[1]) == typeof(1.0 * u"m^3") @test typeof(quad( func2, xmin2, xmax2, rtol = rtol, method = :suave, )[1]) == typeof(1.0 * u"m^3") f(x) = x^4 @test quad(f, -1, 1, method=:gausslegendre, order=100000)[1] ≈ 2/5 @test quad(f, -1, 1, method=:gausslegendre, order=100000, multithreading=true)[1] ≈ 2/5 @test quad(f, -1, 1, method=:gausslegendre, order=100000, multithreading=true, verbose=true)[1] ≈ 2/5 @test quad(f, method=:gausshermite, order=10000)[1] ≈ 3(√π)/4 @test quad(f, method=:gausslaguerre, order=10000)[1] ≈ 24 @test quad(f, method=:gausslaguerre, order=3, α=1.0)[1] ≈ 120 @test quad(f, -1, 1, method=:gausschebyshev, order=3)[1] ≈ 3π/8 @test quad(f, -1, 1, method=:gausschebyshev, order=3, kind=1)[1] ≈ 3π/8 @test quad(f, -1, 1, method=:gausschebyshev, order=3, kind=2)[1] ≈ π/16 @test quad(f, -1, 1, method=:gausschebyshev, order=3, kind=3)[1] ≈ 3π/8 @test quad(f, -1, 1, method=:gausschebyshev, order=3, kind=4)[1] ≈ 3π/8 @test quad(f, -1, 1, method=:gaussradau, order=3)[1] ≈ 2/5 @test quad(f, -1, 1, method=:gausslobatto, order=4)[1] ≈ 2/5 @test_throws ErrorException quad(func1, 0, 4, method = :none) end @testset "dblquad" begin rtol = 1e-10 xmin = 0 xmax = 4 ymin(x) = x^2 ymax(x) = x^3 func1(y, x) = y * x^3 res1 = 241664 / 5 int1, err1 = dblquad( func1, xmin, xmax, ymin, ymax, rtol = rtol, method = :cuhre, ) int1b, err1b = dblquad( func1, xmin, xmax, ymin, ymax, rtol = rtol, method = :hcubature, ) @test dblquad( (y,x)->x*y, 0, 2, 0, 3, rtol = rtol, method = :hcubature, )[1] ≈ 9 @test isapprox(int1, res1, atol = err1) @test isapprox(int1b, res1, atol = err1b) @test typeof(dblquad( func1, xmin, xmax, ymin, ymax, rtol = rtol, method = :vegas, )[1]) == Float64 @test typeof(dblquad( func1, xmin, xmax, ymin, ymax, rtol = rtol, method = :suave, )[1]) == Float64 @test typeof(dblquad( func1, xmin, xmax, ymin, ymax, rtol = rtol, method = :divonne, )[1]) == Float64 xmin2 = 0 * u"m" xmax2 = 4 * u"m" ymin2(x) = x^2 * u"m" ymax2(x) = x^3 func2(y, x) = y * x^3 int2, err2 = dblquad(func2, xmin2, xmax2, ymin2, ymax2, rtol = rtol) int2b, err2b = dblquad( func2, xmin2, xmax2, ymin2, ymax2, rtol = rtol, method = :hcubature, ) @test isapprox(int2, res1 * u"m^10", atol = err2) @test isapprox(int2b, res1 * u"m^10", atol = err2b) @test typeof(dblquad( func2, xmin2, xmax2, ymin2, ymax2, rtol = rtol, method = :vegas, )[1]) == typeof(1.0 * u"m^10") @test typeof(dblquad( func2, xmin2, xmax2, ymin2, ymax2, rtol = rtol, method = :suave, )[1]) == typeof(1.0 * u"m^10") @test typeof(dblquad( func2, xmin2, xmax2, ymin2, ymax2, rtol = rtol, method = :divonne, )[1]) == typeof(1.0 * u"m^10") @test_throws ErrorException dblquad( func1, xmin, xmax, ymin, ymax, rtol = rtol, method = :none, ) end @testset "tblquad" begin rtol = 1e-10 xmin = 0 xmax = 4 ymin(x) = x^2 ymax(x) = x^3 zmin(x, y) = 3 zmax(x, y) = 4 func1(z, y, x) = y * x^3 * sin(z) res = 241664 / 5 * (cos(3) - cos(4)) int1, err1 = tplquad(func1, xmin, xmax, ymin, ymax, zmin, zmax, rtol = rtol) int1b, err1b = tplquad( func1, xmin, xmax, ymin, ymax, zmin, zmax, rtol = rtol, method = :hcubature, ) @test isapprox(int1, res, atol = err1) @test isapprox(int1b, res, atol = err1b) @test typeof(tplquad( func1, xmin, xmax, ymin, ymax, zmin, zmax, rtol = rtol, method = :vegas, )[1]) == Float64 @test typeof(tplquad( func1, xmin, xmax, ymin, ymax, zmin, zmax, rtol = rtol, method = :suave, )[1]) == Float64 @test tplquad( (z,y,x)->x*y*z, 0, 2, 0, 2, 0, 3, rtol = rtol, method = :hcubature, )[1] ≈ 18 @test typeof(tplquad( func1, xmin, xmax, ymin, ymax, zmin, zmax, rtol = rtol, method = :divonne, )[1]) == Float64 xmin2 = 0 * u"m" xmax2 = 4 * u"m" ymin2(x) = x^2 * u"m" ymax2(x) = x^3 zmin2(x, y) = 3 zmax2(x, y) = 4 func2(z, y, x) = y * x^3 * sin(z) int2, err2 = tplquad( func2, xmin2, xmax2, ymin2, ymax2, zmin2, zmax2, rtol = rtol, ) int2b, err2b = tplquad( func2, xmin2, xmax2, ymin2, ymax2, zmin2, zmax2, rtol = rtol, method = :hcubature, ) @test isapprox(int2, res * u"m^10", atol = err2) @test isapprox(int2b, res * u"m^10", atol = err2b) @test typeof(tplquad( func2, xmin2, xmax2, ymin2, ymax2, zmin2, zmax2, rtol = rtol, method = :vegas, )[1]) == typeof(1.0 * u"m^10") @test typeof(tplquad( func2, xmin2, xmax2, ymin2, ymax2, zmin2, zmax2, rtol = rtol, method = :suave, )[1]) == typeof(1.0 * u"m^10") @test typeof(tplquad( func2, xmin2, xmax2, ymin2, ymax2, zmin2, zmax2, rtol = rtol, method = :divonne, )[1]) == typeof(1.0 * u"m^10") @test_throws ErrorException tplquad( func2, xmin2, xmax2, ymin2, ymax2, zmin2, zmax2, rtol = rtol, method = :none, )[1] end
MultiQuad
https://github.com/aurelio-amerio/MultiQuad.jl.git
[ "MIT" ]
1.3.1
b6eb90a8a48763177796cb6944fec798ba482239
docs
7390
# MultiQuad.jl [![CI](https://github.com/aurelio-amerio/MultiQuad.jl/actions/workflows/CI.yml/badge.svg?branch=master)](https://github.com/aurelio-amerio/MultiQuad.jl/actions/workflows/CI.yml) [![codecov.io](https://codecov.io/github/aurelio-amerio/MultiQuad.jl/coverage.svg?branch=master)](https://codecov.io/github/aurelio-amerio/MultiQuad.jl?branch=master) **MultiQuad.jl** is a convenient interface to perform 1D, 2D and 3D numerical integrations. It uses [QuadGK](https://github.com/JuliaMath/QuadGK.jl), [Cuba](https://github.com/giordano/Cuba.jl) and [HCubature](https://github.com/stevengj/HCubature.jl) as back-ends. # Usage ## `quad` ```julia quad(arg::Function, x1, x2; method = :quadgk, kwargs...) ``` It is possible to use `quad` to perform 1D integrals of the following kind: <img src="https://latex.codecogs.com/png.latex?\dpi{150}&space;\int_{x1}^{x2}f(x)dx" title="\int_{x1}^{x2}f(x)dx" /> The supported adaptive integration methods are: - `:quadgk` - `:vegas` - `:suave` There are several fixed order quadrature methods available based on [`FastGaussQuadrature`](https://github.com/JuliaApproximation/FastGaussQuadrature.jl) - `:gausslegendre` - `:gausshermite` - `:gausslaguerre` - `:gausschebyshev` - `:gaussradau` - `:gausslobatto` If a specific integration routine is not needed, it is suggested to use `:quadgk` (the default option). For highly oscillating integrals, it is advised to use `:gausslegendre`with a high order (~10000). Please note that `:gausshermite` and `:gausslaguerre` are used to specific kind of integrals with infinite bounds. For more informations on these integration techniques, please follow the official documentation [here](https://juliaapproximation.github.io/FastGaussQuadrature.jl/stable/gaussquadrature/). While using fixed order quadrature methods, it is possible to use multithreading to compute the 1D quadrature, by passing the keyword argument `mutithreading=true` to `quad`. If the forseen integration time is long, it is also possible to display a progress bar by passing the keyword argument `verbose=true`. See [QuadGK](https://github.com/JuliaMath/QuadGK.jl) and [Cuba.jl](https://giordano.github.io/Cuba.jl/stable/) for all the available keyword arguments. ### Example 1 Compute: <img src="https://latex.codecogs.com/png.latex?\dpi{150}&space;\int_{0}^{4}&space;x^2e^{-x}dx" title="\int_{0}^{4} x^2e^{-x}dx" /> ```julia using MultiQuad func(x) = x^2*exp(-x) quad(func, 0, 4) # equivalent to quad(func, 0, 4, method=:quadgk) quad(func, 0, 4, method=:gausslegendre, order=1000) # or add a progress bar and use multithreading quad(func, 0, 4, method=:gausslegendre, order=10000, multithreading=true, verbose=true) # for certain kinds of integrals with infinite bounds, it may be possible to use a specific integration routine func(x) = x^2*exp(-x) quad(func, 0, Inf, method=:quadgk)[1] # gausslaguerre computes the integral of f(x)*exp(-x) from 0 to infinity quad(x -> x^2, method=:gausslaguerre, order=10000)[1] ``` ### Example 2 It is possible to compute integrals with unit of measurement using `Unitful`. For example, let's compute: <img src="https://latex.codecogs.com/png.latex?\dpi{150}&space;\int_{0&space;m}^{5&space;m}&space;x^2e^{-x}dx" title="\int_{0 m}^{5 m} x^2e^{-x}dx" /> ```julia using MultiQuad using Unitful func(x) = x^2 quad(func, 1u"m", 5u"m") ``` ## `dblquad` ```julia dblquad(arg::Function, x1, x2, y1::Function, y2::Function; method = :cuhre, kwargs...) dblquad(arg::Function, x1, x2, y1, y2; method = :cuhre, kwargs...) ``` It is possible to use `dblquad` to perform 2D integrals of the following kind: <img src="https://latex.codecogs.com/png.latex?\dpi{150}&space;\int_{x1}^{x2}dx\int_{y1(x)}^{y2(x)}dyf(y,x)" title="\int_{x1}^{x2}dx\int_{y1(x)}^{y2(x)}dyf(y,x)" /> The supported integration method are: - `hcubature` (default) - `:cuhre` - `:vegas` - `:suave` - `:divonne` It is suggested to use `:hcubature` (the default option). See [Cuba.jl](https://giordano.github.io/Cuba.jl/stable/) and [HCubature](https://github.com/stevengj/HCubature.jl) for all the available keyword arguments. ### Example 1 Compute: <img src="https://latex.codecogs.com/png.latex?\dpi{150}&space;\int_1^2&space;dx&space;\int_{0}^{x^2}dy&space;\sin(x)&space;y^2" title="\int_1^2 dx \int_{0}^{x^2}dy \sin(x) y^2" /> ```julia using MultiQuad func(y,x) = sin(x)*y^2 integral, error = dblquad(func, 1, 2, x->0, x->x^2, rtol=1e-9) ``` ### Example 2 It is possible to compute integrals with unit of measurement using `Unitful`. For example, let's compute: <img src="https://latex.codecogs.com/png.latex?\dpi{150}&space;\int_{1m}^{2m}dx\int_{0m^2}^{x^2}&space;dy&space;\,&space;x&space;y^2" title="\int_{1m}^{2m}dx\int_{0m^2}^{x^2} dy \, x y^2" /> ```julia using MultiQuad using Unitful func(y,x) = sin(x)*y^2 integral, error = dblquad(func, 1u"m", 2u"m", x->0u"m^2", x->x^2, rtol=1e-9) ``` ### Example 3 Compute: <img src="https://latex.codecogs.com/png.latex?\dpi{150}&space;\int_1^2&space;dx&space;\int_{0}^{4}dy&space;\sin(x)&space;y^2" title="\int_1^2 dx \int_{0}^{4}dy \sin(x) y^2" /> ```julia using MultiQuad func(y,x) = sin(x)*y^2 integral, error = dblquad(func, 1, 2, 0, 4, rtol=1e-9) ``` ## `tplquad` ```julia tplquad(arg::Function, x1, x2, y1::Function, y2::Function, z1::Function, z2::Function; method = :cuhre, kwargs...) ``` It is possible to use `quad` to perform 3D integrals of the following kind: <img src="https://latex.codecogs.com/png.latex?\dpi{150}&space;\int_{x1}^{x2}dx\int_{y1(x)}^{y2(x)}dy\int_{z1(x,y)}^{z2(x,y)}dz&space;\,&space;f(z,y,x)" title="\int_{x1}^{x2}dx\int_{y1(x)}^{y2(x)}dy\int_{z1(x,y)}^{z2(x,y)}dz \, f(z,y,x)" /> The supported integration method are: - `:cuhre` (default) - `:vegas` - `:suave` - `:divonne` It is suggested to use `:cuhre` (the default option) See [Cuba.jl](https://giordano.github.io/Cuba.jl/stable/) for all the available keyword arguments. ### Example 1 Compute: <img src="https://latex.codecogs.com/png.latex?\dpi{150}&space;\int_{0}^{4}dx\int_{x}^{x^2}dy\int_{2}^{3x}dz\sin(z)&space;\,&space;x&space;\,&space;y" title="\int_{0}^{4}dx\int_{x}^{x^2}dy\int_{2}^{3x}dz\sin(z) \, x \, y" /> ```julia using MultiQuad func(z,y,x) = sin(z)*y*x integral, error = tplquad(func, 0, 4, x->x, x->x^2, (x,y)->2, (x,y)->3*x) ``` ### Example 2 It is possible to compute integrals with unit of measurement using `Unitful`. For example, let's compute: <img src="https://latex.codecogs.com/png.latex?\dpi{150}&space;\int_{0m}^{4m}dx\int_{0m^2}^{x^2}dy\int_{0}^{3}dz\sin(z)&space;\,&space;x&space;\,&space;y" title="\int_{0m}^{4m}dx\int_{0m^2}^{x^2}dy\int_{0}^{3}dz\sin(z) \, x \, y" /> ```julia using MultiQuad using Unitful func(z,y,x) = sin(z)*y*x integral, error = tplquad(func, 0u"m", 4u"m", x->0u"m^2", x->x^2, (x,y)->0, (x,y)->3) ``` ### Example 3 Compute: <img src="https://latex.codecogs.com/png.latex?\dpi{150}&space;\int_{0}^{4}dx\int_{x}^{2}dy\int_{2}^{3}dz\sin(z)&space;\,&space;x&space;\,&space;y" title="\int_{0}^{4}dx\int_{1}^{2}dy\int_{2}^{3}dz\sin(z) \, x \, y" /> ```julia using MultiQuad func(z,y,x) = sin(z)*y*x integral, error = tplquad(func, 0, 4, 1, 2, 2, 3) ```
MultiQuad
https://github.com/aurelio-amerio/MultiQuad.jl.git
[ "MIT" ]
0.2.2
5500d6ddb814a60ecebbb204edd196107e258e54
code
3424
module TarIterators export TarIterator using Tar using BoundedStreams struct TarIterator{T,F<:Function} stream::T filter::F closestream::Bool end """ TarIterator(io[, predicate]) Iterator over an input stream open for reading. `io` may also be pathname of an existing tar file. The data in the stream or file must obey the `tar` file format understood by package `Tar`. If `predicate` is given, only tar elements with matching header data are processed. * `String` or `Regex`: `predicate` is applied to the element names. * `Symbol`: it must coincide with field `type` of `Tar.Header`. * boolean function: it is applied to the `Tar.Header` of the elements. * `Tuple`: AND of all predicates contained in tuple * `Vector`: OR of all predicates contained in vector Examples: ``` io = open("/tmp/abc.tar") TarIterator(io) # all entries TarIterator(io, :file) # all entries of file type TarIterator(io, "y") # only entry with name "y" TarIterator(io, r".*[.]txt") # all entries with name ending in ".txt" TarIterator(io, h -> h.size > 100) # only entries with data size > 100 ``` """ function TarIterator(source::T, a::F=nothing; close_stream::Bool=false) where {T,F} TarIterator(source, selector(a), close_stream) end function TarIterator(file::AbstractString, f=nothing; close_stream::Bool=false) TarIterator(open(file), f, close_stream=close_stream) end function Base.iterate(ti::TarIterator, status=nothing) stream = ti.stream status !== nothing && close(status) h = Tar.read_header(stream) while h !== nothing s = align(h.size) if ti.filter(h) closeop = ti.closestream ? BoundedStreams.CLOSE : s io = BoundedInputStream(stream, h.size, close=closeop) return (h, io), io end skip(stream, s) h = Tar.read_header(stream) end nothing end # align to TAR block size align(pos::Integer) = mod(-pos, 512) + pos # predicates processing selector(f::Function) = f selector(a::Tuple) = function AND(h::Tar.Header) for f in a if !selector(f)(h) return false end end true end selector(a::AbstractVector) = function OR(h::Tar.Header) for f in a if selector(f)(h) return true end end false end selector(a::Union{AbstractString,Nothing,Symbol,Regex}) = h::Tar.Header -> predicate(h, a) predicate(h::Tar.Header, ::Nothing) = true predicate(h::Tar.Header, a::AbstractString) = h.path == a predicate(h::Tar.Header, s::Symbol) = h.type == s function predicate(h::Tar.Header, r::Regex) fn = h.path m = match(r, fn) m !== nothing && m.match == fn end """ open(ti::TarIterator)::BoundedInputStream Skip to the first entry in tar stream according to predicates of `ti` and return an open input stream, which allows to read data part of this entry. """ function Base.open(ti::TarIterator) s = iterate(ti) s === nothing && throw(EOFError()) s[1][2] end """ open(ti::TarIterator) do h, io; ... end Process all tar entries selected by `ti` and provide `h::Tar.Header` and `io::BoundedInputStream` to the called function. """ function Base.open(f::Function, ti::TarIterator) for (h, io) in ti f(h, io) end end Base.close(ti::TarIterator) = close(ti.stream) Base.seekstart(ti::TarIterator) = seekstart(ti.stream) end # module
TarIterators
https://github.com/KlausC/TarIterators.jl.git
[ "MIT" ]
0.2.2
5500d6ddb814a60ecebbb204edd196107e258e54
code
167
using Test using TarIterators using BoundedStreams using Tar using CodecZlib using TranscodingStreams @testset "TarIterators" begin include("tariterators.jl"); end
TarIterators
https://github.com/KlausC/TarIterators.jl.git
[ "MIT" ]
0.2.2
5500d6ddb814a60ecebbb204edd196107e258e54
code
2040
# setup test file dir = mkpath(abspath(@__FILE__, "..", "data", "ball")) cd(dir) mkpath("sub") mkpath("empty") for (fn, size) in (("a", 10), ("b", 100), ("c", 0), ("d", 3)), sub in ("", "sub",) open(joinpath(sub, fn * ".dat"), "w") do io write(io, fn^size) end end cd(abspath(dir, "..")) tarfile = "test.tar" run(`sh -c "tar -cf $tarfile ball"`) run(`sh -c "gzip <$tarfile >$tarfile.gz"`) function opener(file::AbstractString, f=nothing; close_stream::Bool=false) source = open(file) if endswith(file, ".tar.gz") || endswith(file, ".tgz") source = GzipDecompressorStream(source) end TarIterator(source, f, close_stream=close_stream) end @testset "reading all elements of $tarfile" for tarfile = (tarfile, tarfile*".gz") ti = opener(tarfile) @test ti !== nothing s = iterate(ti) @test s isa Tuple (h, io), st = s @test h isa Tar.Header @test io isa BoundedInputStream @test h.type == :directory @test h.path == "ball/" @test close(ti) === nothing ti = opener(tarfile) @test open(ti) isa BoundedInputStream seekstart(ti) res1 = Any[] for (h, io) in ti push!(res1, h) push!(res1, read(io, String)) end @test length(res1) == 22 seekstart(ti) res2 = Any[] open(ti) do h, io push!(res2, h) push!(res2, read(io, String)) end @test length(res2) == 22 @test res1 == res2 end @testset "iterations predicate $p" for (p,m) in [(nothing, 11), ("ball/b.dat", 1), (r"^ball/(|.*/)a\.dat", 2), (:file, 8), (h->h.type == :file, 8), ((:file, h->h.size>10), 2), ([:directory, h->h.size>10], 5)] n = 0 open(TarIterator(tarfile, p)) do h, io n += 1 end @test n == m end
TarIterators
https://github.com/KlausC/TarIterators.jl.git
[ "MIT" ]
0.2.2
5500d6ddb814a60ecebbb204edd196107e258e54
docs
1648
# TarIterators.jl [![Build Status][gha-img]][gha-url] [![Coverage Status][codecov-img]][codecov-url] The `TarIterators` package can read from individual elements of POSIX TAR archives ("tarballs") as specified in [POSIX 1003.1-2001](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html). ## API & Usage The public API of `TarIterators` includes only standard functions and one type: * `TarIterator` — struct representing a file stream opened for reading a TAR file, may be restricted by predicates * `iterate` — deliver pairs of `Tar.header` and `BoundedInputStream` for each element * `close` - close wrapped stream * `open` - deliver `BoundedInputStream` for the next element of tar file or process all elements in a loop * `seekstart` - reset input to start ### Usage Example ```julia using TarIterators ti = TarIterator("/tmp/AB.tar", :file) for (h, io) in ti x = read(io, String) println(x) end # reset to start seekstart(ti) # or equivalently open(ti) do h, io x = read(io, String) println(x) end using CodecZlib cio = GzipDecompressorStream(open("/tmp/AB.tar.gz")) # process first file named "B" io = open(TarIterator(cio, "B", close_stream=true)) x = read(io, 10) close(io) # cio is closed implicitly ``` [gha-img]: https://github.com/KlausC/TarIterators.jl/workflows/CI/badge.svg [gha-url]: https://github.com/KlausC/TarIterators.jl/actions?query=workflow%3ACI [codecov-img]: https://codecov.io/gh/KlausC/TarIterators.jl/branch/master/graph/badge.svg [codecov-url]: https://codecov.io/gh/KlausC/TarIterators.jl
TarIterators
https://github.com/KlausC/TarIterators.jl.git
[ "MIT" ]
2.1.1
a9327ceb1e062f3b080ac368e7ce86c15a3499d0
code
302
module ContrastiveDivergenceRBM using Optimisers: AbstractRule, setup, update!, Adam using RestrictedBoltzmannMachines: RBM, moments_from_samples, sample_from_inputs, zerosum!, rescale_weights!, infinite_minibatches, sample_v_from_v, ∂free_energy, ∂regularize! include("cd.jl") end # module
ContrastiveDivergenceRBM
https://github.com/cossio/ContrastiveDivergenceRBM.jl.git
[ "MIT" ]
2.1.1
a9327ceb1e062f3b080ac368e7ce86c15a3499d0
code
1983
""" cd!(rbm, data) Trains the RBM on data using Contrastive divergence. """ function cd!( rbm::RBM, data::AbstractArray; batchsize::Int = 1, iters::Int = 1, # number of gradient updates steps::Int = 1, # MC steps to update fantasy chains optim::AbstractRule = Adam(), # optimizer rule moments = moments_from_samples(rbm.visible, data), # sufficient statistics for visible layer # regularization l2_fields::Real = 0, # visible fields L2 regularization l1_weights::Real = 0, # weights L1 regularization l2_weights::Real = 0, # weights L2 regularization l2l1_weights::Real = 0, # weights L2/L1 regularization # gauge zerosum::Bool = true, # zerosum gauge for Potts layers rescale::Bool = true, # normalize weights to unit norm (for continuous hidden units only) callback = Returns(nothing), # called for every batch shuffle::Bool = true, # parameters to optimize ps = (; visible = rbm.visible.par, hidden = rbm.hidden.par, w = rbm.w), state = setup(optim, ps) # initialize optimiser state ) @assert size(data) == (size(rbm.visible)..., size(data)[end]) # gauge constraints zerosum && zerosum!(rbm) rescale && rescale_weights!(rbm) for (iter, (vd,)) in zip(1:iters, infinite_minibatches(data; batchsize, shuffle)) # fantasy chains, sampled from the data vm = sample_v_from_v(rbm, vd; steps) # compute gradient ∂d = ∂free_energy(rbm, vd; moments) ∂m = ∂free_energy(rbm, vm) ∂ = ∂d - ∂m # weight decay ∂regularize!(∂, rbm; l2_fields, l1_weights, l2_weights, l2l1_weights, zerosum) # feed gradient to Optimiser rule gs = (; visible = ∂.visible, hidden = ∂.hidden, w = ∂.w) state, ps = update!(state, ps, gs) # reset gauge rescale && rescale_weights!(rbm) zerosum && zerosum!(rbm) callback(; rbm, optim, iter, vm, vd, ∂) end return state, ps end
ContrastiveDivergenceRBM
https://github.com/cossio/ContrastiveDivergenceRBM.jl.git
[ "MIT" ]
2.1.1
a9327ceb1e062f3b080ac368e7ce86c15a3499d0
code
172
import Aqua import ContrastiveDivergenceRBM using Test: @testset @testset verbose = true "aqua" begin Aqua.test_all(ContrastiveDivergenceRBM; ambiguities = false) end
ContrastiveDivergenceRBM
https://github.com/cossio/ContrastiveDivergenceRBM.jl.git
[ "MIT" ]
2.1.1
a9327ceb1e062f3b080ac368e7ce86c15a3499d0
code
706
using Test: @test using LinearAlgebra: svd using RestrictedBoltzmannMachines: RBM, Spin using Optimisers: Adam using ContrastiveDivergenceRBM: cd! N = 500 M = 300 K = 5 rbm = RBM(Spin((N,)), Spin((M,)), randn(N, M) / √N) v = sign.(randn(N, K)) train_data = repeat(v, 1, 100) niter = 1000 save_sv_every = 100 _myiter = 0 sv_history = zeros(length(rbm.hidden), niter ÷ save_sv_every) function callback(; rbm, kw...) rbm.visible.θ .= 0 rbm.hidden.θ .= 0 global _myiter += 1 if _myiter % save_sv_every == 0 sv_history[:, _myiter ÷ save_sv_every] .= svd(rbm.w).S end end cd!(rbm, train_data; iters=niter, batchsize=128, callback, l2_weights=0.001, steps=10, optim=Adam(0.0001))
ContrastiveDivergenceRBM
https://github.com/cossio/ContrastiveDivergenceRBM.jl.git
[ "MIT" ]
2.1.1
a9327ceb1e062f3b080ac368e7ce86c15a3499d0
code
78
module aqua_tests include("aqua.jl") end module cd_tests include("cd.jl") end
ContrastiveDivergenceRBM
https://github.com/cossio/ContrastiveDivergenceRBM.jl.git