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
[ "Apache-2.0" ]
0.4.0
0736fd885e445c13b7b58e31d1ccc37a4950f7df
code
4967
using UnitDiskMapping, Test using Graphs, GenericTensorNetworks using UnitDiskMapping: is_independent_set @testset "crossing connect count" begin g = smallgraph(:bull) ug = embed_graph(g; vertex_order=collect(nv(g):-1:1)) gadgets = [ Cross{false}(), Cross{true}(), Turn(), WTurn(), Branch(), BranchFix(), TCon(), TrivialTurn(), RotatedGadget(TCon(), 1), ReflectedGadget(Cross{true}(), "y"), ReflectedGadget(TrivialTurn(), "y"), BranchFixB(), ReflectedGadget(RotatedGadget(TCon(), 1), "y"),] for (s, c) in zip(gadgets, [1,0, 1,1,0,1,1,1, 0, 0, 2, 0, 1, ]) @show s @test sum(match.(Ref(s), Ref(ug.content), (0:size(ug.content, 1))', 0:size(ug.content,2))) == c end mug, tape = apply_crossing_gadgets!(UnitDiskMapping.UnWeighted(), copy(ug)) for s in gadgets @test sum(match.(Ref(s), Ref(mug.content), (0:size(mug.content, 1))', 0:size(mug.content,2))) == 0 end ug2 = unapply_gadgets!(copy(mug), tape, [])[1] @test UnitDiskMapping.padding(ug2) == 2 @test ug == ug2 end @testset "map configurations back" begin for graphname in [:petersen, :bull, :cubical, :house, :diamond, :tutte] @show graphname g = smallgraph(graphname) ug = embed_graph(g) mis_overhead0 = UnitDiskMapping.mis_overhead_copylines(ug) ug2, tape = apply_crossing_gadgets!(UnitDiskMapping.UnWeighted(), copy(ug)) ug3, tape2 = apply_simplifier_gadgets!(copy(ug2); ruleset=[RotatedGadget(UnitDiskMapping.DanglingLeg(), n) for n=0:3]) mis_overhead1 = sum(x->mis_overhead(x[1]), tape) mis_overhead2 = sum(x->mis_overhead(x[1]), tape2) @show mis_overhead2 gp = GenericTensorNetwork(IndependentSet(SimpleGraph(ug3)); optimizer=GreedyMethod(nrepeat=10)) missize_map = solve(gp, SizeMax())[].n missize = solve(GenericTensorNetwork(IndependentSet(g)), SizeMax())[].n @test mis_overhead0 + mis_overhead1 + mis_overhead2 + missize == missize_map misconfig = solve(gp, SingleConfigMax())[].c c = zeros(Int, size(ug3.content)) for (i, loc) in enumerate(findall(!isempty, ug3.content)) c[loc] = misconfig.data[i] end @test all(ci->UnitDiskMapping.safe_get(c, ci.I...)==0 || (UnitDiskMapping.safe_get(c, ci.I[1], ci.I[2]+1) == 0 && UnitDiskMapping.safe_get(c, ci.I[1]+1, ci.I[2]) == 0 && UnitDiskMapping.safe_get(c, ci.I[1]-1, ci.I[2]) == 0 && UnitDiskMapping.safe_get(c, ci.I[1], ci.I[2]-1) == 0 && UnitDiskMapping.safe_get(c, ci.I[1]-1, ci.I[2]-1) == 0 && UnitDiskMapping.safe_get(c, ci.I[1]-1, ci.I[2]+1) == 0 && UnitDiskMapping.safe_get(c, ci.I[1]+1, ci.I[2]-1) == 0 && UnitDiskMapping.safe_get(c, ci.I[1]+1, ci.I[2]+1) == 0 ), CartesianIndices((55, 55))) res, cs = unapply_gadgets!(copy(ug3), [tape..., tape2...], [copy(c)]) @test count(isone, cs[1]) == missize @test is_independent_set(g, cs[1]) end end @testset "interface K23, empty and path" begin K23 = SimpleGraph(5) add_edge!(K23, 1, 5) add_edge!(K23, 4, 5) add_edge!(K23, 4, 3) add_edge!(K23, 3, 2) add_edge!(K23, 5, 2) add_edge!(K23, 1, 3) for g in [K23, SimpleGraph(5), path_graph(5)] res = map_graph(g) # checking size gp = GenericTensorNetwork(IndependentSet(SimpleGraph(res.grid_graph)); optimizer=TreeSA(ntrials=1, niters=10)) missize_map = solve(gp, SizeMax())[].n missize = solve(GenericTensorNetwork(IndependentSet(g)), SizeMax())[].n @test res.mis_overhead + missize == missize_map # checking mapping back misconfig = solve(gp, SingleConfigMax())[].c original_configs = map_config_back(res, collect(Bool, misconfig.data)) @test count(isone, original_configs) == missize @test is_independent_set(g, original_configs) end end @testset "interface" begin g = smallgraph(:petersen) res = map_graph(g) # checking size gp = GenericTensorNetwork(IndependentSet(SimpleGraph(res.grid_graph)); optimizer=TreeSA(ntrials=1, niters=10)) missize_map = solve(gp, SizeMax())[].n missize = solve(GenericTensorNetwork(IndependentSet(g)), SizeMax())[].n @test res.mis_overhead + missize == missize_map # checking mapping back misconfig = solve(gp, SingleConfigMax())[].c original_configs = map_config_back(res, collect(misconfig.data)) @test count(isone, original_configs) == missize @test is_independent_set(g, original_configs) @test println(res.grid_graph) === nothing c = zeros(Int, size(res.grid_graph)) for (i, n) in enumerate(res.grid_graph.nodes) c[n.loc...] = misconfig.data[i] end @test print_config(res, c) === nothing end
UnitDiskMapping
https://github.com/QuEraComputing/UnitDiskMapping.jl.git
[ "Apache-2.0" ]
0.4.0
0736fd885e445c13b7b58e31d1ccc37a4950f7df
code
1475
using GenericTensorNetworks using Test, UnitDiskMapping, Graphs #using LuxorGraphPlot @testset "multiplier" begin m, pins = UnitDiskMapping.multiplier() g, ws = UnitDiskMapping.graph_and_weights(m) configs = solve(GenericTensorNetwork(IndependentSet(g, ws)), ConfigsMax())[].c # completeness inputs = Int[] for config in configs ci = config[pins[1:4]] push!(inputs, ci[1]+ci[2]<<1+ci[3]<<2+ci[4]<<3) end @test length(unique(inputs)) == 16 # soundness for config in configs ci = Int.(config[pins]) println(ci[1:4], " " ,ci[5]) @test ci[2] == ci[6] @test ci[3] == ci[8] @test ci[1] + ci[2]*ci[3] + ci[4] == ci[5] + 2 * ci[7] end end @testset "factoring" begin mres = UnitDiskMapping.map_factoring(2, 2) res = UnitDiskMapping.solve_factoring(mres, 6) do g, ws collect(Int, solve(GenericTensorNetwork(IndependentSet(g, ws)), SingleConfigMax())[].c.data) end @test res == (2, 3) || res == (3, 2) res = UnitDiskMapping.solve_factoring(mres, 9) do g, ws collect(Int, solve(GenericTensorNetwork(IndependentSet(g, ws)), SingleConfigMax())[].c.data) end @test res == (3, 3) mres = UnitDiskMapping.map_factoring(2, 3) res = UnitDiskMapping.solve_factoring(mres, 15) do g, ws collect(Int, solve(GenericTensorNetwork(IndependentSet(g, ws)), SingleConfigMax())[].c.data) end @test res == (5, 3) || res == (3, 5) end
UnitDiskMapping
https://github.com/QuEraComputing/UnitDiskMapping.jl.git
[ "Apache-2.0" ]
0.4.0
0736fd885e445c13b7b58e31d1ccc37a4950f7df
code
800
using UnitDiskMapping using Test @testset "utils" begin include("utils.jl") end @testset "copyline" begin include("copyline.jl") end @testset "multiplier" begin include("multiplier.jl") end @testset "logic gates" begin include("logicgates.jl") end @testset "mapping" begin include("mapping.jl") end @testset "extracting_results" begin include("extracting_results.jl") end @testset "gadgets" begin include("gadgets.jl") end @testset "path decomposition" begin include("pathdecomposition/pathdecomposition.jl") end @testset "simplifiers" begin include("simplifiers.jl") end @testset "weighted" begin include("weighted.jl") end @testset "drag and drop" begin include("dragondrop.jl") end @testset "visualize" begin include("visualize.jl") end
UnitDiskMapping
https://github.com/QuEraComputing/UnitDiskMapping.jl.git
[ "Apache-2.0" ]
0.4.0
0736fd885e445c13b7b58e31d1ccc37a4950f7df
code
842
using UnitDiskMapping, Test, Graphs @testset "constructor" begin p = UnitDiskMapping.DanglingLeg() @test size(p) == (4, 3) @test UnitDiskMapping.source_locations(p) == UnitDiskMapping.Node.([(2,2), (3,2), (4,2)]) @test UnitDiskMapping.mapped_locations(p) == UnitDiskMapping.Node.([(4,2)]) end @testset "macros" begin @gg Test1 = """ . . . . . . @ . . @ . . . @ . . """ => """ . . . . . . . . . . . . . @ . . """ sl, sg, sp = source_graph(Test1()) ml, mg, mp = mapped_graph(Test1()) @show sg, collect(edges(sg)) @test sl == UnitDiskMapping.Node.([(3, 2), (4,2), (2, 3)]) @test sg == UnitDiskMapping.simplegraph([(1,2), (1,3)]) @test sp == [2] @test ml == [UnitDiskMapping.Node(4,2)] @test mg == UnitDiskMapping.SimpleGraph(1) @test mp == [1] end
UnitDiskMapping
https://github.com/QuEraComputing/UnitDiskMapping.jl.git
[ "Apache-2.0" ]
0.4.0
0736fd885e445c13b7b58e31d1ccc37a4950f7df
code
382
using UnitDiskMapping: rotate90, reflectx, reflecty, reflectdiag, reflectoffdiag using Test @testset "symmetry operations" begin center = (2,2) loc = (4,3) @test rotate90(loc, center) == (1,4) @test reflectx(loc, center) == (4,1) @test reflecty(loc, center) == (0,3) @test reflectdiag(loc, center) == (1,0) @test reflectoffdiag(loc, center) == (3,4) end
UnitDiskMapping
https://github.com/QuEraComputing/UnitDiskMapping.jl.git
[ "Apache-2.0" ]
0.4.0
0736fd885e445c13b7b58e31d1ccc37a4950f7df
code
1449
using UnitDiskMapping, Graphs, LuxorGraphPlot, LuxorGraphPlot.Luxor, LinearAlgebra using Test @testset "show_graph" begin g = smallgraph(:petersen) res = map_graph(g) @test show_graph(res.grid_graph) isa Luxor.Drawing @test show_grayscale(res.grid_graph) isa Luxor.Drawing @test show_pins(res.grid_graph, Dict("red"=>[1,2,4])) isa Luxor.Drawing config = rand(0:1, length(coordinates(res.grid_graph))) @test show_config(res.grid_graph, config; show_number=true) isa Drawing end @testset "show_graph - weighted" begin g = smallgraph(:petersen) res = map_graph(Weighted(), g) @test show_grayscale(res.grid_graph) isa Luxor.Drawing @test show_pins(res) isa Luxor.Drawing end @testset "show_pins, logic" begin mres = UnitDiskMapping.map_factoring(2, 2) @test show_pins(mres) isa Luxor.Drawing gd = UnitDiskMapping.Gate(:AND) @test show_pins(gd) isa Luxor.Drawing end @testset "show_pins, qubo" begin n = 7 H = -randn(n) * 0.05 J = triu(randn(n, n) * 0.001, 1); J += J' qubo = UnitDiskMapping.map_qubo(J, H) @test show_pins(qubo) isa Luxor.Drawing m, n = 6, 6 coupling = [ [(i,j,i,j+1,0.01*randn()) for i=1:m, j=1:n-1]..., [(i,j,i+1,j,0.01*randn()) for i=1:m-1, j=1:n]... ] onsite = vec([(i, j, 0.01*randn()) for i=1:m, j=1:n]) qubo = UnitDiskMapping.map_qubo_square(coupling, onsite) @test show_pins(qubo) isa Luxor.Drawing end
UnitDiskMapping
https://github.com/QuEraComputing/UnitDiskMapping.jl.git
[ "Apache-2.0" ]
0.4.0
0736fd885e445c13b7b58e31d1ccc37a4950f7df
code
4712
using Test, UnitDiskMapping, Graphs, GenericTensorNetworks using GenericTensorNetworks: TropicalF64, content using Random using UnitDiskMapping: is_independent_set @testset "gadgets" begin for s in [UnitDiskMapping.crossing_ruleset_weighted..., UnitDiskMapping.default_simplifier_ruleset(Weighted())...] println("Testing gadget:\n$s") locs1, g1, pins1 = source_graph(s) locs2, g2, pins2 = mapped_graph(s) @assert length(locs1) == nv(g1) w1 = getfield.(locs1, :weight) w2 = getfield.(locs2, :weight) w1[pins1] .-= 1 w2[pins2] .-= 1 gp1 = GenericTensorNetwork(IndependentSet(g1, w1), openvertices=pins1) gp2 = GenericTensorNetwork(IndependentSet(g2, w2), openvertices=pins2) m1 = solve(gp1, SizeMax()) m2 = solve(gp2, SizeMax()) mm1 = maximum(m1) mm2 = maximum(m2) @test nv(g1) == length(locs1) && nv(g2) == length(locs2) if !(all((mm1 .== m1) .== (mm2 .== m2))) @show m1 @show m2 end @test all((mm1 .== m1) .== (mm2 .== m2)) @test content(mm1 / mm2) == -mis_overhead(s) end end @testset "copy lines" begin for (vstart, vstop, hstop) in [ (3, 7, 8), (3, 5, 8), (5, 9, 8), (5, 5, 8), (1, 7, 5), (5, 8, 5), (1, 5, 5), (5, 5, 5)] tc = UnitDiskMapping.CopyLine(1, 5, 5, vstart, vstop, hstop) locs = UnitDiskMapping.copyline_locations(UnitDiskMapping.WeightedNode, tc; padding=2) g = SimpleGraph(length(locs)) weights = getfield.(locs, :weight) for i=1:length(locs)-1 if i==1 || locs[i-1].weight == 1 # starting point add_edge!(g, length(locs), i) else add_edge!(g, i, i-1) end end gp = GenericTensorNetwork(IndependentSet(g, weights)) @test solve(gp, SizeMax())[].n == UnitDiskMapping.mis_overhead_copyline(Weighted(), tc) end end @testset "map configurations back" begin Random.seed!(2) for graphname in [:petersen, :bull, :cubical, :house, :diamond, :tutte] @show graphname g = smallgraph(graphname) ug = embed_graph(Weighted(), g) mis_overhead0 = UnitDiskMapping.mis_overhead_copylines(ug) ug2, tape = apply_crossing_gadgets!(Weighted(), copy(ug)) ug3, tape2 = apply_simplifier_gadgets!(copy(ug2); ruleset=[UnitDiskMapping.weighted(RotatedGadget(UnitDiskMapping.DanglingLeg(), n)) for n=0:3]) mis_overhead1 = sum(x->mis_overhead(x[1]), tape) mis_overhead2 = isempty(tape2) ? 0 : sum(x->mis_overhead(x[1]), tape2) # trace back configurations mgraph = SimpleGraph(ug3) weights = fill(0.5, nv(g)) r = UnitDiskMapping.MappingResult(GridGraph(ug3), ug3.lines, ug3.padding, [tape..., tape2...], mis_overhead0+mis_overhead1+mis_overhead2) mapped_weights = UnitDiskMapping.map_weights(r, weights) gp = GenericTensorNetwork(IndependentSet(mgraph, mapped_weights); optimizer=GreedyMethod(nrepeat=10)) missize_map = solve(gp, CountingMax())[] missize = solve(GenericTensorNetwork(IndependentSet(g, weights)), CountingMax())[] @test mis_overhead0 + mis_overhead1 + mis_overhead2 + missize.n == missize_map.n @test missize.c == missize_map.c T = GenericTensorNetworks.sampler_type(nv(mgraph), 2) misconfig = solve(gp, SingleConfigMax())[].c c = zeros(Int, size(ug3)) for (i, n) in enumerate(r.grid_graph.nodes) c[n.loc...] = misconfig.data[i] end center_locations = trace_centers(r) indices = CartesianIndex.(center_locations) sc = c[indices] @test count(isone, sc) == missize.n * 2 @test is_independent_set(g, sc) end end @testset "interface" begin Random.seed!(2) g = smallgraph(:petersen) res = map_graph(Weighted(), g) # checking size mgraph, _ = graph_and_weights(res.grid_graph) ws = rand(nv(g)) weights = UnitDiskMapping.map_weights(res, ws) gp = GenericTensorNetwork(IndependentSet(mgraph, weights); optimizer=TreeSA(ntrials=1, niters=10)) missize_map = solve(gp, SizeMax())[].n missize = solve(GenericTensorNetwork(IndependentSet(g, ws)), SizeMax())[].n @test res.mis_overhead + missize == missize_map # checking mapping back T = GenericTensorNetworks.sampler_type(nv(mgraph), 2) misconfig = solve(gp, SingleConfigMax())[].c original_configs = map_config_back(res, collect(misconfig.data)) @test count(isone, original_configs) == solve(GenericTensorNetwork(IndependentSet(g)), SizeMax())[].n @test is_independent_set(g, original_configs) end
UnitDiskMapping
https://github.com/QuEraComputing/UnitDiskMapping.jl.git
[ "Apache-2.0" ]
0.4.0
0736fd885e445c13b7b58e31d1ccc37a4950f7df
code
715
using Random, Test, UnitDiskMapping using UnitDiskMapping.PathDecomposition: branch_and_bound, vsep, Layout using Graphs @testset "B & B" begin Random.seed!(2) g = smallgraph(:petersen) adjm = adjacency_matrix(g) for i=1:10 pm = randperm(nv(g)) gi = SimpleGraph(adjm[pm, pm]) L = branch_and_bound(gi) @test vsep(L) == 5 @test vsep(Layout(gi, L.vertices)) == 5 arem = UnitDiskMapping.remove_order(g, vertices(L)) @test sum(length, arem) == nv(g) end g = smallgraph(:tutte) res = pathwidth(g, MinhThiTrick()) @test vsep(res) == 6 g = smallgraph(:tutte) res = pathwidth(g, Greedy(nrepeat=50)) @test vsep(res) == 6 end
UnitDiskMapping
https://github.com/QuEraComputing/UnitDiskMapping.jl.git
[ "Apache-2.0" ]
0.4.0
0736fd885e445c13b7b58e31d1ccc37a4950f7df
docs
3804
# UnitDiskMapping [![CI](https://github.com/QuEraComputing/UnitDiskMapping.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/QuEraComputing/UnitDiskMapping.jl/actions/workflows/ci.yml) [![codecov](https://codecov.io/github/QuEraComputing/UnitDiskMapping.jl/branch/main/graph/badge.svg?token=fwlEQnQICw)](https://codecov.io/github/QuEraComputing/UnitDiskMapping.jl) ## Installation <p> <code>UnitDiskMapping</code> is a &nbsp; <a href="https://julialang.org"> <img src="https://raw.githubusercontent.com/JuliaLang/julia-logo-graphics/master/images/julia.ico" width="16em"> Julia Language </a> &nbsp; package for reducing a <a href="https://en.wikipedia.org/wiki/Independent_set_(graph_theory)">generic maximum (weighted) independent set problem</a>, <a href="https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization"> quadratic unconstrained binary optimization (QUBO) problem</a> or <a href="https://en.wikipedia.org/wiki/Integer_factorization">integer factorization problem</a> to a maximum independent set problem on a unit disk grid graph (or hardcore lattice gas in physics), which can then be naturally encoded in neutral-atom quantum computers. To install <code>UnitDiskMapping</code>, please <a href="https://docs.julialang.org/en/v1/manual/getting-started/">open Julia's interactive session (known as REPL)</a> and press the <kbd>]</kbd> key in the REPL to use the package mode, and then type the commands below. </p> For installing the current master branch, please type: ```julia pkg> add https://github.com/QuEraComputing/UnitDiskMapping.jl.git ``` For stable release (not yet ready): ```julia pkg> add UnitDiskMapping ``` ## Examples Please check the following notebooks: 1. [Unit Disk Mapping](https://queracomputing.github.io/UnitDiskMapping.jl/notebooks/tutorial.html), which contains the examples in ["Quantum Optimization with Arbitrary Connectivity Using Rydberg Atom Arrays"](https://journals.aps.org/prxquantum/abstract/10.1103/PRXQuantum.4.010316): * Reduction from a generic weighted or unweighted maximum independent set (MIS) problem to that on a King's subgraph (KSG). * Reduction from a generic or square-lattice QUBO problem to an MIS problem on a unit-disk grid graph. * Reduction from an integer factorization problem to an MIS problem on a unit-disk grid graph. 2. [Unweighted KSG reduction of the independent set problem](https://queracomputing.github.io/UnitDiskMapping.jl/notebooks/unweighted.html), which contains the unweighted reduction from a general graph to a King's subgraph. It covers all example graphs in paper: "Computer-Assisted Gadget Design and Problem Reduction of Unweighted Maximum Independent Set" (To be published). ![](https://user-images.githubusercontent.com/6257240/198861111-4499c17d-9938-406b-8253-943b01f4633c.png) To run the notebook locally, you will need to activate and instantiate the local environment that specified in the [`notebooks`](notebooks) directory: ```bash $ cd notebooks $ julia --project -e 'using Pkg; Pkg.instantiate()' ``` To run the notebook, just type in the same terminal: ```bash julia --project -e "import Pluto; Pluto.run()" ``` At this point, your browser should automatically launch and display a list of available notebooks you can run. You should just see the notebooks listed. ## Supporting and Citing Much of the software in this ecosystem was developed as a part of an academic research project. If you would like to help support it, please star the repository. If you use our software as part of your research, teaching, or other activities, we would like to request you to cite our [work](https://arxiv.org/abs/2209.03965). The [CITATION.bib](CITATION.bib) file in the root of this repository lists the relevant papers.
UnitDiskMapping
https://github.com/QuEraComputing/UnitDiskMapping.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
code
2016
""" NumaAllocators.LibNUMA NUMA Support for Linux See https://github.com/numactl/numactl """ module LibNUMA using ..NumaAllocators: AbstractNumaAllocator import ArrayAllocators: AbstractArrayAllocator, nbytes, allocate import ArrayAllocators: lineage_finalizer using NUMA_jll @static if ( VERSION >= v"1.6" && NUMA_jll.is_available() ) || isdefined(NUMA_jll, :libnuma) const libnuma = NUMA_jll.libnuma else const libnuma = nothing end function numa_alloc_onnode(size, node) return ccall((:numa_alloc_onnode, libnuma), Ptr{Nothing}, (Csize_t, Cint), size, node) end function numa_alloc_local(size) return ccall((:numa_alloc_local, libnuma), Ptr{Nothing}, (Csize_t,), size) end function numa_free(arr::AbstractArray) numa_free(arr, sizeof(arr)) end function numa_free(mem, size) return ccall((:numa_free, libnuma), Nothing, (Ptr{Nothing}, Csize_t), mem, size) end function numa_num_task_nodes() return ccall((:numa_numa_task_nodes, libnuma), Cint, ()) end function numa_max_node() return ccall((:numa_max_node, libnuma), Cint, ()) end function numa_node_of_cpu(cpu = sched_getcpu()) return ccall((:numa_node_of_cpu, libnuma), Cint, (Cint,), cpu) end function sched_getcpu() return ccall(:sched_getcpu, Cint, ()) end function wrap_numa(::Type{ArrayType}, ptr::Ptr{T}, dims) where {T, ArrayType <: AbstractArray{T}} if ptr == C_NULL throw(OutOfMemoryError()) end arr = unsafe_wrap(ArrayType, ptr, dims; own = false) lineage_finalizer(numa_free, arr) return arr end abstract type AbstractLibNumaAllocator{B} <: AbstractNumaAllocator{B} end Base.unsafe_wrap(::AbstractLibNumaAllocator, args...) = wrap_numa(args...) """ LibNumaAllocator{B} Allocate memory via `numa_alloc_onnode`. See https://linux.die.net/man/3/numa """ struct LibNumaAllocator{B} <: AbstractLibNumaAllocator{B} node::Cint end function allocate(n::LibNumaAllocator, num_bytes) return numa_alloc_onnode(num_bytes, n.node) end end # module LibNUMA
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
code
2009
""" NumaAllocators Extends `ArrayAllocators` to allocate memory on specific NUMA nodes. # Examples ```julia using NumaAllocators Array{UInt8}(numa(0), 100) Array{UInt8}(NumaAllocator(1), 100) ``` """ module NumaAllocators @static if VERSION >= v"1.3" using NUMA_jll end using ArrayAllocators: AbstractArrayAllocator export NumaAllocator, numa export current_numa_node, highest_numa_node abstract type AbstractNumaAllocator{B} <: AbstractArrayAllocator{B} end include("Windows.jl") include("LibNUMA.jl") @static if Sys.iswindows() import .Windows: WinNumaAllocator const NumaAllocator = WinNumaAllocator elseif ( VERSION >= v"1.6" && NUMA_jll.is_available() ) || isdefined(NUMA_jll, :libnuma) import .LibNUMA: LibNumaAllocator const NumaAllocator = LibNumaAllocator end if @isdefined(NumaAllocator) numa(node) = NumaAllocator(node) end """ NumaAllocator(node) Cross-platform NUMA allocator # Example ```jldoctest julia> using NumaAllocators julia> Array{UInt8}(NumaAllocator(0), 32, 32); ``` """ NumaAllocator """ numa(node) Create a `NumaAllocator` on NUMA node `node`. Short hand for [`NumaAllocator`](@ref) constructor. # Example ```jldoctest julia> using NumaAllocators julia> Array{UInt8}(numa(0), 32, 32); ``` """ numa """ current_numa_node()::Int Returns the current NUMA node as an Int """ function current_numa_node()::Int @static if Sys.iswindows() return Int(Windows.GetNumaProcessorNode()) elseif Sys.islinux() return Int(LibNUMA.numa_node_of_cpu()) else error("current_numa_node is not implemented for this platform") end end """ highest_numa_node()::Int Returns the highest NUMA node as an Int """ function highest_numa_node()::Int @static if Sys.iswindows() return Int(Windows.GetNumaHighestNodeNumber()) elseif Sys.islinux() return Int(LibNUMA.numa_max_node()) else error("highest_numa_node is not implemented for this platform") end end end
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
code
2598
""" NumaAllocators.Windows NUMA support for Windows. See also https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocexnuma """ module Windows using ..NumaAllocators: AbstractNumaAllocator import ArrayAllocators: allocate, iszeroinit using ArrayAllocators.ByteCalculators: nbytes using ArrayAllocators.Windows: wrap_virtual, hCurrentProcess, MEM_COMMIT_RESERVE, PAGE_READWRITE, kernel32 function GetNumaProcessorNode(processor = GetCurrentProcessorNumber()) node_number = Ref{Cuchar}(0) status = ccall((:GetNumaProcessorNode, kernel32), Cint, (Cuchar, Ptr{Cuchar}), processor, node_number) if status == 0 error("Could not retrieve NUMA node for processor $processor.") end return node_number[] end # https://docs.microsoft.com/en-us/windows/win32/api/systemtopologyapi/nf-systemtopologyapi-getnumahighestnodenumber function GetNumaHighestNodeNumber() node_number = Ref{Culong}(0) status = ccall((:GetNumaHighestNodeNumber, kernel32), Cint, (Ptr{Culong},), node_number) if status == 0 error("Could not retrieve highest NUMA node.") end return node_number[] end function GetCurrentProcessorNumber() return ccall((:GetCurrentProcessorNumber, "kernel32"), Cint, ()) end #= LPVOID VirtualAllocExNuma( [in] HANDLE hProcess, [in, optional] LPVOID lpAddress, [in] SIZE_T dwSize, [in] DWORD flAllocationType, [in] DWORD flProtect, [in] DWORD nndPreferred ); =# function VirtualAllocExNuma(hProcess, lpAddress, dwSize, flAllocationType, flProtect, nndPreferred) ccall((:VirtualAllocExNuma, kernel32), Ptr{Nothing}, (Ptr{Nothing}, Ptr{Nothing}, Csize_t, Culong, Culong, Culong), hProcess, lpAddress, dwSize, flAllocationType, flProtect, nndPreferred) end function VirtualAllocExNuma(dest_size, numa_node) VirtualAllocExNuma(hCurrentProcess, C_NULL, dest_size, MEM_COMMIT_RESERVE, PAGE_READWRITE, numa_node) end abstract type AbstractWinNumaAllocator{B} <: AbstractNumaAllocator{B} end """ WinNumaAllocator Allocate memory on a specific NUMA node with `VirtualAllocExNuma`. See also https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocexnuma """ struct WinNumaAllocator{B} <: AbstractWinNumaAllocator{B} node::Int end function allocate(n::WinNumaAllocator, num_bytes) return VirtualAllocExNuma(num_bytes, n.node) end Base.unsafe_wrap(::WinNumaAllocator, args...) = wrap_virtual(args...) iszeroinit(::Type{A}) where A <: WinNumaAllocator = true end # module Windows
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
code
694
""" SafeByteCalculators Extension of [`ArrayAllocators.ByteCalculators`](@ref) using [SaferIntegers.jl](https://github.com/JeffreySarnoff/SaferIntegers.jl). """ module SafeByteCalculators import ArrayAllocators using ArrayAllocators.ByteCalculators: AbstractByteCalculator using SaferIntegers: SafeInt export SafeByteCalculator """ SafeByteCalculator Use `SafeInt` from SaferIntegers.jl to calculate the number of bytes to allocate for an Array. """ struct SafeByteCalculator{T} <: AbstractByteCalculator{T} dims::Dims SafeByteCalculator{T}(dims::Dims) where T = new{T}(dims) end Base.length(b::SafeByteCalculator) = prod(SafeInt.(b.dims)) end # module SafeByteCalculator
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
code
1197
using ArrayAllocators using SafeByteCalculators using NumaAllocators using Documenter DocMeta.setdocmeta!(ArrayAllocators, :DocTestSetup, :(using ArrayAllocators); recursive=true) makedocs(; modules=[ArrayAllocators, SafeByteCalculators, NumaAllocators], authors="Mark Kittisopikul <[email protected]> and contributors", repo="https://github.com/mkitti/ArrayAllocators.jl/blob/{commit}{path}#{line}", sitename="ArrayAllocators.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://mkitti.github.io/ArrayAllocators.jl", assets=String[], ), pages=[ "Home" => "index.md", "Detailed Overview" => "detailed_overview.md", "Byte Calculators" => "bytecalculators.md", "NUMA Allocators" => "numa.md", "Compositions" => "compositions.md", "API" => [ "ArrayAllocators.jl" => "api.md", "ArrayAllocators.ByteCalculators" => "bytecalculators_api.md", "NumaAllocators.jl" => "numa_api.md", ] ], ) deploydocs(; repo="github.com/mkitti/ArrayAllocators.jl", devbranch="main", push_preview = true )
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
code
6519
""" ArrayAllocators Defines an array allocator interface and concrete array allocators using `malloc`, `calloc`, and memory alignment. # Examples ```julia using ArrayAllocators Array{UInt8}(malloc, 100) Array{UInt8}(calloc, 1024, 1024) Array{UInt8}(MemAlign(2^16), (1024, 1024, 16)) ``` See also `NumaAllocators`, `SafeByteCalculators` """ module ArrayAllocators import Core: Array export malloc, calloc include("ByteCalculators.jl") using .ByteCalculators """ DefaultByteCalculator Alias for [`ByteCalculators.CheckedMulByteCalculator`](@ref) representing the byte calculator used with subtypes of `AbstractArrayAllocator` when one is not specified. """ const DefaultByteCalculator = CheckedMulByteCalculator export AbstractArrayAllocator, UndefAllocator, MallocAllocator, CallocAllocator export MemAlign """ lineage_finalizer(f, x) Attach a finalizer function `f` to `x` or an ancestor of `x` using `parent`. """ function lineage_finalizer(f, x) try finalizer(f, x) catch err if applicable(parent, x) lineage_finalizer(f, parent(x)) else rethrow(err) end end end """ AbstractArrayAllocator{B} Parent abstract type for array allocators. Parameter `B` is an AbstractByteCalculator Defines `Array{T}(allocator, dims...) where T = Array{T}(allocator, dims)` """ abstract type AbstractArrayAllocator{B} end # Allocate arrays when the dims are given as arguments rather than as a tuple function (::Type{ArrayType})(alloc::A, dims...) where {T, ArrayType <: AbstractArray{T}, A <: AbstractArrayAllocator} return ArrayType(alloc, dims) end function (::Type{ArrayType})(alloc::A, dims) where {T, ArrayType <: AbstractArray{T}, B, A <: AbstractArrayAllocator{B}} num_bytes = nbytes(B{T}(dims)) ptr = allocate(alloc, T, num_bytes) return unsafe_wrap(alloc, ArrayType, ptr, dims) end function allocate(alloc::A, ::Type{T}, num_bytes) where {A <: AbstractArrayAllocator, T} iszeroinit(A) || isbitstype(T) || throw(ArgumentError("$T is not a bitstype")) return Ptr{T}(allocate(alloc, num_bytes)) end (::Type{A})(args...) where A <: AbstractArrayAllocator = A{DefaultByteCalculator}(args...) iszeroinit(::Type{A}) where A <: AbstractArrayAllocator = false """ UndefAllocator{B} Allocate arrays using the builtin `undef` method. The `B` parameter is a `ByteCalculator` """ struct UndefAllocator{B} <: AbstractArrayAllocator{B} end allocate(::UndefAllocator, num_bytes) = C_NULL Base.unsafe_wrap(::UndefAllocator, ::Type{ArrayType}, ::Ptr, dims::Dims) where {T, ArrayType <: AbstractArray{T}} = ArrayType(Core.undef, dims) abstract type LibcArrayAllocator{B} <: AbstractArrayAllocator{B} end """ wrap_libc_pointer(::Type{A}, ptr::Ptr{T}, dims) where {T, A <: AbstractArray{T}} wrap_libc_pointer(ptr::Ptr{T}, dims) where {T, A <: AbstractArray{T}} Checks to see if `ptr` is C_NULL for an OutOfMemoryError. Owns the array such that `Libc.free` is used. """ function wrap_libc_pointer(::Type{A}, ptr::Ptr{T}, dims) where {T, A <: AbstractArray{T}} if ptr == C_NULL throw(OutOfMemoryError()) end # We use own = true, so we do not need Libc.free explicitly arr = unsafe_wrap(A, ptr, dims; own = true) return arr end wrap_libc_pointer(ptr::Ptr{T}, dims) where T = wrap_libc_pointer(Array{T}, ptr, dims) Base.unsafe_wrap(alloc::A, args...) where A <: LibcArrayAllocator = wrap_libc_pointer(args...) """ MallocAllocator() Allocate array using [`Libc.malloc`](https://docs.julialang.org/en/v1/base/libc/#Base.Libc.malloc). This is not meant to be useful but rather just to prototype the concept for a custom array allocator concept. This should be similar to using `undef`. See also https://en.cppreference.com/w/c/memory/malloc . """ struct MallocAllocator{B} <: LibcArrayAllocator{B} end allocate(::MallocAllocator, num_bytes) = Libc.malloc(num_bytes) """ malloc [`MallocAllocator`](@ref) singleton instance. `malloc` will only allocate memory. It does not initialize memory is is similar in use as `undef`. See the type and the [C standard library function](https://en.cppreference.com/w/c/memory/malloc) for details. # Example ```jldoctest julia> Array{UInt8}(malloc, 16, 16); ``` """ const malloc = MallocAllocator() """ CallocAllocator() Use [`Libc.calloc`](https://docs.julialang.org/en/v1/base/libc/#Base.Libc.calloc) to allocate an array. This is similar to `zeros`, except that the Libc implementation or the operating system may allocate and zero the memory in a lazy fashion. See also https://en.cppreference.com/w/c/memory/calloc . """ struct CallocAllocator{B} <: LibcArrayAllocator{B} end allocate(::CallocAllocator, num_bytes) = Libc.calloc(num_bytes, 1) iszeroinit(::Type{A}) where A <: CallocAllocator = true """ calloc [`CallocAllocator`](@ref) singleton instance. `calloc` will allocate memory and guarantee initialization to `0`. See the type for details and the [C standard library function](https://en.cppreference.com/w/c/memory/calloc) for further details. # Example ```jldoctest julia> A = Array{UInt8}(calloc, 16, 16); julia> sum(A) 0x0000000000000000 ``` """ const calloc = CallocAllocator() """ MemAlign([alignment::Integer]) Allocate aligned memory. Alias for platform specific implementations. `alignment` must be a power of 2. On POSIX systems, `alignment` must be a multiple of `sizeof(Ptr)`. On Windows, `alignment` must be a multiple of 2^16. If `alignment` is not specified, it will be set to `min_alignment(MemAlign)`. `MemAlign` is a constant alias for one the following platform specific implementations. * POSIX (Linux and macOS): [`POSIX.PosixMemAlign`](@ref) * Windows: [`Windows.WinMemAlign`](@ref). """ MemAlign """ AbstractMemAlign{B} <: AbstractArrayAllocator{B} Abstract supertype for aligned memory allocators. """ abstract type AbstractMemAlign{B} <: AbstractArrayAllocator{B} end """ alignment(alloc::AbstractMemAlign) Get byte alignment of the AbstractMemAlign array allocator. """ alignment(alloc::AbstractMemAlign) = alloc.alignment """ min_alignment(::AbstractMemAlign) Get the minimum byte alignment of the AbstractMemAlign array allocator. """ function min_alignment() end include("Windows.jl") include("POSIX.jl") import .Windows: WinMemAlign import .POSIX: PosixMemAlign @static if Sys.iswindows() const MemAlign = WinMemAlign elseif Sys.isunix() const MemAlign = PosixMemAlign end include("zeros.jl") end # module ArrayAllocators
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
code
3382
""" ArrayAllocators.ByteCalculators Defines calculators for computing the number of bytes needed to allocate an array while detecting integer overflow. # Examples ```julia using ArrayAllocators.ByteCalculators bc = CheckedMulByteCalculator{UInt8}(1024, 2048) elsize(bc) nbytes(bc) ``` """ module ByteCalculators export nbytes, elsize export UnsafeByteCalculator, CheckedMulByteCalculator, WideningByteCalculator """ AbstractByteCalculator Parent abstract type for byte calculators, which calculate the total number of bytes of memory to allocate. """ abstract type AbstractByteCalculator{T} end # Allow dimensions to be passed as individual arguments function (::Type{B})(dims::Int...) where {T, B <: AbstractByteCalculator{T}} return B(dims) end function (::Type{B})(dims::AbstractUnitRange...) where {T, B <: AbstractByteCalculator{T}} return B(length.(dims)) end function (::Type{B})(dims::NTuple{N, AbstractUnitRange}) where {N, T, B <: AbstractByteCalculator{T}} return B(length.(dims)) end elsize(::AbstractByteCalculator{T}) where T = isbitstype(T) ? sizeof(T) : sizeof(Ptr) nbytes(b::AbstractByteCalculator{T}) where T = elsize(b) * length(b) """ UnsafeByteCalculator Calculate number of bytes to allocate for an array without any integer overflow checking. """ struct UnsafeByteCalculator{T} <: AbstractByteCalculator{T} dims::Dims UnsafeByteCalculator{T}(dims::Dims) where T = new{T}(dims) end Base.length(b::UnsafeByteCalculator{T}) where T = prod(b.dims) """ CheckedMulByteCalculator Calculate the number of bytes by using `Base.checked_mul` to check if the product of the dimensions (length) or the product of the length and the element size will cause an integer overflow. """ struct CheckedMulByteCalculator{T} <: AbstractByteCalculator{T} dims::Dims CheckedMulByteCalculator{T}(dims::Dims) where T = new{T}(dims) end function Base.length(b::CheckedMulByteCalculator) try return reduce(Base.checked_mul, b.dims) catch err if err isa OverflowError rethrow(OverflowError("The product of the dimensions results in integer overflow.")) else rethrow(err) end end end function nbytes(b::CheckedMulByteCalculator{T}) where T element_size = sizeof(T) len = length(b) if len > typemax(typeof(element_size)) ÷ element_size throw(OverflowError("The product of array length and element size will cause an overflow.")) end return element_size * len end """ WideningByteCalculator Widens `eltype(Dims)`, Int in order to catch integer overflow. """ struct WideningByteCalculator{T} <: AbstractByteCalculator{T} dims::Dims WideningByteCalculator{T}(dims::Dims) where T = new{T}(dims) end function Base.length(bc::WideningByteCalculator) D = eltype(Dims) M = typemax(D) W = widen(D) len = reduce(bc.dims) do a,b c = W(a) * W(b) if c > M throw(OverflowError("The product of the dimensions results in integer overflow.")) end return D(c) end return len end function nbytes(b::WideningByteCalculator{T}) where T nb = widen(sizeof(T)) * widen(length(b)) if nb > typemax(eltype(Dims)) throw(OverflowError("The product of array length and element size will cause an overflow.")) end return nb end end # module ByteCalculators
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
code
2169
""" ArrayAllocators.POSIX Defines ArrayAllocators for POSIX systems such as macOS or Linux. # Example ```julia using ArrayAllocators.POSIX Array{UInt16}(PosixMemAlign(), 1024) ``` """ module POSIX using ..ArrayAllocators: AbstractArrayAllocator, wrap_libc_pointer, LibcArrayAllocator import ..ArrayAllocators: AbstractMemAlign, min_alignment, alignment import ..ArrayAllocators: allocate export PosixMemAlign # Copied from https://github.com/JuliaPerf/BandwidthBenchmark.jl/blob/main/src/allocate.jl # Copyright (c) 2021 Carsten Bauer <[email protected]> and contributors # Originating from https://discourse.julialang.org/t/julia-alignas-is-there-a-way-to-specify-the-alignment-of-julia-objects-in-memory/57501/2 # Copyright (c) 2021 Steven G. Johnson const POSIX_MEMALIGN_MIN_ALIGNMENT = sizeof(Ptr) function check_alignment(alignment) ispow2(alignment) || throw(ArgumentError("$alignment is not a power of 2")) alignment ≥ POSIX_MEMALIGN_MIN_ALIGNMENT || throw(ArgumentError("$alignment is not a multiple of $POSIX_MEMALIGN_MIN_ALIGNMENT")) return nothing end function posix_memalign(alignment, num_bytes) ptr = Ref{Ptr{Cvoid}}() err = ccall(:posix_memalign, Cint, (Ref{Ptr{Cvoid}}, Csize_t, Csize_t), ptr, alignment, num_bytes) iszero(err) || throw(OutOfMemoryError()) return ptr[] end """ PosixMemAlign([alignment::Integer]) Uses `posix_memalign` to allocate aligned memory. `alignment` must be a power of 2 and larger than `sizeof(Ptr)`. If `alignment` is provided, it will be set to `min_alignment(PosixMemAlign)`. # Example ```julia julia> Array{UInt8}(PosixMemAlign(32), 16, 16); ``` """ struct PosixMemAlign{B} <: AbstractMemAlign{B} alignment::Integer function PosixMemAlign{B}(alignment) where B check_alignment(alignment) return new{B}(alignment) end end PosixMemAlign() = PosixMemAlign(POSIX_MEMALIGN_MIN_ALIGNMENT) Base.unsafe_wrap(::PosixMemAlign, args...) = wrap_libc_pointer(args...) min_alignment(::Type{PosixMemAlign}) = POSIX_MEMALIGN_MIN_ALIGNMENT allocate(alloc::PosixMemAlign{B}, num_bytes) where B = posix_memalign(alloc.alignment, num_bytes) end # module POSIX
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
code
7764
""" ArrayAllocators.Windows Defines array allocators on Windows. # Examples ```julia using ArrayAllocators.Windows Array{UInt8}(WinMemAlign(2^16), 1024) ``` """ module Windows import ..ArrayAllocators: AbstractArrayAllocator, nbytes, allocate import ..ArrayAllocators: AbstractMemAlign, min_alignment, alignment import ..ArrayAllocators: iszeroinit, lineage_finalizer import Base: Array export WinMemAlign @static if Sys.iswindows() const hCurrentProcess = ccall((:GetCurrentProcess, "kernel32"), Ptr{Nothing}, ()) else # The value below is the typical default value on Windows when executing the above const hCurrentProcess = Ptr{Nothing}(0xffffffffffffffff) end const kernel32 = "kernel32" const kernelbase = "kernelbase" const MEM_COMMIT = 0x00001000 const MEM_RESERVE = 0x00002000 const MEM_RESET = 0x00080000 const MEM_RESET_UNDO = 0x10000000 const MEM_LARGE_PAGES = 0x20000000 const MEM_PHYSICAL = 0x00400000 const MEM_TOP_DOWN = 0x00100000 const MEM_COMMIT_RESERVE = MEM_COMMIT | MEM_RESERVE const PAGE_READWRITE = 0x04 const MEM_DECOMMIT = 0x00004000 const MEM_RELEASE = 0x00008000 const DWORD = Culong abstract type MemExtendedParameterType end """ MemAddressRequirements See https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-mem_address_requirements """ struct MemAddressRequirements lowestStartingAddress::Ptr{Nothing} highestStartingAddress::Ptr{Nothing} alignment::Csize_t end MemAddressRequirements(alignment) = MemAddressRequirements(C_NULL, C_NULL, alignment) """ MemExtendedParameterAddressRequirements This is a Julian structure where the `requirements` field is `Base.RefValue{MemAddressRequirements}` See https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-mem_extended_parameter See also `_MemExtendedParameterAddressRequirements` """ struct MemExtendedParameterAddressRequirements <: MemExtendedParameterType type::UInt64 requirements::Base.RefValue{MemAddressRequirements} function MemExtendedParameterAddressRequirements(requirements) new(1, Ref(requirements)) end end #= _MemExtendedParameterAddressRequirements Internal structure compatible with C definition See https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-mem_extended_parameter =# struct _MemExtendedParameterAddressRequirements type::UInt64 pointer::Ptr{MemAddressRequirements} end function Base.convert(::Type{_MemExtendedParameterAddressRequirements}, p::MemExtendedParameterAddressRequirements) _MemExtendedParameterAddressRequirements(p.type, pointer_from_objref(p.requirements)) end #= LPVOID VirtualAllocEx( [in] HANDLE hProcess, [in, optional] LPVOID lpAddress, [in] SIZE_T dwSize, [in] DWORD flAllocationType, [in] DWORD flProtect ); =# function VirtualAllocEx(hProcess, lpAddress, dwSize, flAllocationType, flProtect) ccall((:VirtualAllocEx, kernel32), Ptr{Nothing}, (Ptr{Nothing}, Ptr{Nothing}, Csize_t, DWORD, DWORD), hProcess, lpAddress, dwSize, flAllocationType, flProtect ) end function VirtualAllocEx(dwSize) VirtualAllocEx(hCurrentProcess, C_NULL, dwSize, MEM_COMMIT_RESERVE, PAGE_READWRITE) end #= PVOID VirtualAlloc2( [in, optional] HANDLE Process, [in, optional] PVOID BaseAddress, [in] SIZE_T Size, [in] ULONG AllocationType, [in] ULONG PageProtection, [in, out, optional] MEM_EXTENDED_PARAMETER *ExtendedParameters, [in] ULONG ParameterCount ); =# # https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc2 function VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount) # Docs say ccall((:VirtualAlloc2, kernelbase), Ptr{Nothing}, (Ptr{Nothing}, Ptr{Nothing}, Csize_t, Culong, Culong, Ptr{Nothing}, Culong), Process, BaseAddress, Size, AllocationType, PageProtection, ExtendedParameters, ParameterCount ) end function VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, ParameterCount) VirtualAlloc2(Process, BaseAddress, Size, AllocationType, PageProtection, C_NULL, ParameterCount) end function win_memalign(alignment, num_bytes; lowestStartingAddress::Ptr{Nothing} = C_NULL, highestStartingAddress::Ptr{Nothing} = C_NULL) reqs = MemAddressRequirements(lowestStartingAddress, highestStartingAddress, alignment) pr = MemExtendedParameterAddressRequirements(reqs) p = Ref{_MemExtendedParameterAddressRequirements}(pr) GC.@preserve reqs pr p begin ptr = VirtualAlloc2(hCurrentProcess, C_NULL, num_bytes, MEM_COMMIT_RESERVE, PAGE_READWRITE, p, 1) end return ptr end const WIN_MEMALIGN_MIN_ALIGNMENT = 2^16 function check_alignment(alignment) ispow2(alignment) || throw(ArgumentError("Alignment must be a power of 2")) alignment ≥ WIN_MEMALIGN_MIN_ALIGNMENT || throw(ArgumentError("Alignment must be a multiple of $(WIN_MEMALIGN_MIN_ALIGNMENT)")) return nothing end #= BOOL VirtualFreeEx( [in] HANDLE hProcess, [in] LPVOID lpAddress, [in] SIZE_T dwSize, [in] DWORD dwFreeType ); =# const BOOL = Cint function VirtualFreeEx(hProcess, lpAddress, dwSize, dwFreeType) ccall((:VirtualFreeEx, kernel32), BOOL, (Ptr{Nothing}, Ptr{Nothing}, Csize_t, DWORD), hProcess, lpAddress, dwSize, dwFreeType ) end function VirtualFreeEx(lpAddress) VirtualFreeEx(hCurrentProcess, lpAddress, 0, MEM_RELEASE) end function virtual_free(array::Array{T}) where T VirtualFreeEx(array) end function wrap_virtual(::Type{A}, ptr::Ptr{T}, dims) where {T, A <: AbstractArray{T}} if ptr == C_NULL throw(OutOfMemoryError()) end arr = unsafe_wrap(A, ptr, dims; own = false) lineage_finalizer(virtual_free, arr) return arr end wrap_virtual(ptr::Ptr{T}, dims) where T = wrap_virtual(Array{T}, ptr, dims) # == AbstractWinVirtualAllocator == # abstract type AbstractWinVirtualAllocator{B} <: AbstractArrayAllocator{B} end allocate(::AbstractWinVirtualAllocator, num_bytes) = VirtualAllocEx(num_bytes) Base.unsafe_wrap(::AbstractWinVirtualAllocator, args...) = wrap_virtual(args...) iszeroinit(::Type{A}) where A <: AbstractWinVirtualAllocator = true # == WinVirtualAllocator == # struct WinVirtualAllocator{B} <: AbstractWinVirtualAllocator{B} end const virtual = WinVirtualAllocator() # == WindowsMemAlign == # """ WinMemAlign([alignment, lowestStartingAddress, highestStartingAddress]) Uses `VirtualAlloc2` to allocate aligned memory. `alignment` must be a power of 2 and larger than $(WIN_MEMALIGN_MIN_ALIGNMENT). """ struct WinMemAlign{B} <: AbstractMemAlign{B} alignment::Int lowestStartingAddress::Ptr{Nothing} highestStartingAddress::Ptr{Nothing} function WinMemAlign{B}(alignment, lowestStartingAddress = C_NULL, highestStartingAddress = C_NULL) where B check_alignment(alignment) return new{B}( alignment, reinterpret(Ptr{Nothing}, lowestStartingAddress), reinterpret(Ptr{Nothing}, highestStartingAddress) ) end end WinMemAlign() = WinMemAlign(WIN_MEMALIGN_MIN_ALIGNMENT) allocate(alloc::WinMemAlign, num_bytes) = win_memalign( alloc.alignment, num_bytes; lowestStartingAddress = alloc.lowestStartingAddress, highestStartingAddress = alloc.highestStartingAddress ) Base.unsafe_wrap(::WinMemAlign, args...) = wrap_virtual(args...) min_alignment(::Type{WinMemAlign}) = WIN_MEMALIGN_MIN_ALIGNMENT iszeroinit(::Type{A}) where A <: WinMemAlign = true end # module Windows
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
code
996
""" ArrayAllocators.zeros(T=Float64, dims::Integer...) ArrayAllocators.zeros(T=Float64, dims::Dims) Return an Array with element type `T` with size `dims` filled by `0`s via `calloc`. Depending on the libc implementation, the operating system may lazily wait for a page fault before obtaining memory initialized to `0`. This is an alternative to `Base.zeros` that always fills the array with `0` eagerly. # Examples ```julia julia> @time ArrayAllocators.zeros(Int, 3200, 3200); 0.000026 seconds (4 allocations: 78.125 MiB) julia> @time Base.zeros(Int, 3200, 3200); 0.133595 seconds (2 allocations: 78.125 MiB, 67.36% gc time) julia> ArrayAllocators.zeros(Int, 256, 256) == Base.zeros(Int, 256, 256) true ``` """ function zeros(::Type{T}, dims::Integer...) where T return Array{T}(calloc, dims...) end function zeros(::Type{T}, dims::Dims) where T return Array{T}(calloc, dims) end zeros(dims::Integer...) = zeros(Float64, dims) zeros(dims::Dims) = zeros(Float64, dims)
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
code
2561
using Pkg using ArrayAllocators using ArrayAllocators.ByteCalculators using OffsetArrays using Test # Load in subpackages Pkg.develop(PackageSpec(path=joinpath(dirname(@__DIR__), "./NumaAllocators"))) Pkg.develop(PackageSpec(path=joinpath(dirname(@__DIR__), "./SafeByteCalculators"))) using NumaAllocators using SafeByteCalculators @testset "ArrayAllocators.jl" begin A = zeros(UInt8, 2048, 2048); B = Array{UInt8}(calloc, 2048, 2048); M = Array{UInt8}(malloc, 1024, 4096) Z = ArrayAllocators.zeros(UInt8, 2048, 2048) Z2 = ArrayAllocators.zeros(UInt8, (2048, 2048)) @test A == B @test A == Z @test size(Z) == (2048, 2048) @test size(Z2) == (2048, 2048) @test size(M) == (1024, 4096) @test_throws OverflowError Array{UInt8}(calloc, 20480000, typemax(Int64)) @test_throws OverflowError Array{UInt16}(calloc, 2, typemax(Int64)÷2) @test_throws OverflowError Array{UInt16}(MallocAllocator(), 2, typemax(Int64)÷2) @test_throws OverflowError Array{UInt16}(MallocAllocator{CheckedMulByteCalculator}(), 2, typemax(Int64)÷2) @test_throws OverflowError Array{UInt16}(MallocAllocator{WideningByteCalculator}(), 2, typemax(Int64)÷2) @test_throws OverflowError Array{UInt16}(MallocAllocator{SafeByteCalculator}(), 2, typemax(Int64)÷2) @static if Sys.iswindows() WV = Array{UInt8}(ArrayAllocators.Windows.virtual, 64, 1024); @test size(WV) == (64, 1024) @test WV == zeros(UInt8, 64, 1024) end @static if Sys.islinux() || Sys.iswindows() C = Array{UInt8}(NumaAllocator(0), 2048, 2048); @test A == C @test current_numa_node() isa Int @test highest_numa_node() isa Int end @static if Sys.isunix() || Sys.iswindows() D = Array{UInt8}(MemAlign(), 1024, 4096) @test size(D) == (1024, 4096) @test reinterpret(Int, pointer(D)) % ArrayAllocators.alignment(MemAlign()) == 0 E = Array{UInt8}(MemAlign(2^16), 1024, 2048) @test size(E) == (1024, 2048) @test reinterpret(Int, pointer(E)) % 2^16 == 0 end end @testset "Composition with OffsetArrays.jl" begin OA = OffsetArray{UInt8}(calloc, -1024:1023, -5:5) @test all(OA .== 0) @test size(OA) == (2048,11) @test OA[-1024,-3] == 0 OA = OffsetArray{UInt8}(calloc, -5:3, Base.OneTo(9)) @test all(OA .== 0) @test size(OA) == (9,9) @test OA[-1,5] == 0 @static if Sys.islinux() || Sys.iswindows() numaOA = OffsetArray{UInt8}(numa(0), -5:5, 1:9) @test numaOA[-5, 1] == numaOA[1] end end
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
docs
3628
# ArrayAllocators.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://mkitti.github.io/ArrayAllocators.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://mkitti.github.io/ArrayAllocators.jl/dev) [![Build Status](https://github.com/mkitti/ArrayAllocators.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/mkitti/ArrayAllocators.jl/actions/workflows/CI.yml?query=branch%3Amain) ArrayAllocators.jl is a Julia language package that provides various methods to allocate memory for arrays. It also implements various ways of calculating the total number of bytes in order to detect integer overflow conditions when multiplying the dimensions of an array and the size of the array elements. For example, [`calloc`](https://en.cppreference.com/w/c/memory/calloc) is a standard C function that allocates memory while initializing the bytes in the memory to `0`, which may be done lazily by some operating sytems as needed. Contrast this with Julia's `Base.zeros` which eagerly fills sets all the bytes in memory to `0`. This often means that allocating memory via `calloc` may be initially faster than using `Base.zeros`. The Python package NumPy for example, implements [`numpy.zeros`](https://numpy.org/doc/stable/reference/generated/numpy.zeros.html) with `calloc`. At times, `numpy.zeros` and Python code using this method may seem to outperform Julia code using `Base.zeros`. See the Discourse link under the discussion below for further details. Other examples of specialized array allocation techniques include aligned memory on POSIX systems or virtual allocations on Windows systems. Multiple processor socket systems may also implement Non-Uniform Memory Access (NUMA) memory architecture. To optimally use the NUMA architecture, memory must be explicitly allocated on a specific NUMA node. The subpackage [NumaAllocators.jl](NumaAllocators) implements this functionality for Windows and Linux operating systems. `AbstractArrayAllocator` can be provided as first argument when constructing any subtype of `AbstractArray` where `undef` is usually provided. Any C function that returns a pointer can be wrapped by the `AbstractArrayAllocator` interface by implementing the `allocate` method and overriding `Base.unsafe_wrap`. ## Installation ```julia using Pkg Pkg.add("ArrayAllocators") ``` ## Usage ``` julia> using ArrayAllocators julia> @time zeros(UInt8, 2048, 2048); 0.000514 seconds (2 allocations: 4.000 MiB) julia> @time Array{UInt8}(undef, 2048, 2048); 0.000017 seconds (2 allocations: 4.000 MiB) julia> @time Array{UInt8}(calloc, 2048, 2048); # Allocates zeros, but is much faster than `Base.zeros` 0.000015 seconds (2 allocations: 4.000 MiB) julia> @time Array{UInt8}(calloc, 20480000, typemax(Int64)); ERROR: OverflowError: 20480000 * 9223372036854775807 overflowed for type Int64 ... julia> using NumaAllocators julia> @time Array{UInt8}(NumaAllocator(0), 2048, 2048); 0.000010 seconds (2 allocations: 80 bytes) ``` ## Subpackages * [NumaAllocators.jl](NumaAllocators): Allocate memory on Non-Uniform Memory Access (NUMA) nodes * [SafeByteCalculators.jl](SafeByteCalculators): Implement byte calculations using SaferIntegers.jl to detect integer overflow. Note that a form of integer overflow detection is implemented in ArrayAllocators.jl itself. This package just provides an alternative implementation. ## Discussion See https://discourse.julialang.org/t/faster-zeros-with-calloc/69860 for discussion about this approach. ## License Per [LICENSE](LICENSE), ArrayAllocators.jl is licensed under the MIT License.
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
docs
1127
# NumaAllocators.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://mkitti.github.io/ArrayAllocators.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://mkitti.github.io/ArrayAllocators.jl/dev) [![Build Status](https://github.com/mkitti/ArrayAllocators.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/mkitti/ArrayAllocators.jl/actions/workflows/CI.yml?query=branch%3Amain) Extends [ArrayAllocators.jl](https://github.com/mkitti/ArrayAllocators.jl) to handle Non-Uniform Memory Access (NUMA) allocation on Windows and Linux. See the ArrayAllocators.jl documentation for more information. ## Installation ```julia using Pkg Pkg.add("NumaAllocators") ``` ## Basic Usage ```julia julia> A = Array{UInt8}(numa(0), 1024, 1024); # Allocate 1 MB Matrix on NUMA Node 0 julia> B = Array{UInt8}(numa(1), 1024, 1024); # Allocate 1 MB Matrix on NUMA Node 1 ``` ## Documentation See the [documentation](https://mkitti.github.io/ArrayAllocators.jl) for ArrayAllocators.jl. ## License Per [LICENSE](LICENSE), NumaAllocators.jl is licenesed under the MIT License.
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
docs
1500
# SafeByteCalculators [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://mkitti.github.io/ArrayAllocators.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://mkitti.github.io/ArrayAllocators.jl/dev) [![Build Status](https://github.com/mkitti/ArrayAllocators.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/mkitti/ArrayAllocators.jl/actions/workflows/CI.yml?query=branch%3Amain) Implements `ArrayAllocators.AbstractByteCalculator` by using `SaferIntegers.jl` in order to detect integer overflow when calculating the number of bytes to allocate. ## Installation ```julia using Pkg Pkg.add(url="https://github.com/mkitti/ArrayAllocators.jl", subdir="SafeByteCalculators") ``` Currently, I do have not have plans to register this package. It mainly serves as an example of how to implement a custom `AbstractByteCalculator`. ## Basic usage ```julia julia> using ArrayAllocators julia> using SafeByteCalculators julia> const safe_malloc = MallocAllocator{SafeByteCalculator}() MallocAllocator{SafeByteCalculator}() julia> A = Array{UInt8}(safe_malloc, 1024, 1024); julia> A = Array{UInt8}(safe_malloc, 1024, typemax(Int)); ERROR: OverflowError: 1024 * 9223372036854775807 overflowed for type Int64 ``` ## Documentation See the ArrayAllocators.jl [documentation](https://mkitti.github.io/ArrayAllocators.jl) for more information. ## License Per [LICENSE](LICENSE), SafeByteCalculators.jl is licenesed under the MIT License.
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
docs
690
```@meta CurrentModule = ArrayAllocators ``` # Application Programming Interface for ArrayAllocators.jl ```@docs ArrayAllocators ``` ## Allocators ```@docs calloc malloc ``` ## Aligned Memory ```@docs MemAlign alignment min_alignment ``` ## Types ```@docs CallocAllocator MallocAllocator UndefAllocator ``` ## Internals ```@docs AbstractArrayAllocator AbstractMemAlign DefaultByteCalculator wrap_libc_pointer lineage_finalizer ``` ## Platform Specific Interface ### Windows ```@docs ArrayAllocators.Windows Windows.WinMemAlign Windows.MemAddressRequirements Windows.MemExtendedParameterAddressRequirements ``` ### POSIX ```@docs ArrayAllocators.POSIX POSIX.PosixMemAlign ```
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
docs
800
```@meta CurrentModule = ArrayAllocators.ByteCalculators ``` # ByteCalculators Byte calculators perform the task of computing the total number of bytes to calculate. In doing so, they try to detect integer overflow conditions. ## Example ```julia julia> using ArrayAllocators, ArrayAllocators.ByteCalculators julia> bc = ArrayAllocators.DefaultByteCalculator{UInt16}(typemax(Int)) CheckedMulByteCalculator{UInt16}((9223372036854775807,)) julia> length(bc) 9223372036854775807 julia> nbytes(bc) ERROR: OverflowError: The product of array length and element size will cause an overflow. Stacktrace: [...] julia> bc = ByteCalculators.UnsafeByteCalculator{UInt16}(typemax(Int)) UnsafeByteCalculator{UInt16}((9223372036854775807,)) julia> length(bc) 9223372036854775807 julia> nbytes(bc) -2 ```
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
docs
562
```@meta CurrentModule = ArrayAllocators.ByteCalculators ``` # Application Programming Interface for ArrayAllocators.ByteCalculators ```@docs ByteCalculators ``` ## Default Byte Calculator ```@docs CheckedMulByteCalculator ``` ## Alternative Byte Calculators ```@docs WideningByteCalculator UnsafeByteCalculator ``` ```@meta CurrentModule = SafeByteCalculators ``` ```@docs SafeByteCalculators SafeByteCalculators.SafeByteCalculator ``` ```@meta CurrentModule = ArrayAllocators.ByteCalculators ``` ## Abstract Type ```@docs AbstractByteCalculator ```
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
docs
1272
# Compositions with other packages ## Compositions that are tested ### OffsetArrays.jl [OffsetArrays.jl](https://github.com/JuliaArrays/OffsetArrays.jl) allows for the use of shifted indices. Composition is enabled by 1. `OffsetArrays` implements `Base.unsafe_wrap` 2. `AbstractByteCalculators` accept `AbstractUnitRange` arguments ```jldoctest julia> using ArrayAllocators, OffsetArrays julia> OffsetArray{Int}(calloc, -5:5, Base.OneTo(3)) 11×3 OffsetArray(::Matrix{Int64}, -5:5, 1:3) with eltype Int64 with indices -5:5×1:3: 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 julia> OffsetArray{Int}(calloc, 2, 3) 2×3 OffsetArray(::Matrix{Int64}, 1:2, 1:3) with eltype Int64 with indices 1:2×1:3: 0 0 0 0 0 0 ``` ## Adding to the list of known compositions Does your package compose well with ArrayAllocators or its subpackages? If so, please let me know by [creating an issue](https://github.com/mkitti/ArrayAllocators.jl/issues/new). It is important to list known compositions so users know which packages are known to work well together. Additionally, this helps to make sure that packages continue to compose over time. Beyond listing the known composition, I will also add additional tests for them.
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
docs
2662
# Detailed Overview The original inspiration for this package is the memory allocator [`calloc`](https://en.cppreference.com/w/c/memory/calloc). `calloc` allocates the memory and guarantees that the memory will be initialized by zeros. By this definition, it would appear equivalent to `Base.zeros`. However, `calloc` is potentially able to take advantage of operating system facilities that allocate memory lazily on demand rather than eagerly. Additionally, it may be able to obtain memory from the operating system that has already been initialized by zeros due to security constraints. On many systems, this allocator returns as quickly as `malloc`, the allocator used by `Array{T}(undef, dims)`. In particular, in Python, [`numpy.zeros`](https://github.com/juliantaylor/numpy/commit/d271d977bdfb977959db1ff26956666f3836b56b) uses `calloc`, which may at times appear faster than `Base.zeros` in Julia. In contrast, `Base.zeros` allocates memory using `malloc` and then uses `fill!` to eagerly and explicitly fill the array with zeros. On some systems, this may be a redundant operation since the operating system may already know the allocated memory is filled with zeros. This package makes `calloc` and other allocators available. Some of these allocators are specific to particular kinds of systems. One example is allocating on Non-Uniform Memory Access (NUMA) nodes. On a NUMA system, random-access memory (RAM) may be accessible by certain processor cores at lower latency and higher bandwidth than other cores. Thus, it makes sense to allocate memory on particular NUMA nodes. On Linux, this is facilitated by [`numactl`](https://github.com/numactl/numactl) software which includes `libnuma`. On Windows, NUMA-aware memory allocation is exposed via the Kernel32 memory application programming interface such as via the function [`VirtualAllocExNuma`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocexnuma`). This package provides an abstraction over the two libraries. Another application is memory alignment which may facilitate the use of advanced vector instructions in modern processors. One other feature of this package is implementation of "Safe" allocators. These allocators provide extra protection by detecting integer overflow situations. Integer overflow can occur when multiplying large numbers causing the result to potentially wrap around. Memory allocators may report success after allocating an wrapped around number of bytes. The "Safe" allocators use the [`SaferIntegers`](https://github.com/JeffreySarnoff/SaferIntegers.jl) to detect integer overflow avoiding this erroneous situation.
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
docs
2545
```@meta CurrentModule = ArrayAllocators ``` # ArrayAllocators *Documentation for [ArrayAllocators](https://github.com/mkitti/ArrayAllocators.jl).* # Introduction This Julia package provides mechanisms to allocate arrays beyond that provided in the `Base` module of Julia. The instances of the sub types of [`AbstractArrayAllocator`](@ref) take the place of `undef` in the `Array{T}(undef, dims)` invocation. This allows us to take advantage of alternative ways of allocating memory. The allocators take advantage of `Base.unsafe_wrap` in order to create arrays from pointers. A finalizer is also added for allocators that do not use `Libc.free`. In the base `ArrayAllocators` package, the following allocators are provided. * [`calloc`](@ref) * [`malloc`](@ref) * [`MemAlign(alignment)`](@ref MemAlign) An extension for use with Non-Uniform Memory Access allocations is available via the subpackage [NumaAllocators.jl](@ref NumaAllocators). ## Example Basic Usage Each of the methods below allocate 1 MiB of memory. Using `undef` as the first argument allocate uninitialized memory. The values are not guaranteed to be `0` or any other value. In `Base`, the method `zeros` can be used to explicitly fill the memory with zeros. This is equivalent to using `fill!(..., 0)`. Using `calloc` guarantees the values will be `0`, yet is often as fast as using `undef` initialization. ```julia julia> using ArrayAllocators julia> @time U = Array{Int8}(undef, 1024, 1024); 0.000019 seconds (2 allocations: 1.000 MiB) julia> @time Z1 = zeros(Int8, 1024, 1024); 0.000327 seconds (2 allocations: 1.000 MiB) julia> @time Z2 = fill!(Array{UInt8}(undef, 1024, 1024), 0); 0.000301 seconds (2 allocations: 1.000 MiB) julia> @time C = Array{Int8}(calloc, 1024, 1024); 0.000020 seconds (4 allocations: 1.000 MiB) julia> sum(C) 0 ``` ## Caveats Above `calloc` appears to be much faster than `zeros` at generating an array full of `0`s. However, some of the array created with `zeros` has already been fully allocated. The array allocated with `calloc` take longer to initialize since the operating system may have deferred the actual allocation of memory. ```julia julia> @time Z = zeros(Int8, 1024, 1024); 0.000324 seconds (2 allocations: 1.000 MiB) julia> @time fill!(Z, 1); 0.000138 seconds julia> @time fill!(Z, 2); 0.000136 seconds julia> @time U = Array{Int8}(calloc, 1024, 1024); 0.000020 seconds (4 allocations: 1.000 MiB) julia> @time fill!(U, 1); 0.000349 seconds julia> @time fill!(U, 2); 0.000136 seconds ```
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
docs
1542
```@meta CurrentModule = NumaAllocators ``` # NumaAllocators Non-Uniform Memory Access (NUMA) array allocators allow you to allocate memory on specific NUMA nodes. ## Basic Usage A `NumaAllocator` can be instantiated via `numa(node)` and passed to the `Array` constructor as below. ```julia julia> using NumaAllocators julia> a0 = Array{Int8}(numa(0), 1024, 1024); julia> b0 = Array{Int8}(numa(0), 1024, 1024); julia> a1 = Array{Int8}(numa(1), 1024, 1024); julia> b1 = Array{Int8}(numa(1), 1024, 1024); ``` Depending on your processor architecture, some operations may be between NUMA nodes may be faster than others. ```julia julia> @time fill!(a0, 1); 0.000374 seconds julia> @time fill!(b0, 2); 0.000307 seconds julia> @time fill!(a1, 3); 0.000418 seconds julia> @time fill!(b1, 4); 0.000383 seconds julia> @time copyto!(b0, a0); 0.000439 seconds julia> @time copyto!(b1, a0); 0.000287 seconds julia> @time copyto!(b1, a1); 0.000376 seconds julia> @time copyto!(b0, a1); 0.000455 seconds julia> current_numa_node() 0 julia> highest_numa_node() 1 julia> versioninfo() Julia Version 1.7.2 Commit bf53498635 (2022-02-06 15:21 UTC) Platform Info: OS: Windows (x86_64-w64-mingw32) CPU: Intel(R) Xeon(R) Gold 5220R CPU @ 2.20GHz WORD_SIZE: 64 LIBM: libopenlibm LLVM: libLLVM-12.0.1 (ORCJIT, cascadelake) ``` In the example above, copying 1 MB of data from NUMA node 0 to NUMA node 1 is faster than copying between memory local to either NUMA node or copying data from NUMA node 1 to NUMA node 0.
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.3.0
9b79e996ba9ceda798f9cf4dab30aa69fc3e537f
docs
430
```@meta CurrentModule = NumaAllocators ``` # Application Programming Interface for NumaAllocators.jl ```@docs NumaAllocators ``` ## Main Interface ```@docs numa NumaAllocator current_numa_node highest_numa_node ``` ## Platform Specific Interface ### Windows ```@docs NumaAllocators.Windows NumaAllocators.Windows.WinNumaAllocator ``` ### Linux ```@docs NumaAllocators.LibNUMA NumaAllocators.LibNUMA.LibNumaAllocator ```
ArrayAllocators
https://github.com/mkitti/ArrayAllocators.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
185
using Documenter makedocs( sitename = "Jabalizer Documentation", modules = [Jabalizer] ) # deploydocs( # deps = Deps.pip("pygments", "mkdocs", "python-markdown-math") # )
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1266
using Jabalizer using PythonCall, Compose cirq = pyimport("cirq"); circuit_file_name = "circuits/control_v.json" circuit_string = cirq.read_json(circuit_file_name) cirq_circuit = cirq.read_json(json_text=circuit_string) println("\n-------------") println("Input circuit") println("-------------\n") println(cirq_circuit) gates_to_decomp = ["T", "T^-1"]; icm_input = Jabalizer.load_circuit_from_cirq_json("circuits/control_v.json") (icm_circuit, _) = Jabalizer.compile(icm_input, gates_to_decomp) Jabalizer.save_circuit_to_cirq_json(icm_circuit, "icm_output.json"); cirq_circuit = cirq.read_json("icm_output.json") rm("icm_output.json") println("\n-----------------") println("ICM decomposition") println("-----------------\n") println(cirq_circuit) n_qubits = Jabalizer.count_qubits(icm_circuit) state = Jabalizer.zero_state(n_qubits); print("\n Initial Stabilizer State\n") println(state) Jabalizer.execute_circuit(state, icm_circuit) print("\n Final Stabilizer State\n") print(state) (g,A,seq) = Jabalizer.to_graph(state) # Save generated graph as image file draw(SVG("ctrl_v_graph.svg", 16cm, 16cm), Jabalizer.gplot(g)) println("\nGraph State") println(g) println("Adjacency matrix") display(A) println("\n\nLocal corrections") println(seq)
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
651
using Jabalizer # Prepare a 6-qubit GHZ state n = 6 state = zero_state(n) println("\nInitial State") print(state) state |> Jabalizer.H(1) |> Jabalizer.CNOT(1,2) |> Jabalizer.CNOT(1,3) |> Jabalizer.CNOT(1,4) |> Jabalizer.CNOT(1,5) |> Jabalizer.CNOT(1,6) println("\nGHZ state") print(state) # Convert to graph state graph_state = GraphState(state) println("\nGraph adjacency matrix") display(graph_state.A) # This requires some kind of plotting backend. # Works with Atom and VScode. display(Jabalizer.gplot(graph_state)) # Convert back to stabilizer state stab_state = StabilizerState(graph_state) println("\nStabilizer State") print(stab_state)
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
532
using Revise using Jabalizer frames = Jabalizer.Frames() for i in 0:7 frames.new_qubit(i) end frame_flags = [] frames.into_py_dict_recursive() # frame_flags = collect(2:5) qubits = collect(2:5) # track frames.track_z(2) frames.track_x(2) frames.track_z(3) frames.track_x(3) #update frame_flags append!(frame_flags, [6, 0, 7, 1,2,4]) # Jabalizer.pauli_corrections(frames, frame_flags, qubits) # apply gates frames.cx(2,3) frames.cx(2,4) frames.cx(4,5) frames.cx(3,5) Jabalizer.pauli_corrections(frames, frame_flags, qubits)
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
5560
#!/usr/bin/env julia # Copyright 2022-2024 Rigetti & Co, LLC # # This Computer Software is developed under Agreement HR00112230006 between Rigetti & Co, LLC and # the Defense Advanced Research Projects Agency (DARPA). Use, duplication, or disclosure is subject # to the restrictions as stated in Agreement HR00112230006 between the Government and the Performer. # This Computer Software is provided to the U.S. Government with Unlimited Rights; refer to LICENSE # file for Data Rights Statements. Any opinions, findings, conclusions or recommendations expressed # in this material are those of the author(s) and do not necessarily reflect the views of the DARPA. # # Use of this work other than as specifically authorized by the U.S. Government is licensed under # the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. # A julia wrapper script to manage RRE's default FT-compiler, Jabalizer. # # Parts of the following code are inspired and/or customized from the original templates in the # open-source references of: # [1] https://github.com/QSI-BAQS/Jabalizer.jl # [2] https://github.com/zapatacomputing/benchq # [1] is distributed under the MIT License and includes the following copyright and permission # statements: # Copyright (c) 2021 Peter Rohde, Madhav Krishnan Vijayan, Simon Devitt, Alexandru Paler. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and # associated documentation files (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, publish, distribute, # sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT # NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. if !isinteractive() import Pkg Pkg.activate("Jabalizer.jl/") end using Jabalizer # circuit is an orquestra.quantum.circuits.Circuit object function run_jabalizer(circuit, circuit_fname, suffix, debug_flag=false) if debug_flag println("\nRRE: Jabalizer FT-compiler starts ...\n") end mkpath("output/$(circuit_fname)/") # circuit is an orquestra.quantum.circuits.Circuit object representing # a quantum circuit acting on [0,1,...,n_qubits-1] qubits # Reading the orquestra circuit and convert to one-based indexing onebased_circuit = Gate[] for op in circuit.operations name = Jabalizer.pyconvert(String, op.gate.name) cargs = nothing # Thinh: read in rotation gate angles, for example if RX(0.5) then cargs = [0.5] a list of one Float64 qargs = [Jabalizer.pyconvert(Int, qubit) + 1 for qubit in op.qubit_indices] # one-based indexing push!(onebased_circuit, Jabalizer.Gate(name, cargs, qargs)) end n_qubits = Jabalizer.pyconvert(Int, circuit.n_qubits) # Warning: from now on assume input_circuit is a list of Jabalizer.Gate # acting on [1,2,...,n_qubits]. Please ensure this when splitting qasm files. filepath = "output/$(circuit_fname)/$(circuit_fname)$(suffix)_all0init_jabalizer.out.json" if debug_flag @info "RRE: Running `Jabalizer.mbqccompile` ...\n" end # ASSUME qubits are indexed from 1 to n_qubits js = Jabalizer.mbqccompile( Jabalizer.QuantumCircuit([1:n_qubits], onebased_circuit); universal=true, ptracking=true, filepath=filepath, ) return js # return the Jabalizer output in JSON format # js = JSON.json(Dict( # :time => time, # length(steps) how many time steps # :space => space, # maximum number of qubits required # :steps => steps, # actual MBQC instructions: for each step in steps init nodes and CZ based on spacialgraph # :spacialgraph => [zerobasing(nb) for nb in Graphs.SimpleGraphs.adj(fullgraph)], # description of CZ gates to be applied (edge = apply CZ gate) # :correction => [(g, zerobasing(q)) for (g, q) in correction], # potential local Clifford correction on each nodes right after CZ above # :measurements => map(unpackGate, measurements), # list of measurements # :statenodes => zerobasing(labels[:state]), # nodes where the input state is currently in # :outputnodes => zerobasing(labels[:output]), # get the output state returned by the circuit from these nodes # :frameflags => ptracker[:frameflags], # already zero-based # used to be frame_maps # :initializer => initializer, # what was passed in from caller # )) end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
476
using Revise using Jabalizer using JSON input_file = "examples/mwe.qasm" qc = parse_file(input_file) # g, loc_corr, mseq, data_qubits, ptracker = gcompile(qc, # universal=true, # ptracking=true) output = mbqccompile(qc, pcorrctions=true) outfile = "examples/test.qasm" qasm_instruction(outfile, output) # output_dict = JSON.parse(output) # output_dict["steps"]
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
3245
using Revise using Jabalizer using GraphPlot using Graphs using PythonCall import Graphs.SimpleGraphs mbqc_scheduling = pyimport("mbqc_scheduling") SpacialGraph = pyimport("mbqc_scheduling").SpacialGraph PartialOrderGraph = pyimport("mbqc_scheduling").PartialOrderGraph input_file = "examples/mwe.qasm" # Commented code below shows how to use icmcompile. For graph # compilation icmcompile can be used directly instead # qc = parse_file(input_file) # # Display input circuit # display(gates(qc)) # universal = true # ptracking = true # icm_circuit, mseq, qubit_map, frames_array = icmcompile(qc; # universal=universal, # ptracking=ptracking # ) # # Compiled icm circuit # display(gates(icm_circuit)) # # Measurement sequence # display(mseq) # # input-output map, keys are input and values are output # display(qubit_map) # # Frames array is one of [], [frames, frame_flags], # # or [frames, frame_flags, buffer, buffer_flags] depending on whether universal # # and ptracking flags are set # if ptracking # if universal # frames, frame_flags, buffer, buffer_flags = frames_array # else # frames, frame_flags = frames_array # end # end # Using gcompile directly ptracking = true universal = true graph, loc_corr, mseq, data_qubits, frames_array = gcompile(input_file; universal=universal, ptracking=ptracking) # unpack frames if ptracking if universal frames, frame_flags, buffer, buffer_flags = frames_array else frames, frame_flags = frames_array end end index=1 gplot(graph,nodelabel=(1-index):(nv(graph)-index)) # We now generate a spatial graph that includes nodes for incoming state; # This could be the qubits holding the input state or qubits holding the # output of a previous graph widget. The spatial graph is stored as # edge list # mbqc_scheduling sparse_rep = SimpleGraphs.adj(graph) #add state nodes to sparse_rep, this is needed to properly schedule for (s,i) in zip(data_qubits[:state], data_qubits[:input]) insert!(sparse_rep, s, [i]) end # shift indices for mbqc_scheduling sparse_rep = [e.-1 for e in sparse_rep] # Convert to native types used by mbqc_scheduling sparse_rep_py = SpacialGraph(sparse_rep) order = frames.get_py_order(frame_flags) py_order = PartialOrderGraph(order) AcceptFunc = pyimport("mbqc_scheduling.probabilistic").AcceptFunc paths = mbqc_scheduling.run(sparse_rep_py, py_order) # Time optimal path for path in paths.into_py_paths() println("time: $(path.time); space: $(path.space); steps: $(path.steps)") end # RRE output # save path -> decide format # Full search (only possible for very small graphs) full_search_path = mbqc_scheduling.run( sparse_rep_py, py_order; do_search=true, nthreads=3, # ,timeout=0 # timeout=1, # probabilistic = (AcceptFunc(), nothing) ) for path in full_search_path.into_py_paths() println("time: $(path.time); space: $(path.space); steps: $(path.steps)") end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1348
# Example of how to use qasm_instruction to output a qasm file # for the outputs of gcompile and mbqccompile using Jabalizer input_file = "examples/mwe.qasm" # input_file = "examples/toffoli.qasm" gcompile_outfile = "examples/gcompile_mwe_out.qasm" mbqccompile_outfile = "examples/mbqccompile_mwe_out.qasm" # gcompile output -> qasm file graph, loc_corr, mseq, data_qubits, frames_array = gcompile(input_file; universal=true, ptracking=true ) frames, frame_flags = frames_array outqubits = data_qubits[:output] .- 1 qubits = [q for q in frame_flags] # we want to find pauli corrections for measured and output qubits append!(qubits, outqubits) # pauli_corrections translates frame information # into pauli correction information for the specified qubits pc = Jabalizer.pauli_corrections(frames, frame_flags, qubits); display(pc) # qasm_instruction generates a qasm file which generates the graph # state, applies local corrections, applies pauli corrections and # measurements and writes it to outfile. qasm_instruction(gcompile_outfile, graph, loc_corr, mseq, data_qubits, frames_array); # mbqccompile output -> qasm file mbqc_output = mbqccompile(qc,pcorrections=true) qasm_instruction(mbqccompile_outfile, mbqc_output)
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1292
using Jabalizer using PythonCall, Compose cirq = pyimport("cirq"); circuit_file_name = "circuits/toffoli_circuit_3.json" circuit_string = cirq.read_json(circuit_file_name) cirq_circuit = cirq.read_json(json_text=circuit_string) println("\n-------------") println("Input circuit") println("-------------\n") println(cirq_circuit) gates_to_decomp = ["T", "T^-1"]; icm_input = Jabalizer.load_circuit_from_cirq_json("circuits/toffoli_circuit_3.json") (icm_circuit, qubit_dict) = Jabalizer.compile(icm_input, gates_to_decomp) Jabalizer.save_circuit_to_cirq_json(icm_circuit, "icm_output.json"); cirq_circuit = cirq.read_json("icm_output.json") rm("icm_output.json") println("\n-----------------") println("ICM decomposition") println("-----------------\n") println(cirq_circuit) n_qubits = Jabalizer.count_qubits(icm_circuit) state = Jabalizer.zero_state(n_qubits); print("\n Initial Stabilizer State\n") println(state) Jabalizer.execute_circuit(state, icm_circuit) print("\n Final Stabilizer State\n") print(state) (g,A,seq) = Jabalizer.to_graph(state) # Save generated graph as image file draw(SVG("toffoli_graph.svg", 16cm, 16cm), Jabalizer.gplot(g)) println("\nGraph State") println(g) println("Adjacency matrix") display(A) println("\n\nLocal corrections") println(seq)
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
2480
using Revise using Jabalizer using Graphs using GraphPlot using PythonCall import Graphs.SimpleGraphs mbqc_scheduling = pyimport("mbqc_scheduling") SpacialGraph = pyimport("mbqc_scheduling").SpacialGraph PartialOrderGraph = pyimport("mbqc_scheduling").PartialOrderGraph source_filename = "examples/mwe.qasm" # source_filename = "examples/toffoli.qasm" # gates_to_decompose = ["T", "T_Dagger"] # Some commented code accessing internal functions that gcompile uses. # uncomment to play with these methods. # qubits, inp_circ = load_icm_circuit_from_qasm(source_filename) # data = compile( # inp_circ, # qubits, # gates_to_decompose; # ptrack=false # ) # icm_circuit, data_qubits, mseq, frames, frame_flags = data # icm_q = Jabalizer.count_qubits(icm_circuit) # state = zero_state(icm_q) # Jabalizer.execute_circuit(state, icm_circuit) universal=true ptracking=true data = gcompile( source_filename; universal=universal, ptracking=ptracking ) graph, loc_corr, mseq, data_qubits, frames_array = data # unpack frames if ptracking if universal frames, frame_flags, buffer, buffer_flags = frames_array else frames, frame_flags = frames_array end end # graph plot (requires plotting backend) gplot(graph, nodelabel=0:nv(graph)-1) sparse_rep = SimpleGraphs.adj(graph) # shift indices for mbqc_scheduling sparse_rep = [e.-1 for e in sparse_rep] for (s,i) in zip(data_qubits[:state], data_qubits[:input]) insert!(sparse_rep, s, [i]) end sparse_rep = SpacialGraph(sparse_rep) order = frames.get_py_order(frame_flags) order = PartialOrderGraph(order) paths = mbqc_scheduling.run(sparse_rep, order) AcceptFunc = pyimport("mbqc_scheduling.probabilistic").AcceptFunc # Time optimal path for path in paths.into_py_paths() println("time: $(path.time); space: $(path.space); steps: $(path.steps)") end # Full search full_search_path = mbqc_scheduling.run( sparse_rep, order; do_search=true, nthreads=3, # ,timeout=0 # timeout=1, # probabilistic = (AcceptFunc(), nothing) ) for path in full_search_path.into_py_paths() println("time: $(path.time); space: $(path.space); steps: $(path.steps)") end # println("Input Nodes") # println(input_nodes) # println("Output Nodes") # println(output_nodes) # println("Local Corrections to internal nodes") # println(loc_corr) # println("Measurement order") # println(mseq[1]) # println("Measurement basis") # println(mseq[2])
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1126
module Jabalizer using Graphs, GraphPlot, LinearAlgebra using JSON using Documenter using PythonCall # using CondaPkg export Stabilizer, StabilizerState, GraphState, Gates export zero_state, to_tableau, tableau_to_state, to_graph, graph_to_state export measure_x, measure_y, measure_z include("gates.jl") using .Gates const stim = PythonCall.pynew() # initially NULL const cirq = PythonCall.pynew() # initially NULL const Frames = PythonCall.pynew() const mbqc_scheduling = PythonCall.pynew() function __init__() PythonCall.pycopy!(stim, pyimport("stim")) PythonCall.pycopy!(cirq, pyimport("cirq")) PythonCall.pycopy!(Frames, pyimport("pauli_tracker.frames.map").Frames) PythonCall.pycopy!(mbqc_scheduling, pyimport("mbqc_scheduling")) end include("cirq_io.jl") include("qasm.jl") include("icm.jl") include("stabilizer.jl") include("stabilizer_state.jl") include("stabilizer_gates.jl") include("graph_state.jl") include("util.jl") include("fast_tograph.jl") include("execute_circuit.jl") include("stabilizer_measurements.jl") include("gcompile.jl") include("mbqccompile.jl") include("qasm_out.jl") end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
3592
""" Parses cirq qubits to qubits in the format needed for icm. Helper function. """ function parse_cirq_qubits(cirq_qubits::Vector{Any}) output_qubits = Vector{String}() for qubit in cirq_qubits if qubit["cirq_type"] == "LineQubit" push!(output_qubits, string(qubit["x"])) else throw(DomainError(qubit["cirq_type"], "Only LineQubits are supported right now.")) end end return output_qubits end """ Loads cirq circuit from json into a format compatible with icm. """ function load_circuit_from_cirq_json(file_name::String) raw_circuit = JSON.parsefile(file_name) # Sometimes cirq saves to circuit as json with "\n" characters which require escaping if typeof(raw_circuit) == String raw_circuit = JSON.parse(replace(raw_circuit, "\n" => "")) end circuit = Vector{Tuple{String,Vector{String}}}() for moment in raw_circuit["moments"] for operation in moment["operations"] if not haskey(operation, "gate") # There are other types of gates such as PauliStrings which do not have in the json # the gate attribute throw(DomainError(cirq_gate_name, "Gate type not supported")) end cirq_gate_name = operation["gate"]["cirq_type"] qubits = parse_cirq_qubits(operation["qubits"]) if cirq_gate_name == "ZPowGate" && operation["gate"]["exponent"] == 0.25 gate_name = "T" elseif cirq_gate_name == "ZPowGate" && operation["gate"]["exponent"] == -0.25 gate_name = "T^-1" elseif cirq_gate_name == "HPowGate" && operation["gate"]["exponent"] == 1.0 gate_name = "H" elseif cirq_gate_name == "CXPowGate" && operation["gate"]["exponent"] == 1.0 gate_name = "CNOT" else throw(DomainError(cirq_gate_name, "Gate type not supported")) end push!(circuit, (gate_name, qubits)) end end return circuit end """ Saves an icm-compatible circuit to CirQ-compatible json. """ function save_circuit_to_cirq_json(circuit, file_name::String) cirq_dict = Dict() cirq_dict["cirq_type"] = "Circuit" cirq_dict["moments"] = [] for (gate, qubits) in circuit moment = Dict() moment["cirq_type"] = "Moment" operation = Dict() operation["cirq_type"] = "GateOperation" cirq_gate = Dict() if gate == "T" cirq_gate["cirq_type"] = "ZPowGate" cirq_gate["exponent"] = 0.25 elseif gate == "T^-1" cirq_gate["cirq_type"] = "ZPowGate" cirq_gate["exponent"] = 0.25 elseif gate == "H" cirq_gate["cirq_type"] = "HPowGate" cirq_gate["exponent"] = 1.0 elseif gate == "CNOT" cirq_gate["cirq_type"] = "CXPowGate" cirq_gate["exponent"] = 1.0 else throw(DomainError(gate, "Gate type not supported")) end cirq_gate["global_shift"] = 0.0 cirq_qubits = [] for qubit in qubits cirq_qubit = Dict() cirq_qubit["cirq_type"] = "NamedQubit" cirq_qubit["name"] = qubit push!(cirq_qubits, cirq_qubit) end operation["gate"] = cirq_gate operation["qubits"] = cirq_qubits moment["operations"] = [operation] push!(cirq_dict["moments"], moment) end json_string = JSON.json(cirq_dict) open(file_name, "w") do f write(f, json_string) end end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
676
""" Executes circuit using stim simulator and applies it to a given state. """ function execute_circuit( state::StabilizerState, circuit::Vector{ICMGate}; ) for (op, qubits) in circuit gate = gate_map[op]([q + index for q in qubits]...) gate(state) end end # support QuantumCircuit function execute_circuit( state::StabilizerState, circuit::QuantumCircuit) for gate in Jabalizer.gates(circuit) try state |> gate_map[gate.name](gate.qargs...) catch err if isa(err, KeyError) error(gate.name*" is not a known Stabilizer Gate.") end end end end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
3190
### Fast to_graph implementation """ _swap_row!(svec::Vector{Stabilizer}, r1::Int, r2::Int) Row swap operation """ function _swap_row!(svec::Vector{Stabilizer}, r1::Int, r2::Int) temp = svec[r1] svec[r1] = svec[r2] svec[r2] = temp end """ x_locs(svec::Vector{Stabilizer}, qubits::Int, bit::Int) Find locations of Xs above or below the diagonal in a tableau column. By default returns the ones below. """ function x_locs(svec::Vector{Stabilizer}, qubits::Int, bit::Int; above::Bool=false) incr = above ? -1 : 1 stop = above ? 1 : qubits locs = Int64[] for i = bit:incr:stop if svec[i].X[bit] push!(locs ,i) end end return locs end function fast_to_graph(state::StabilizerState) #TODO: Add a check if state is not empty. If it is, throw an exception. # update the state tableau from the stim simulator update_tableau(state) qubits = state.qubits svec = deepcopy(state.stabilizers) # Sequence of local operations performed op_seq = Tuple{String, Int}[] # Make X-block upper triangular for n in 1:qubits # sort!(svec, rev=true) # getting rid of this sort, also why rev? # lead_sum = calc_sum(svec, qubits, n) locs = x_locs(svec, qubits, n) x_num = length(locs) if x_num == 0 # Perform Hadamard operation for stab in svec x, z = stab.X[n], stab.Z[n] x == 1 && z == 1 && (stab.phase ⊻= 2) # toggle bit 2 of phase if Y # Swap bits stab.X[n], stab.Z[n] = z, x end push!(op_seq, ("H", n)) # sort!(svec, rev=true) locs = x_locs(svec, qubits, n) x_num = length(locs) end # If first X is not on the diagonal locs[1] != n && _swap_row!(svec,n, locs[1]) # Remove Xs below the diagonal popfirst!(locs) for r_idx in locs _add_row!(svec, n, r_idx) end end # Make diagonal X-block for n = qubits:-1:2 # Find x locations above the diagonal locs = x_locs(svec, qubits, n; above=true) # Remove diagonal index test_idx = popfirst!(locs) if test_idx != n error("No diagonal X in upper-triangular block - algorithm failure!") end for idx in locs _add_row!(svec, n, idx) end end # Adjacency matrix A = Array{Int}(undef, qubits, qubits) for n = 1:qubits stab = svec[n] # Y correct if stab.X[n] == 1 && stab.Z[n] == 1 # Change Y to X stab.Z[n] = 0 push!(op_seq, ("Pdag", n)) end # Phase correction if stab.phase != 0 stab.phase = 0 push!(op_seq, ("Z", n)) end # Copy Z to adjacency matrix A[n, :] .= stab.Z # Check diagonal for any non-zero values A[n, n] == 0 || println("Error: invalid graph conversion (non-zero trace).") end issymmetric(A) || println("Error: invalid graph conversion (non-symmetric).") return (graph_to_state(A), A, op_seq) end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
2116
module Gates const gate_alias = [("H_XZ", :H), ("P", :S), ("PHASE", :S), ("SQRT_Z", :S), ("SQRT_Z_DAG", :S_DAG), ("S^-1", :S_DAG), ("S_Dagger", :S_DAG), ("CX", :CNOT), ("ZCX", :CNOT), ("ZCY", :CY), ("ZCZ", :CZ), ] const gate1_list = [("I", :Id), ("X", :X), # HSSH ("Y", :Y), # SSHSSH ("Z", :Z), # SS ("C_XYZ", :C_XYZ), # SSSH ("C_ZYX", :C_ZYX), # HS ("H", :H), ("H_XY", :H_XY), # HSSHS ("H_YZ", :H_YZ), # HSHSS ("S", :S), ("S_DAG", :S_DAG), ("SQRT_X", :SQRT_X), # HSH ("SQRT_X_DAG", :SQRT_X_DAG), # SHS ("SQRT_Y", :SQRT_Y), # SSH ("SQRT_Y_DAG", :SQRT_Y_DAG), # HSS ] const gate2_list = [("CNOT", :CNOT), ("CY", :CY), # S1 S1 S1 CNOT01 S1 ("CZ", :CZ), # H1 CNOT01 H1 ("XCX", :XCX), # H0 CNOT01 H0 ("XCY", :XCY), # H0 S1 S1 S1 CNOT01 H0 S1 ("XCZ", :XCZ), # CNOT10 ("YCX", :YCX), # S0 S0 S0 H1 CNOT10 S0 H1 ("YCY", :YCY), # S0 S0 S0 S1 S1 S1 H0 CNOT01 H0 S0 S1 ("YCZ", :YCZ), ("SWAP", :SWAP), # CNOT01 CNOT10 CNOT01 ("ISWAP", :ISWAP), # H0 S0 S0 S0 CNOT01 S0 CNOT10 H1 S1 S0 ("ISWAP_DAG", :ISWAP_DAG), # S0 S0 S0 S1 S1 S1 H1 CNOT10 S0 S0 S0 CNOT01 S0 H0 ] abstract type Gate end abstract type OneQubitGate <: Gate end abstract type TwoQubitGate <: Gate end export Gate, OneQubitGate, TwoQubitGate #= "Pauli-I" "Pauli-X" "Pauli-Y" "Pauli-Z" "S (Phase)" "Hadamard" "Controlled NOT" "CZ" "SWAP" =# const gate_map = Dict{String,Type{<:Gate}}() export gate_map for (name, sym) in gate1_list @eval begin export $sym ; struct $sym <: OneQubitGate ; qubit::Int ; end end end for (name, sym) in gate2_list @eval begin export $sym ; struct $sym <: TwoQubitGate ; qubit1::Int ; qubit2::Int ; end end end for (name, sym) in vcat(gate1_list, gate2_list, gate_alias) @eval gate_map[$name] = $sym end # Aliases const P = S ; export P const PHASE = S ; export PHASE end # module Gates
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
3717
using Graphs export gcompile """ Run a full graph compilation on an input circuit. """ function gcompile( circuit::Vector{ICMGate}, args...; kwargs...) icm_circuit, data_qubits, mseq = compile( circuit, args...; kwargs... ) icm_qubits = Jabalizer.count_qubits(icm_circuit) state = zero_state(icm_qubits) Jabalizer.execute_circuit(state, icm_circuit) adj, op_seq = to_graph(state)[2:3] g = Graphs.SimpleGraph(adj) input_nodes = Dict{Int, Int}() logical_qubits = args[1] for i in 1:logical_qubits input_nodes[i] = i + logical_qubits end output_nodes = data_qubits # Add Hadamard corrections to boundry nodes. del=[] for (idx, corr) in enumerate(op_seq) # add H corrections to input nodes if (corr[1] == "H") && corr[2] in values(input_nodes) # add new node to graph add_vertex!(g) new_node = nv(g) add_edge!(g, corr[2], new_node) # add index for deletion push!(del, idx) # find the input label for the node for (k,v) in input_nodes if v == corr[2] input_nodes[k] = new_node break end end # Add measurement to mseq to implement the Hadamard pushfirst!(mseq, ("X", [new_node] )) # qubit_map[string(new_node)] = new_node end # add H corrections to output nodes if (corr[1] == "H") && corr[2] in values(output_nodes) # add new node to graph add_vertex!(g) new_node = nv(g) add_edge!(g, corr[2], new_node) # add index for deletion from mseq push!(del, idx) # find the output label for the node for (k,v) in output_nodes if v == corr[2] push!(mseq, ("X", [corr[2]] )) output_nodes[k] = new_node break end end end end deleteat!(op_seq, del) # Measurement sequence meas_order = [] meas_basis = [] for (gate, qubit) in mseq push!(meas_order, qubit[1]) push!(meas_basis, gate ) end mseq = [meas_order, meas_basis] return g, op_seq, mseq, input_nodes, output_nodes end """ gcompile for QuantumCircuit """ function gcompile( circuit::QuantumCircuit; universal::Bool, ptracking::Bool, teleport=["T", "T_Dagger", "RZ"] ) icm_circuit, mseq, data_qubits, frames_array = icmcompile(circuit; universal=universal, ptracking = ptracking, teleport = teleport ) icm_qubits = icm_circuit.registers |> length state = zero_state(icm_qubits) Jabalizer.execute_circuit(state, icm_circuit) adj, loc_corr = to_graph(state)[2:3] #Hadamard corr TODO g = Graphs.SimpleGraph(adj) return g, loc_corr, mseq, data_qubits, frames_array end """ run gcompile on an input file """ function gcompile( filename::String; kwargs... ) qc = parse_file(filename) # qubits, inp_circ = load_icm_circuit_from_qasm(filename) return gcompile( qc; kwargs... ) end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1127
""" Graph state type Type for a stabilizer state constrained to graph form. """ mutable struct GraphState qubits::Int A::Matrix{Int} GraphState() = new(0, Matrix{Int}(undef, 0, 0)) GraphState(A::AbstractMatrix{<:Integer}) = new(size(A, 1), A) GraphState(state::StabilizerState) = new(state.qubits, to_graph(state)[2]) end StabilizerState(graphState::GraphState) = graph_to_state(graphState.A) """ gplot(graphState) Plot the graph of a GraphState. """ function GraphPlot.gplot(graphState::GraphState; node_dist=5.0) # Creates an anonymous function to allow changing the layout params # in gplot. The value of C determines distance between connected nodes. layout = (args...) -> spring_layout(args...; C=node_dist) gplot(Graph(graphState.A), nodelabel=1:graphState.qubits) end Base.:(==)(g1::GraphState, g2::GraphState) = g1.qubits == g2.qubits && g1.A == g2.A function Base.display(graphState::GraphState) println("Adjacency matrix for ", graphState.qubits, " qubits:\n") display(graphState.A) end Base.print(io::IO, graphState::GraphState) = print(io, graphState.A)
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
10553
const ICMGate = Tuple{String,Vector{Int}} export icmcompile # Assume registers(qc) is of the form collect(1:n) for some n function icmcompile(qc::QuantumCircuit; universal, ptracking, teleport=["T", "T_Dagger", "RZ"], debug=false) # Register layout: [input, universal, teleport, state] # We do not write part of the circuit involving state input = copy(registers(qc)) # teleport state into these nodes allqubit = copy(registers(qc)) state = zeros(Int, length(input)) # register storing input state mapping = Dict(zip(input, allqubit)) debug && @info mapping circuit = Gate[] measure = Gate[] if ptracking # Pauli correction in this widget frames = Frames(length(input)) debug && @info frames.into_py_dict_recursive() frame_flags = Int[] end if universal debug && @info "Universal compilation..." allqubit, mapping = extend!!(allqubit, mapping, registers(qc)) # append universal register debug && @info mapping append!(circuit, Gate("H", nothing, [i]) for i in allqubit) append!(circuit, Gate("CZ", nothing, [i, mapping[i]]) for i in input) # Not written: immediately before X measurement, needs CZ current state and input # Add state and input measurements for i in input push!(measure, Gate("X", nothing, [-1])) # outcome s push!(measure, Gate("X", nothing, [i])) # outcome t end # append!(measure, Gate("X", nothing, [i]) for i in input) # outcome t # Not written: X measurement on state register # push!(measure, Gate("X", nothing, [i]) for i in state) # outcome s if ptracking # to zero indexing # buffer frames are used to modify current frames, dont need buffer_flags buffer = Frames() # Pauli correction from previous widget buffer_flags = state # adjust zero indexing later # qubits of the PREVIOUS widget? for i in input frames.new_qubit(mapping[i]-1) # Zˢ correction on system mapping[i] from outcome s frames.track_z(mapping[i]-1) push!(frame_flags, -1) # placeholder # push!(frame_flags, state[i]) # adjust zero indexing later MUTABLE... # Xᵗ correction on system mapping[i] from outcome t frames.track_x(mapping[i]-1) push!(frame_flags, i-1) # Potential correction on system mapping[i] from previous widget buffer.new_qubit(mapping[i]-1) buffer.track_z(mapping[i]-1) buffer.track_x(mapping[i]-1) # Q: use buffer to modify frame and pauli track? end end end debug && @info "Teleporting all non-Clifford gates..." for gate in gates(qc) # gate in the original circuit actingon = [mapping[q] for q in qargs(gate)] # with teleportation so far, the gate becomes currentgate = Gate(name(gate), cargs(gate), actingon) # @info "Current gate: $currentgate" # previousmapping = copy(mapping) # would remove additional keys to mapping, modify extend!! if name(gate) in teleport # specific individual gate allqubit, mapping = extend!!(allqubit, mapping, actingon) # append teleport register debug && @info mapping append!(circuit, Gate("CNOT", nothing, [q, mapping[q]]) for q in actingon) # append!(circuit, Gate("CNOT", nothing, [previousmapping[q], mapping[q]]) for q in qargs(gate)) push!(measure, Gate(name(gate), cargs(gate), actingon)) if ptracking # to zero indexing # frames.new_qubit(first(actingon)-1) frames.new_qubit(mapping[first(actingon)]-1) frames.cx(first(actingon)-1, mapping[first(actingon)]-1) # could just call ptracking_apply_gate push!(frame_flags, first(actingon)-1) frames.track_z(mapping[first(actingon)]-1) # e.g. for exp(iαZ) gates end else push!(circuit, currentgate) # apply Clifford gates to the pauli tracker ptracking && ptracking_apply_gate(frames, currentgate) end end debug && @info mapping output = [mapping[q] for q in input] # store output state # Calculate the state register and write to frame_flags state .= collect(length(allqubit)+1:length(allqubit)+length(state)) # Initialise frames for state indices for i in state frames.new_qubit(i-1) end # add state qubit indices to measure # @info measure counter = 0 for m in measure if qargs(m)[1] == -1 counter += 1 qargs(m)[1] = state[counter] end end # @info measure if universal && ptracking counter = 0 for (idx, val) in enumerate(frame_flags) if val == -1 counter += 1 frame_flags[idx] = state[counter] - 1 # to zero indexing end end @assert counter == length(state) end # Check sizes if ptracking universal && @assert length(frame_flags) == length(allqubit) universal || @assert length(frame_flags) == length(allqubit) - length(input) end # Preparing return data circuit = QuantumCircuit(allqubit, circuit) # labels = (input = input, output = output, state = state) labels = Dict(:input => input, :output => output, :state => state) ptracker = (frames = ptracking ? frames : nothing, frameflags = ptracking ? frame_flags : nothing, buffer = universal ? buffer : nothing, bufferflags = universal ? buffer_flags : nothing, ) return (circuit, measure, labels, ptracker) end # Never call with registers = allqubits: infinite loop extension # Assume allqubits is of the form collect(1:n) for some n function extend!!( allqubits::Vector{<:Integer}, mapping::Dict{<:Integer, <:Integer}, registers::Vector{<:Integer} ) @assert registers ⊆ allqubits # nextinteger(v, i=1) = i ∈ v ? nextinteger(v, i+1) : i nextinteger(v) = length(v) + 1 for reg in registers newqubit = nextinteger(allqubits) push!(allqubits, newqubit) # mapping[reg] = newqubit for key in keys(mapping) if mapping[key] == reg mapping[key] = newqubit end end mapping[reg] = newqubit end return allqubits, mapping end function ptracking_apply_gate(frames, gate::Gate) bits = qargs(gate) .-1 # Vector{UInt} # to zero indexing if name(gate) == "H" frames.h(bits[1]) elseif name(gate) == "S" frames.s(bits[1]) elseif name(gate) == "CZ" frames.cz(bits[1], bits[2]) elseif name(gate) == "X" || name(gate) == "Y" || name(gate) == "Z" # commute or anticommute elseif name(gate) == "S_DAG" frames.sdg(bits[1]) elseif name(gate) == "SQRT_X" frames.sx(bits[1]) elseif name(gate) == "SQRT_X_DAG" frames.sxdg(bits[1]) elseif name(gate) == "SQRT_Y" frames.sy(bits[1]) elseif name(gate) == "SQRT_Y_DAG" frames.sydg(bits[1]) elseif name(gate) == "SQRT_Z" frames.sz(bits[1]) elseif name(gate) == "SQRT_Z_DAG" frames.szdg(bits[1]) elseif name(gate) == "CNOT" frames.cx(bits[1], bits[2]) elseif name(gate) == "SWAP" frames.swap(bits[1], bits[2]) else error("Unknown gate: $(name(gate))") end end # BELOW WILL BE DELETED """ Perfoms gates decomposition to provide a circuit in the icm format. Reference: https://arxiv.org/abs/1509.02004 compile expects qubits to be indexed as integers from 1:n_qubits. If the universal flag is set, input nodes are added which are indexed n+1:2n. Ancillas introduced for teleportation are indexed starting from 2n+1 onwards. universal flag = false is not supported yet. gates_to_decompose are expected to by RZ gates. Rx, Ry and single qubit unitary support will be added soon. """ function compile(circuit::Vector{ICMGate}, n_qubits::Int, gates_to_decompose::Vector{String}; universal::Bool=true ) # Initialize dictionary to track teleported qubits qubit_dict = Dict{Int, Int}() # Initialise measurement sequence mseq::Vector{ICMGate} = [] if universal """ Generate pairs of Bell states for every logical qubit. Gates on logical qubits will act on one qubit of the bell pair for that logical qubit. This allows for injecting arbitrary input states through teleportation using the other qubit of the Bell pair. """ initialize::Vector{ICMGate} = [] for i in 1:n_qubits # Initialise (graph) Bell states for every logical qubit" push!(initialize, ("H", [i])) push!(initialize, ("H", [i + n_qubits])) push!(initialize, ("CZ",[i, i + n_qubits])) # Add input measurements to mseq # This does not include the measurement on the incoming qubit! push!(mseq, ("X", [i + n_qubits])) end # Prepend input initialisation to circuit circuit = [initialize; circuit] end # Initalizse the compiled circuit compiled_circuit::Vector{ICMGate} = [] ancilla_num = 1 for (gate, qubits) in circuit # Get the teleported qubit index if qubit has been teleported. compiled_qubits = [get(qubit_dict, q, q) for q in qubits] if gate in gates_to_decompose for (original_qubit, compiled_qubit) in zip(qubits, compiled_qubits) # Generate index for new ancilla to telport to. new_qubit = 2 * n_qubits + ancilla_num # update ancilla count ancilla_num += 1 # Update data qubit map qubit_dict[original_qubit] = new_qubit push!(compiled_circuit, ("CNOT", [compiled_qubit, new_qubit])) # Update measuremnet sequence push!(mseq, (gate, [compiled_qubit])) end else push!(compiled_circuit, (gate, compiled_qubits)) end end return compiled_circuit, qubit_dict, mseq end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
3770
# using Graphs, PythonCall, JSON # done in Jabalizer.jl export mbqccompile # """ # Return MBQC instructions for a given QuantumCircuit # """ function mbqccompile( circuit::QuantumCircuit; universal = true, ptracking = true, pcorrections=false, teleport = ["T", "T_Dagger", "RZ"], filepath = nothing, initializer = [], ) icm, measure, labels, ptracker = icmcompile(circuit; universal=universal, ptracking = ptracking, teleport = teleport) state = zero_state(width(icm)) Jabalizer.execute_circuit(state, icm) graphstate, correction = to_graph(state)[2:3] # Extract MBQC instructions fullgraph = Graph(graphstate) add_vertices!(fullgraph, length(labels[:state])) for (s, i) in zip(labels[:state], labels[:input]) # teleporting state into input registers add_edge!(fullgraph, s, i) end # extended graph state with state registers for scheduling spacialgraph = mbqc_scheduling.SpacialGraph([zerobasing(nb) for nb in Graphs.SimpleGraphs.adj(fullgraph)]) ptracking && (order = mbqc_scheduling.PartialOrderGraph(ptracker[:frames].get_py_order(ptracker[:frameflags]))) # already zero-based AcceptFunc = pyimport("mbqc_scheduling.probabilistic").AcceptFunc paths = mbqc_scheduling.run(spacialgraph, order) path0 = paths.into_py_paths()[0] time = pyconvert(Int, path0.time) space = pyconvert(Int, path0.space) steps = [pyconvert(Vector, step) for step in path0.steps] # Jabalizer output, converted to zero-based indexing # measurements = append!(measure, Gate("X", nothing, [i]) for i in labels[:state]) # Generate pauli-tracker for all qubits if pcorrections allqubits = reduce(vcat, steps) pcorrs = pauli_corrections(ptracker[:frames],ptracker[:frameflags], allqubits) end jabalizer_out = Dict( "time" => time, # length(steps) how many time steps "space" => space, # maximum number of qubits required "steps" => steps, # actual MBQC instructions: for each step in steps init nodes and CZ based on spacialgraph "spatialgraph" => [zerobasing(nb) for nb in Graphs.SimpleGraphs.adj(fullgraph)], # description of CZ gates to be applied (edge = apply CZ gate) "correction" => [[g, zerobasing(q)] for (g, q) in correction], # potential local Clifford correction on each nodes right after CZ above "measurements" => map(unpackGate, measure), # list of measurements "statenodes" => zerobasing(labels[:state]), # nodes where the input state is currently in "outputnodes" => zerobasing(labels[:output]), # get the output state returned by the circuit from these nodes "frameflags" => ptracker[:frameflags], # already zero-based # used to be frame_maps "initializer" => initializer, # what was passed in from caller ) if pcorrections jabalizer_out["pcorrs"] = pcorrs end js = JSON.json(jabalizer_out) if !isnothing(filepath) # @info "Jabalizer: writing to $(filepath)" open(filepath, "w") do f write(f, js) end end return jabalizer_out end function unpackGate(gate::Gate; tozerobased = true) gatename = name(gate) @assert !isnothing(qargs(gate)) "Error: $(gatename) must act on some qubits, got $(qargs(gate))." if length(qargs(gate)) == 1 tozerobased ? (actingon = zerobasing(qargs(gate)[1])) : (actingon = qargs(gate)[1]) else tozerobased ? (actingon = zerobasing(qargs(gate))) : (actingon = qargs(gate)) end if !isnothing(cargs(gate)) && length(cargs(gate)) == 1 params = cargs(gate)[1] else params = cargs(gate) end return [gatename, actingon, params] end function zerobasing(index) return index .- 1 end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
6928
using OpenQASM using MLStyle import RBNF: Token export Gate, QuantumCircuit, parse_file, width, depth export cargs, qargs,registers, gates using OpenQASM.Types # abstract type QuantumRegister end # abstract type QuantumCircuit end # interface getregisters() and getcircuit() # Wrapper for OpenQASM.Types.Instruction struct Gate name cargs qargs end name(g::Gate) = g.name cargs(g::Gate) = g.cargs qargs(g::Gate) = g.qargs width(g::Gate) = length(qargs(g)) # struct QuantumCircuit registers::Vector{Int} # allow tensor product of circuits circuit::Vector{Gate} function QuantumCircuit(registers, circuit) @assert all(qargs(g) ⊆ registers for g in circuit) return new(registers, circuit) end end width(qc::QuantumCircuit) = length(qc.registers) depth(qc::QuantumCircuit) = length(qc.circuit) registers(qc::QuantumCircuit) = qc.registers gates(qc::QuantumCircuit) = qc.circuit Base.show(io::IO, qc::QuantumCircuit) = Base.show(io, gates(qc)) # Parse qasm file and return a QuantumCircuit function parse_file(filename::String) ast = OpenQASM.parse(read(filename, String)) # Only support the following qasm format @assert ast.version == v"2.0.0" "Unsupported QASM version: $(ast.version)" @assert length(filter(x->x isa OpenQASM.Types.Include, ast.prog)) == 1 "Incorrect qasm file format: must have one include statement" @assert ast.prog[1] isa OpenQASM.Types.Include "Incorrect qasm file format: first statement must be an include statement" @assert length(filter(x->x isa OpenQASM.Types.RegDecl, ast.prog)) == 1 "Unsupported multiple qubit register declarations" @assert ast.prog[2] isa OpenQASM.Types.RegDecl "Incorrect qasm file format: second statement must be a qubit register declaration" return transform(ast) end # TODO: expand include statements function transform(qasm) return @match qasm begin t::Token{:id} => convert(Symbol, t) t::Token{:float64} => convert(Float64, t) t::Token{:int} => convert(Int, t) t::Token{:str} => convert(String, t) t::Token{:reserved} => convert(Symbol, t) OpenQASM.Types.Include(file) => transform(file) OpenQASM.Types.RegDecl(type, name, size) => (transform(type), transform(name), transform(size)) OpenQASM.Types.Bit(name=id, address=int) => transform(int) + 1 # convert to one-based indexing OpenQASM.Types.Instruction(name, cargs, qargs) => @match name begin "id" => Gate("I", nothing, map(transform, qargs)) "h" => Gate("H", nothing, map(transform, qargs)) "x" => Gate("X", nothing, map(transform, qargs)) "y" => Gate("Y", nothing, map(transform, qargs)) "z" => Gate("Z", nothing, map(transform, qargs)) "cnot" => Gate("CNOT", nothing, map(transform, qargs)) "swap" => Gate("SWAP", nothing, map(transform, qargs)) "s" => Gate("S", nothing, map(transform, qargs)) "sdg" => Gate("S_DAG", nothing, map(transform, qargs)) "t" => Gate("T", nothing, map(transform, qargs)) "tdg" => Gate("T_Dagger", nothing, map(transform, qargs)) "cx" => Gate("CNOT", nothing, map(transform, qargs)) "cz" => Gate("CZ", nothing, map(transform, qargs)) "rz" => Gate("RZ", map(transform, cargs), map(transform, qargs)) #TODO: fix rz(pi/2) q[1]; _ => error("Instruction not supported by Jabalizer yet") end OpenQASM.Types.MainProgram(prog=stmts) => let result = map(transform, stmts) qubits = 1:result[2][3] # ASSUME continuous register declaration circuit = result[3:end] QuantumCircuit(qubits, circuit) end end end # BELOW WILL BE DELETED const qasm_map = Dict("id" => "I", "h" => "H", "x" => "X", "y" => "Y", "z" => "Z", "cnot" => "CNOT", "swap" => "SWAP", "s" => "S", "sdg" => "S_DAG", "t" => "T", "tdg" => "T_Dagger", # Temp hack removed; "T", # "T_Dagger", # Temporary Hack! "cx" => "CNOT", "cz" => "CZ") const hdr3beg = """OPENQASM 3;\ninclude "stdgates.inc";\nqubit[""" const hdr3end = """] _all_qubits;\nlet q = _all_qubits[0:""" const hdr2 = """OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[""" """ Convert a very specific input string with a OpenQASM 3.0 header to a OpenQASM 2.0 header, as a convenience hack until we have a real 3.0 parser """ function convert3to2(str::String) pos = sizeof(hdr3beg) nxt = findnext(']', str, pos) startswith(SubString(str, nxt), hdr3end) || error("Header doesn't match template") qubits = parse(Int, str[pos+1:nxt-1]) pos = nxt + sizeof(hdr3end) nxt = findnext(']', str, pos) maxqb = parse(Int, str[pos:nxt-1]) maxqb == qubits - 1 || error("Mismatched number of qubits $maxqb != $qubits - 1") string(hdr2, qubits, SubString(str, nxt)) end export load_icm_circuit_from_qasm, icm_circuit_from_qasm """ Loads icm compatible circuit from a QASM (2.0) file """ load_icm_circuit_from_qasm(filename) = icm_circuit_from_qasm(read(filename, String)) """ Parses icm compatible circuit from a QASM (2.0) input string Note : qasm is 0 indexed while Jabalizer is 1 indexed so qubits labels will be transalated from i -> i+1. """ function icm_circuit_from_qasm(str::String) # Hack to handle QASM 3 header startswith(str, hdr3beg) && (str = convert3to2(str)) ast = OpenQASM.parse(str) # Check header information ast.version == v"2.0.0" || error("Unsupported QASM version: $(ast.version)") ap = ast.prog inc = ap[1] (inc isa Include && inc.file isa Token{:str} && inc.file.str == "\"qelib1.inc\"") || error("Standard include missing") reg = ap[2] (reg isa RegDecl && reg.type isa Token{:reserved} && reg.type.str == "qreg" && reg.size isa Token{:int} && reg.name isa Token{:id}) || error("Missing qubit register declaration") # Pick up qubit reg name nam = reg.name.str siz = parse(Int, reg.size.str) circuit = Vector{Tuple{String, Vector{Int}}}() for i = 3:length(ap) gate = ap[i] gate isa Instruction || error("Not an instruction: $gate") isempty(gate.cargs) || error("Classical bits not supported yet") ins = get(qasm_map, gate.name, "") ins == "" && error("Instruction $ins not found") args = gate.qargs vals = Int[] for qarg in args (qarg isa Bit && qarg.name isa Token{:id} && qarg.name.str == nam && qarg.address isa Token{:int}) || error("Invalid instruction argument: $qarg") # convert to 1 index from qasm 0 index push!(vals, parse(Int, qarg.address.str) + 1) end push!(circuit, (ins, vals)) end siz, circuit end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
11521
# write graph compilation to qasm file using Graphs using JSON const qasm_inversemap = Dict(map(reverse,collect(qasm_map))) qasm_inversemap["RZ"] = "rz" export qasm_instruction function correction_controls(frame_bitvector, frame_flags) corr = [] if sum(frame_bitvector) != 0 for idx in reverse(findall(frame_bitvector .== 1)) push!(corr, frame_flags[idx]) end end return corr end """ frame_bitvector(frame_vec, frames_length) Return a bitvector of Pauli corrections given a vector of python integers It is assumed that each integer in `frames_vec` represents a 64 bit chunk of the full bitvector. """ function frame_bitvector(frame_vec, frames_length) intvec = [pyconvert(UInt, pint) for pint in frame_vec] bitvec = [digits(jint, base=2, pad=64) for jint in intvec] # concatenate all bitvector chunks and return frame_length bits return vcat(bitvec...)[1:frames_length] end """ pauli_corrections(frames, frame_flags, qubits) Returns a dictionary of Pauli correction for every qubit in the vector `qubits`. `frames` are expected to be `pauli_tracker.frames.map.Frames` class. """ function pauli_corrections(frames, frame_flags, qubits) corr = Dict() frame_dict = frames.into_py_dict_recursive() flen = frame_flags |> length for q in qubits qcorr = [] z_bitvector = frame_bitvector(frame_dict[q][0], flen) x_bitvector = frame_bitvector(frame_dict[q][1], flen) zcontrol = correction_controls(z_bitvector, frame_flags) xcontrol = correction_controls(x_bitvector, frame_flags) for mq in reverse(frame_flags) for z in zcontrol if z == mq push!(qcorr, ["z", z]) end end for x in xcontrol if x == mq push!(qcorr, ["x", x]) end end end if ! isempty(qcorr) corr[q] = qcorr end end return corr end """ export qasm file given a graph compilation """ function qasm_instruction(outfile, graph::SimpleGraph{Int}, loc_corr, mseq, data_qubits, frames_array) # open output file file = open(outfile, "w") # unpack frames frames, frame_flags = frames_array # initialise qasm file println(file, "OPENQASM 2.0;\ninclude \"qelib1.inc\";" ) # qasm_str = "OPENQASM 2.0;\ninclude qelib1.inc;\n" # # initialise qregs and cregs qregs = nv(graph) qregs_total = qregs + length(data_qubits[:state]) println(file, "\nqreg q[$qregs_total];") for i in 0:qregs_total-1 println(file, "creg c$(i)[1];") end # Graph state generation println(file, "\n// Graph state generation") for i in 0:qregs-1 println(file, "h q[$i];") end for e in edges(graph) s = src(e) - 1 d = dst(e) - 1 println(file, "cz q[$s], q[$d];") end println(file) # state input edges println(file, "// state input edges") for (s,i) in zip(data_qubits[:state], data_qubits[:input]) println(file, "cz q[$(s-1)], q[$(i-1)];") end # local correction println(file, "\n// Local Clifford correction") for gate in loc_corr if gate[1] == "H" println(file, "h q[$(gate[2]-1)];") end if gate[1] == "Z" println(file, "z q[$(gate[2]-1)];") end # inverting local clifford corrections applies the inverse gate if gate[1] == "Pdag" println(file, "s q[$(gate[2]-1)];") end end println(file) println(file, "// Measurement sequence") # Generate Pauli Corrections outqubits = data_qubits[:output] .- 1 qubits = [q for q in frame_flags] append!(qubits, outqubits) pc = pauli_corrections(frames, frame_flags, qubits) for m in mseq gate = qasm_inversemap[m.name] qargs = m.qargs .- 1 # Add pauli correction if haskey(pc, qargs[1]) pcorr = pc[qargs[1]] for p in pcorr println(file, "if(c$(p[2]) == 1) $(p[1]) q$qargs;") end end if gate == "x" println(file, "h q$(qargs);") println(file, "measure q$(qargs) -> c$(qargs[1])[0];") elseif gate in ["t", "tdg"] println(file, "$gate q$(qargs);" ) println(file, "h q$(qargs);") println(file, "measure q$(qargs) -> c$(qargs[1])[0];") elseif gate == "rz" println(file, "$(gate)($(m.cargs[1])) q$(qargs);" ) println(file, "h q$qargs;") println(file, "measure q$(qargs) -> c$(qargs[1])[0];") end println(file) end # Add pauli corrections to output qubits println(file, "// Pauli correct output qubits") for q in outqubits if haskey(pc, q) pcorr = pc[q] for p in pcorr println(file, "if(c$(p[2]) == 1) $(p[1]) q[$q];") end end end close(file) # convert data_qubits to 0 index d = Dict() for k in keys(data_qubits) d[k] = data_qubits[k] .-1 end data_file = splitext(outfile)[1]*"_dqubits.json" open(data_file,"w") do f JSON.print(f, d) end return nothing end """ memory allocation helper function """ function alloc(logicalq, physicalmap, ram) if !(logicalq in keys(physicalmap)) physicalmap[logicalq] = pop!(ram) end end """ memory deallocation helper function """ function dealloc(logicalq, physicalmap, ram) if (logicalq in keys(physicalmap)) freeq = pop!(physicalmap, logicalq) push!(ram, freeq) end end """ Generates a qasm file implementing the mbqc instruction """ function qasm_instruction(outfile, mbqc_inst::Dict) # open output file file = open(outfile, "w") # unpack data dictionary qphysical = mbqc_inst["space"] mlayers = mbqc_inst["steps"] pc = mbqc_inst["pcorrs"] outqubits = mbqc_inst["outputnodes"] statequbits = mbqc_inst["statenodes"] # @info statequbits loc_corr = mbqc_inst["correction"] measurements = mbqc_inst["measurements"] graph = mbqc_inst["spatialgraph"] # initialise map to phyiscal qubits for memory management mq = Dict{Int, Int}() # Convert measurement sequence to a dictionary. # the sequence is now decided by layers mdict = Dict() for m in measurements mdict[m[2]] = (m[1], m[3]) end # initialise qasm file println(file, "OPENQASM 2.0;\ninclude \"qelib1.inc\";" ) # # initialise qregs and cregs # qregs = nv(graph) # qregs_total = qregs + length(data_qubits[:state]) qlogical = length(measurements) + length(outqubits) # println(file, "\nqreg q[$qlogical];") println(file, "\nqreg q[$qphysical];") # defining a classical register for every logical qubit for i in 0:qlogical-1 println(file, "creg c$(i)[1];") end # keep track of initialised qubits # init = copy(statequbits) init = [] # keep track of qubit connections connection_graph = SimpleGraph(qlogical) # initialise available physical qubits ram = collect(qphysical-1:-1:0) # tracker for state qubit assignment state_physical = Dict() state_layer = Dict() # Generate and measure layers for (idx,lr) in enumerate(mlayers) # initialise qubits and neighbors if not initialised for q in lr if !(q in init) # allocate qubit in memory if unallocated alloc(q, mq, ram) # skip hadamard for incoming state qubits if !(q in statequbits) println(file, "h q[$(mq[q])];") else # store state input physical qubit and layer state_physical[q] = mq[q] state_layer[q] = idx-1 # @info state_physical end push!(init, q) end for n in graph[q+1] if !(n in init) alloc(n, mq, ram) # skip hadamard for incoming state qubits if !(n in statequbits) println(file, "h q[$(mq[n])];") else # store state input physical qubit and layer state_physical[n] = mq[n] state_layer[n] = idx-1 end push!(init, n) end end end # conect all neighbors of qubits in measurement layer for q in lr for n in graph[q+1] # check if already connected if !(n+1 in neighbors(connection_graph, q+1)) println(file, "cz q[$(mq[q])], q[$(mq[n])];") add_edge!(connection_graph, q+1, n+1) end end end # apply local corrections for gate in loc_corr if gate[2] in lr if gate[1] == "H" println(file, "h q[$(mq[gate[2]])];") end if gate[1] == "Z" println(file, "z q[$(mq[gate[2]])];") end # inverting local clifford corrections applies the inverse gate if gate[1] == "Pdag" println(file, "s q[$(mq[gate[2]])];") end end end # measurement for q in lr # apply Pauli corrections. if haskey(pc, q) for p in pc[q] println(file, "if(c$(p[2]) == 1) $(p[1]) q[$(mq[q])];") end end # skip measurement for output qubits (q in outqubits) && continue # perform measurements gate = qasm_inversemap[mdict[q][1]] if gate == "x" println(file, "h q[$(mq[q])];") println(file, "measure q[$(mq[q])] -> c$q[0];") elseif gate in ["t", "tdg"] println(file, "$gate q[$(mq[q])];" ) println(file, "h q[$(mq[q])];") println(file, "measure q[$(mq[q])] -> c$q[0];") elseif gate == "rz" # @info mdict[q] println(file, "$gate($(mdict[q][2])) q[$(mq[q])];" ) println(file, "h q[$(mq[q])];") println(file, "measure q[$(mq[q])] -> c$q[0];") else error("unsupported gate teleportation: ", gate) end # reset qubit println(file, "reset q[$(mq[q])];") # release measured physical qubit back to ram dealloc(q, mq, ram) end end close(file) data_qubits = Dict() data_qubits[:state] = [state_physical[s] for s in statequbits] data_qubits[:output] = [mq[o] for o in outqubits] data_qubits[:state_layer] = [state_layer[s] for s in statequbits] data_file = splitext(outfile)[1]*"_dqubits.json" open(data_file,"w") do f JSON.print(f, data_qubits) end return nothing end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
3284
""" Stabilizer type Type for a single stabilizer in the n-qubit Pauli group. """ mutable struct Stabilizer qubits::Int X::BitVector Z::BitVector phase::Int8 """ Stabilizer() Constructor for an empty stabilizer. """ Stabilizer() = new(0, falses(0), falses(0), 0) """ Stabilizer(n) Constructor for an n-qubit identity stabilizer. """ Stabilizer(n::Int) = new(n, falses(n), falses(n), 0) """ Stabilizer(tableau[, row]) Constructor for a stabilizer from tableau form. """ function Stabilizer(tab::AbstractMatrix{<:Integer}, row=1) qubits = size(tab, 2) >> 1 new(qubits, view(tab, row, 1:qubits), view(tab, row, qubits+1:2*qubits), tab[row, end]) end function Stabilizer(vec::AbstractVector{<:Integer}) qubits = length(vec) >> 1 new(qubits, view(vec, 1:qubits), view(vec, qubits+1:2*qubits), vec[end]) end """ Stabilizer(X::BitVector, Z::BitVector, phase) Constructor for a stabilizer from tableau form. """ function Stabilizer(X, Z, phase) lx, lz = length(X), length(Z) lx == lz || error("X & Z vectors have different lengths ($lx != $lz)") new(lx, X, Z, phase) end end """ Convert stabilizer to vector form (one row of a tableau) """ to_tableau_row(stabilizer::Stabilizer) = vcat(stabilizer.X, stabilizer.Z, stabilizer.phase) """ adjoint(stabilizer) Conjugate of a stabilizer. """ function Base.adjoint(stabilizer::Stabilizer)::Stabilizer conj = deepcopy(stabilizer) conj.phase = mod(-conj.phase, 4) return conj end # This table is used to calculate the product by indexing a vector of tuples of the # results (X, Z, phase), by the values of the left X, left Z, right X, right Z used # as a 4 bit index (left X is most signficant bit, right Z is least significant bit) # (+ 1 for Julia 1-based indexing) const _prodtab = [(0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 0), (1, 1, 1), (1, 0, 3), (1, 0, 0), (1, 1, 3), (0, 0, 0), (0, 1, 1), (1, 1, 0), (1, 0, 1), (0, 1, 3), (0, 0, 0)] """ *(left,right) Multiplication operator for stabilizers. """ function Base.:*(left::Stabilizer, right::Stabilizer)::Stabilizer left.qubits == right.qubits || return left qubits = left.qubits prod = Stabilizer(qubits) prod.phase = (left.phase + right.phase) & 3 for n = 1:qubits (prod.X[n], prod.Z[n], phase) = _prodtab[((left.X[n]<<3)|(left.Z[n]<<2)|(right.X[n]<<1)|right.Z[n])+1] prod.phase = (prod.phase + phase) & 3 end return prod end Base.:(==)(s1::Stabilizer, s2::Stabilizer) = s1.qubits == s2.qubits && s1.X == s2.X && s1.Z == s2.Z && s1.phase == s2.phase function Base.isless(s1::Stabilizer, s2::Stabilizer) s1.X < s2.X && return true s1.X > s2.X && return false s1.Z < s2.Z && return true s1.Z > s2.Z && return false s1.phase < s2.phase end function Base.print(io::IO, stabilizer::Stabilizer) print(io, stabilizer.phase == 0 ? '+' : '-') for (x, z) in zip(stabilizer.X, stabilizer.Z) print(io, "IXZY"[((z<<1)|x)+1]) end end Base.display(stabilizer::Stabilizer) = println("Stabilizer for ", stabilizer.qubits, " qubits:\n", stabilizer)
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
704
# Pauli-I no-op operation (normally named I, but that conflicts with a LinearAlgebra name) function (g::Id)(state::StabilizerState) ; state ; end # One qubit gates for (nam, typ) in Gates.gate1_list typ == :Id && continue # already handled op = Symbol(lowercase(string(typ))) @eval function (g::$typ)(state::StabilizerState) state.is_updated = false state.simulator.$(op)(g.qubit - 1) state end end # Two qubit gates for (nam, typ) in Gates.gate2_list op = Symbol(lowercase(string(typ))) @eval function (g::$typ)(state::StabilizerState) state.is_updated = false state.simulator.$(op)(g.qubit1 - 1, g.qubit2 - 1) state end end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
810
# implement the row reduction procedure as per Gottesman # randomly choose outcome # update the state # return outcome measure_z(state::StabilizerState, qubit::Int) = pyconvert(Int, state.simulator.measure(qubit - 1)) function measure_x(state::StabilizerState, qubit::Int) # Convert to |+>, |-> basis H(qubit)(state) # Measure along z (now x) outcome = measure_z(state, qubit) # Return to computational basis H(qubit)(state) return outcome end function measure_y(state::StabilizerState, qubit::Int) # Map Y eigenstates to X eigenstates # Note that P^dagger = ZP state |> Z(qubit) |> P(qubit) |> H(qubit) # Measure along z (now y) outcome = measure_z(state, qubit) # Return to original basis state |> H(qubit) |> P(qubit) return outcome end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
3194
""" Stabilizer state type qubits: number of qubits stabilizers: set of state stabilizers simulator: simulator state is_updated: flag for whether or not Julia state has been updated to match Stim simulator state """ mutable struct StabilizerState qubits::Int stabilizers::Vector{Stabilizer} simulator::Py is_updated::Bool StabilizerState(n::Int) = new(n, Stabilizer[], stim.TableauSimulator(), true) StabilizerState() = StabilizerState(0) end const Tableau = Matrix{Int} """ zero_state(n::Int) Generates a state of n qubits in the +1 Z eigenstate. """ function zero_state(n::Int) state = StabilizerState(n) state.simulator.set_num_qubits(n) for i in 0:n-1 state.simulator.z(i) end state.is_updated = false return state end # This function is problematic with the stim integration # This doesn't seem to affect the simulator state at all """ Generate stabilizer from tableau """ function tableau_to_state(tab::AbstractArray{<:Integer})::StabilizerState qubits = size(tab, 2) >> 1 stabs = size(tab, 1) state = StabilizerState(qubits) for row = 1:stabs stab = Stabilizer(@view tab[row, :]) push!(state.stabilizers, stab) end return state end """ to_tableau(state) Convert state to tableau form. """ function to_tableau(state::StabilizerState)::Tableau tab = Int[] update_tableau(state) for s in state.stabilizers tab = vcat(tab, to_tableau_row(s)) end Array(transpose(reshape(tab, 2 * state.qubits + 1, length(state.stabilizers),))) end function Base.print(io::IO, state::StabilizerState) update_tableau(state) for s in state.stabilizers println(io, s) end nothing end function Base.display(state::StabilizerState) update_tableau(state) println("Stabilizers ($(length(state.stabilizers)) stabilizers, $(state.qubits) qubits):") println(state) end """ gplot(state) Plot the graph equivalent of a state. """ function GraphPlot.gplot(state::StabilizerState; node_dist=5.0) # Creates an anonymous function to allow changing the layout params # in gplot. The value of C determines distance between connected nodes. layout = (args...) -> GraphPlot.spring_layout(args...; C=node_dist) gplot(GraphPlot.Graph(GraphState(state).A), nodelabel=1:state.qubits, layout=layout) end function graph_to_state(A::AbstractArray{<:Integer})::StabilizerState n = size(A, 1) state = zero_state(n) for i = 1:n H(i)(state) end for i = 1:n, j = (i+1):n A[i, j] == 1 && CZ(i, j)(state) end update_tableau(state) return state end """ ==(state_1::StabilizerState, state_2::StabilizerState) Checks if two stabilizer states are equal. """ function Base.:(==)(state_1::StabilizerState, state_2::StabilizerState) # Make sure the Julia representation matches the simulator state update_tableau(state_1) update_tableau(state_2) for (stab1, stab2) in zip(state_1.stabilizers, state_2.stabilizers) (stab1.X == stab2.X && stab1.Z == stab2.Z && stab1.phase == stab2.phase) || return false end return true end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
10671
const debug_out = Ref(false) # Debugging timing output (if debug_out is set) macro disp_time(msg, ex) quote if debug_out[] print($(esc(msg))) @time $(esc(ex)) else $(esc(ex)) end end end """Set debugging output flag""" set_debug(flag) = (debug_out[] = flag) export set_debug """ stim_tableau(stim_sim::Py)::Matrix{Int} Return a Jabalizer tableau from a stim TableauSimulator instance # Arguments - `stim_sim::Py`: stim.TableauSimulator from which to compute the Jabalizer tableau """ function stim_tableau(stim_sim::Py)::Matrix{Int} forward_tableau = stim_sim.current_inverse_tableau().inverse() qubits = length(forward_tableau) tab_arr = [forward_tableau.z_output(i - 1) for i in 1:qubits] tableau = zeros(Int, qubits, 2 * qubits + 1) for i in 1:qubits ps = tab_arr[i] # Get stim PauliString representation # update sign pyconvert(Number, ps.sign) == -1 && (tableau[i, end] = 2) # Stabilizer replacement for j in 1:qubits v = pyconvert(Int, get(ps, j - 1, -1)) # Note: 0123 represent IXYZ (different from the xz representation used here) if v == 1 # X replacement tableau[i, j] = 1 elseif v == 3 # Z replacement tableau[i, j+qubits] = 1 elseif v == 2 # Y replacement tableau[i, j] = 1 tableau[i, j+qubits] = 1 end end end return tableau end function out_time(n, a, tottim, totcnt=0) print("\t$n:\t$(round(a/1000000000,digits=3))s, ") tim = tottim/1000000000/60 print("elapsed time: ", round(tim, digits=2), " min") totcnt == 0 || print(", remaining time: ", round(tim/n*(totcnt-n), digits=2), " min") println() end """ update_tableau(state::StabilizerState) Update the state tableau with the current state of the stim simulator """ function update_tableau(state::StabilizerState) state.is_updated && return # Extract the tableau in Jabalizer format stim_sim = state.simulator @disp_time "\tcurrent_inverse_tableau: " tb = stim_sim.current_inverse_tableau() @disp_time "\tinverse: " tb = tb.inverse() oldlen = state.qubits state.qubits = qubits = length(tb) svec = state.stabilizers pt = t0 = time_ns() cnt = 0 @disp_time "\tupdate stabilizers: \n" begin if isempty(svec) for i in 1:qubits ps = tb.z_output(i-1) xs, zs = ps.to_numpy() xv = pyconvert(BitVector, xs) zv = pyconvert(BitVector, zs) push!(svec, Stabilizer(xv, zv, pyconvert(Number, ps.sign) == -1 ? 2 : 0)) if debug_out[] && (cnt += 1) > 9999 tn = time_ns() ; out_time(i, tn-pt, tn-t0, qubits) ; pt = tn cnt = 0 end end else qubits == oldlen || error("Mismatch qubits $qubits != $oldlen, $(length(svec))") for i in 1:qubits ps = tb.z_output(i-1) xs, zs = ps.to_numpy() stab = svec[i] stab.X = pyconvert(BitVector, xs) stab.Z = pyconvert(BitVector, zs) stab.phase = pyconvert(Number, ps.sign) == -1 ? 2 : 0 if debug_out[] && (cnt += 1) > 9999 tn = time_ns() ; out_time(i, tn-pt, tn-t0, qubits) ; pt = tn cnt = 0 end end end debug_out[] && (tn = time_ns() ; out_time(cnt, tn-pt, tn-t0)) end # mark it as updated state.is_updated = true end """ rand(StabilizerState, qubits::Int) Return a random (valid) stabilizer state with the given number of qubits """ function Base.rand(::Type{StabilizerState}, qubits::Int) tableau = stim.Tableau.random(qubits).inverse() state = StabilizerState(qubits) state.simulator.set_inverse_tableau(tableau) svec = state.stabilizers (_, _, z2x, z2z, _, z_signs) = tableau.to_numpy() signs = pyconvert(BitVector, z_signs) for i in 1:qubits xv = pyconvert(BitVector, z2x[i-1]) zv = pyconvert(BitVector, z2z[i-1]) push!(svec, Stabilizer(xv, zv, signs[i]<<1)) end # mark it as updated state.is_updated = true return state end function _is_symmetric(svec::Vector{Stabilizer}) qubits = length(svec) for i = 1:qubits-1 sz = svec[i].Z for j = i+1:qubits sz[j] == svec[j].Z[i] || return false end end return true end export graph_as_stabilizer_vector """ graph_as_stabilizer_vector(state) Convert a state to its adjacency graph state equivalent under local operations. Returns a vector of Stabilizers, and a vector of operations performed """ function graph_as_stabilizer_vector(state::StabilizerState) #TODO: Add a check if state is not empty. If it is, throw an exception. # update the state tableau from the stim simulator @disp_time "update_tableau: " update_tableau(state) qubits = state.qubits svec = deepcopy(state.stabilizers) # Sequence of local operations performed op_seq = Tuple{String, Int}[] @disp_time "\tsort!: " sort!(svec, rev=true) @disp_time "\tMake X-block upper triangular: " begin # Make X-block upper triangular for n in 1:qubits # Find first X (or Y) below diagonal. first_x = find_first_x(svec, qubits, n, n) # if diagonal is zero, # 1) perform Hadamard operation if no other X found # 2) swap rows with first X found if svec[n].X[n] == 0 if first_x == 0 # Perform Hadamard operation for stab in svec x, z = stab.X[n], stab.Z[n] if xor(x, z) == 1 # Swap bits stab.X[n], stab.Z[n] = z, x elseif x == 1 && z == 1 stab.phase ⊻= 2 # toggle bit 2 of phase if Y end end push!(op_seq, ("H", n)) # Recalculate first_x (should always be non-zero, # since Z column should have at least 1 bit set first_x = find_first_x(svec, qubits, n, n) end # If we are not already at end (i.e. n == qubits), and diagonal is still 0, swap rows if first_x != 0 && svec[n].X[n] == 0 # Swap rows to bring X to diagonal svec[n], svec[first_x] = svec[first_x], svec[n] # Recalculate first_x after swap, starting after first_x row (which now has 0 X) first_x = find_first_x(svec, qubits, first_x, n) end end # If there are any rows with X set in this column below the diagonal, # perform rowadd operations if first_x != 0 for m in first_x:qubits svec[m].X[n] == 0 || _add_row!(svec, n, m) end end end end # Make diagonal X-block @disp_time "\tMake diagonal: " begin for n = (qubits-1):-1:1, m = (n+1):qubits svec[n].X[m] == 1 && _add_row!(svec, m, n) end end @disp_time "\tPhase correction and checks: " begin for n = 1:qubits stab = svec[n] # Phase correction if stab.phase != 0 stab.phase = 0 push!(op_seq, ("Z", n)) end # Y correct if stab.Z[n] == 1 if stab.X[n] == 1 # Change Y to X stab.Z[n] = 0 push!(op_seq, ("Pdag", n)) else # Check diagonal for any non-zero values println("Error: invalid graph conversion (non-zero trace).") end end end end @disp_time "\tCheck symmetry: " begin if !_is_symmetric(svec) println("Error: invalid graph conversion (non-symmetric).") if debug_out[] && qubits < 33 show(to_tableau(state)) println() show(state) println() end end end return (svec, op_seq) end export adjacency_matrix """ adjacency_matrix(::Vector{Stabilizer}) Convert an adjacency graph stored in the Z bits of a vector of Stabilizers to an adjacency matrix """ function adjacency_matrix(svec::Vector{Stabilizer}) qubits = length(svec) # Adjacency matrix A = BitMatrix(undef, qubits, qubits) for n = 1:qubits stab = svec[n] # Copy Z to adjacency matrix A[n, :] .= stab.Z end A end """ adjacency_matrix(state::StabilizerState) Convert a state to its adjacency graph state equivalent under local operations. """ adjacency_matrix(state::StabilizerState) = adjacency_matrix(graph_as_stabilizer_vector(state)[1]) """ to_graph(state) Convert a state to its adjacency graph state equivalent under local operations. Returns stabilizer state, adjacency matrix, and sequence of operations. """ function to_graph(state::StabilizerState) @disp_time "to_graph: " begin svec, op_seq = graph_as_stabilizer_vector(state) @disp_time "\tCreate Adjacency Matrix: " A = adjacency_matrix(svec) @disp_time "\tgraph_to_state: " g = graph_to_state(A) end g, A, op_seq end """Find first X set below the diagonal in column col""" function find_first_x(svec, qubits, row, col) while (row += 1) <= qubits svec[row].X[col] == 0 || return row end return 0 end """ _add_row!(tableau, source, dest) Row addition operation """ function _add_row!(svec::Vector{Stabilizer}, source::Int, dest::Int) left = svec[source] right = svec[dest] # Calculate product of source & dest rows right.phase = (left.phase + right.phase) & 3 for n = 1:length(svec) (right.X[n], right.Z[n], phase) = _prodtab[((left.X[n]<<3)|(left.Z[n]<<2)|(right.X[n]<<1)|right.Z[n])+1] right.phase = (right.phase + phase) & 3 end return end """ Returns number of qubits in the icm-compatible circuit. """ function count_qubits(circuit::Vector{ICMGate}) qubit_ids = Set() for gate in circuit union!(qubit_ids, Set(gate[2])) end return length(qubit_ids) end export write_adjlist """ Output adjacency list from adjacency matrix in stabilizer Z bits """ function write_adjlist(svec::Vector{Stabilizer}, nam) len = length(svec) open(nam, "w") do io print(io, "# $len") for i = 1:len z = svec[i].Z print(io, '\n', i-1) for j = i+1:len z[j] && print(io, ' ', j-1) end end println(io) end end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
3272
module QiskitSim using CondaPkg using PythonCall using Jabalizer using JSON # add qiskit python backends for circuit simulation if !(haskey(CondaPkg.current_pip_packages(), "qiskit-aer")) CondaPkg.add_pip("qiskit-aer") end qaer = pyimport("qiskit_aer") qiskit = pyimport("qiskit") Aer = qaer.Aer """ Simulate the compiled circuit + input_circuit.inverse() on the computational basis. Returns the measured shots for each basis input for the outcome 0^n. """ function simulate(input_qasm, shots; compiled_qasm="", data_qubits=Dict()) # flag to cleanup any generated files clean = false if compiled_qasm == "" clean = true compiled_qasm = "outfile.qasm" graph, loc_corr, mseq, data_qubits, frames_array = gcompile(input_qasm; universal=true, ptracking=true ) # write qasm instructions to outfile qasm_instruction(compiled_qasm, graph, loc_corr, mseq, data_qubits, frames_array); data_qubits[:output] = data_qubits[:output] .- 1 data_qubits[:state] = data_qubits[:state] .- 1 end output_qubits = data_qubits[:output] state_qubits = data_qubits[:state] # check that for mbqccompile, path is time optimal sl = get(data_qubits, :state_layer, [0]) all([i ==0 for i in sl]) || error("Only time optimal paths are supported") # @info state_qubits # @info output_qubits # load circuits into qiskit simulator = Aer.get_backend("aer_simulator") input_circ = qiskit.QuantumCircuit.from_qasm_file(input_qasm) # @info compiled_qasm compiled_circ = qiskit.QuantumCircuit.from_qasm_file(compiled_qasm) compiled_circ.barrier() # println(compiled_circ) qtot = length(output_qubits) meas_outcomes = [] for i in 0:2^qtot-1 new_circ = compiled_circ.compose(input_circ.inverse(), output_qubits) x_locs = digits(i, base=2, pad=qtot) # input state local input_state = qiskit.QuantumCircuit(length(output_qubits)) x_locs = findall(!iszero, x_locs) .- 1 if ! isempty(x_locs) input_state.x(x_locs) end # append input state and invert at output new_circ = new_circ.compose(input_state, qubits=state_qubits, front=true) new_circ = new_circ.compose(input_state.inverse(), qubits=output_qubits) for q in output_qubits new_circ.measure(q,q) end # might need a transpile step job = simulator.run(new_circ, shots=shots) result = job.result() measured_statistics = qiskit.result.marginal_counts(result, indices=output_qubits).get_counts() # println(measured_statistics) # Obtain statisics of 0^n meas_0 = measured_statistics[repeat("0 ", length(output_qubits)) |> rstrip] meas_0 = pyconvert(Int,meas_0) push!(meas_outcomes, meas_0) end # clean generated output files if clean rm(compiled_qasm) rm(splitext(compiled_qasm)[1]*"_dqubits.json") end return meas_outcomes end end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1190
using LinearAlgebra const graph_state_test_cases = ( ("star", [0 1 1 1 1; 1 0 0 0 0; 1 0 0 0 0; 1 0 0 0 0; 1 0 0 0 0]), ("diagonal", [1 0 0; 0 1 0; 0 0 1]), ("empty", [0 0 0; 0 0 0; 0 0 0]), ) @testset "GraphState to State conversion" begin for (name, A) in graph_state_test_cases @testset "Graph $name" begin graph_state = GraphState(A) stabilizer_state = StabilizerState(graph_state) n_qubits = size(A)[1] target_x_matrix = Diagonal(ones(n_qubits)) # Target Z matrix is the same as the adjacency matrix, but with diagonal elements ignored target_z_matrix = A target_z_matrix[diagind(A)] .= 0 target_phase = zeros(n_qubits) intermediate_tableau = to_tableau(stabilizer_state) @test intermediate_tableau[:, 1:n_qubits] == target_x_matrix @test intermediate_tableau[:, n_qubits+1:2*n_qubits] == target_z_matrix @test intermediate_tableau[:, 2*n_qubits+1] == target_phase recovered_graph_state = GraphState(stabilizer_state) @test graph_state == recovered_graph_state end end end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
698
using Jabalizer @testset "E2E Jabalizer test" begin circuit = Vector{Tuple{String,Vector{String}}}( [("CNOT", Vector(["0", "anc_0"])), ("H", ["1"]), ("CNOT", ["1", "anc_0"]), ("CNOT", ["anc_0", "anc_1"]), ("CNOT", ["1", "anc_2"]), ("CNOT", ["anc_2", "anc_0"]), ("H", ["anc_2"]) ] ) gates_to_decomp = ["T", "T^-1"] (icm_circuit, data_qubits_map) = compile(circuit, gates_to_decomp) n_qubits = count_qubits(icm_circuit) state = zero_state(n_qubits) execute_circuit(state, icm_circuit) (g, A, seq) = to_graph(state) Jabalizer.gplot(g) # TODO: check if the result is correct @test true end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1157
using Test using Jabalizer @testset "Executing cirq circuits" begin # TODO: Add the following tests: # 1. Check if it fails if the circuit has gates that are not allowed # 2. Check if it correctly transoforms all the different combinations of stabilizer state and gates # 3. Check if it correctly skips the measurement gate # 4. Check if it works correctly if the size of the state doesn't match the size of the circuit # Input Circuits -> generate canonical clifford circuits, e.g.: GHZ state, trivial circuits # Input states -> Zero states, # Output states -> # See cases in runtests.jl # gate_map = Dict(cirq.I => Jabalizer.Id, # cirq.H => Jabalizer.H, # cirq.X => Jabalizer.X, # cirq.Y => Jabalizer.Y, # cirq.Z => Jabalizer.Z, # cirq.CNOT => Jabalizer.CNOT, # cirq.SWAP => Jabalizer.SWAP, # cirq.S => Jabalizer.P, # cirq.CZ => Jabalizer.CZ # TEST CASE 1: # Input -> circuit(I(0)) # Outputs -> Zero state # Compare ToTableau(state) == target_tableau # TEST CASE 2: # Input -> circuit(H(0)) # Outputs -> STH end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1252
using Test using Jabalizer @testset "GraphState initialization" begin # Check if initialization of empty Graph state works graph_state = GraphState() # Why simply GraphState() doesn't work? @test graph_state.qubits == 0 @test graph_state.A isa AbstractMatrix{<:Integer} @test isempty(graph_state.A) # Check if initialization from an adjacency matrix works A = [0 1; 1 0] graph_state = GraphState(A) @test graph_state.qubits == 2 @test graph_state.A == A stabilizer_state = zero_state(4) graph_state = GraphState(stabilizer_state) A = [0 0 0 0; 0 0 0 0; 0 0 0 0; 0 0 0 0] @test graph_state.qubits == 4 @test graph_state.A == A end @testset "GraphState to State conversion" begin A = [0 1 1 1 1; 1 0 0 0 0; 1 0 0 0 0; 1 0 0 0 0; 1 0 0 0 0] graph_state = GraphState(A) stabilizer_state = StabilizerState(graph_state) # TODO: test whether StabilizerState is what we expect it to be recovered_graph_state = GraphState(stabilizer_state) @test graph_state.qubits == recovered_graph_state.qubits @test graph_state.A == recovered_graph_state.A @test graph_state == recovered_graph_state @test graph_state.qubits == 5 @test graph_state.A == A end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
847
const qasm2hdr = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[8]; """ const qasm3hdr = """ OPENQASM 3; include "stdgates.inc"; qubit[8] _all_qubits; let q = _all_qubits[0:7]; """ const qasmbody = """ h q[0]; x q[1]; y q[2]; z q[3]; cnot q[4],q[5]; swap q[6],q[7]; s q[0]; sdg q[1]; t q[2]; tdg q[3]; cz q[4],q[5]; """ const icminput = (8, [("H", [1]), ("X", [2]), ("Y", [3]), ("Z", [4]), ("CNOT", [5, 6]), ("SWAP", [7, 8]), ("S", [1]), ("S_DAG", [2]), ("T", [3]), ("T_Dagger", [4]), # Will need to change to T_DAG when that is handled directly ("CZ", [5, 6])] ) @testset "QASM file input" begin circ2 = icm_circuit_from_qasm(qasm2hdr * qasmbody) circ3 = icm_circuit_from_qasm(qasm3hdr * qasmbody) @test circ2 == icminput @test circ3 == icminput end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1392
using Jabalizer using JSON test_circuits = ["test_circuits/mwe.qasm", "test_circuits/toffoli.qasm"] shots = 1024 @testset "gcompile simulation with Qiskit" begin for inp in test_circuits meas_outcomes = QiskitSim.simulate(inp, shots) @test all(m == shots for m in meas_outcomes) end end outfile = "mbqcoutfile.qasm" json_filepath = "jsonout.json" @testset "mbqccompile simulation with Qiskit" begin for inp in test_circuits qc = parse_file(inp) output = mbqccompile(qc; pcorrections=true, filepath=json_filepath) testjson = JSON.parsefile(json_filepath) # convert pcorrs keys from String to Int testjson["pcorrs"] = Dict(parse(Int, k) => v for (k,v) in testjson["pcorrs"]) # check that saved JSON file is the same as output @test testjson == output qasm_instruction(outfile, output) dq = JSON.parsefile(splitext(outfile)[1]*"_dqubits.json") # Keeps data_qubits def consistent with gcompile output dq = Dict( Symbol(k) => v for (k,v) in dq) meas_id = [s == shots for s in QiskitSim.simulate(inp, shots, compiled_qasm=outfile, data_qubits=dq)] @test all(meas_id) end end # clean if isfile(json_filepath) rm(json_filepath) end if isfile(splitext(outfile)[1]*"_dqubits.json") rm(splitext(outfile)[1]*"_dqubits.json") end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
431
using Jabalizer using Jabalizer.Gates using Test # include("end_to_end.jl") include("QiskitSim.jl") include("qasm_simulation.jl") # include("mbqccompile.jl") # include("circuit_sim.jl") include("graph_state.jl") include("to_graph_test.jl") include("stabilizer_gates.jl") include("stabilizer_measurements.jl") include("stabilizer_state.jl") include("stabilizer.jl") include("conversions.jl") include("util.jl") include("qasm.jl")
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1807
@testset "Stabilizer initialization" begin @testset "Empty stabilizer" begin stabilizer = Stabilizer() @test stabilizer.qubits == 0 @test stabilizer.X == [] @test stabilizer.Z == [] @test stabilizer.phase == 0 end for i in 1:5 @testset "Empty stabilizer with n = $i" begin stabilizer = Stabilizer(i) @test stabilizer.qubits == i @test stabilizer.X == zeros(i) @test stabilizer.Z == zeros(i) @test stabilizer.phase == 0 end end @testset "Stabilizer from tableau" begin tableau = [0 1 0] stabilizer = Stabilizer(tableau) @test stabilizer.qubits == 1 @test stabilizer.X == [0] @test stabilizer.Z == [1] @test stabilizer.phase == 0 tableau = [0 1 1 0 2; 1 0 0 1 2] stabilizer = Stabilizer(tableau) @test stabilizer.qubits == 2 @test stabilizer.X == [0, 1] @test stabilizer.Z == [1, 0] @test stabilizer.phase == 2 end end @testset "Stabilizer to Tableau conversion" begin # TODO: Add the following tests: # 1. Check if the conversion works (both ways?) # TODO: what are some good test cases? end @testset "Stabilizer operations" begin # TODO: This is failing # tableau = [0 0 1 0 0] # stabilizer = Stabilizer(tableau) # adjoint_stabilizer = adjoint(stabilizer) # @test adjoint_stabilizer.qubits == stabilizer.qubits # @test adjoint_stabilizer.X == stabilizer.X # @test adjoint_stabilizer.Z == stabilizer.Z # @test adjoint_stabilizer.phase == 0 # TODO: Add the following tests: # 1. Check if adjoint operation works well # 2. Check if multiplication works well # TODO: come up with some test cases. end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
8794
""" Generates one-qubit states used for testing """ function generate_one_qubit_state(state_chr) state = zero_state(1) (state_chr == '1' || state_chr == '-') && X(1)(state) (state_chr == '+' || state_chr == '-') && H(1)(state) return state end """ Returns the state H_2^d H_1^c X_2^b X_1^a | 0 0 >, where arr = [a b c d]. for arr in {0,1}^4 this generates all the computational and conjugate basis state combinations (e.g. |0 +> for [0 0 0 1] ) """ function generate_two_qubit_state(arr) a, b, c, d = arr state = zero_state(2) Bool(a) && X(1)(state) Bool(b) && X(2)(state) Bool(c) && H(1)(state) Bool(d) && H(2)(state) return state end # Test cases for basic one qubit gates (P,X,Y,Z,H) const one_qubit_test_cases = (('0', P, [0 1 0]), ('0', X, [0 1 2]), ('0', Y, [0 1 2]), ('0', Z, [0 1 0]), ('0', H, [1 0 0]), ('1', P, [0 1 2]), ('1', X, [0 1 0]), ('1', Y, [0 1 0]), ('1', Z, [0 1 2]), ('1', H, [1 0 2]), ('+', P, [1 1 0]), ('+', X, [1 0 0]), ('+', Y, [1 0 2]), ('+', Z, [1 0 2]), ('+', H, [0 1 0]), ('-', P, [1 1 2]), ('-', X, [1 0 2]), ('-', Y, [1 0 0]), ('-', Z, [1 0 0]), ('-', H, [0 1 2])) @testset "One qubit gates" begin for (state_chr, op, target_tableau) in one_qubit_test_cases @testset "Gate $op on state $state_chr" begin state = generate_one_qubit_state(state_chr) op(1)(state) @test target_tableau == to_tableau(state) end end end # Test cases for basic two qubit gates (CNOT, CZ, SWAP) # Tableau dictionary contains result of applying CNOT to # H_2^d H_1^c X_2^b X_1^a | 0 0 > with key [a b c d] const cnot_output = Dict((0,0,0,0) => [0 0 1 0 0; 0 0 1 1 0], # |0 0> => |0 0> (0,0,0,1) => [0 0 1 0 0; 0 1 0 0 0], # |0 +> => |0 +> (0,0,1,0) => [1 1 0 0 0; 0 0 1 1 0], # |+ 0> => |00> + |11> (0,0,1,1) => [1 1 0 0 0; 0 1 0 0 0], # |+ +> => |++> (0,1,0,0) => [0 0 1 0 0; 0 0 1 1 2], # |0 1> => |0 1> (0,1,0,1) => [0 0 1 0 0; 0 1 0 0 2], # |0 -> => |0 1> (0,1,1,0) => [1 1 0 0 0; 0 0 1 1 2], # |0 -> => |0 -> (0,1,1,1) => [1 1 0 0 0; 0 1 0 0 2], # |+ -> => |- -> (1,0,0,0) => [0 0 1 0 2; 0 0 1 1 0], # |1 0> => |1 1> (1,0,0,1) => [0 0 1 0 2; 0 1 0 0 0], # |1 +> => |1 +> (1,0,1,0) => [1 1 0 0 2; 0 0 1 1 0], # |1 +> => |1 +> (1,0,1,1) => [1 1 0 0 2; 0 1 0 0 0], # |- +> => |- +> (1,1,0,0) => [0 0 1 0 2; 0 0 1 1 2], # |1 1> => |1 0> (1,1,0,1) => [0 0 1 0 2; 0 1 0 0 2], # |1 -> => -|1 -> (1,1,1,0) => [1 1 0 0 2; 0 0 1 1 2], # |- 1> => |0 1> - |10> (1,1,1,1) => [1 1 0 0 2; 0 1 0 0 2]) # |- -> => |+ -> const cz_output = Dict((0,0,0,0) => [0 0 1 0 0; 0 0 0 1 0], # |0 0> => |0 0> (0,0,0,1) => [0 0 1 0 0; 0 1 1 0 0], # |0 +> => |0 +> (0,0,1,0) => [1 0 0 1 0; 0 0 0 1 0], # |+ 0> => |00> + |11> (0,0,1,1) => [1 0 0 1 0; 0 1 1 0 0], # |+ +> => |++> (0,1,0,0) => [0 0 1 0 0; 0 0 0 1 2], # |0 1> => |0 1> (0,1,0,1) => [0 0 1 0 0; 0 1 1 0 2], # |0 -> => |0 1> (0,1,1,0) => [1 0 0 1 0; 0 0 0 1 2], # |+ 1> => |0 1> + |10> (0,1,1,1) => [1 0 0 1 0; 0 1 1 0 2], # |+ -> => |- -> (1,0,0,0) => [0 0 1 0 2; 0 0 0 1 0], # |1 0> => |1 1> (1,0,0,1) => [0 0 1 0 2; 0 1 1 0 0], # |1 +> => |1 +> (1,0,1,0) => [1 0 0 1 2; 0 0 0 1 0], # |- 0> => |00> - |11> (1,0,1,1) => [1 0 0 1 2; 0 1 1 0 0], # |- +> => |- +> (1,1,0,0) => [0 0 1 0 2; 0 0 0 1 2], # |1 1> => |1 0> (1,1,0,1) => [0 0 1 0 2; 0 1 1 0 2], # |1 -> => -|1 -> (1,1,1,0) => [1 0 0 1 2; 0 0 0 1 2], # |- 1> => |0 1> - |10> (1,1,1,1) => [1 0 0 1 2; 0 1 1 0 2]) # |- -> => |+ -> const swap_output = Dict((0,0,0,0) => [0 0 0 1 0; 0 0 1 0 0], (0,0,0,1) => [0 0 0 1 0; 1 0 0 0 0], (0,0,1,0) => [0 1 0 0 0; 0 0 1 0 0], (0,0,1,1) => [0 1 0 0 0; 1 0 0 0 0], (0,1,0,0) => [0 0 0 1 0; 0 0 1 0 2], (0,1,0,1) => [0 0 0 1 0; 1 0 0 0 2], (0,1,1,0) => [0 1 0 0 0; 0 0 1 0 2], (0,1,1,1) => [0 1 0 0 0; 1 0 0 0 2], (1,0,0,0) => [0 0 0 1 2; 0 0 1 0 0], (1,0,0,1) => [0 0 0 1 2; 1 0 0 0 0], (1,0,1,0) => [0 1 0 0 2; 0 0 1 0 0], (1,0,1,1) => [0 1 0 0 2; 1 0 0 0 0], (1,1,0,0) => [0 0 0 1 2; 0 0 1 0 2], (1,1,0,1) => [0 0 0 1 2; 1 0 0 0 2], (1,1,1,0) => [0 1 0 0 2; 0 0 1 0 2], (1,1,1,1) => [0 1 0 0 2; 1 0 0 0 2]) @testset "Two qubit gates" begin # Loop generates all arrays (a, b, c, d) with a,b,c,d in {0,1} for bitarr in Base.Iterators.product(0:1, 0:1, 0:1, 0:1) @testset "CNOT for array: $bitarr " begin state = generate_two_qubit_state(bitarr) CNOT(1, 2)(state) @test cnot_output[bitarr] == to_tableau(state) end @testset "CZ for array: $bitarr " begin state = generate_two_qubit_state(bitarr) CZ(1, 2)(state) @test cz_output[bitarr] == to_tableau(state) end @testset "SWAP for array: $bitarr " begin state = generate_two_qubit_state(bitarr) SWAP(1, 2)(state) @test swap_output[bitarr] == to_tableau(state) end end end @testset "Gate Aliases" begin @test gate_map["H_XZ"] == H @test gate_map["P"] == S @test gate_map["PHASE"] == S @test gate_map["SQRT_Z"] == S @test gate_map["SQRT_Z_DAG"] == S_DAG @test gate_map["S^-1"] == S_DAG @test gate_map["S_Dagger"] == S_DAG @test gate_map["CX"] == CNOT @test gate_map["ZCX"] == CNOT @test gate_map["ZCY"] == CY @test gate_map["ZCZ"] == CZ end # Test cases for more complex one qubit gates supported by STIM # which can be decomposed into a series of S and H gates const gate1_decomp = [(C_XYZ, "SSSH"), (C_ZYX, "HS"), (H_XY, "HSSHS"), (H_YZ, "HSHSS"), (S_DAG, "SSS"), (SQRT_X, "HSH"), (SQRT_X_DAG, "SHS"), (SQRT_Y, "SSH"), (SQRT_Y_DAG, "HSS")] @testset "Single qubit operations" begin for (gate, oplist) in gate1_decomp, state_chr in ('0', '1', '+', '-') @testset "Gate $gate on state $state_chr" begin state1 = generate_one_qubit_state(state_chr) state2 = generate_one_qubit_state(state_chr) for op in oplist (op == 'H' ? H : S)(1)(state1) end gate(1)(state2) @test state1 == state2 end end end # Test cases for more complex two qubit gates supported by STIM # which can be decomposed into a series of S, H, and CNOT gates const gate2_decomp = [(CY, (S(2), S(2), S(2), CNOT(1,2), S(2))), (CZ, (H(2), CNOT(1,2), H(2))), (XCX, (H(1), CNOT(1,2), H(1))), (XCY, (H(1), S(2), S(2), S(2), CNOT(1,2), H(1), S(2))), (XCZ, (CNOT(2,1),)), (YCX, (S(1), S(1), S(1), H(2), CNOT(2,1), S(1), H(2))), (YCY, (S(1), S(1), S(1), S(2), S(2), S(2), H(1), CNOT(1,2), H(1), S(1), S(2))), (YCZ, (S(1), S(1), S(1), CNOT(2, 1), S(1))), # stim ops that don't have function calls #(CXSWAP, (CNOT(2,1), CNOT(1,2))), #(SWAPCX, (CNOT(1,2), CNOT(2,1))), (ISWAP, (H(1), S(1), S(1), S(1), CNOT(1,2), S(1), CNOT(2,1), H(2), S(2), S(1))), (ISWAP_DAG, (S(1), S(1), S(1), S(2), S(2), S(2), H(2), CNOT(2,1), S(1), S(1), S(1), CNOT(1,2), S(1), H(1))), #= # stim ops that don't have function calls (SQRT_XX, (H(1), CNOT(1,2), H(2), S(1), S(2), H(1), H(2))), (SQRT_XX_DAG, (H(1), CNOT(1,2), H(2), S(1), S(1), S(1), S(2), S(2), S(2), H(1), H(2))), (SQRT_YY, (S(1), S(1), S(1), S(2), S(2), S(2), H(1), CNOT(1,2), H(2), S(1), S(2), H(1), H(2), S(1), S(2))), (SQRT_YY_DAG, (S(1), S(1), S(1), S(2), H(1), CNOT(1,2), H(2), S(1), S(2), H(1), H(2), S(1), S(2), S(2), S(2))), (SQRT_ZZ, (H(2), CNOT(1,2), H(2), S(1), S(2))), (SQRT_ZZ_DAG, (H(2), CNOT(1,2), H(2), S(1), S(1), S(1), S(2), S(2), S(2))) =# ] @testset "Two qubit operations" begin # Loop generates all arrays (a, b, c, d) with a,b,c,d in {0,1} for (gate, oplist) in gate2_decomp @testset "Gate $gate:" begin for bitarr in Base.Iterators.product(0:1, 0:1, 0:1, 0:1) state1 = generate_two_qubit_state(bitarr) state2 = generate_two_qubit_state(bitarr) for op in oplist op(state1) end gate(1, 2)(state2) @test state1 == state2 end end end end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
938
const measurement_test_cases = (("0", measure_z, 0, [0 1 0]), ("1", measure_z, 1, [0 1 2]), ("+", measure_x, 0, [1 0 0]), ("-", measure_x, 1, [1 0 2]), ("+y", measure_y, 0, [1 1 0]), ("-y", measure_y, 1, [1 1 2])) const init_operations = Dict("0" => (), "1" => (X,), "+" => (H,), "-" => (X, H), "+y" => (H, P), "-y" => (X, H, P)) @testset "Measurements" begin for (init_state_str, measurement_op, target_output, target_tableau) in measurement_test_cases @testset "Measurement $measurement_op on state $init_state_str" begin state = zero_state(1) for init_op in init_operations[init_state_str] init_op(1)(state) end measurement = measurement_op(state, 1) @test measurement == target_output @test to_tableau(state) == target_tableau end end end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1279
@testset "StabilizerState initialization" begin state = StabilizerState() @test state.qubits == 0 @test isempty(state.stabilizers) for i in 1:4 state = StabilizerState(i) @test state.qubits == i @test isempty(state.stabilizers) end end @testset "zero_state initialization" begin for i in 1:4 target_tableau = zeros(Int8, (i, 2 * i + 1)) for j in 1:i target_tableau[j, i+j] = 1 end state = zero_state(i) @test state.qubits == i @test to_tableau(state) == target_tableau end end @testset "Tableau <> State conversion" begin # TODO: Add the following tests: # 1. Checks whether the conversions both ways works well # TODO: come up with good test cases. end @testset "State to Tableau conversion" begin # TODO: Add the following tests: # 1. Checks whether the conversions works well # TODO: come up with good test cases. end @testset "StabilizerState to string conversion" begin # TODO: Add the following tests: # 1. Checks whether the conversions works well end @testset "Graph to StabilizerState conversion" begin # TODO: Add the following tests: # 1. Check if works # TODO: come up with some good test cases. end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
502
@testset "Graph conversion tests" begin state = zero_state(5) for i in 1:state.qubits H(i)(state) end CZ(1,2)(state) H(1)(state) CNOT(1,2)(state) CZ(2,3)(state) CNOT(3,4)(state) P(4)(state) Z(4)(state) CZ(4,5)(state) H(5)(state) gs, adj, mseq = Jabalizer.fast_to_graph(state) A = [0 0 0 0 0; 0 0 0 0 0; 0 0 0 0 0; 0 0 0 0 1; 0 0 0 1 0] M = [("H", 2), ("H", 5), ("Pdag", 4), ("Z", 4)] @test adj == A @test mseq == M end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
code
1480
@testset "stim tableau to tableau" begin # TODO: Add the following tests: # 1. Check if the conversion works well. # TODO: What should the test cases be? end @testset "Update tableau" begin # TODO: Add the following tests: # 1. Check if update works correctly # TODO: What should the test cases be? end @testset "Generate random stabilizer state" begin # TODO: Add more validity checks len = 5 ss = rand(StabilizerState, len) @test ss.qubits == len @test length(ss.stabilizers) == len st = ss.stabilizers for i = 1:len stab = st[i] @test stab.qubits == len @test length(stab.X) == len @test length(stab.Z) == len @test 0 <= stab.phase <= 3 end end @testset "Stabilizer State to Graph" begin # TODO: Add the following tests: # 1. Check if the conversion works back and forth # TODO: What should the test cases be? end @testset "Test Tab operations" begin # TODO: Add the following tests: # 1. Check if H works properly # 2. Check if RowAdd works properly # TODO: What should the test cases be? end @testset "Test Pauli - Tableau conversion" begin # TODO: Add the following tests: # 1. Check if the conversion works back and forth # TODO: What should the test cases be? end @testset "Test Pauli operations" begin # TODO: Add the following tests: # 1. Check if PauliProd works well # TODO: What should the test cases be? end
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
docs
7759
# Jabalizer [![Build Status](https://github.com/QSI-BAQS/Jabalizer.jl/workflows/CI/badge.svg)](https://github.com/madhavkrishnan/Jabalizer.jl/actions) [![Build Status](https://ci.appveyor.com/api/projects/status/github/QSI-BAQS/Jabalizer.jl?svg=true)](https://ci.appveyor.com/project/madhavkrishnan/Jabalizer-jl) [![Coverage](https://codecov.io/gh/QSI-BAQS/Jabalizer.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/QSI-BAQS/Jabalizer.jl) [![Coverage](https://coveralls.io/repos/github/QSI-BAQS/Jabalizer.jl/badge.svg?branch=master)](https://coveralls.io/github/QSI-BAQS/Jabalizer.jl?branch=main) # Developers + Madhav Krishnan Vijayan ([[email protected]](mailto:[email protected])) + Simon Devitt + Peter Rohde ([[email protected]](mailto:[email protected]), [www.peterrohde.org](https://www.peterrohde.org)) + Alexandru Paler + Casey Myers + Jason Gavriel + Michał Stęchły([[email protected]](mailto:[email protected])) + Scott Jones ([[email protected]](mailto:[email protected])) + Athena Caesura # About Jabalizer is a quantum graph state compiler for quantum circuits written in Julia. It has the functionality to manipulate stabilizer states and graph states and provides generic functions able to operate within both pictures and dynamically convert between them, allowing arbitrary Clifford circuits to be simulated and converted into graph state language, and vice-versa. Jabalizer also provides functionality to convert Clifford + T gate circuits to an aglorithm specific graph state using the ``icm`` module. The computation can now be implemented by passing this graph state and a measurement procedure to a quantum backend. You can learn more about the Julia language at [www.julialang.org](https://www.julialang.org). # Technical Manuscript A techical paper on Jabalizer can be found here [https://arxiv.org/abs/2209.07345](https://arxiv.org/abs/2209.07345) # Installation Jabalizer can be installed like any Julia package. type `]` in the Julia REPL to enter the pkg mode and enter ``` pkg> add Jabalizer ``` The module can be tested using ``` pkg> test Jabalizer ``` # Stabilizer circuits While simulating arbitrary quantum circuits is classically inefficient with exponential resource overhead, via the [Gottesman-Knill theorem](https://arxiv.org/abs/quant-ph/9807006) it is known that circuits comprising only Clifford operations (ones that commute with the Pauli group) can be efficiently simulated using the stabilizer formalism. In the stabilizer formalism an _n_-qubit state is defined as the simultaneous positive eigenstate of _n_ 'stabilizers', each of which is an _n_-fold tensor product of Pauli operators (_I_,_X_,_Y_,_Z_) and a sign (+/-). That is, for each stabilizer $S_i$ (for $i\in 1\dots n$) the state, $$ |\psi\rangle $$ satisfies $$ S_i|\psi\rangle = |\psi\rangle. $$ As an example, the Bell state $$ \frac{1}{\sqrt{2}}(|00\rangle + |11\rangle) $$ can equivalently be represented by the two stabilizers $$ S_1 = XX, $$ $$ S_2 = ZZ. $$ The orthogonal Bell state $$ \frac{1}{\sqrt{2}}(|01\rangle + |10\rangle) $$ differs only slightly with stabilizers, $$ S_1 = XX, $$ $$ S_2 = -ZZ. $$ Similarly, the three-qubit GHZ state $$ \frac{1}{\sqrt{2}}(|000\rangle + |111\rangle) $$ can be represented by the three stabilizers, $$ S_1 = XXX, $$ $$ S_2 = ZZI, $$ $$ S_3 = IZZ. $$ Evolving stabilizer states can be performed in the Heisenberg picture by conjugating the stabilizers with the unitary operations acting upon the state since for the evolution, $$ |\psi'\rangle = U |\psi\rangle, $$ we can equivalently write, $$ |\psi'\rangle = U S_i |\psi\rangle = U S_i U^\dagger U |\psi\rangle = U S_i U^\dagger |\psi'\rangle = S_i' |\psi'\rangle, $$ where, $$ S_i' = U S_i U^\dagger, $$ stabilizes the evolved state $$|\psi'\rangle = U |\psi\rangle. $$ Thus the rule for evolving states in the stabilizer formalism is to simply update each of the _n_ stabilizers via $$ S_i' = U S_i U^\dagger. $$ The efficiency of classically simulating stabilizer circuits was subsequently improved upon by [Aaronson & Gottesman](https://arxiv.org/abs/quant-ph/0406196) using the so-called CHP approach which tracks both stabilizers and anti-stabilizers, improving the performance of measurements within this model. Jabalizer employs the highly-optimised [STIM simulator](https://github.com/quantumlib/Stim) as its CHP backend. # Graph states A graph state is defined as a set of _n_ qubits represented as vertices in a graph, where qubits are initialised into the $$ |+\rangle = \frac{1}{\sqrt{2}}(|0\rangle + |1\rangle) $$ state and edges between them represent the application of controlled-phase (CZ) gates. This leads to the general stabilizer representation for graph states, $$ S_i = X_i \prod_{j\in n_i} Z_j, $$ for each qubit _i_, where $$ n_i $$ denotes the graph neighbourhood of vertex _i_. For example, the set of stabilizers associated with the graph, <p align="center"><img src="https://user-images.githubusercontent.com/4382522/123741542-96930b80-d8ed-11eb-9b9a-1caf37f5fcf0.jpeg" width="50%"></p> <!--- ![image](https://user-images.githubusercontent.com/4382522/123741542-96930b80-d8ed-11eb-9b9a-1caf37f5fcf0.jpeg) ---> is given by, $$ S_1 = XZII, $$ $$ S_2 = ZXZZ, $$ $$ S_3 = IZXZ, $$ $$ S_4 = IZZX. $$ Viewing this as a matrix note that the _X_ operators appear along the main diagonal, which the locations of the _Z_ operators define the adjacency matrix for the graph. All stabilizer states can be converted to graph states via local operations, achieved via a tailored Gaussian elimination procedure on the stabilizer tableau. Jabalizer allows an arbitrary stabilizer state to be converted to a locally equivalent graph state and provide the associated adjacency matrix for the respective graph. # Example code Here's some simple Jabalizer code that executes the gate sequence used to generate a GHZ state, display the associated set of stabilizers, and then convert it to its locally equivalent graph state, which is then manipulated via several Pauli measurements and finally converted back to stabilizer form. ```julia using Jabalizer # Prepare a 6-qubit GHZ state n = 6 state = zero_state(n) Jabalizer.H(1)(state) Jabalizer.CNOT(1,2)(state) Jabalizer.CNOT(1,3)(state) Jabalizer.CNOT(1,4)(state) Jabalizer.CNOT(1,5)(state) Jabalizer.CNOT(1,6)(state) # Display the stabilizer tableau Jabalizer.update_tableau(state) tab = Jabalizer.to_tableau(state) display(tab) # Convert to graph state graphState = GraphState(state) # Display graph adjacency matrix display(graphState.A) # Plot graph Jabalizer.gplot(Jabalizer.Graph(graphState.A)) # Convert back to stabilizer state stabState = StabilizerState(graphState) ``` Produces the output: ```julia 6×13 Matrix{Int64}: 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 6×6 Matrix{Int64}: 0 1 1 1 1 1 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 ``` <p align="center"><img src="https://user-images.githubusercontent.com/4382522/123879677-b45f7f80-d984-11eb-8590-67a3714eec71.png" width="50%"></p> # Acknowledgements We especially thank [Craig Gidney](https://algassert.com) and co-developers for developing the [STIM package](https://github.com/quantumlib/Stim) which provides the CHP backend upon which Jabalizer is based, and especially for implementing some modifications that provided the functionality necessary for this integration. The technical whitepaper for STIM is available [here](https://arxiv.org/abs/2103.02202).
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
docs
653
--- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: [e.g. OSX, Windows] - Python version [e.g. 3.7.11] **Additional context** Add any other context about the problem here.
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
docs
595
--- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here.
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
0.5.2
1a94764b239bd1867078fcf9eed76af9c07b7dc0
docs
490
# Jabalizer Documentation ```@meta CurrentModule = Jabalizer ``` ## Contents ```@contents ``` ## Types ```@docs Stabilizer StabilizerState GraphState ``` ## Functions ### State preparation ```@docs AddQubit AddQubits AddBell AddGHZ AddGraph ``` ### Gates ```@docs Id X Y Z H P SWAP CNOT CZ FusionI FusionII ``` ### Channels ```@docs ChannelX ChannelY ChannelZ ChannelPauli ChannelDepol ChannelLoss ``` ### Utilities ```@docs RowAdd print string * ``` ## Index ```@index ```
Jabalizer
https://github.com/QSI-BAQS/Jabalizer.jl.git
[ "MIT" ]
1.1.0
82fd3c3088a45c7d9f23318992417dc39f539ac6
code
13197
module Polyomino using DataStructures using MatrixNetworks using JuMP using HiGHS using ProgressMeter struct Poly tiles::Set{Pair{Int64, Int64}} vertices::Int64 edges::Int64 end include("algorithms.jl") include("min-line-cover.jl") Base.show(io::IO, x::Poly) = begin minX, maxX, minY, maxY = dimensionPoly(x) for i in minX:maxX for j in minY:maxY (Pair(i, j) in x.tiles) ? print(io, "*") : print(io, " ") end println() end end @inline function dimensionPoly(p::Poly) minX = typemax(Int64); minY = typemax(Int64); maxX = typemin(Int64); maxY = typemin(Int64); for i in p.tiles maxX = (i.first > maxX) ? i.first : maxX maxY = (i.second > maxY) ? i.second : maxY minX = (i.first < minX) ? i.first : minX minY = (i.second < minY) ? i.second : minY end return minX, maxX, minY, maxY end @inline function holes(p::Poly) return p.edges - p.vertices - length(p.tiles) + 1 # number of holes with euler characteristic end function demo() println("<Polyomino Generation (n = 30)>") println("Shuffling (p = 0):") show(Poly(30, 0.0)) println("Shuffling (p = 0.8):") show(Poly(30, 0.8)) println("Eden Model:") show(Poly(30)) println("<Polyomino Analysis (n = 100)>") poly = Poly(100) println("Maximal Rook Setup:") printSet(poly, maxRooks(poly)[2]) println("Maximal Queen Setup:") printSet(poly, maxQueens(poly, output=false)[2]) println("Minimal Rook Setup:") printSet(poly, minRooks(poly, output=false)[2]) println("Minimal Queen Setup:") printSet(poly, minQueens(poly; output=false)[2]) println("Minimal Line Cover:") printMinLineCover(poly) end """ Poly(size, p) Polyomino generation wih shuffling model Generates uniformly distributed polyominoes after size^3 successful shuffles. # Arguments * `size`: Number of tiles of polyomino * `p`: Perculation probability between 0 and 1, higher p results in more compact polyominoes """ function Poly(size::Int64, p::Float64) tiles = Set{Pair{Int64, Int64}}() neighbours = Set{Pair{Int64, Int64}}([0 => 0, 0 => size + 1]) for i in 1:size push!(tiles, 0 => i) push!(neighbours, 1 => i) push!(neighbours, -1 => i) end euler = [2 * size + 2, (2 * size + 2) + (size - 1)] # vertices, edges @showprogress 1 "Shuffling..." for i in 1 : size^3 while (!shuffle(tiles, neighbours, p, euler)) end end Poly(tiles, euler[1], euler[2]) end @inline function shuffle(tiles::Set{Pair{Int64, Int64}}, neighbours::Set{Pair{Int64, Int64}}, p::Float64, euler::Vector{Int64}) diff = 0 # circumfrence difference vertexDiff = 0 edgeDiff = 0 ranTile = rand(tiles) # move random tile to new position ranNeigh = rand(neighbours) delete!(tiles, ranTile) # vertex update from tile remval if !(Pair(ranTile.first - 1, ranTile.second) in tiles) && !(Pair(ranTile.first - 1, ranTile.second - 1) in tiles) && !(Pair(ranTile.first, ranTile.second - 1) in tiles) # left upper corner vertexDiff -= 1 end if !(Pair(ranTile.first, ranTile.second - 1) in tiles) && !(Pair(ranTile.first + 1, ranTile.second - 1) in tiles) && !(Pair(ranTile.first + 1, ranTile.second) in tiles) # left lower corner vertexDiff -= 1 end if !(Pair(ranTile.first + 1, ranTile.second) in tiles) && !(Pair(ranTile.first + 1, ranTile.second + 1) in tiles) && !(Pair(ranTile.first, ranTile.second + 1) in tiles) # right lower corner vertexDiff -= 1 end if !(Pair(ranTile.first, ranTile.second + 1) in tiles) && !(Pair(ranTile.first - 1, ranTile.second + 1) in tiles) && !(Pair(ranTile.first - 1, ranTile.second) in tiles) # right upper corner vertexDiff -= 1 end # vertex change from tile addition if !(Pair(ranNeigh.first - 1, ranNeigh.second) in tiles) && !(Pair(ranNeigh.first - 1, ranNeigh.second - 1) in tiles) && !(Pair(ranNeigh.first, ranNeigh.second - 1) in tiles) # left upper corner vertexDiff += 1 end if !(Pair(ranNeigh.first, ranNeigh.second - 1) in tiles) && !(Pair(ranNeigh.first + 1, ranNeigh.second - 1) in tiles) && !(Pair(ranNeigh.first + 1, ranNeigh.second) in tiles) # left lower corner vertexDiff += 1 end if !(Pair(ranNeigh.first + 1, ranNeigh.second) in tiles) && !(Pair(ranNeigh.first + 1, ranNeigh.second + 1) in tiles) && !(Pair(ranNeigh.first, ranNeigh.second + 1) in tiles) # right lower corner vertexDiff += 1 end if !(Pair(ranNeigh.first, ranNeigh.second + 1) in tiles) && !(Pair(ranNeigh.first - 1, ranNeigh.second + 1) in tiles) && !(Pair(ranNeigh.first - 1, ranNeigh.second) in tiles) # right upper corner vertexDiff += 1 end #edge change from tile removal edgeDiff -= !(Pair(ranTile.first - 1, ranTile.second) in tiles) + !(Pair(ranTile.first, ranTile.second - 1) in tiles) + !(Pair(ranTile.first + 1, ranTile.second) in tiles) + !(Pair(ranTile.first, ranTile.second + 1) in tiles) #edge change from tile addition edgeDiff += !(Pair(ranNeigh.first - 1, ranNeigh.second) in tiles) + !(Pair(ranNeigh.first, ranNeigh.second - 1) in tiles) + !(Pair(ranNeigh.first + 1, ranNeigh.second) in tiles) + !(Pair(ranNeigh.first, ranNeigh.second + 1) in tiles) push!(tiles, ranNeigh) toCheck = Pair{Int64, Int64}[] # collect neighbours to check connectivity if ((Pair(ranTile.first - 1, ranTile.second) in tiles)) push!(toCheck, Pair(ranTile.first - 1, ranTile.second)) diff += 1 end if ((Pair(ranTile.first, ranTile.second - 1) in tiles)) push!(toCheck, Pair(ranTile.first, ranTile.second - 1)) diff += 1 end if ((Pair(ranTile.first + 1, ranTile.second) in tiles)) push!(toCheck, Pair(ranTile.first + 1, ranTile.second)) diff += 1 end if ((Pair(ranTile.first, ranTile.second + 1) in tiles)) push!(toCheck, Pair(ranTile.first, ranTile.second + 1)) diff += 1 end connected = true # check connectivity for i = 1 : length(toCheck) - 1 if !(bfs(tiles, toCheck[i], toCheck[i + 1])) connected = false break end end if (connected) if ((Pair(ranNeigh.first - 1, ranNeigh.second) in tiles)) # calculate diffrence in polyomino neighbour count diff -= 1 end if ((Pair(ranNeigh.first, ranNeigh.second - 1) in tiles)) diff -= 1 end if ((Pair(ranNeigh.first + 1, ranNeigh.second) in tiles)) diff -= 1 end if ((Pair(ranNeigh.first, ranNeigh.second + 1) in tiles)) diff -= 1 end accepted = true # accepted shuffle with probability (1 - p)^diff if !iszero(p) accepted = rand() < (1 - p)^diff; end if accepted push!(neighbours, ranTile) if (!(Pair(ranTile.first - 1, ranTile.second - 1) in tiles) && !(Pair(ranTile.first - 2, ranTile.second) in tiles) && !(Pair(ranTile.first - 1, ranTile.second + 1) in tiles)) delete!(neighbours, Pair(ranTile.first - 1, ranTile.second)) # neighbour above does not stay neighbour end if (!(Pair(ranTile.first + 1, ranTile.second - 1) in tiles) && !(Pair(ranTile.first, ranTile.second - 2) in tiles) && !(Pair(ranTile.first - 1, ranTile.second - 1) in tiles)) delete!(neighbours, Pair(ranTile.first, ranTile.second - 1)) # neighbour to the left does not stay neighbour end if (!(Pair(ranTile.first + 1, ranTile.second + 1) in tiles) && !(Pair(ranTile.first + 2, ranTile.second) in tiles) && !(Pair(ranTile.first + 1, ranTile.second - 1) in tiles)) delete!(neighbours, Pair(ranTile.first + 1, ranTile.second)) # neighbour below does not stay neighbour end if (!(Pair(ranTile.first - 1, ranTile.second + 1) in tiles) && !(Pair(ranTile.first, ranTile.second + 2) in tiles) && !(Pair(ranTile.first + 1, ranTile.second + 1) in tiles)) delete!(neighbours, Pair(ranTile.first, ranTile.second + 1)) # neighbour to the right does not stay neighbour end delete!(neighbours, ranNeigh) # update neighbours if (!(Pair(ranNeigh.first - 1, ranNeigh.second) in tiles)) push!(neighbours, Pair(ranNeigh.first - 1, ranNeigh.second)) end if (!(Pair(ranNeigh.first, ranNeigh.second - 1) in tiles)) push!(neighbours, Pair(ranNeigh.first, ranNeigh.second - 1)) end if (!(Pair(ranNeigh.first + 1, ranNeigh.second) in tiles)) push!(neighbours, Pair(ranNeigh.first + 1, ranNeigh.second)) end if (!(Pair(ranNeigh.first, ranNeigh.second + 1) in tiles)) push!(neighbours, Pair(ranNeigh.first, ranNeigh.second + 1)) end euler[1] += vertexDiff euler[2] += edgeDiff return true end end delete!(tiles, ranNeigh) # undo shuffle push!(tiles, ranTile) return false end @inline function bfs(tiles::Set{Pair{Int64, Int64}}, start::Pair{Int64, Int64}, goal::Pair{Int64, Int64}) if (abs(start.first - goal.first) == 1 && abs(start.second - goal.second) == 1) # start and goal directly connect via corner if Pair(start.first, goal.second) in tiles return true elseif Pair(goal.first, start.second) in tiles return true end end q = Queue{Pair{Int64, Int64}}() done = Set{Pair{Int64, Int64}}() enqueue!(q, start); push!(done, start) while (!isempty(q)) tile = dequeue!(q) if (tile == goal) return true end if ((Pair(tile.first - 1, tile.second) in tiles) && !(Pair(tile.first - 1, tile.second) in done)) # above enqueue!(q, Pair(tile.first - 1, tile.second)) push!(done, Pair(tile.first - 1, tile.second)) end if ((Pair(tile.first, tile.second - 1) in tiles) && !(Pair(tile.first, tile.second - 1) in done)) # left enqueue!(q, Pair(tile.first, tile.second - 1)) push!(done, Pair(tile.first, tile.second - 1)) end if ((Pair(tile.first + 1, tile.second) in tiles) && !(Pair(tile.first + 1, tile.second) in done)) # below enqueue!(q, Pair(tile.first + 1, tile.second)) push!(done, Pair(tile.first + 1, tile.second)) end if ((Pair(tile.first, tile.second + 1) in tiles) && !(Pair(tile.first, tile.second + 1) in done)) # right enqueue!(q, Pair(tile.first, tile.second + 1)) push!(done, Pair(tile.first, tile.second + 1)) end end return false end """ Poly(size) Polyomino generation wih Eden model Start with one tile and iteratively add random neighbour tile. Linear runtime, but compact polyominoes with few holes. # Arguments * `size`: Number of tiles of polyomino """ function Poly(size::Int64) tiles = Set{Pair{Int64, Int64}}([0 => 0]) neighbours = Set{Pair{Int64, Int64}}([-1 => 0, 0 => -1, 1 => 0, 0 => 1]) vertices = 0 edges = 0 for i in 1 : size - 1 ranElem = rand(neighbours) # choose random element from set push!(tiles, ranElem) delete!(neighbours, ranElem) # edge update edges += !(Pair(ranElem.first - 1, ranElem.second) in tiles) + !(Pair(ranElem.first, ranElem.second - 1) in tiles) + !(Pair(ranElem.first + 1, ranElem.second) in tiles) + !(Pair(ranElem.first, ranElem.second + 1) in tiles) # vertex update if !(Pair(ranElem.first - 1, ranElem.second) in tiles) && !(Pair(ranElem.first - 1, ranElem.second - 1) in tiles) && !(Pair(ranElem.first, ranElem.second - 1) in tiles) # left upper corner vertices += 1 end if !(Pair(ranElem.first, ranElem.second - 1) in tiles) && !(Pair(ranElem.first + 1, ranElem.second - 1) in tiles) && !(Pair(ranElem.first + 1, ranElem.second) in tiles) # left lower corner vertices += 1 end if !(Pair(ranElem.first + 1, ranElem.second) in tiles) && !(Pair(ranElem.first + 1, ranElem.second + 1) in tiles) && !(Pair(ranElem.first, ranElem.second + 1) in tiles) # right lower corner vertices += 1 end if !(Pair(ranElem.first, ranElem.second + 1) in tiles) && !(Pair(ranElem.first - 1, ranElem.second + 1) in tiles) && !(Pair(ranElem.first - 1, ranElem.second) in tiles) # right upper corner vertices += 1 end !(Pair(ranElem.first - 1, ranElem.second) in tiles) && push!(neighbours, Pair(ranElem.first - 1, ranElem.second)) # update neighbours set !(Pair(ranElem.first, ranElem.second - 1) in tiles) && push!(neighbours, Pair(ranElem.first, ranElem.second - 1)) !(Pair(ranElem.first + 1, ranElem.second) in tiles) && push!(neighbours, Pair(ranElem.first + 1, ranElem.second)) !(Pair(ranElem.first, ranElem.second + 1) in tiles) && push!(neighbours, Pair(ranElem.first, ranElem.second + 1)) end Poly(tiles, vertices, edges) end end # module
Polyomino
https://github.com/PhoenixSmaug/Polyomino.jl.git
[ "MIT" ]
1.1.0
82fd3c3088a45c7d9f23318992417dc39f539ac6
code
10489
function printSet(p::Poly, set::Vector{Pair{Int64, Int64}}) minX, maxX, minY, maxY = dimensionPoly(p) for i in minX : maxX for j in minY : maxY if (Pair(i, j) in p.tiles) (Pair(i, j) in set) ? print("+") : print("*") else print(" ") end end println() end end """ maxRooks(p) Solves the maximal non-attacking rook set problem Polynomial runtime as translation of maximal matching problem in corresponding biparite graph, details in https://link.springer.com/content/pdf/10.1007/s00373-020-02272-8.pdf Chapter 4 # Arguments * `p`: Polyomino to calculate the rook set on """ function maxRooks(p::Poly) minX, maxX, minY, maxY = dimensionPoly(p) start = Dict{Pair{Int64, Int64}, Int64}() # key = position of tile, value = start of edge in bipartite graph counter = 0 previous = false for i in minX - 1 : maxX + 1 for j in minY - 1 : maxY + 1 if (Pair(i, j) in p.tiles) if (!previous) counter += 1 end start[i => j] = counter previous = true else previous = false end end end finish = Dict{Pair{Int64, Int64}, Int64}() # key = position of tile, value = end of edge in bipartite graph counter = 0 previous = false for j in minY - 1 : maxY + 1 for i in minX - 1 : maxX + 1 if (Pair(i, j) in p.tiles) if (!previous) counter += 1 end finish[i => j] = counter previous = true else previous = false end end end edgeStart = Int64[]; edgeEnd = Int64[] biGraphOrder = Dict{Pair{Int64, Int64}, Pair{Int64, Int64}}() # key = edge in bipartite graph, value = position of tile for i in minX : maxX # convert to required form for j in minY : maxY if (Pair(i, j) in p.tiles) push!(edgeStart, start[i => j]) push!(edgeEnd, finish[i => j]) biGraphOrder[Pair(start[i => j], finish[i => j])] = i => j end end end weights = fill(1, length(edgeStart)) matching = bipartite_matching(weights, edgeStart, edgeEnd) # calculate matching matchingStart = edge_list(matching)[1] matchingEnd = edge_list(matching)[2] rooks = Pair{Int64, Int64}[] for i in 1 : length(matchingStart) push!(rooks, biGraphOrder[Pair(matchingStart[i], matchingEnd[i])]) end return matching.cardinality, rooks # number, set end """ maxQueens(p) Solves the maximal non-attacking queen set problem NP complete problem, solve as LIP with HiGHS optimizer # Arguments * `p`: Polyomino to calculate the queen set on * `output`: If logging of HiGHS is enabled """ function maxQueens(p::Poly; output=true) tileId = Dict{Pair{Int64, Int64}, Int64}() # enumerate tiles tileIdRev = Pair{Int64, Int64}[] t = 1 for i in p.tiles tileId[i] = t push!(tileIdRev, i) t += 1 end tileRow = Dict{Int64, Vector{Int64}}() # key: tile by id, value: ids of attackable tiles in this direction tileColumn = Dict{Int64, Vector{Int64}}() tileDiagDown = Dict{Int64, Vector{Int64}}() tileDiagUp = Dict{Int64, Vector{Int64}}() for (key, value) in tileId tileRow[value] = Vector{Int64}([value]) tileColumn[value] = Vector{Int64}([value]) tileDiagDown[value] = Vector{Int64}([value]) tileDiagUp[value] = Vector{Int64}([value]) t = 1 while (Pair(key.first - t, key.second) in p.tiles) # up push!(tileColumn[value], tileId[Pair(key.first - t, key.second)]) t += 1 end t = 1 while (Pair(key.first - t, key.second - t) in p.tiles) # up left push!(tileDiagUp[value], tileId[Pair(key.first - t, key.second - t)]) t += 1 end t = 1 while (Pair(key.first, key.second - t) in p.tiles) # left push!(tileRow[value], tileId[Pair(key.first, key.second - t)]) t += 1 end t = 1 while (Pair(key.first + t, key.second - t) in p.tiles) # down left push!(tileDiagDown[value], tileId[Pair(key.first + t, key.second - t)]) t += 1 end t = 1 while (Pair(key.first + t, key.second) in p.tiles) # down push!(tileColumn[value], tileId[Pair(key.first + t, key.second)]) t += 1 end t = 1 while (Pair(key.first + t, key.second + t) in p.tiles) # down right push!(tileDiagUp[value], tileId[Pair(key.first + t, key.second + t)]) t += 1 end t = 1 while (Pair(key.first, key.second + t) in p.tiles) # right push!(tileRow[value], tileId[Pair(key.first, key.second + t)]) t += 1 end t = 1 while (Pair(key.first - t, key.second + t) in p.tiles) # up right push!(tileDiagDown[value], tileId[Pair(key.first - t, key.second + t)]) t += 1 end end model = Model(HiGHS.Optimizer) # construct linear integer programm set_optimizer_attribute(model, "log_to_console", output) @variable(model, x[1 : length(p.tiles)], Bin) for (key, value) in tileId @constraint(model, sum(x[i] for i in tileRow[value]) <= 1) # one queen per row @constraint(model, sum(x[i] for i in tileColumn[value]) <= 1) # one queen per column @constraint(model, sum(x[i] for i in tileDiagDown[value]) <= 1) # one queen per diagonal @constraint(model, sum(x[i] for i in tileDiagUp[value]) <= 1) end @objective(model, Max, sum(x)) optimize!(model) return Int(sum(round.(value.(x)))), tileIdRev[round.(value.(x)) .== 1] # number, set end """ minRooks(p) Solves the minimal guarding rook set problem NP complete problem, solve as LIP with HiGHS optimizer # Arguments * `p`: Polyomino to calculate the rook set on * `output`: If logging of HiGHS is enabled """ function minRooks(p::Poly; output=true) tileId = Dict{Pair{Int64, Int64}, Int64}() # enumerate tiles tileIdRev = Pair{Int64, Int64}[] t = 1 for i in p.tiles tileId[i] = t push!(tileIdRev, i) t += 1 end tileAttack = Dict{Int64, Vector{Int64}}() # key: tile id, value: ids of attackable tiles for (key, value) in tileId tileAttack[value] = Vector{Int64}([value]) t = 1 while (Pair(key.first - t, key.second) in p.tiles) # up push!(tileAttack[value], tileId[Pair(key.first - t, key.second)]) t += 1 end t = 1 while (Pair(key.first, key.second - t) in p.tiles) # left push!(tileAttack[value], tileId[Pair(key.first, key.second - t)]) t += 1 end t = 1 while (Pair(key.first + t, key.second) in p.tiles) # down push!(tileAttack[value], tileId[Pair(key.first + t, key.second)]) t += 1 end t = 1 while (Pair(key.first, key.second + t) in p.tiles) # right push!(tileAttack[value], tileId[Pair(key.first, key.second + t)]) t += 1 end end model = Model(HiGHS.Optimizer) # construct linear integer programm set_optimizer_attribute(model, "log_to_console", output) @variable(model, x[1 : length(p.tiles)], Bin) for (key, value) in tileId @constraint(model, sum(x[i] for i in tileAttack[value]) >= 1) # the tile is guarded end @objective(model, Min, sum(x)) optimize!(model) return Int(sum(round.(value.(x)))), tileIdRev[round.(value.(x)) .== 1] # number, set end """ minQueens(p) Solves the minimal guarding queen set problem NP complete problem, solve as LIP with HiGHS optimizer # Arguments * `p`: Polyomino to calculate the queen set on * `output`: If logging of HiGHS is enabled """ function minQueens(p::Poly; output=true) tileId = Dict{Pair{Int64, Int64}, Int64}() # enumerate tiles tileIdRev = Pair{Int64, Int64}[] t = 1 for i in p.tiles tileId[i] = t push!(tileIdRev, i) t += 1 end tileAttack = Dict{Int64, Vector{Int64}}() # key: tile id, value: ids of attackable tiles for (key, value) in tileId tileAttack[value] = Vector{Int64}([value]) t = 1 while (Pair(key.first - t, key.second) in p.tiles) # up push!(tileAttack[value], tileId[Pair(key.first - t, key.second)]) t += 1 end t = 1 while (Pair(key.first - t, key.second - t) in p.tiles) # up left push!(tileAttack[value], tileId[Pair(key.first - t, key.second - t)]) t += 1 end t = 1 while (Pair(key.first, key.second - t) in p.tiles) # left push!(tileAttack[value], tileId[Pair(key.first, key.second - t)]) t += 1 end t = 1 while (Pair(key.first + t, key.second - t) in p.tiles) # down left push!(tileAttack[value], tileId[Pair(key.first + t, key.second - t)]) t += 1 end t = 1 while (Pair(key.first + t, key.second) in p.tiles) # down push!(tileAttack[value], tileId[Pair(key.first + t, key.second)]) t += 1 end t = 1 while (Pair(key.first + t, key.second + t) in p.tiles) # down right push!(tileAttack[value], tileId[Pair(key.first + t, key.second + t)]) t += 1 end t = 1 while (Pair(key.first, key.second + t) in p.tiles) # right push!(tileAttack[value], tileId[Pair(key.first, key.second + t)]) t += 1 end t = 1 while (Pair(key.first - t, key.second + t) in p.tiles) # up right push!(tileAttack[value], tileId[Pair(key.first - t, key.second + t)]) t += 1 end end model = Model(HiGHS.Optimizer) # construct linear integer programm set_optimizer_attribute(model, "log_to_console", output) @variable(model, x[1 : length(p.tiles)], Bin) for (key, value) in tileId @constraint(model, sum(x[i] for i in tileAttack[value]) >= 1) # the tile is guarded end @objective(model, Min, sum(x)) optimize!(model) return Int(sum(round.(value.(x)))), tileIdRev[round.(value.(x)) .== 1] # number, set end
Polyomino
https://github.com/PhoenixSmaug/Polyomino.jl.git
[ "MIT" ]
1.1.0
82fd3c3088a45c7d9f23318992417dc39f539ac6
code
7887
""" minLineCover(p) Conversion to Minimal Line Cover (MLC) (I) Find maximal non-attacking rook set and construct vertical and horizontal line through each rook (II) If one of the lines of a rook has size 1, add the other to the MLC. Otherwise add random horizontal line to MLC. In both cases delete rook of the line. (III) Repeat II until no rooks are left. # Arguments * `p`: Polyomino to be converted """ function minLineCover(p::Poly) _, rooksVec = maxRooks(p) rooks = Set(rooksVec) minLineCover = Set{Array{Pair{Int64, Int64}}}() done = Set{Pair{Int64, Int64}}() while (!isempty(rooks)) tilesOneLine = Set{Pair{Int64, Int64}}() # find all tiles where one line has size 1 for i in rooks t = 1 while (Pair(i.first - t, i.second) in p.tiles) # up (Pair(i.first - t, i.second) in tilesOneLine) ? delete!(tilesOneLine, Pair(i.first - t, i.second)) : push!(tilesOneLine, Pair(i.first - t, i.second)) t += 1 end t = 1 while (Pair(i.first, i.second - t) in p.tiles) # left (Pair(i.first, i.second - t) in tilesOneLine) ? delete!(tilesOneLine, Pair(i.first, i.second - t)) : push!(tilesOneLine, Pair(i.first, i.second - t)) t += 1 end t = 1 while (Pair(i.first + t, i.second) in p.tiles) # down (Pair(i.first + t, i.second) in tilesOneLine) ? delete!(tilesOneLine, Pair(i.first + t, i.second)) : push!(tilesOneLine, Pair(i.first + t, i.second)) t += 1 end t = 1 while (Pair(i.first, i.second + t) in p.tiles) # right (Pair(i.first, i.second + t) in tilesOneLine) ? delete!(tilesOneLine, Pair(i.first, i.second + t)) : push!(tilesOneLine, Pair(i.first, i.second + t)) t += 1 end end setdiff!(tilesOneLine, done) # remove all tiles already in the MLC if (isempty(tilesOneLine)) ranRook = first(rooks) # any rook can be choosen up = Pair{Int64, Int64}[]; left = Pair{Int64, Int64}[]; down = Pair{Int64, Int64}[]; right = Pair{Int64, Int64}[]; t = 1 while (Pair(ranRook.first - t, ranRook.second) in p.tiles) # up push!(up, Pair(ranRook.first - t, ranRook.second)) t += 1 end t = 1 while (Pair(ranRook.first, ranRook.second - t) in p.tiles) # left push!(left, Pair(ranRook.first, ranRook.second - t)) t += 1 end t = 1 while (Pair(ranRook.first + t, ranRook.second) in p.tiles) # down push!(down, Pair(ranRook.first + t, ranRook.second)) t += 1 end t = 1 while (Pair(ranRook.first, ranRook.second + t) in p.tiles) # right push!(right, Pair(ranRook.first, ranRook.second + t)) t += 1 end row = Pair{Int64, Int64}[]; column = Pair{Int64, Int64}[]; # combine parts into vertical and horizontal line for i in length(left) : -1 : 1 push!(row, left[i]) end push!(row, ranRook) for i in 1 : length(right) push!(row, right[i]) end for i in length(up) : -1 : 1 push!(column, up[i]) end push!(column, ranRook) for i in 1 : length(down) push!(column, down[i]) end if (length(row) != 1) push!(minLineCover, row) for i in row push!(done, i) end else push!(minLineCover, column) for i in column push!(done, i) end end delete!(rooks, ranRook) else rooksCopy = copy(rooks) # prevent change of the object the for loop is iterating on for i in rooksCopy horizontal = false; vertical = false up = Pair{Int64, Int64}[]; left = Pair{Int64, Int64}[]; down = Pair{Int64, Int64}[]; right = Pair{Int64, Int64}[]; t = 1 while (Pair(i.first, i.second - t) in p.tiles) push!(left, Pair(i.first, i.second - t)) if (Pair(i.first, i.second - t) in tilesOneLine) horizontal = true end t += 1 end t = 1 while (Pair(i.first, i.second + t) in p.tiles) push!(right, Pair(i.first, i.second + t)) if (Pair(i.first, i.second + t) in tilesOneLine) horizontal = true end t += 1 end t = 1 while (Pair(i.first - t, i.second) in p.tiles) push!(up, Pair(i.first - t, i.second)) if (Pair(i.first - t, i.second) in tilesOneLine) vertical = true end t += 1 end t = 1 while (Pair(i.first + t, i.second) in p.tiles) push!(down, Pair(i.first + t, i.second)) if (Pair(i.first + t, i.second) in tilesOneLine) vertical = true end t += 1 end row = Pair{Int64, Int64}[]; column = Pair{Int64, Int64}[]; # combine parts into vertical and horizontal line for j in length(left) : -1 : 1 push!(row, left[j]) end push!(row, i) for j in 1 : length(right) push!(row, right[j]) end for j in length(up) : -1 : 1 push!(column, up[j]) end push!(column, i) for j in 1 : length(down) push!(column, down[j]) end if (length(column) == 1 || horizontal) push!(minLineCover, row) for j in row push!(done, j) end delete!(rooks, i) end if (length(row) == 1 || vertical) push!(minLineCover, column) for j in column push!(done, j) end delete!(rooks, i) end end end end return minLineCover end function printMinLineCover(p::Poly) # "-" if tile is part of horizontal line, "|" if tile is part of vertical line, "+" if both mlc = minLineCover(p) minX, maxX, minY, maxY = dimensionPoly(p) for i in minX:maxX for j in minY:maxY isRow = false; isColumn = false; for k in mlc for l in 1:length(k) if (k[l].first == i && k[l].second == j) if (k[l].first == k[l % length(k) + 1].first) isColumn = true; end if (k[l].second == k[l % length(k) + 1].second) isRow = true; end end end end if (isRow && isColumn) print("+") elseif (isRow) print("|") elseif (isColumn) print("-") elseif (Pair(i, j) in p.tiles) print("X") else print(" ") end end println() end end
Polyomino
https://github.com/PhoenixSmaug/Polyomino.jl.git
[ "MIT" ]
1.1.0
82fd3c3088a45c7d9f23318992417dc39f539ac6
code
1112
using Test, Polyomino # polyomino generation polyominoA = Polyomino.Poly(30) polyominoB = Polyomino.Poly(20, 0.6) @test length(polyominoA.tiles) == 30 @test length(polyominoB.tiles) == 20 # min and max rooks polyomino = Polyomino.Poly(Set([-2 => 1, -2 => 0, -4 => 2, 3 => -2, -2 => -1, -2 => -2, 1 => -4, -1 => 1, -1 => 0, -1 => -1, -3 => 2, -4 => 1, 0 => 1, 1 => -3, 0 => 0, 0 => -1, 1 => 0, 1 => -1, 0 => -2, 2 => -3, 1 => -2, 2 => 1, -3 => 1, 2 => 0, -3 => 0, 2 => -1, -3 => -1, -5 => 2, 3 => -1, 2 => -2])) min, _ = Polyomino.minRooks(polyomino, false) max, _ = Polyomino.maxRooks(polyomino) @test min == 5 @test max == 8 # minimal line cover mlc = Polyomino.minLineCover(polyomino) @test issetequal(mlc, Set(Array{Pair{Int64, Int64}}[[0 => -2, 1 => -2, 2 => -2, 3 => -2], [-3 => -1, -2 => -1, -1 => -1, 0 => -1, 1 => -1, 2 => -1, 3 => -1], [-5 => 2, -4 => 2, -3 => 2], [-3 => 0, -2 => 0, -1 => 0, 0 => 0, 1 => 0, 2 => 0], [1 => -4, 1 => -3, 1 => -2, 1 => -1, 1 => 0], [2 => -3, 2 => -2, 2 => -1, 2 => 0, 2 => 1], [-4 => 1, -3 => 1, -2 => 1, -1 => 1, 0 => 1], [-2 => -2, -2 => -1, -2 => 0, -2 => 1]]))
Polyomino
https://github.com/PhoenixSmaug/Polyomino.jl.git
[ "MIT" ]
1.1.0
82fd3c3088a45c7d9f23318992417dc39f539ac6
docs
1482
# Chess Domination Problems on Polyominoes ### Authors * Alexis Langlois-Rémillard ([email protected]) https://alexisl-r.github.io/ * Christoph Müßig ([email protected]) * Erika Roldan ([email protected]) https://www.erikaroldan.net/ --- ## Overview A short presentation of all implemented functions is available by calling `Polyomino.demo()`. ### Polyomino generation * `Poly(size::Int64)`: Eden model, O(n) * `Poly(size::Int64, p::Float64)`: Shuffling model for uniformly random polyominoes, O(n^3) ### Chess problems * `maxRooks(p::Poly)`: Solves the maximal non-attacking rook set problem, O(n^4) * `maxQueens(p::Poly)`: Solves the maximal non-attacking queen set problem, NP-complete * `minRooks(p::Poly)`: Solves the minimal guarding rook set problem, NP-complete * `minQueens(p::Poly)`: Solves the minimal guarding queen set problem, NP-complete ### Polyomino analysis * `minimalLineCover(p::Poly)`: Calculate minimal line cover, O(n^4) --- ### Acknowledgements Erika Roldan received funding from the European Union’s Horizon 2020 research and innovation program under the Marie Skłodowska-Curie grant agreement No. 754462. ### License This project is licensed under the MIT License - see LICENSE file for details. If you use this code for academic purposes, please cite the paper: Alexis Langlois-Rémillard, Christoph Müßig, and Érika Róldan, Complexity of Chess Domination Problems, https://arxiv.org/abs/2211.05651 [math.CO], 2022.
Polyomino
https://github.com/PhoenixSmaug/Polyomino.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
614
using Documenter, KadanoffBaym makedocs( sitename="KadanoffBaym.jl", pages = [ "Overview" => "index.md", "Examples" => ["examples/TightBindingModel.md", "examples/FermiHubbard2B.md", "examples/FermiHubbardTM.md", "examples/OpenBoseDimer.md", "examples/BoseEinsteinCondensate.md", "examples/StochasticProcesses.md"] ] ) deploydocs( repo = "github.com/NonequilibriumDynamics/KadanoffBaym.jl.git", )
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
443
module KadanoffBaym using LinearAlgebra using SpecialMatrices using AbstractFFTs using RecursiveArrayTools include("utils.jl") include("gf.jl") export GreenFunction, Symmetrical, SkewHermitian, OnePoint include("vie.jl") include("vcabm.jl") include("kb.jl") export kbsolve! include("wigner.jl") export wigner_transform include("langreth.jl") export TimeOrderedGreenFunction, conv export greater, lesser, advanced, retarded end # module
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
6816
abstract type AbstractSymmetry end abstract type AbstractGreenFunction{T,N} <: AbstractArray{T,N} end """ Symmetrical Defined as ``G(t,t') = G(t',t)^\\top`` """ struct Symmetrical <: AbstractSymmetry end """ SkewHermitian Defined as ``G(t,t') = -G(t',t)^\\dagger`` """ struct SkewHermitian <: AbstractSymmetry end """ OnePoint """ struct OnePoint <: KadanoffBaym.AbstractSymmetry end @inline symmetry(::Type{<:AbstractSymmetry}) = error("Not defined") @inline symmetry(::Type{Symmetrical}) = transpose @inline symmetry(::Type{SkewHermitian}) = (-) ∘ adjoint """ GreenFunction(g::AbstractArray, s::AbstractSymmetry) A container interface for `g` with array indexing respecting some symmetry rule `s`. Because of that, `g` must be square in its last 2 dimensions, which can be resized with [`resize!`](@ref). The array `g` is not restricted to being contiguous. For example, `g` can have `Matrix{T}`, `Array{T,4}`, `Matrix{SparseMatrixCSC{T}}`, etc as its type. # Notes The GreenFunction *does not* own `g`. Proper care must be taken when using multiple GreenFunctions since using the same array will result in unexpected behaviour ```julia-repl julia> data = zeros(2,2) julia> g1 = GreenFunction(data, Symmetrical) julia> g2 = GreenFunction(data, Symmetrical) julia> g1[1,1] = 3 julia> @show g2[1,1] julia> g1.data === g2.data # they share the same data ``` Indexing with less indices than the dimension of `g` results in a "take-all-to-the-left" indexing ```julia-repl julia> gf[i,j] == gf[:,:,...,:,i,j] julia> gf[i,j,k] == gf[:,:,...,:,i,j,k] ``` In order to ensure a correct behaviour of the symmetries, `setindex!` is only defined at the level of time coordinates ```julia-repl julia> gf[i, j] = a # is equivalent to gf[..., i, j] = a[...] ``` Custom symmetries can be implemented via multiple dispatch ```julia-repl julia> struct MySymmetry <: KadanoffBaym.AbstractSymmetry end julia> @inline KadanoffBaym.symmetry(::Type{MySymmetry}) = conj ``` # Examples `GreenFunction` simply takes some data `g` and embeds the symmetry `s` in its indexing ```julia-repl julia> time_dim = 3 julia> spin_dim = 2 julia> data = zeros(spin_dim, spin_dim, time_dim, time_dim) julia> gf = GreenFunction(data, Symmetrical) julia> gf[2,1] = rand(spin_dim, spin_dim) julia> @show gf[1,2] julia> @show KadanoffBaym.symmetry(Symmetrical)(gf[2,1]) ``` """ mutable struct GreenFunction{T,N,A,U<:AbstractSymmetry} <: AbstractGreenFunction{T,N} data::A end function GreenFunction(G::AbstractArray, U::Type{<:AbstractSymmetry}) if U <: Union{Symmetrical,SkewHermitian} @assert ==(last2(size(G)...)...) "Time dimension ($(last2(size(G)...))) must be a square" end return GreenFunction{eltype(G),ndims(G),typeof(G),U}(G) end @inline Base.size(G::GreenFunction, I...) = size(G.data, I...) @inline Base.length(G::GreenFunction) = length(G.data) @inline Base.ndims(G::GreenFunction) = ndims(G.data) @inline Base.axes(G::GreenFunction, d) = axes(G.data, d) Base.copy(G::GreenFunction) = oftype(G, copy(G.data)) Base.eltype(::GreenFunction{T}) where {T} = T @inline Base.getindex(::GreenFunction{T,N,A,U}, I) where {T,N,A,U} = error("Single indexing not allowed") Base.@propagate_inbounds Base.getindex(G::GreenFunction{T,N,A,U}, I::Vararg{T1,N1}) where {T,N,A,U,T1,N1} = G.data[ntuple(i -> Colon(), N-N1)..., I...] Base.@propagate_inbounds function Base.setindex!(G::GreenFunction{T,N,A,U}, v, i1::Int, i2::Int) where {T,N,A,U} G.data[ntuple(i -> Colon(), Val(N - 2))..., i1, i2] = v if i1 != i2 G.data[ntuple(i -> Colon(), Val(N - 2))..., i2, i1] = symmetry(U)(v) end end Base.@propagate_inbounds Base.getindex(G::GreenFunction{T,N,A,OnePoint}, I::Vararg{T1,N1}) where {T,N,A,T1,N1} = G.data[ntuple(i -> Colon(), N-N1)..., I...] Base.@propagate_inbounds function Base.setindex!(G::GreenFunction{T,N,A,OnePoint}, v, I::Vararg{T1,N1}) where {T,N,A,T1,N1} G.data[ntuple(i -> Colon(), N-N1)..., Base.front(I)..., last(I)] = v end for g in (:GreenFunction,) for f in (:-, :conj, :real, :imag, :adjoint, :transpose, :zero) @eval (Base.$f)(G::$g{T,N,A,U}) where {T,N,A,U} = $g(Base.$f(G.data), U) end for f in (:+, :-, :/, :\, :*) if f != :/ @eval (Base.$f)(a::Number, G::$g{T,N,A,U}) where {T,N,A,U} = $g(Base.$f(a, G.data), U) end if f != :\ @eval (Base.$f)(G::$g{T,N,A,U}, b::Number) where {T,N,A,U} = $g(Base.$f(G.data, b), U) end end end function Base.show(io::IO, x::GreenFunction) #if get(io, :compact, false) || get(io, :typeinfo, nothing) == GreenFunction # return Base.show_default(IOContext(io, :limit => true), x) #else # # dump(IOContext(io, :limit => true), p, maxdepth=1) # for field in fieldnames(typeof(x)) # if field === :data # print(io, "\ndata: ") # Base.show(io, MIME"text/plain"(), x.data) # else # Base.show(io, getfield(x, field)) # end # end #end return show(io, x.data) end Base.resize!(A::GreenFunction, t::Int) = (A.data = _resize!(A.data, t); A) function _resize!(a::Array{T,N}, t::Int) where {T,N} a′ = Array{T,N}(undef, front2(size(a)...)..., t, t) k = min(last(size(a)), t) for t in 1:k, t′ in 1:k a′[ntuple(i -> Colon(), N-2)..., t′, t] = a[ntuple(i -> Colon(), N-2)..., t′, t] end return a′ end function Base.resize!(g::GreenFunction{T,N,A,OnePoint}, t::Int) where {T,N,A} a′ = Array{T,N}(undef, Base.front(size(g))..., t) k = min(last(size(g)), t) for t in 1:k a′[ntuple(i -> Colon(), N-1)..., t] = g[t] end g.data = a′ return g end """ SkewHermitianArray Provides a different (but not necessarily more efficient) data storage for elastic skew-Hermitian data """ struct SkewHermitianArray{T,N} <: AbstractGreenFunction{T,N} data::Vector{Vector{T}} function SkewHermitianArray(a::T) where {T<:Union{Number,AbstractArray}} return new{T,2 + ndims(a)}([[a]]) end end @inline Base.size(a::SkewHermitianArray{<:Number}) = (length(a.data), length(a.data)) @inline Base.size(a::SkewHermitianArray{<:AbstractArray}) = (size(a.data[1][1])..., length(a.data), length(a.data)) Base.getindex(::SkewHermitianArray, I) = error("Single indexing not allowed") @inline function Base.getindex(a::SkewHermitianArray{T,N}, i::Int, j::Int) where {T,N} return (i >= j) ? a.data[i - j + 1][j] : -adjoint(a.data[j - i + 1][i]) end @inline function Base.setindex!(a::SkewHermitianArray, v, i::Int, j::Int) if i >= j a.data[i - j + 1][j] = v else a.data[j - i + 1][i] = -adjoint(v) end end Base.resize!(A::SkewHermitianArray, t::Int) = (_resize!(A, t); A) function _resize!(a::SkewHermitianArray{T}, t::Int) where {T} l = length(a) resize!(a.data, t) for k in 1:min(l, t) resize!(a.data[k], t - k + 1) end for k in (min(l, t) + 1):t a.data[k] = Array{T}(undef, t - k + 1) end end
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
7439
""" kbsolve!(fv!::Function, fd!::Function, u0::Vector{<:AbstractGreenFunction}, (t0, tmax)::Tuple{Union{Real, Vector{<:Real}}, Real}) Solves the 2-time Voltera integro-differential equation `` du(t_1,t_2) / dt_1 = f_v(t_1,t_2) = v[u,t_1,t_2] + ∫_{t0}^{t1} dτ K_1^v[u,t_1,t_2,τ] + ∫_{t0}^{t2} dτ K_2^v[u,t_1,t_2,τ] `` `` du(t_1,t_2) / dt_2 = f_h(t_1,t_2) = h[u,t_1,t_2] + ∫_{t0}^{t1} dτ K_1^h[u,t_1,t_2,τ] + ∫_{t0}^{t2} dτ K_2^h[u,t_1,t_2,τ] `` for 2-point functions `u0` from `t0` to `tmax`. # Parameters - `fv!(out, ts, w1, w2, t1, t2)`: The right-hand side of ``du(t_1,t_2)/dt_1`` on the time-grid (`ts` x `ts`). The weights `w1` and `w2` can be used to integrate the Volterra kernels `K1v` and `K2v` as `sum_i w1_i K1v_i` and `sum_i w2_i K2v_i`, respectively. The output is saved in-place in `out`, which has the same shape as `u0` - `fd!(out, ts, w1, w2, t1, t2)`: The right-hand side of ``(du(t_1,t_2)/dt_1 + du(t_1,t_2)/dt_2)|_{t_2 → t_1}`` - `u0::Vector{<:GreenFunction}`: List of 2-point functions to be integrated - `(t0, tmax)`: A tuple with the initial time(s) `t0` – can be a vector of past times – and final time `tmax` # Optional keyword parameters - `f1!(out, ts, w1, t1)`: The right-hand-side of ``dv(t_1)/dt_1``. The weight `w1` can be used to integrate the Volterra kernel and the output is saved in-place in `out`, which has the same shape as `v0` - `v0::Vector{<:GreenFunction}`: List of 1-point functions to be integrated - `callback(ts, w1, w2, t1, t2)`: A function that gets called everytime the 2-point function at *indices* (`t1`, `t2`) is updated. Can be used to update functions which are not being integrated, such as self-energies - `stop(ts)`: A function that gets called at every time-step that stops the integration when it evaluates to `true` - `atol::Real`: Absolute tolerance (components with magnitude lower than `atol` do not guarantee number of local correct digits) - `rtol::Real`: Relative tolerance (roughly the local number of correct digits) - `dtini::Real`: Initial step-size - `dtmax::Real`: Maximal step-size - `qmax::Real`: Maximum step-size factor when adjusting the time-step - `qmin::Real`: Minimum step-size factor when adjusting the time-step - `γ::Real`: Safety factor for the calculated time-step such that it is accepted with a higher probability - `kmax::Integer`: Maximum order of the adaptive Adams method - `kmax_vie::Integer`: Maximum order of interpolant of the Volterra integrals Heuristically, it seems that having too high of a `kmax_vie` can result in numerical instabilities # Notes - Due to high memory and computation costs, `kbsolve!` mutates the initial condition `u0` and only works with in-place rhs functions, unlike standard ODE solvers. - The Kadanoff-Baym timestepper is a 2-time generalization of the variable Adams method presented in E. Hairer, S. Norsett and G. Wanner, *Solving Ordinary Differential Equations I: Non- stiff Problems*, vol. 8, Springer-Verlag Berlin Heidelberg, ISBN 978-3-540-56670-0, [doi:10.1007/978-3-540-78862-1](https://doi.org/10.1007/978-3-540-78862-1) (1993). """ function kbsolve!(fv!::Function, fd!::Function, u0::Vector{<:AbstractGreenFunction}, (t0, tmax)::Tuple{Union{Real, Vector{<:Real}}, Real}; f1! =nothing, v0::Vector=[], callback=(x...)->nothing, stop=(x...)->false, atol=1e-8, rtol=1e-6, dtini=0.0, dtmax=Inf, qmax=5, qmin=1 // 5, γ=9 // 10, kmax=12, kmax_vie=kmax ÷ 2) # Support for an initial time-grid if t0 isa Real t0 = [t0] else @assert issorted(t0) "Initial time-grid is not in ascending order" end @assert last(t0) <= tmax "Only t0 <= tmax supported" # Holds the information about the integration state = (u=u0, v=v0, t=t0, w=initialize_weights(t0), start=[true]) # Holds the information necessary to integrate cache = let t1 = length(state.t) VCABMCache{eltype(state.t)}(kmax, VectorOfArray([[u[t1, t2] for t2 in 1:t1] for u in state.u])) end cache_v = isempty(state.v) ? nothing : let t1 = length(state.t) cache_v = VCABMCache{eltype(state.t)}(kmax, VectorOfArray([[v[t1],] for v in state.v])) cache_v.dts = cache.dts cache_v end # The rhs is reshaped into a univariate problem f2v!(t1, t2) = fv!(view(cache.f_next, t2, :), state.t, state.w[t1], state.w[t2], t1, t2) f2d!(t1, t2) = fd!(view(cache.f_next, t2, :), state.t, state.w[t1], state.w[t2], t1, t2) function f2t!() t1 = length(state.t) Threads.@threads for t2 in 1:(t1 - 1) f2v!(t1, t2) end f2d!(t1, t1) return cache.f_next end function f1t!() t1 = length(state.t) f1!(view(cache_v.f_next, :), state.t, state.w[t1], t1) return cache_v.f_next end cache.f_prev .= f2t!() if !isempty(state.v) cache_v.f_prev .= f1t!() end while timeloop!(state, cache, tmax, dtmax, dtini, atol, rtol, qmax, qmin, γ, kmax_vie, stop) t1 = length(state.t) # Extend the caches to accomodate the new time column extend!(cache, state.t, f2v!) # Predictor u_next = predict!(cache, state.t) foreach((u, u′) -> foreach(t2 -> u[t1, t2] = u′[t2], 1:t1), state.u, u_next.u) if !isempty(state.v) u_next = predict!(cache_v, state.t) foreach((v, v′) -> v[t1] = v′[1], state.v, u_next.u) end foreach(t2 -> callback(state.t, state.w[t1], state.w[t2], t1, t2), 1:t1) # Corrector u_next = correct!(cache, f2t!) foreach((u, u′) -> foreach(t2 -> u[t1, t2] = u′[t2], 1:t1), state.u, u_next.u) if !isempty(state.v) u_next = correct!(cache_v, f1t!) foreach((v, v′) -> v[t1] = v′[1], state.v, u_next.u) end foreach(t2 -> callback(state.t, state.w[t1], state.w[t2], t1, t2), 1:t1) # Calculate error and adjust order adjust!(cache, cache_v, state.t, f2t!, f1t!, kmax, atol, rtol) end # timeloop! return (t=state.t, w=state.w) end # Controls the step size & resizes the Green functions if required function timeloop!(state, cache, tmax, dtmax, dtini, atol, rtol, qmax, qmin, γ, kmax_vie, stop) if isone(length(state.t)) || state.start[1] # Section II.4: Starting Step Size, Eq. (4.14) dt = iszero(dtini) ? initial_step(cache.f_prev, cache.u_prev, atol, rtol) : dtini state.start[1] = false else # Section II.4: Automatic Step Size Control, Eq. (4.13) q = max(inv(qmax), min(inv(qmin), cache.error_k^(1 / (cache.k + 1)) / γ)) dt = min((state.t[end] - state.t[end - 1]) / q, dtmax) end # Don't go over tmax if last(state.t) + dt > tmax dt = tmax - last(state.t) end # Remove the last element of the time-grid / weights if last step failed if cache.error_k > one(cache.error_k) pop!(state.t) pop!(state.w) end # Reached the end of the integration if iszero(dt) || stop(state.t) # trim solution foreach(u -> resize!(u, length(state.t)), state.u) foreach(v -> resize!(v, length(state.t)), state.v) return false else if length(state.t) == (last ∘ size ∘ last)(state.u) l = length(state.t) + min(50, ceil(Int, (tmax - state.t[end]) / dt)) # resize solution foreach(u -> resize!(u, l), state.u) foreach(v -> resize!(v, l), state.v) end push!(state.t, last(state.t) + dt) push!(state.w, update_weights(last(state.w), state.t, min(cache.k, kmax_vie))) return true end end
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
2114
abstract type AbstractTimeOrderedGreenFunction end """ TimeOrderedGreenFunction(L::AbstractMatrix, G::AbstractMatrix) A simple time-ordered Green function structure for a hassle-free computation of the Langreth rules. # Parameters - `L::AbstractMatrix`: The *lesser* component - `G::AbstractMatrix`: The *greater* component """ struct TimeOrderedGreenFunction <: AbstractTimeOrderedGreenFunction L # Lesser G # Greater end Base.:*(a::Number, g::TimeOrderedGreenFunction) = TimeOrderedGreenFunction(a * lesser(g), a * greater(g)) Base.:+(g1::TimeOrderedGreenFunction, g2::TimeOrderedGreenFunction) = TimeOrderedGreenFunction(lesser(g1) + lesser(g2), greater(g1) + greater(g2)) """ """ struct TimeOrderedConvolution{TA<:AbstractTimeOrderedGreenFunction, TB<:AbstractTimeOrderedGreenFunction} <: AbstractTimeOrderedGreenFunction L::TA R::TB ws::UpperTriangular end """ conv(L::AbstractTimeOrderedGreenFunction, R::AbstractTimeOrderedGreenFunction, ws::UpperTriangular) Calculates a time-convolution between time-ordered Green functions through the Langreth rules. # Parameters - `L::AbstractTimeOrderedGreenFunction`: The left time-ordered Green function - `R::AbstractTimeOrderedGreenFunction`: The right time-ordered Green function - `ws::UpperTriangular`: An upper-triangular weight matrix containing the integration weights """ function conv(L::AbstractTimeOrderedGreenFunction, R::AbstractTimeOrderedGreenFunction, ws::UpperTriangular) c = TimeOrderedConvolution(L, R, ws) return TimeOrderedGreenFunction(lesser(c), greater(c)) end # Langreth's rules greater(g::TimeOrderedGreenFunction) = g.G lesser(g::TimeOrderedGreenFunction) = g.L advanced(g::TimeOrderedGreenFunction) = UpperTriangular(lesser(g) - greater(g)) retarded(g::TimeOrderedGreenFunction) = adjoint(advanced(g)) greater(c::TimeOrderedConvolution) = (retarded(c.L) .* adjoint(c.ws)) * greater(c.R) + greater(c.L) * (c.ws .* advanced(c.R)) |> skew_hermitify! lesser(c::TimeOrderedConvolution) = (retarded(c.L) .* adjoint(c.ws)) * lesser(c.R) + lesser(c.L) * (c.ws .* advanced(c.R)) |> skew_hermitify!
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
1722
# ODE norm: Section II.4 (4.11) @inline norm(u, y=nothing) = LinearAlgebra.norm(u) / sqrt(total_length(u)) @inline total_length(u::Number) = length(u) @inline total_length(u::AbstractArray{<:Number}) = length(u) @inline total_length(u::AbstractArray{<:AbstractArray}) = sum(total_length, u) @inline total_length(u::VectorOfArray) = sum(total_length, u.u) # Error estimation and norm: Section II.4 Eq. (4.11) @inline function calculate_residuals!(out::AbstractArray, ũ::AbstractArray, u₀::AbstractArray, u₁::AbstractArray, atol, rtol, norm) @. out = calculate_residuals!(out, ũ, u₀, u₁, atol, rtol, norm) return out end @inline function calculate_residuals!(out::AbstractArray{<:Number}, ũ::AbstractArray{<:Number}, u₀::AbstractArray{<:Number}, u₁::AbstractArray{<:Number}, atol, rtol, norm) @. out = calculate_residuals(ũ, u₀, u₁, atol, rtol, norm) return out end @inline function calculate_residuals(ũ::Number, u₀::Number, u₁::Number, atol::Real, rtol::Real, norm) return ũ / (atol + max(norm(u₀), norm(u₁)) * rtol) end # Starting Step Size: Section II.4 function initial_step(f0, u0, atol, rtol) sc = atol + rtol * norm(u0) d0 = norm(u0 ./ sc) d1 = norm(f0 ./ sc) return dt0 = min(d0, d1) < 1e-5 ? 1e-6 : 1e-2 * d0 / d1 end # Returns a `Tuple` consisting of all but the last 2 components of `t`. @inline front2(v1, v2) = () @inline front2(v, t...) = (v, front2(t...)...) # Returns a `Tuple` consisting of the last 2 components of `t`. @inline last2(v1, v2) = (v1, v2) @inline last2(v, t...) = last2(t...) function skew_hermitify!(x) for i in 1:size(x, 1) for j in 1:(i - 1) x[j,i] = -conj(x[i,j]) end x[i,i] = eltype(x) <: Real ? 0.0 : im * imag(x[i,i]) end return x end
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
6481
# Part of the following code is licensed under the MIT "Expact" Lience, # from https://github.com/SciML/OrdinaryDiffEq.jl mutable struct VCABMCache{T,U} u_prev::U u_next::U u_erro::U f_prev::U f_next::U ϕ_n::Vector{U} ϕ_np1::Vector{U} ϕstar_n::Vector{U} ϕstar_nm1::Vector{U} c::Matrix{T} g::Vector{T} k::Int error_k::T β::Vector{T} dts::Vector{T} ξ::T ξ0::T function VCABMCache{T}(kmax, u_prev::U) where {T,U} return new{T,typeof(u_prev)}(u_prev, zero.(u_prev), zero.(u_prev), zero.(u_prev), zero.(u_prev), [zero.(u_prev) for _ in 1:(kmax + 1)], [zero.(u_prev) for _ in 1:(kmax + 2)], [zero.(u_prev) for _ in 1:(kmax + 1)], [zero.(u_prev) for _ in 1:(kmax + 1)], zeros(T, kmax + 1, kmax + 1), zeros(T, kmax + 1), 1, zero(T), zeros(T, kmax + 1), zeros(T, kmax + 1), zero(T), zero(T)) end end # Explicit Adams: Section III.5 Eq. (5.5) function predict!(cache::VCABMCache, times) (; u_prev, u_next, g, ϕstar_n, k) = cache @inbounds begin ϕ_and_ϕstar!(cache, times, k + 1 == length(times) ? k : k + 1) g_coeffs!(cache, times, k + 1 == length(times) ? k : k + 1) @. u_next = muladd(g[1], ϕstar_n[1], u_prev) for i in 2:(k - 1) @. u_next = muladd(g[i], ϕstar_n[i], u_next) end end return u_next end # Implicit Adams: Section III.5 Eq (5.7) function correct!(cache::VCABMCache, f) (; u_next, g, ϕ_np1, ϕstar_n, k) = cache @inbounds begin ϕ_np1!(cache, f(), k + 1) @. u_next = muladd(g[k], ϕ_np1[k], u_next) end return u_next end # Control order: Section III.7 Eq. (7.7) function adjust!(cache::VCABMCache, cache_v, times, f2, f1, kmax, atol, rtol) (; u_prev, u_next, g, ϕ_np1, ϕstar_n, k, u_erro) = cache @inbounds begin # Calculate error: Section III.7 Eq. (7.3) calculate_residuals!(u_erro, ϕ_np1[k + 1], u_prev, u_next, atol, rtol, norm) cache.error_k = norm(g[k + 1] - g[k]) * norm(u_erro) # Fail step: Section III.7 Eq. (7.4) if cache.error_k > one(cache.error_k) return end cache.f_prev .= f2() if !isnothing(cache_v) cache_v.f_prev .= f1() end if length(times) <= 5 || k < 3 cache.k = min(k + 1, 3, kmax) else calculate_residuals!(u_erro, ϕ_np1[k], u_prev, u_next, atol, rtol, norm) error_k1 = norm(g[k] - g[k - 1]) * norm(u_erro) calculate_residuals!(u_erro, ϕ_np1[k - 1], u_prev, u_next, atol, rtol, norm) error_k2 = norm(g[k - 1] - g[k - 2]) * norm(u_erro) if max(error_k2, error_k1) <= cache.error_k cache.k = k - 1 else ϕ_np1!(cache, cache.f_prev, k + 2) if !isnothing(cache_v) ϕ_np1!(cache_v, cache_v.f_prev, k + 2) end calculate_residuals!(u_erro, ϕ_np1[k + 2], u_prev, u_next, atol, rtol, norm) error_kstar = norm((times[end] - times[end - 1]) * γstar[k + 2]) * norm(u_erro) if error_kstar < cache.error_k cache.k = min(k + 1, kmax) cache.error_k = one(cache.error_k) # constant dt end end end @. cache.u_prev = cache.u_next cache.ϕstar_nm1, cache.ϕstar_n = cache.ϕstar_n, cache.ϕstar_nm1 if !isnothing(cache_v) cache_v.k = cache.k @. cache_v.u_prev = cache_v.u_next cache_v.ϕstar_nm1, cache_v.ϕstar_n = cache_v.ϕstar_n, cache_v.ϕstar_nm1 end end end function extend!(cache::VCABMCache, times, fv!) (; f_prev, f_next, u_prev, u_next, u_erro, ϕ_n, ϕ_np1, ϕstar_n, ϕstar_nm1, error_k) = cache @inbounds begin t = length(times) - 1 # `t` from the last iteration k = t == cache.k ? cache.k - 1 : cache.k if error_k > one(error_k) return end _ϕ_n = [zero.(f_next[t, :]) for _ in eachindex(ϕ_n)] _ϕ_np1 = [zero.(f_next[t, :]) for _ in eachindex(ϕ_np1)] _ϕstar_n = [zero.(f_next[t, :]) for _ in eachindex(ϕstar_n)] _ϕstar_nm1 = [zero.(f_next[t, :]) for _ in eachindex(ϕstar_nm1)] # When extending, i.e., adding a new time column, an interpolant for the rhs in this column # has to be built. Since sometimes fv! is discontinuous at the diagonal it is assumed that # fv! is built always assuming t1 > t2. This way, the interpolant (which requires points t1 < t2) # is smooth and the solver does not stall. for k′ in 1:k fv!(max(1, t - 1 - k + k′), t) # result is stored in f_next ϕ_and_ϕstar!((f_prev=f_next[t, :], ϕ_n=_ϕ_n, ϕstar_n=_ϕstar_n, ϕstar_nm1=_ϕstar_nm1), view(times, 1:(t - k + k′)), k′) _ϕstar_nm1, _ϕstar_n = _ϕstar_n, _ϕstar_nm1 end for i in eachindex(f_prev.u) foreach((ϕ, ϕ′) -> insert!(ϕ.u[i], t, ϕ′[i]), ϕ_n, _ϕ_n) foreach((ϕ, ϕ′) -> insert!(ϕ.u[i], t, ϕ′[i]), ϕ_np1, _ϕ_np1) foreach((ϕ, ϕ′) -> insert!(ϕ.u[i], t, ϕ′[i]), ϕstar_n, _ϕstar_n) foreach((ϕ, ϕ′) -> insert!(ϕ.u[i], t, ϕ′[i]), ϕstar_nm1, _ϕstar_nm1) end fv!(t, t) # result is stored in f_next for i in eachindex(u_prev.u) insert!(f_prev.u[i], t, copy(f_next[t, i])) insert!(f_next.u[i], t, zero(f_next[t, i])) insert!(u_prev.u[i], t, copy(u_prev[t, i])) insert!(u_next.u[i], t, zero(u_prev[t, i])) insert!(u_erro.u[i], t, zero(u_prev[t, i])) end end end # Section III.5: Eq (5.9-5.10) function ϕ_and_ϕstar!(cache, times, k) (; f_prev, ϕstar_nm1, ϕ_n, ϕstar_n) = cache @inbounds begin t = reverse(times) β = one(eltype(times)) ϕ_n[1] .= f_prev ϕstar_n[1] .= f_prev for i in 2:k β = β * (t[1] - t[i]) / (t[2] - t[i + 1]) @. ϕ_n[i] = ϕ_n[i - 1] - ϕstar_nm1[i - 1] @. ϕstar_n[i] = β * ϕ_n[i] end end end function g_coeffs!(cache, times, k) (; c, g) = cache @inbounds begin t = reverse(times) dt = t[1] - t[2] for i in 1:k for q in 1:(k - (i - 1)) if i > 2 c[i, q] = muladd(-dt / (t[1] - t[i]), c[i - 1, q + 1], c[i - 1, q]) elseif i == 1 c[i, q] = inv(q) elseif i == 2 c[i, q] = inv(q * (q + 1)) end end g[i] = c[i, 1] * dt end end end function ϕ_np1!(cache, du_np1, k) (; ϕ_np1, ϕstar_n) = cache @inbounds begin for i in 1:k if i != 1 @. ϕ_np1[i] = ϕ_np1[i - 1] - ϕstar_n[i - 1] else @. ϕ_np1[i] = du_np1 end end end end const γstar = [1, -1 / 2, -1 / 12, -1 / 24, -19 / 720, -3 / 160, -863 / 60480, -275 / 24192, -33953 / 3628800, -0.00789255, -0.00678585, -0.00592406, -0.00523669, -0.0046775, -0.00421495, -0.0038269]
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
569
function initialize_weights(ts::Vector{T}) where T ws = [zeros(T, 1), ] for i in 2:length(ts) push!(ws, update_weights(last(ws), ts[1:i], 1)) end return ws end function update_weights(ws, ts, k) ws = copy(ws) push!(ws, zero(eltype(ws))) l = length(ts) r = max(1, l - k):l t0 = ts[r[1]] # This subtraction controls large numerical errors when `ts` >> 1. For large Δts, switch to weight integration (see previous implementation) ws[r] += Vandermonde(ts[r] .- t0)' \ [((ts[l] - t0)^j - (ts[l-1] - t0)^j) / j for j in eachindex(r)] return ws end
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
2915
""" wigner_transform(x::AbstractMatrix; ts=1:size(x,1), fourier=true) Wigner-Ville transformation ``x_W(ω, T) = i ∫dt x(T + t/2, T - t/2) e^{+i ω t}`` or ``x_W(τ, T) = x(T + t/2, T - t/2)`` of a 2-point function `x`. Returns a tuple of `x_W` and the corresponding axes (`ω, T`) or (`τ`, `T`), depending on the `fourier` keyword. The motivation for the Wigner transformation is that, given an autocorrelation function `x`, it reduces to the spectral density function at all times `T` for stationary processes, yet it is fully equivalent to the non-stationary autocorrelation function. Therefore, the Wigner (distribution) function tells us, roughly, how the spectral density changes in time. # Optional keyword parameters - `ts::AbstractVector`: Time grid for `x`. Defaults to a `UnitRange`. - `fourier::Bool`: Whether to Fourier transform. Defaults to `true`. # Notes The algorithm only works when `ts` – and consequently `x` – is equidistant. # References <https://en.wikipedia.org/wiki/Wigner_distribution_function> <http://tftb.nongnu.org> """ function wigner_transform(x::AbstractMatrix; ts=1:size(x, 1), fourier=true) # LinearAlgebra.checksquare(x) Nt = size(x, 1) @assert length(ts) == Nt @assert let x = diff(ts); all(z -> z ≈ x[1], x) end "`ts` is not equidistant" # Change of basis x(t1, t2) → x_W(t1 - t2, (t1 + t2)/2) x_W = zero(x) for T in 1:Nt # For a certain T ≡ (t1 + t2)/2, τ ≡ (t1 - t2) can be at most τ_max τ_max = minimum([T - 1, Nt - T, Nt ÷ 2 - 1]) τs = (-τ_max):τ_max is = 1 .+ rem.(Nt .+ τs, Nt) for (i, τᵢ) in zip(is, τs) x_W[i, T] = x[T + τᵢ, T - τᵢ] end τ = Nt ÷ 2 if T <= Nt - τ && T >= τ + 1 x_W[τ + 1, T] = 0.5 * (x[T + τ, T - τ] + x[T - τ, T + τ]) end end x_W = fftshift(x_W, 1) τs = ts - reverse(ts) τs = τs .- (isodd(Nt) ? 0.0 : 0.5(τs[2] - τs[1])) if !fourier return x_W, (τs, ts) else ωs = ft(τs, τs)[1] x_Ŵ = mapslices(x -> ft(τs, x; inverse = false)[2], x_W; dims=1) return x_Ŵ, (ωs, ts) end end """ ft(xs, ys; inverse = false) Fourier transform of the points `(xs, ys)`: if `inverse` ``ŷ(t) = ∫dω/(2π) y(ω) e^{- i ω t}`` else ``ŷ(ω) = ∫dt y(t) e^{+ i ω t}`` Returns a tuple of the Fourier transformed points `(x̂s, ŷs)` """ function ft(xs, ys; inverse::Bool = false) @assert issorted(xs) L = length(xs) dx = xs[2] - xs[1] # Because the FFT calculates the transform as # ỹ_k = \sum_j e^{±2pi i j k/n} y_j, from j=0 to j=n-1, # we need to transform this into the time and frequency units, # which ends up scaling the frequencies `x̂s` by (2pi / dx). x̂s = fftfreq(L, 2π / dx) # The resulting Fourier transform also picks up a phase ℯⁱᵠ = (inverse ? 1 / (2π) : 1.0) * dx * exp.((inverse ? -1.0 : 1.0) * im * xs[1] .* x̂s) # FFT ŷs = ℯⁱᵠ .* (inverse ? fft : bfft)(ys) return fftshift(x̂s), fftshift(ŷs) end
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
1733
N = 10 @testset "2D GF" begin # Test 2d getindex setindex! data = zeros(ComplexF64, N, N) lgf = GreenFunction(copy(data), SkewHermitian) ggf = GreenFunction(copy(data), SkewHermitian) v = 30 + 30im lgf[2, N] = v ggf[N, 2] = v @test lgf.data[N, 2] == -adjoint(v) @test ggf.data[2, N] == -adjoint(v) @test lgf[2, N] == -adjoint(lgf.data[N, 2]) @test ggf.data[2, N] == -adjoint(ggf[N, 2]) end @testset "4D GF" begin # Test 4d getindex setindex! data = zeros(ComplexF64, N, N, N, N) lgf = GreenFunction(copy(data), SkewHermitian) ggf = GreenFunction(copy(data), SkewHermitian) v = rand(ComplexF64, N, N) lgf[2, N] = v ggf[N, 2] = v @test lgf.data[:, :, N, 2] == -adjoint(v) @test ggf.data[:, :, 2, N] == -adjoint(v) @test lgf[2, N] == -adjoint(lgf.data[:, :, N, 2]) @test ggf.data[:, :, 2, N] == -adjoint(ggf[N, 2]) end @testset "Base functions & setindex!" begin # Test AbstractArray-like behaviour data = rand(ComplexF64, N, N, N, N) gf = GreenFunction(copy(data), SkewHermitian) @test (-gf).data == (-data) @test (conj(gf)).data == conj(data) @test (real(gf)).data == real(data) @test (imag(gf)).data == imag(data) end @testset "setindex!" begin data = zeros(ComplexF64, N, N, N, N) gf = GreenFunction(copy(data), SkewHermitian) b = rand(ComplexF64, N, N) gf[1, 2] = b data[:, :, 1, 2] = b data[:, :, 2, 1] = -adjoint(b) @test gf.data == data # # this used to fail # gf[:, :, 2, 1] = b # data[:, :, 2, 1] = b # data[:, :, 1, 2] = -adjoint(b) for i in 1:N, j in 1:i data[:, :, i, j] = b if j != i data[:, :, j, i] = -adjoint(b) end end for i in 1:N, j in 1:i gf[i, j] = b end @test gf.data == data end
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
2969
@testset "1-time benchmark" begin λ = 0.2 atol = 1e-7 rtol = 1e-5 function fv!(out, ts, h1, h2, t, t′) out[1] = 1im * L[t, t′] out[2] = 1im * G[t, t′] - λ * L[t, t′] end function fd!(out, ts, h1, h2, t, t′) out[1] = zero(out[1]) out[2] = zero(out[2]) end function f1!(out, ts, h1, t) out[1] = -1.0im * J[t] end # two-time initial conditions G = GreenFunction(zeros(ComplexF64, 1, 1), SkewHermitian) L = GreenFunction(1im * ones(ComplexF64, 1, 1), SkewHermitian) # one-time initial conditions J = GreenFunction(ones(ComplexF64, 1, 1), OnePoint) kb = kbsolve!(fv!, fd!, [G, L], (0.0, 30.0); atol=atol, rtol=rtol, v0 = [J,], f1! =f1!) function sol1(t, g0, l0) s = sqrt(Complex(λ^2 - 4)) return exp(-λ * t / 2) * (l0 * cosh(0.5 * t * s) + (2im * g0 + l0 * λ) * sinh(0.5 * t * s) / s) end function sol2(t, g0, l0) s = sqrt(Complex(λ^2 - 4)) return exp(-λ * t / 2) * (g0 * cosh(0.5 * t * s) + (2im * l0 - g0 * λ) * sinh(0.5 * t * s) / s) end @testset begin @test G[:, 1] ≈ [sol1(t1, L[1, 1], G[1, 1]) for t1 in kb.t] atol = atol rtol = rtol @test L[:, 1] ≈ [sol2(t1, L[1, 1], G[1, 1]) for t1 in kb.t] atol = atol rtol = rtol @test real(J).data[:] ≈ cos.(kb.t) atol = atol rtol = rtol end end @testset "1-time Volterra benchmark" begin atol = 1e-6 rtol = 1e-3 function fv!(out, times, h1, h2, t, t′) I = sum(h1[s] * G[t′, s] for s in eachindex(h1)) out[1] = (1 - I) end function fd!(out, times, h1, h2, t, t′) out[1] = zero(out[1]) end G = GreenFunction(ones(1, 1), Symmetrical) kb = kbsolve!(fv!, fd!, [G], (0.0, 30.0); atol=atol, rtol=rtol) sol(t) = cos(t) + sin(t) @test G[:, 1] ≈ [sol(t1) for t1 in kb.t] atol = atol rtol = 2e0rtol end @testset "2-time benchmark" begin λ = 0.2 atol = 1e-8 rtol = 1e-5 function fv!(out, ts, h1, h2, t, t′) out[1] = -1im * λ * cos(λ * (ts[t] - ts[t′])) * L[t, t′] end function fd!(out, ts, h1, h2, t, t′) out[1] = zero(out[1]) end L = GreenFunction(-1im * ones(ComplexF64, 1, 1), SkewHermitian) kb = kbsolve!(fv!, fd!, [L], (0.0, 200.0); atol=atol, rtol=rtol) sol(t, t′) = -1.0im * exp(-1.0im * sin(λ * (t - t′))) @test L.data ≈ [sol(t1, t2) for t1 in kb.t, t2 in kb.t] atol = atol rtol = 2e0rtol end @testset "2-time Volterra benchmark" begin atol = 1e-8 rtol = 1e-5 function fv!(out, times, h1, h2, t, t′) I = sum(h1[s] * G[s, t′] for s in eachindex(h1)) I-= sum(h2[s] * G[s, t′] for s in eachindex(h2)) out[1] = (1 - I) end function fd!(out, times, h1, h2, t, t′) out[1] = zero(out[1]) end function sol(t) return cos(t) + sin(t) end G = GreenFunction(ones(1, 1), Symmetrical) kb = kbsolve!(fv!, fd!, [G], (0.0, 1.0); atol=atol, rtol=rtol) sol_ = hcat([vcat(sol.(kb.t[i] .- kb.t[1:i]), sol.(kb.t[(1 + i):length(kb.t)] .- kb.t[i])) for i in eachindex(kb.t)]...) @test G.data ≈ sol_ atol = atol rtol = 2e1rtol end
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
2078
function integrate(x::AbstractVector, y::AbstractVector) if isone(length(y)) return zero(first(y)) end @inbounds retval = (x[2] - x[1]) * (y[1] + y[2]) @inbounds @fastmath @simd for i in 2:(length(y)-1) retval += (x[i+1] - x[i]) * (y[i] + y[i+1]) end return 1 // 2 * retval end function compute(A, B, ts) l = zero(lesser(A)) for i in 1:size(l, 1) for j in 1:i l[i,j] += integrate(ts, greater(A)[i, 1:i] .* lesser(B)[1:i, j]) l[i,j] -= integrate(ts, lesser(A)[i, 1:j] .* greater(B)[1:j, j]) l[i,j] -= integrate(ts[j:i], lesser(A)[i, j:i] .* lesser(B)[j:i, j]) l[j,i] = -conj(l[i,j]) end l[i,i] = eltype(l) <: Real ? 0.0 : im * imag(l[i,i]) end g = zero(greater(A)) for i in 1:size(g, 1) for j in 1:i g[i,j] -= integrate(ts, lesser(A)[i, 1:i] .* greater(B)[1:i, j]) g[i,j] += integrate(ts, greater(A)[i, 1:j] .* lesser(B)[1:j, j]) g[i,j] += integrate(ts[j:i], greater(A)[i, j:i] .* greater(B)[j:i, j]) g[j,i] = -conj(g[i,j]) end g[i,i] = eltype(g) <: Real ? 0.0 : im * imag(g[i,i]) end TimeOrderedGreenFunction(l, g) end N = 100 # Suppose a non-equidistant time-grid ts = sort(N*rand(N)); # And 2 time-ordered GFs defined on that grid a = let x = rand(ComplexF64,N,N) y = rand(ComplexF64,N,N) TimeOrderedGreenFunction(x - x', y - y') # Skew-symmetric L and G components end b = let x = rand(ComplexF64,N,N) y = rand(ComplexF64,N,N) TimeOrderedGreenFunction(x - x', y - y') # Skew-symmetric L and G components end dts = let ws = KadanoffBaym.initialize_weights(ts) # Trapezium rule by default reduce(hcat, [[w; zeros(length(ts) - length(w))] for w in ws]) |> UpperTriangular end ⋆(a, b) = conv(a, b, dts) @testset "Langreth's rules" begin @test greater(a ⋆ b) ≈ greater(compute(a, b, ts)) @test lesser(a ⋆ b) ≈ lesser(compute(a, b, ts)) @test retarded(a ⋆ b) ≈ retarded(compute(a, b, ts)) @test greater(a ⋆ b ⋆ a) ≈ greater(compute(compute(a, b, ts), a, ts)) @test retarded(a ⋆ b ⋆ a) ≈ retarded(compute(compute(a, b, ts), a, ts)) end
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
335
using KadanoffBaym using LinearAlgebra using Test @testset verbose=true "KadanoffBaym.jl" begin @testset "GreenFunction" begin include("gf.jl") end @testset "Solver" begin include("kb.jl") end @testset "Langreth" begin include("langreth.jl") end @testset "Wigner" begin include("wigner.jl") end end
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
code
389
using FFTW const ft = KadanoffBaym.ft N = 100 a = rand(ComplexF64, N, N) a .-= a' w, _ = wigner_transform(a; fourier = false) xs = range(-3.0, 3.0, length = N - 1) # needs to be odd and symmetric for double FFT to yield itself ys = (x -> sin(x^2)).(xs) @test ft(ft(xs, ys; inverse = true)...; inverse = false)[1] ≈ xs @test ft(ft(xs, ys; inverse = true)...; inverse = false)[2] ≈ ys
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
docs
1720
# KadanoffBaym.jl [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://nonequilibriumdynamics.github.io/KadanoffBaym.jl/dev/) [![CI](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/workflows/CI/badge.svg)](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/actions?query=workflow%3ACI) [![codecov](https://codecov.io/gh/NonequilibriumDynamics/KadanoffBaym.jl/branch/master/graph/badge.svg?token=AAZVQLIKN2)](https://codecov.io/gh/NonequilibriumDynamics/KadanoffBaym.jl) ## Overview `KadanoffBaym.jl` is an *adaptive* solver for Kadanoff-Baym equations written in Julia. To learn more about the solver and Kadanoff-Baym equations, have a look into our [accompanying paper](https://doi.org/10.21468/SciPostPhysCore.5.2.030). ## Documentation The documentation can be found [here](https://nonequilibriumdynamics.github.io/KadanoffBaym.jl). ## Contributing This is meant to be a community project and all contributions, via [issues](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/issues), [PRs](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/pulls) and [discussions](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/discussions) are encouraged and greatly appreciated. ## Citing If you use `KadanoffBaym.jl` in your research, please cite our work: ``` @Article{10.21468/SciPostPhysCore.5.2.030, title={{Adaptive Numerical Solution of Kadanoff-Baym Equations}}, author={Francisco Meirinhos and Michael Kajan and Johann Kroha and Tim Bode}, journal={SciPost Phys. Core}, volume={5}, issue={2}, pages={30}, year={2022}, publisher={SciPost}, doi={10.21468/SciPostPhysCore.5.2.030}, url={https://scipost.org/10.21468/SciPostPhysCore.5.2.030}, } ```
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
docs
2990
# Welcome! `KadanoffBaym.jl` is the first fully *adaptive* solver for Kadanoff-Baym equations written in Julia. !!! tip To learn more about the solver and Kadanoff-Baym equations, have a look into our [accompanying paper](https://doi.org/10.21468/SciPostPhysCore.5.2.030). ## Installation To install, use Julia's built-in package manager ```julia julia> ] add KadanoffBaym ``` ## Scalability For now, `KadanoffBaym.jl` is restricted to run on a single machine, for which the maximum number of threads available will be used. You can set this number by running Julia with the `thread` [flag](https://docs.julialang.org/en/v1/manual/multi-threading/#man-multithreading) ``` julia -t auto ``` ## Examples To learn how to work with `KadanoffBaym.jl`, there are two options: - The [examples folder](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/tree/master/examples) of our repository, which contains notebooks for all of the systems studied in [our paper](https://doi.org/10.21468/SciPostPhysCore.5.2.030). - The examples section of this documentation. If you are interested in _quantum_ dynamics, we recommend you start with the [tight-binding model](@ref TightBinding). More advanced users can jump directly to [Fermi-Hubbard model part I](@ref FHM_I) about the _second Born approximation_. [Part II](@ref FHM_II) shows how to solve the more involved ``T``-matrix approximation. !!! note `KadanoffBaym.jl` can also be used to simulate _stochastic processes_. An introduction to this topic is given [here](@ref StochasticProcesses). ## Library `KadanoffBaym.jl` was designed to be lean and simple and hence only exports a handful of functions, namely [`GreenFunction`](@ref) (together with two possible time symmetries, `Symmetrical` and `SkewHermitian`) and the integrator [`kbsolve!`](@ref). Besides these, [`wigner_transform`](@ref) can be used to analyze data in a Wigner(-Ville) transformed basis and [`TimeOrderedGreenFunction`](@ref) to quickly compute the Keldysh components (`greater`, `lesser`, `retarded` and `advanced`) of time [`conv`](@ref)olutions via the Langreth rules. !!! note You need to import an FFT library -- e.g., `FFTW` -- to use `wigner_transform`. ### Index ```@index ``` ### Solver ```@docs kbsolve! ``` ### Green Functions ```@docs GreenFunction ``` ### Wigner Transformation ```@docs wigner_transform ``` ### Langreth's rules ```@docs TimeOrderedGreenFunction ``` ```@docs conv ``` ## Citation If you use `KadanoffBaym.jl` in your research, please cite our [paper](https://scipost.org/SciPostPhysCore.5.2.030): ``` @Article{10.21468/SciPostPhysCore.5.2.030, title={{Adaptive Numerical Solution of Kadanoff-Baym Equations}}, author={Francisco Meirinhos and Michael Kajan and Johann Kroha and Tim Bode}, journal={SciPost Phys. Core}, volume={5}, issue={2}, pages={30}, year={2022}, publisher={SciPost}, doi={10.21468/SciPostPhysCore.5.2.030}, url={https://scipost.org/10.21468/SciPostPhysCore.5.2.030}, } ```
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
docs
3780
# [Bose-Einstein Condensate] (@id BEC) In this example we will use `KadanoffBaym.jl` to study _dephasing_ in Bose-Einstein condensates (see Chp. 3 [here](https://bonndoc.ulb.uni-bonn.de/xmlui/handle/20.500.11811/8961)). To do this, we will need to solve _one-time_ differential equations for the condensate amplitude ``\varphi(t)`` and the so-called equal-time _Keldysh Green_ function ``G^K(t, t)``. !!! hint A [Jupyter notebook](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/blob/master/examples/bose-einstein-condensate.ipynb) for this example is available in our [examples folder](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/tree/master/examples). The Lindblad master equation describing this systems reads ```math \begin{align} \begin{split} \dot{\hat{\rho}} &= -i\omega_0[a^\dagger a, \hat{\rho}] +\frac{\lambda}{2}\left\{ 2a\hat{\rho} a^{\dagger} - \left( a^{\dagger}a\hat{\rho} + \hat{\rho} a^{\dagger}a \right)\right\} + \frac{\gamma}{2}\left\{ 2a^{\dagger}\hat{\rho} a - \left( aa^{\dagger}\hat{\rho} + \hat{\rho} aa^{\dagger} \right)\right\} \\ &+ D\left\{ 2a^{\dagger}a\hat{\rho} a^{\dagger}a - \left( a^{\dagger}aa^{\dagger}a\hat{\rho} + \hat{\rho} a^{\dagger}aa^{\dagger}a \right)\right\}, \end{split} \end{align} ``` where $\lambda > 0$ is the loss parameter, $\gamma > 0$ represents the corresponding gain, and $D > 0$ is the constant that introduces dephasing. The derivation for the equations of motion for $\varphi(t)$ and $G^K(t, t)$ is again given [here](https://bonndoc.ulb.uni-bonn.de/xmlui/handle/20.500.11811/8961) and leads to ```math \begin{align} \begin{split} \dot{\varphi}(t) &= -i\omega_0\varphi(t) -\frac{1}{2}{(\lambda - \gamma + {2} D)}\varphi(t), \\ \dot{G}^K(t, t) &= -{(\lambda - \gamma)}G^K(t, t) - i{\left(\lambda + \gamma + {2} D |\varphi(t)|^2\right)}. \end{split} \end{align} ``` To make these expressions more transparent, we set $\varphi(t) = \sqrt{2N(t)}\mathrm{e}^{i \theta(t)}$ and $G^K(t, t) = -i{(2\delta N(t) + 1)}$, where $N$ and $\delta N$ are the condensate and non-condensate occupation, respectively. For these quantities, we obtain ```math \begin{align} \begin{split} \dot{N} &= {(\gamma - \lambda -{2} D)}N, \\ \delta \dot{N} &= \gamma{(\delta N + 1)} - \lambda\delta N + {2}DN. \end{split} \end{align} ``` Translating all of this into code is now straightforward! We start by defining the condensate and the _Keldysh_ Green function along with their initial conditions: ```julia using KadanoffBaym, LinearAlgebra # parameters ω₀ = 1.0 λ = 0.0 γ = 0.0 D = 1.0 # initial occupations N = 1.0 δN = 0.0 # One-time function for the condensate φ = GreenFunction(zeros(ComplexF64, 1), OnePoint) # Allocate the initial Green functions (time arguments at the end) GK = GreenFunction(zeros(ComplexF64, 1, 1), SkewHermitian) # Initial conditions GK[1, 1] = -im * (2δN + 1) φ[1] = sqrt(2N) ``` In the next step, we write down the equations of motion: ```julia # we leave the vertical equation empty since we can solve for GK in equal-time only function fv!(out, ts, h1, h2, t, t′) out[1] = zero(out[1]) end # diagonal equation for GK function fd!(out, ts, h1, h2, t, _) out[1] = -(λ - γ) * GK[t, t] - im * (λ + γ + 2D * abs2(φ[t])) end # one-time equation for condensate amplitude function f1!(out, ts, h1, t) out[1] = -im * ω₀ * φ[t] - (1/2) * (λ - γ + 2D) * φ[t] end ``` Calling the solver is again a one-liner: ```julia sol = kbsolve!(fv!, fd!, [GK,], (0.0, 1.0); atol=1e-6, rtol=1e-4, v0 = [φ,], f1! =f1!) ``` If you want a plot of the results, you can find it in our corresponding [Jupyter notebook](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/blob/master/examples/bose-einstein-condensate.ipynb).
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
docs
11442
# [Fermi-Hubbard Model I] (@id FHM_I) !!! note A [Jupyter notebook](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/blob/master/examples/fermi-hubbard.ipynb) related to this example is available in our [examples folder](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/tree/master/examples). To see `KadanoffBaym.jl` in full strength, we need to consider an interacting system such as the _Fermi-Hubbard_ model ```math \begin{align*} \hat{H} &= - J \sum_{\langle{i,\,j}\rangle}\sum_\sigma \hat{c}^{\dagger}_{i,\sigma} \hat{c}^{\phantom{\dagger}}_{i+1,\sigma} + U\sum_{i=1}^L \hat{c}^{\dagger}_{i,\uparrow} \hat{c}^{\phantom{\dagger}}_{i,\uparrow} \hat{c}^{\dagger}_{i,\downarrow} \hat{c}^{\phantom{\dagger}}_{i,\downarrow}, \end{align*} ``` where the ``\hat{c}_{i,\sigma}^{\dagger},\, \hat{c}_{i,\sigma}^{\phantom{\dagger}}``, ``\sigma=\uparrow, \downarrow`` are now spin-dependent fermionic creation and annihilation operators. The model describes electrons on a lattice that can hop to neighbouring sites via the coupling ``J`` while also feeling an on-site interaction ``U``. The *spin-diagonal* Green functions are defined by ```math \begin{align*} \left[\boldsymbol{G}_\sigma^<(t, t')\right]_{ij} &= G^<_{ij, \sigma}(t, t') = \phantom{-} \mathrm{i}\left\langle{\hat{c}_{j, \sigma}^{{\dagger}}(t')\hat{c}_{i, \sigma}^{\phantom{\dagger}}(t)}\right\rangle, \\ \left[\boldsymbol{G}_\sigma^>(t, t')\right]_{ij} &= G^>_{ij, \sigma}(t, t') = -\mathrm{i}\left\langle{\hat{c}_{i, \sigma}^{\phantom{\dagger}}(t)\hat{c}_{j, \sigma}^{{\dagger}}(t')}\right\rangle. \end{align*} ``` The equations of motion for these Green functions in "vertical" time ``t`` can be written compactly as ```math \begin{align*} (\mathrm{i}\partial_t - \boldsymbol{h}) \boldsymbol{G}_\sigma^\lessgtr(t, t') &= \int_{t_0}^{t}\mathrm{d}{s} \left[\boldsymbol{\Sigma}_\sigma^>(t, s) - \boldsymbol{\Sigma}_\sigma^<(t, s) \right] \boldsymbol{G}_\sigma^\lessgtr(s, t') + \int_{t_0}^{t'}\mathrm{d}{s} \boldsymbol{\Sigma}_\sigma^\lessgtr(t, s) \left[\boldsymbol{G}_\sigma^<(s, t') - \boldsymbol{G}_\sigma^>(s, t') \right], \end{align*} ``` where ``\boldsymbol{h}`` describes the single-particle contributions (i.e. the hopping), and the matrices ``\boldsymbol{G}^\lessgtr`` are assumed to be block-diagonal in the spin degree-of-freedom. The *Hartree-Fock* part of the self-energy now is ```math \begin{align*} \Sigma^{\mathrm{HF}}_{\uparrow,\,ij}(t, t') = {\mathrm{i}}\delta_{ij}\delta(t - t') G^<_{\downarrow,ii}(t, t),\\ \Sigma^{\mathrm{HF}}_{\downarrow,\,ij}(t, t') = {\mathrm{i}}\delta_{ij}\delta(t - t') G^<_{\uparrow,ii}(t, t). \end{align*} ``` In the so-called _second Born approximation_, the contribution to next order in ``U`` is also taken into account: ```math \begin{align*} \Sigma^\lessgtr_{ij, \uparrow} (t, t') = U^2 G^\lessgtr_{ij, \uparrow}(t, t') G^\lessgtr_{ij, \downarrow}(t, t') G^\gtrless_{ji, \downarrow}(t', t),\\ \Sigma^\lessgtr_{ij, \downarrow}(t, t') = U^2 G^\lessgtr_{ij, \downarrow}(t, t') G^\lessgtr_{ij, \uparrow}(t, t') G^\gtrless_{ji, \uparrow}(t', t). \end{align*} ``` Now that we have the equations set up, we import `KadanoffBaym.jl` alongside some auxiliary packages: ```julia using KadanoffBaym, LinearAlgebra, BlockArrays ``` Then, we use `KadanoffBaym`'s built-in data structure [`GreenFunction`](@ref) to define our lesser and greater Green functions ```julia # Lattice size L = 8 # Allocate the initial Green functions (time arguments at the end) GL_u = GreenFunction(zeros(ComplexF64, L, L, 1, 1), SkewHermitian) GG_u = GreenFunction(zeros(ComplexF64, L, L, 1, 1), SkewHermitian) GL_d = GreenFunction(zeros(ComplexF64, L, L, 1, 1), SkewHermitian) GG_d = GreenFunction(zeros(ComplexF64, L, L, 1, 1), SkewHermitian) ``` Observe that we denote ``\boldsymbol{G}_\uparrow^<`` by `GL_u` and ``\boldsymbol{G}_\downarrow^<`` by `GL_d`, for instance. As a lattice structure, we choose the 8-site _3D qubic lattice_ shown in Fig. 8 of [our paper](https://doi.org/10.21468/SciPostPhysCore.5.2.030). As an (arbitrary) Gaussian initial condition, we take a non-equilibrium distribution of the charge over the cube (all electrons at the bottom of the cube): ```julia # Initial conditions N_u = zeros(L) N_d = zeros(L) N_u[1:4] = 0.1 .* [1, 1, 1, 1] N_d[1:4] = 0.1 .* [1, 1, 1, 1] N_u[5:8] = 0.0 .* [1, 1, 1, 1] N_d[5:8] = 0.0 .* [1, 1, 1, 1] GL_u[1, 1] = 1.0im * diagm(N_u) GG_u[1, 1] = -1.0im * (I - diagm(N_u)) GL_d[1, 1] = 1.0im * diagm(N_d) GG_d[1, 1] = -1.0im * (I - diagm(N_d)) ``` !!! note Accessing [`GreenFunction`](@ref) with only *two* arguments gives the whole matrix at a given time, i.e. `GL_u[1, 1]` is equivalent to `GL_u[:, :, 1, 1]`. To keep our data ordered, we define an auxiliary `struct` to hold them: ```julia Base.@kwdef struct FermiHubbardData2B{T} GL_u::T GG_u::T GL_d::T GG_d::T ΣL_u::T = zero(GL_u) ΣG_u::T = zero(GG_u) ΣL_d::T = zero(GL_d) ΣG_d::T = zero(GG_d) end data = FermiHubbardData2B(GL_u=GL_u, GG_u=GG_u, GL_d=GL_d, GG_d=GG_d) ``` Furthermore, we also defined an auxiliary `struct` specifying the parameters of the model: ```julia Base.@kwdef struct FermiHubbardModel{T} # interaction strength U::T # 8-site 3D cubic lattice h = begin h = BlockArray{ComplexF64}(undef_blocks, [4, 4], [4, 4]) diag_block = [0 -1 0 -1; -1 0 -1 0; 0 -1 0 -1; -1 0 -1 0] setblock!(h, diag_block, 1, 1) setblock!(h, diag_block, 2, 2) setblock!(h, Diagonal(-1 .* ones(4)), 1, 2) setblock!(h, Diagonal(-1 .* ones(4)), 2, 1) h |> Array end H_u = h H_d = h end # Relatively small interaction parameter const U₀ = 0.25 model = FermiHubbardModel(U = t -> U₀) ``` Note how we have defined the interaction parameter ``U`` as a (constant) Julia `Function` - this enables us to study quenches with time-dependent interaction (s. also [our paper](https://doi.org/10.21468/SciPostPhysCore.5.2.030)). The final step before setting up the actual equations is to define a callback function for the self-energies in *second Born approximation*: ```julia # Callback function for the self-energies function second_Born!(model, data, times, _, _, t, t′) # Unpack data and model (; GL_u, GG_u, GL_d, GG_d, ΣL_u, ΣG_u, ΣL_d, ΣG_d) = data (; U) = model # Resize self-energies when Green functions are resized if (n = size(GL_u, 3)) > size(ΣL_u, 3) resize!(ΣL_u, n) resize!(ΣG_u, n) resize!(ΣL_d, n) resize!(ΣG_d, n) end # The interaction varies as a function of the forward time (t+t')/2 U_t = U((times[t] + times[t′])/2) # Define the self-energies ΣL_u[t, t′] = U_t^2 .* GL_u[t, t′] .* GL_d[t, t′] .* transpose(GG_d[t′, t]) ΣL_d[t, t′] = U_t^2 .* GL_u[t, t′] .* GL_d[t, t′] .* transpose(GG_u[t′, t]) ΣG_u[t, t′] = U_t^2 .* GG_u[t, t′] .* GG_d[t, t′] .* transpose(GL_d[t′, t]) ΣG_d[t, t′] = U_t^2 .* GG_u[t, t′] .* GG_d[t, t′] .* transpose(GL_u[t′, t]) end ``` !!! note The omitted arguments `_` in the function definition refer to the _adaptive_ integration weights of `KadanoffBaym`. They are only needed when the self-energy contains actual time integrals (as in the ``T``-matrix approximation). Unlike for the non-interacting [tight-binding model](@ref TightBinding), the equations of motion above contain _integrals_ over time. This makes them so-called _Volterra integro-differential equations_ (VIDEs). Now the integrals are always either of the _first_ form ``\int_{t_0}^{t}\mathrm{d}{s} \left[\boldsymbol{\Sigma}_\sigma^>(t, s) - \boldsymbol{\Sigma}_\sigma^<(t, s) \right] \boldsymbol{G}_\sigma^\lessgtr(s, t')`` or of the _second_ form ``\int_{t_0}^{t'}\mathrm{d}{s} \boldsymbol{\Sigma}_\sigma^\lessgtr(t, s) \left[\boldsymbol{G}_\sigma^<(s, t') - \boldsymbol{G}_\sigma^>(s, t') \right].`` The discretization of these time convolutions results in a sum of matrix-products over all time indices. To be as efficient as possible, this suggests to introduce two auxiliary functions that handle these integrations by avoiding unnecessary allocations: ```julia # Auxiliary integrator for the first type of integral function integrate1(hs::Vector, t1, t2, A::GreenFunction, B::GreenFunction, C::GreenFunction; tmax=t1) retval = zero(A[t1, t1]) @inbounds for k in 1:tmax @views LinearAlgebra.mul!(retval, A[t1, k] - B[t1, k], C[k, t2], hs[k], 1.0) end return retval end # Auxiliary integrator for the second type of integral function integrate2(hs::Vector, t1, t2, A::GreenFunction, B::GreenFunction, C::GreenFunction; tmax=t2) retval = zero(A[t1, t1]) @inbounds for k in 1:tmax @views LinearAlgebra.mul!(retval, A[t1, k], B[k, t2] - C[k, t2], hs[k], 1.0) end return retval end ``` !!! note The first argument `hs::Vector` denotes the _adaptive_ integration weights provided by `KadanoffBaym`. Since these depend on the boundary points of the integration, there will usually be different weight vectors for the two integrals. We are finally ready to define the equations of motion! In "vertical" time, we have ```julia # Right-hand side for the "vertical" evolution function fv!(model, data, out, times, h1, h2, t, t′) # Unpack data and model (; GL_u, GG_u, GL_u, GG_d, ΣL_u, ΣG_u, ΣL_d, ΣG_d) = data (; H_u, H_d, U) = model # Real-time collision integrals ∫dt1(A, B, C) = integrate1(h1, t, t′, A, B, C) ∫dt2(A, B, C) = integrate2(h2, t, t′, A, B, C) # The interaction varies as a function of the forward time (t+t')/2 U_t = U((times[t] + times[t′])/2) # Hartree-Fock self-energies ΣHF_u(t, t′) = im * U_t * Diagonal(GL_d[t, t]) ΣHF_d(t, t′) = im * U_t * Diagonal(GL_u[t, t]) # Equations of motion out[1] = -1.0im * ((H_u + ΣHF_u(t, t′)) * GL_u[t, t′] + ∫dt1(ΣG_u, ΣL_u, GL_u) + ∫dt2(ΣL_u, GL_u, GG_u) ) out[2] = -1.0im * ((H_u + ΣHF_u(t, t′)) * GG_u[t, t′] + ∫dt1(ΣG_u, ΣL_u, GG_u) + ∫dt2(ΣG_u, GL_u, GG_u) ) out[3] = -1.0im * ((H_d + ΣHF_d(t, t′)) * GL_d[t, t′] + ∫dt1(ΣG_d, ΣL_d, GL_d) + ∫dt2(ΣL_d, GL_d, GG_d) ) out[4] = -1.0im * ((H_d + ΣHF_d(t, t′)) * GG_d[t, t′] + ∫dt1(ΣG_d, ΣL_d, GG_d) + ∫dt2(ΣG_d, GL_d, GG_d) ) return out end ``` As for the [tight-binding model](@ref TightBinding), the equation of motion in "diagonal" time ``T`` follows by subtracting its own adjoint from the vertical equation: ```julia # Right-hand side for the "diagonal" evolution function fd!(model, data, out, times, h1, h2, t, t′) fv!(model, data, out, times, h1, h2, t, t) out .-= adjoint.(out) end ``` After defining a final time and some tolerances, we give everything to [`kbsolve!`](@ref): ```julia # final time tmax = 4 # tolerances atol = 1e-8 rtol = 1e-6 # Call the solver sol = kbsolve!( (x...) -> fv!(model, data, x...), (x...) -> fd!(model, data, x...), [data.GL_u, data.GG_u, data.GL_d, data.GG_d], (0.0, tmax); callback = (x...) -> second_Born!(model, data, x...), atol = atol, rtol = rtol, stop = x -> (println("t: $(x[end])"); flush(stdout); false) ) ``` That's it! Results for `tmax=32` are shown in [our paper](https://doi.org/10.21468/SciPostPhysCore.5.2.030). Note that this implementation via `KadanoffBaym` is about as compact as possible.
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
docs
6695
# [Fermi-Hubbard Model II] (@id FHM_II) !!! note This example is the continuation of [Fermi-Hubbard Model I](@ref FHM_I). It is recommended that you familiarize yourself with the latter first. In part II of our example about the Fermi-Hubbard model, we will solve the so-called ``T``-matrix approximation, which is a "non-perturbative" self-energy resummation. As we saw in [part I](@ref FHM_I), in the standard perturbative second Born approximation, the self-energies are given by ```math \begin{align*} \Sigma^\lessgtr_{ij, \uparrow} (t, t') = \mathrm{i}U^2 \Phi^\lessgtr_{ij}(t, t') G^\gtrless_{ji, \downarrow}(t', t),\\ \Sigma^\lessgtr_{ij, \downarrow}(t, t') = \mathrm{i}U^2 \Phi^\lessgtr_{ij}(t, t')G^\gtrless_{ji, \uparrow}(t', t), \end{align*} ``` where ```math \begin{align*} \left[\boldsymbol{\Phi}^\lessgtr(t, t')\right]_{ij} = \Phi^\lessgtr_{ij}(t, t') = -i G^\lessgtr_{ij, \uparrow}(t, t') G^\lessgtr_{ij, \downarrow}(t, t'). \end{align*} ``` If we now define the so-called ``T``-matrix ```math \begin{align*} \boldsymbol{T}(t, t') = \boldsymbol{\Phi}(t, t') - U \int_{\mathcal{C}}\mathrm{d}s\; \boldsymbol{\Phi}(t, s) \boldsymbol{T}(s, t'), \end{align*} ``` the new self-energies in ``T``-matrix approximation become ```math \begin{align*} \Sigma^\lessgtr_{ij, \uparrow} (t, t') = \mathrm{i}U^2 T^\lessgtr_{ij}(t, t') G^\gtrless_{ji, \downarrow}(t', t),\\ \Sigma^\lessgtr_{ij, \downarrow}(t, t') = \mathrm{i}U^2 T^\lessgtr_{ij}(t, t')G^\gtrless_{ji, \uparrow}(t', t), \end{align*} ``` While we keep the _same initial conditions_ as in [Fermi-Hubbard Model I](@ref FHM_I), we intrdoce a new data `struct` that also holds the ``T``-matrix (and the "bubbles" ``\Phi`` since this is more efficient): ```julia Base.@kwdef struct FermiHubbardDataTM{T} GL_u::T GG_u::T GL_d::T GG_d::T ΣL_u::T = zero(GL_u) ΣG_u::T = zero(GG_u) ΣL_d::T = zero(GL_d) ΣG_d::T = zero(GG_d) TL::T = zero(GL_u) TG::T = zero(GG_u) ΦL::T = zero(GL_u) ΦG::T = zero(GG_u) end data = FermiHubbardDataTM(GL_u=GL_u, GG_u=GG_u, GL_d=GL_d, GG_d=GG_d) # Initialize T-matrix data.TL[1, 1] = -1.0im .* GL_u[1, 1] .* GL_d[1, 1] data.TG[1, 1] = -1.0im .* GG_u[1, 1] .* GG_d[1, 1] data.ΦL[1, 1] = data.TL[1, 1] data.ΦG[1, 1] = data.TG[1, 1] ``` !!! note As should be clear from the new definition of the self-energies in terms of the ``T``-matrix, the former now contain additional time integrals. This means that at every time step, on top of the Volterra integro-differential equations (VIDEs), we now also have to solve so-called _Volterra integral equations_ (VIEs). Furthermore, it is important for stability reasons to solve these VIEs _implicitly_. For a more detailed discussion, please consult [our paper](https://doi.org/10.21468/SciPostPhysCore.5.2.030). Accordingly, we introduce an auxiliary fixed-point solver that does this for us: ```julia function fixed_point(F::Function, x0::AbstractArray; mixing::Float64=0.5, abstol::Float64=1e-12, maxiter::Int=1000, verbose::Bool=true, norm=x -> LinearAlgebra.norm(x, Inf) ) x_old = copy(x0) step = 0 while step < maxiter x = F(x_old) res = norm(x - x_old) if verbose @info "step: $step // res: $res" end if res < abstol break end @. x_old = mixing * x + (1.0 - mixing) * x_old step += 1 end if step == maxiter @warn "No convergence reached." end return x_old end ``` Instead of writing one ourselves, we could also have worked directly with [`NLsolve.jl`](https://github.com/JuliaNLSolvers/NLsolve.jl). Note that to keep our number of dependencies low, we have opted for not including this by default. [As in part I](@ref FHM_I), we define our `FermiHubbardModel`, yet this time with a stronger interaction: ```julia # Interaction parameter const U₀ = 2.0 model = FermiHubbardModel(U = t -> U₀) ``` The previous callback `second_Born!` is now replaced with the following: ```julia # Callback function for the self-energies function T_matrix!(model, data, times, h1, h2, t, t′) # Unpack data and model (; GL_u, GG_u, GL_d, GG_d, TL, TG, ΣL_u, ΣG_u, ΣL_d, ΣG_d, ΦL, ΦG) = data (; U) = model # Real-time collision integral ∫dt1(A, B, C) = integrate1(h1, t, t′, A, B, C) ∫dt2(A, B, C) = integrate2(h2, t, t′, A, B, C) # Resize self-energies etc. when Green functions are resized if (n = size(GL_u, 3)) > size(ΣL_u, 3) resize!(ΣL_u, n) resize!(ΣG_u, n) resize!(ΣL_d, n) resize!(ΣG_d, n) resize!(TL, n) resize!(TG, n) resize!(ΦL, n) resize!(ΦG, n) end # The interaction varies as a function of the forward time (t+t')/2 U_t = U((times[t] + times[t′])/2) # Set all Φs at the very first t′ since they are all known by then if t′ == 1 for t′ in 1:t ΦL[t, t′] = -1.0im .* GL_u[t, t′] .* GL_d[t, t′] ΦG[t, t′] = -1.0im .* GG_u[t, t′] .* GG_d[t, t′] end end # Solve VIEs implicitly TL[t, t′], TG[t, t′] = fixed_point([ΦL[t, t′], ΦG[t, t′]]; mixing=0.5, verbose=false) do x TL[t, t′], TG[t, t′] = x[1], x[2] [ ΦL[t, t′] - U_t * (∫dt1(ΦG, ΦL, TL) + ∫dt2(ΦL, TL, TG)), ΦG[t, t′] - U_t * (∫dt1(ΦG, ΦL, TG) + ∫dt2(ΦG, TL, TG)) ] end # Define the self-energies ΣL_u[t, t′] = 1.0im .* U_t^2 .* TL[t, t′] .* transpose(GG_d[t′, t]) ΣL_d[t, t′] = 1.0im .* U_t^2 .* TL[t, t′] .* transpose(GG_u[t′, t]) ΣG_u[t, t′] = 1.0im .* U_t^2 .* TG[t, t′] .* transpose(GL_d[t′, t]) ΣG_d[t, t′] = 1.0im .* U_t^2 .* TG[t, t′] .* transpose(GL_u[t′, t]) end ``` For a given final time `tmax`, and tolerances `atol` and `rtol`, [`kbsolve!`](@ref) is ready to solve the problem: ```julia # Call the solver sol = kbsolve!( (x...) -> fv!(model, data, x...), (x...) -> fd!(model, data, x...), [data.GL_u, data.GG_u, data.GL_d, data.GG_d], (0.0, tmax); callback = (x...) -> T_matrix!(model, data, x...), atol = atol, rtol = rtol, dtini=1e-10, stop = x -> (println("t: $(x[end])"); flush(stdout); false) ) ``` At large `tmax=32` and with `atol = 1e-2 rtol`, we obtain ![Comparison of T-matrix and second Born approximations for different tolerances](../assets/FermiHubbard_II.png) This confirms that the resummation performed by the T-matrix is indeed superior to the second Born approximation in the current regime of large ``U`` and small occupation numbers!
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git
[ "MIT" ]
1.3.2
20ceb97a9f5eab5b460f7683ee70f48db43bd69c
docs
6619
# [Open Bose Dimer] (@id OpenBose) A nice example to illustrate how one can use `KadanoffBaym.jl` to study *open systems* is the Bose dimer depicted below. !!! hint A [Jupyter notebook](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/blob/master/examples/bosonic-dimer.ipynb) for this example is available in our [examples folder](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/tree/master/examples). ![Set-up of the open Bose dimer](../assets/OpenBoseDimer.png) It consists of two bosonics modes ``\omega_{1,2}`` (you can imagine two single-mode cavities at different frequencies), which are coupled with strength ``J``. Additionally, each mode is coupled to its own reservoir at inverse temperature ``\beta_{1,2}``, respectively. Such a system is described by the master equation ```math \begin{align*} \partial_{t} \hat{\rho}=-i\left[\hat{H} \hat{\rho}-\hat{\rho} \hat{H}^{ \dagger}\right] + \lambda\sum_{i=1}^L \left[(N_i + 1)\hat{a}^{\phantom{\dagger}}_i \hat{\rho} \hat{a}^{\dagger}_i + N_i \hat{a}^{\dagger}_i\hat{\rho} \hat{a}^{\phantom{\dagger}}_i \right] \end{align*} ``` for ``[\hat{a}^{\phantom{\dagger}}_i, \hat{a}^{\dagger}_i]=1``, ``i=1, ..., L`` and ``L=2``. The ``N_i=1/(e^{\beta_i \omega_i}-1)`` denote the thermal occupations of the reservoirs. The in this case *non-Hermitian* Hamiltonian is given by ```math \begin{align*} \hat{H}=\sum_{i=1}^L (\omega_{i}-i \lambda (N_i + 1/2)) \hat{a}^{\dagger}_i \hat{a}^{\phantom{\dagger}}_i. \end{align*} ``` The bosonic *lesser* and *greater* Green functions are ```math \begin{align*} \left[\boldsymbol{G}^<(t, t')\right]_{ij} &= G^<_{ij}(t, t') = -i\left\langle{\hat{a}_j^{{\dagger}}(t')\hat{a}_i^{\phantom{\dagger}}(t)}\right\rangle, \\ \left[\boldsymbol{G}^>(t, t')\right]_{ij} &= G^>_{ij}(t, t') = -i\left\langle{\hat{a}_i^{\phantom{\dagger}}(t)\hat{a}_j^{{\dagger}}(t')}\right\rangle. \end{align*} ``` For convenience, we also introduce the (anti-) time-ordered Green functions ```math \begin{align*} G^{T}_{ij}(t, t') &= \Theta(t - t') G^>_{ij}(t, t') + \Theta(t' - t) G^<_{ij}(t, t'), \\ G^{\tilde{T}}_{ij}(t, t') &= \Theta(t - t') G^<_{ij}(t, t') + \Theta(t' - t) G^>_{ij}(t, t'). \end{align*} ``` With the help of these, we can express the "vertical" equations of motion compactly: ```math \begin{align*} \partial_t \boldsymbol{G}^<(t, t') &= -i \boldsymbol{H} \boldsymbol{G}^<(t, t') + \lambda \operatorname{diag} (N_1, ..., N_L) \boldsymbol{G}^{\tilde{T}}(t, t') , \\ \partial_t \boldsymbol{G}^>(t, t') &= -i \boldsymbol{H}^\dagger \boldsymbol{G}^>(t, t') - \lambda \operatorname{diag} (N_1 + 1, ..., N_L + 1) \boldsymbol{G}^{{T}}(t, t') , \end{align*} ``` where ``\boldsymbol{H} = \operatorname{diag}(\omega_{1}- i\lambda (N_1 + 1/2), ..., \omega_{L}- i\lambda(N_L + 1/2))``. As in our [previous example](@ref TightBinding), we also need the equations in the "diaognal" time direction, which in the present case become ```math \begin{align*} \partial_T {G}_{{ij}}^<(T, 0)_W &= -i \left[\boldsymbol{H} \boldsymbol{G}^<(T, 0)_W - \boldsymbol{G}^<(T, 0)_W \boldsymbol{H}^\dagger\right]_{ij} \\ &+ \frac{i\lambda}{2} (N_i + N_j) ({G}_{{ij}}^<(T, 0)_W + {G}_{{ij}}^>(T, 0)_W), \\ \partial_T {G}_{{ij}}^>(T, 0)_W &= -i \left[\boldsymbol{H}^\dagger \boldsymbol{G}^>(T, 0)_W - \boldsymbol{G}^>(T, 0)_W \boldsymbol{H}\right]_{ij} \\ &- \frac{i\lambda}{2} (N_i + N_j + 2) ({G}_{{ij}}^<(T, 0)_W + {G}_{{ij}}^>(T, 0)_W), \end{align*} ``` where the subscript ``W`` again indicates *Wigner coordinates*. Translating all of this into code is now straightforward! We start by defining the Green functions and their initial conditions: ```julia using KadanoffBaym, LinearAlgebra # Lattice size L = 2 # Allocate the initial Green functions (time arguments at the end) GL = GreenFunction(zeros(ComplexF64, L, L, 1, 1), SkewHermitian) GG = GreenFunction(zeros(ComplexF64, L, L, 1, 1), SkewHermitian) # Initial condition GL[1, 1] = -im * diagm([0.0, 2]) GG[1, 1] = -im * I(2) + GL[1,1] ``` Then we assign all of the parameters we need: ```julia # Non-Hermitian Hamiltonian ω₁ = 2.5 ω₂ = 0.0 J = pi / 4 λ = 1 N₁ = 1. N₂ = 0.1 H = [ω₁ - 0.5im * λ * ((N₁ + 1) + N₁) J; J ω₂ - 0.5im * λ * ((N₂ + 1) + N₂)] ``` As the last step, we write down the equations of motion: ```julia # Right-hand side for the "vertical" evolution function fv!(out, _, _, _, t, t′) out[1] = -1.0im * (H * GL[t, t′] + λ * [[1.0im * N₁, 0] [0, 1.0im * N₂]] * GL[t, t′]) out[2] = -1.0im * (adjoint(H) * GG[t, t′] - 1.0im * λ * [[(N₁ + 1), 0] [0, (N₂ + 1)]] * GG[t, t′]) end ``` Observe how we have converted the (anti-) time-ordered Green functions ``G^{T}, G^{\tilde{T}}`` into lesser and greater functions by explicitly using the fact that we are operating on the ``t>t'`` triangle of the two-time grid ``(t, t')``. By combining `fv!` with its adjoint [as before](@ref TightBinding), we also obtain the "diagonal" equations as ```julia # Right-hand side for the "diagonal" evolution function fd!(out, _, _, _, t, t′) out[1] = (-1.0im * (H * GL[t, t] - GL[t, t] * adjoint(H) + 1.0im * λ * [[N₁ * (GL[1, 1, t, t] + GG[1, 1, t, t]), (N₁ + N₂) * (GL[2, 1, t, t] + GG[2, 1, t, t]) / 2] [(N₁ + N₂) * (GL[1, 2, t, t] + GG[1, 2, t, t]) / 2, N₂ * (GL[2, 2, t, t] + GG[2, 2, t, t])]]) ) out[2] = (-1.0im * (adjoint(H) * GG[t, t] - GG[t, t] * H - 1.0im * λ * [[(N₁ + 1) * (GL[1, 1, t, t] + GG[1, 1, t, t]), (N₁ + N₂ + 2) * (GG[2, 1, t, t] + GL[2, 1, t, t]) / 2] [(N₁ + N₂ + 2) * (GG[1, 2, t, t] + GL[1, 2, t, t]) / 2, (N₂ + 1) * (GL[2, 2, t, t] + GG[2, 2, t, t])]]) ) end ``` Calling the solver is again a one-liner: ```julia sol = kbsolve!(fv!, fd!, [GL, GG], (0.0, 32.0); atol=1e-6, rtol=1e-4) ``` !!! tip By importing Julia's `FFTW` and `Interpolations` packages, we can also obtain the Wigner-transformed Green functions. ```julia using FFTW, Interpolations function wigner_transform_itp(x::AbstractMatrix, ts::Vector; fourier = true, ts_lin = range(first(ts), last(ts); length = length(ts))) itp = interpolate((ts, ts), x, Gridded(Linear())) return wigner_transform([itp(t1, t2) for t1 in ts_lin, t2 in ts_lin]; ts = ts_lin, fourier = fourier) end ρ_11_wigner, (taus, ts) = wigner_transform_itp((GG.data - GL.data)[1, 1, :, :], sol.t; fourier=false) ρ_11_FFT, (ωs, ts) = wigner_transform_itp((GG.data - GL.data)[1, 1, :, :], sol.t; fourier=true) ``` If you want to see plots of all the results, you can find those in our corresponding [Jupyter notebook](https://github.com/NonequilibriumDynamics/KadanoffBaym.jl/blob/master/examples/bosonic-dimer.ipynb).
KadanoffBaym
https://github.com/NonequilibriumDynamics/KadanoffBaym.jl.git