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.2.3
8a261ee237dbd5fae2e10192cfd8b1d465c6d7eb
code
604
using Lattices ups(::Type{ST}, ltc::Lattices.AbstractLattice) where ST = ups(ST, size(ltc)) downs(::Type{ST}, ltc::Lattices.AbstractLattice) where ST = downs(ST, size(ltc)) Random.rand(::Type{ST}, ltc::Lattices.AbstractLattice) where ST = rand(ST, size(ltc)) ups(ltc::Lattices.AbstractLattice) = ups(Bit{Int}, ltc) downs(ltc::Lattices.AbstractLattice) = downs(Bit{Int}, ltc) Random.rand(ltc::Lattices.AbstractLattice) = rand(Bit{Int}, ltc) HilbertSpace{L}(ltc::Lattices.AbstractLattice) where L = HilbertSpace{L}(size(ltc)...) HilbertSpace(ltc::Lattices.AbstractLattice) = HilbertSpace{Bit{Int}}(ltc)
LatticeSites
https://github.com/Roger-luo/LatticeSites.jl.git
[ "Apache-2.0" ]
0.2.3
8a261ee237dbd5fae2e10192cfd8b1d465c6d7eb
code
469
function Base.round(::Type{Bit{T}}, x::T) where {T <: Integer} x == zero(T) ? Bit(zero(T)) : Bit(one(T)) end function Base.round(::Type{Bit{T}}, x::T; threshold::T=T(1e-3)) where {T <: AbstractFloat} x < threshold ? Bit(zero(T)) : Bit(one(T)) end function Base.round(::Type{Spin{T}}, x::T) where T x > 0 ? Spin(one(T)) : Spin(-one(T)) end function Base.round(::Type{Half{T}}, x::T) where {T <: AbstractFloat} x > 0 ? Half(T(0.5)) : Half(-T(0.5)) end
LatticeSites
https://github.com/Roger-luo/LatticeSites.jl.git
[ "Apache-2.0" ]
0.2.3
8a261ee237dbd5fae2e10192cfd8b1d465c6d7eb
code
1816
export HilbertSpace """ HilbertSpace{L, S, M} `M` dimension Hilbert space of Site type `L` in with shape `S`. """ struct HilbertSpace{L, Shape, N, NSite} cache::Array{L, N} function HilbertSpace{L}(dims::Int...) where L Shape = Tuple{dims...} N = length(dims) NSite = prod(dims) new{L, Shape, N, NSite}(downs(L, dims)) end end StaticArrays.Size(::Type{HilbertSpace{L, Shape}}) where {L, Shape} = Size(Shape) Base.@pure Base.size(::Type{<:HilbertSpace{L, S}}) where {L, S} = tuple(S.parameters...) function carrybit!(a::Array{L}) where L @inbounds for i in eachindex(a) if a[i] == up(L) a[i] = down(L) else a[i] = up(L) break end end a end Base.iterate(it::HilbertSpace{L}) where L = (fill!(it.cache, down(L)); iterate(it, 1)) function Base.iterate(it::HilbertSpace{L, S, N, NSite}, state) where {L, S, N, NSite} if_stop(it, state) && return nothing state == 1 && return (it.cache, state + 1) carrybit!(it.cache), state + 1 end @generated function if_stop(it::HilbertSpace{L, S, N, NSite}, state) where {L, S, N, NSite} if sizeof(Int) * 8 > NSite :(state == $((1 << NSite) + 1)) else quote flag = true for each in it.cache if each != up($L) flag = false break end end flag end end end Base.eltype(::HilbertSpace{L, S, N}) where {L, S, N} = Array{L, N} Base.length(::HilbertSpace{L, S, N, NSite}) where {L, S, N, NSite} = 1 << NSite function Base.collect(space::HilbertSpace) r = Vector{eltype(space)}(undef, length(space)) @inbounds for (i, each) in enumerate(space) r[i] = copy(each) end r end
LatticeSites
https://github.com/Roger-luo/LatticeSites.jl.git
[ "Apache-2.0" ]
0.2.3
8a261ee237dbd5fae2e10192cfd8b1d465c6d7eb
code
3263
export up, down, Bit, Spin, Half, Clock, Potts, Continuous abstract type AbstractSite{T} end Base.show(io::IO, s::AbstractSite) = show(io, value(s)) Base.:(==)(lhs::AbstractSite, rhs::Number) = value(lhs) == rhs Base.:(==)(lhs::Number, rhs::AbstractSite) = lhs == value(rhs) abstract type IntegerSite{T} <: AbstractSite{T} end abstract type BinarySite{T} <: IntegerSite{T} end abstract type ContinuousSite{T} <: AbstractSite{T} end """ Bit{T} <: BinarySite{T} """ struct Bit{T} <: BinarySite{T} value::T end struct Spin{T} <: BinarySite{T} value::T end struct Half{T} <: BinarySite{T} value::T end struct Clock{T, q} <: IntegerSite{T} value::T end struct Potts{T, q} <: IntegerSite{T} value::T end struct Continuous{T, d} <: ContinuousSite{T} value::T end """ up(site) -> site up(site_type) -> site Up (highest value) tag for this label. e.g. `1` for `Bit`, `0.5` for `Half`. """ up(::ST) where {ST<: IntegerSite} = up(ST) up(::Type{ST}) where {ST <: IntegerSite} = values(ST)[end] """ down(site) -> site down(site_type) -> site Down (lowest value) tag for this label. e.g. `0` for `Bit`, `-0.5` for `Half`. """ down(::ST) where {ST<: IntegerSite} = down(ST) down(::Type{ST}) where {ST <: IntegerSite} = values(ST)[1] """ values(site) -> site values(site_type) -> site Returns a tuple of all possible values of the site type """ Base.values(::ST) where {ST <: AbstractSite} = values(ST) Base.values(::Type{ST}) where {ST <: AbstractSite} = map(ST, _values(ST)) Base.values(::ST, i::Int) where {ST <: AbstractSite} = _values(ST)[i] _values(::Type{Bit{T}}) where T = (zero(T), one(T)) _values(::Type{Spin{T}}) where T = (-one(T), one(T)) _values(::Type{Half{T}}) where T = (-0.5, 0.5) _values(::Type{Clock{T, q}}) where {T, q} = Base.OneTo(q) _values(::Type{Potts{T, q}}) where {T, q} = Tuple(-q:q) # _values(::Type{Continuous{T}}) where {T} = # TODO value(S::AbstractSite) = S.value Base.length(::AbstractSite) = 1 Base.iterate(x::AbstractSite) = (x, nothing) Base.iterate(x::AbstractSite, state) = nothing Random.rand(rng::Random.AbstractRNG, sp::Random.SamplerType{Bit{T}}) where T = Bit{T}(rand(rng, Bool)) Random.rand(rng::Random.AbstractRNG, sp::Random.SamplerType{Spin{T}}) where T = Spin{T}(2 * rand(rng, Bool) - 1) Random.rand(rng::Random.AbstractRNG, sp::Random.SamplerType{Half{T}}) where T = Half{T}(rand(rng, Bool) - 0.5) Random.rand(rng::Random.AbstractRNG, sp::Random.SamplerType{Clock{T, q}}) where {T, q} = Clock{T, q}(rand(rng, 1:q)) Random.rand(rng::Random.AbstractRNG, sp::Random.SamplerType{Potts{T, q}}) where {T, q} = Potts{T, q}(rand(rng, -q:q)) Base.to_index(A::AbstractArray, i::Bit) = Int(value(i) + 1) Base.to_index(A::AbstractArray, i::Spin) = Int(0.5 * (value(i) + 1) + 1) Base.to_index(A::AbstractArray, i::Half) = Int(value(i) + 1.5) Base.to_index(A::AbstractArray, i::Clock) = Int(value(i)) Base.to_index(A::AbstractArray, i::Potts) = Int(value(i) + q + 1) Base.to_index(A::AbstractArray, I::AbstractArray{Bit{T}, N}) where {T, N} = Int(I) + 1 Base.getindex(t::Tuple, i::Bit) = getindex(t, value(i) + 1) Base.getindex(t::Tuple, i::Spin) = getindex(t, Int(div(value(i) + 1, 2) + 1)) include("roundings.jl") include("conversions.jl") include("arraymath.jl")
LatticeSites
https://github.com/Roger-luo/LatticeSites.jl.git
[ "Apache-2.0" ]
0.2.3
8a261ee237dbd5fae2e10192cfd8b1d465c6d7eb
code
1160
using Test, LatticeSites, StaticArrays @testset "site type" begin @test up(Bit{Float64}) == Bit(1.0) @test down(Bit{Float64}) == Bit(0.0) @test up(Spin{Float64}) == Spin(1.0) @test down(Spin{Float64}) == Spin(-1.0) @test up(Half{Float64}) == Half(0.5) @test down(Half{Float64}) == Half(-0.5) end @testset "hilbert space" begin for (i, each) in enumerate(HilbertSpace{Bit{Float64}}(2, 3)) @test size(each) == (2, 3) @test i-1 == convert(Int, each) end end @testset "conversion" begin @test 1 == convert(Int, Bit[1, 0]) @test 1 == convert(Int, Spin[1, -1]) @test 1 == convert(Int, Half[0.5, -0.5]) end @testset "rounding" begin @test round(Bit{Float64}, 1.2) == up(Bit{Float64}) @test round(Bit{Float64}, 0.9) == up(Bit{Float64}) @test round(Bit{Float64}, 0.1; threshold=0.5) == down(Bit{Float64}) @test round(Bit{Int}, 2) == up(Bit{Int}) @test round(Bit{Int}, 0) == down(Bit{Int}) end @testset "static array" begin @test all(ups(SMatrix{2, 2, Bit{Float64}}) .== up(Bit{Float64})) @test all(downs(SMatrix{2, 2, Bit{Float64}}) .== down(Bit{Float64})) end
LatticeSites
https://github.com/Roger-luo/LatticeSites.jl.git
[ "Apache-2.0" ]
0.2.3
8a261ee237dbd5fae2e10192cfd8b1d465c6d7eb
docs
2109
# LatticeSites.jl [![Build Status](https://travis-ci.org/Roger-luo/LatticeSites.jl.svg?branch=master)](https://travis-ci.org/Roger-luo/LatticeSites.jl) Type for different kind of sites on different lattices. ## Installation ``` pkg> add https://github.com/Roger-luo/LatticeSites.jl.git ``` ## Intro This package provides types for sites, which defines the configuration of a lattice. Binary configuration label is provided as: - `Bit`, refers to `0`/`1` - `Spin`, refers to `-1`/`+1` - `Half`, refers to `-0.5`/`+0.5` - `Clock`, refers to the 2D q-state clock model with `q` discrete spin values (`1:q`) - `Potts`, refers to the standard Potts model with values `-q, ..., q` - `Continuous`, is in development still and not ready. `Array`, `StaticArray` and etc. (e.g `SparseArray`) is supported for store configurations. It is simple, and you can use it like a `Number` (but it is not a `Number`) ```julia julia> rand(Bit{Float64}) 0.0 julia> rand(Bit{Float64}, 2, 2) 2×2 Array{Bit{Float64},2}: 0.0 0.0 0.0 0.0 julia> using StaticArrays julia> rand(SMatrix{2, 2, Bit{Int}}) 2×2 SArray{Tuple{2,2},Bit{Int64},2,4}: 0 1 0 1 ``` and to support indexing, you can convert any `AbstractArray` contains sites to an integer (as long as this integer type does not overflow). ```julia julia> convert(Int, rand(SMatrix{2, 2, Bit{Int}})) 12 ``` There is also a `HilbertSpace` iterator that help you iterate through the space. ```julia julia> space = HilbertSpace{Bit{Int}}(2, 2) HilbertSpace{Bit{Int64},Tuple{2,2},2,4}(Bit{Int64}[0 0; 0 0]) julia> collect(space) 16-element Array{Array{Bit{Int64},2},1}: [0 0; 0 0] [1 0; 0 0] [0 0; 1 0] [1 0; 1 0] [0 1; 0 0] [1 1; 0 0] [0 1; 1 0] [1 1; 1 0] [0 0; 0 1] [1 0; 0 1] [0 0; 1 1] [1 0; 1 1] [0 1; 0 1] [1 1; 0 1] [0 1; 1 1] [1 1; 1 1] ``` We use the convention that the first index `a[1]` take the first digit position during the convention, which is opposite to natural notation `0b0101`, where the last digit in bit string take the first position. In short `0b011` is equivalent to `Bit[1, 1, 0]` ## License Apache License 2.0
LatticeSites
https://github.com/Roger-luo/LatticeSites.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
34
using PkgBenchmark, GeometricFlux
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
1193
using CSV, DataFrames using Gadfly import Cairo julia_bmk_file = joinpath("benchmark", "scatter_julia.tsv") python_bmk_file = joinpath("benchmark", "scatter_pytorch.tsv") bmk_jl = CSV.read(julia_bmk_file; delim='\t') bmk_py = CSV.read(python_bmk_file; delim='\t') bmk_jl[!, :framework] .= "ScatterNNlib.jl" bmk_py[!, :framework] .= "Pytorch-scatter" bmk = vcat(bmk_jl, bmk_py) bmk[!, :min_time] .= bmk[!, :min_time]/1000 bmk[!, :mean_time] .= bmk[!, :mean_time]/1000 bmk[!, :max_time] .= bmk[!, :max_time]/1000 function plot_benchmark(device) DEVICE = uppercase(device) p = plot(bmk[bmk[!,:device] .== device, :], x="sample", y="mean_time", color="framework", Geom.point, Geom.line, Scale.x_log2, Scale.y_log10, Guide.title("Scatter add performance on $(DEVICE)"), Guide.xlabel("Matrix Size"), Guide.ylabel("Time (μs)"), Coord.cartesian(xmin=4, xmax=21, ymin=0, ymax=6)) draw(SVG(joinpath("benchmark", "pics", "$(device)_scatter.svg"), 9inch, 6inch), p) draw(PNG(joinpath("benchmark", "pics", "$(device)_scatter.png"), 9inch, 6inch), p) end plot_benchmark("cpu") plot_benchmark("gpu")
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
611
using CUDA using GeometricFlux using Profile using ProfileView ENV["JULIA_NUM_THREADS"] = 1 d = 50 nbins = 20 l = 2^20 hist = zeros(Float32, d, nbins) δ = rand(Float32, d, l) idx = rand(1:nbins, l) scatter_add!(hist, δ, idx) @profile scatter_add!(hist, δ, idx) Profile.print() @profview scatter_add!(hist, δ, idx) # sudo nvprof --profile-from-start off julia benchmark/scatter.jl # sudo nvprof --profile-from-start off --print-gpu-trace julia --proj benchmark/scatter.jl # sudo chown $USER -R $HOME/.julia/ # @profview scatter_add!(hist, δ, idx) # CUDAdrv.@profile scatter_add!(hist_gpu, δ_gpu, idx_gpu)
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
1625
using Pkg using CUDA using ScatterNNlib using DataFrames using CSV using BenchmarkTools using BenchmarkTools: Trial, TrialEstimate, median, mean Pkg.status("ScatterNNlib") Pkg.status("CUDA") ENV["JULIA_NUM_THREADS"] = 1 d = 50 nbins = 20 getinfo(te::TrialEstimate) = te.time, te.gctime, te.memory getstats(t::Trial) = [getinfo(minimum(t)), getinfo(mean(t)), getinfo(maximum(t))] metadata = DataFrame(device=String[], dim=Int[], sample=Int[], bins=Int[]) mintime = DataFrame(min_time=Float64[], min_gc=Float64[], min_mem=Int[]) meantime = DataFrame(mean_time=Float64[], mean_gc=Float64[], mean_mem=Int[]) maxtime = DataFrame(max_time=Float64[], max_gc=Float64[], max_mem=Int[]) for l = [2^5, 2^10, 2^15, 2^20] hist = zeros(Float32, d, nbins) δ = rand(Float32, d, l) idx = rand(1:nbins, l) hist_gpu = CuArray(hist) δ_gpu = CuArray(δ) idx_gpu = CuArray(idx) scatter_add!(hist, δ, idx) scatter_add!(hist_gpu, δ_gpu, idx_gpu) b_cpu = @benchmark scatter_add!($hist, $δ, $idx) b_gpu = @benchmark scatter_add!($hist_gpu, $δ_gpu, $idx_gpu) s_cpu = getstats(b_cpu) s_gpu = getstats(b_gpu) push!(metadata, ("cpu", d, l, nbins)) push!(mintime, s_cpu[1]) push!(meantime, s_cpu[2]) push!(maxtime, s_cpu[3]) push!(metadata, ("gpu", d, l, nbins)) push!(mintime, s_gpu[1]) push!(meantime, s_gpu[2]) push!(maxtime, s_gpu[3]) end data = hcat(metadata, mintime, meantime, maxtime) CSV.write("benchmark/scatter_julia.tsv", data; delim="\t") ## Benchmark # @benchmark scatter_add!($hist, $δ, $idx) # CuArrays.@time scatter_add!(hist_gpu, δ_gpu, idx_gpu)
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
1870
using PyCall using DataFrames using CSV using BenchmarkTools using BenchmarkTools: Trial, TrialEstimate, median, mean py""" import torch import torch_scatter as sc print("Pytorch v", torch.__version__) print("Pytorch-scatter v", sc.__version__) cuda = torch.device("cuda:0") d = 50 nbins = 20 """ d = 50 nbins = 20 getinfo(te::TrialEstimate) = te.time, te.gctime, te.memory getstats(t::Trial) = [getinfo(minimum(t)), getinfo(mean(t)), getinfo(maximum(t))] metadata = DataFrame(device=String[], dim=Int[], sample=Int[], bins=Int[]) mintime = DataFrame(min_time=Float64[], min_gc=Float64[], min_mem=Int[]) meantime = DataFrame(mean_time=Float64[], mean_gc=Float64[], mean_mem=Int[]) maxtime = DataFrame(max_time=Float64[], max_gc=Float64[], max_mem=Int[]) for l = [2^5, 2^10, 2^15, 2^20] py""" hist = torch.zeros([d, nbins], dtype=torch.float32) delta = torch.rand([d, $(l)], dtype=torch.float32) idx = torch.randint(0, nbins, size=($(l),)) hist_gpu = torch.zeros([d, nbins], dtype=torch.float32, device=cuda) delta_gpu = torch.rand([d, $(l)], dtype=torch.float32, device=cuda) idx_gpu = torch.randint(0, nbins, size=($(l),), device=cuda) sc.scatter_add(delta, idx, out=hist) sc.scatter_add(delta_gpu, idx_gpu, out=hist_gpu) """ b_cpu = @benchmark py"sc.scatter(delta, idx, out=hist, reduce='sum')"; b_gpu = @benchmark py"sc.scatter(delta_gpu, idx_gpu, out=hist_gpu, reduce='sum')"; s_cpu = getstats(b_cpu) s_gpu = getstats(b_gpu) push!(metadata, ("cpu", d, l, nbins)) push!(mintime, s_cpu[1]) push!(meantime, s_cpu[2]) push!(maxtime, s_cpu[3]) push!(metadata, ("gpu", d, l, nbins)) push!(mintime, s_gpu[1]) push!(meantime, s_gpu[2]) push!(maxtime, s_gpu[3]) end data = hcat(metadata, mintime, meantime, maxtime) CSV.write("benchmark/scatter_pytorch.tsv", data; delim="\t")
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
536
using ScatterNNlib using Documenter makedocs( modules = [ScatterNNlib], authors = "Yueh-Hua Tu", repo = "https://github.com/yuehhua/ScatterNNlib.jl/blob/{commit}{path}#L{line}", sitename = "ScatterNNlib", format = Documenter.HTML( canonical = "https://yuehhua.github.io/ScatterNNlib.jl/stable" ), pages=[ "Home" => "index.md", "Manual" => ["Scatter operations" => "manual/scatter.md", ] ], ) deploydocs(repo = "github.com/yuehhua/ScatterNNlib.jl")
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
917
module ScatterNNlib using CUDA using DataStructures: DefaultDict using FillArrays: Fill using Statistics: mean using StaticArrays: StaticArray using Zygote using ZygoteRules export # scatter scatter_add!, scatter_sub!, scatter_max!, scatter_min!, scatter_mul!, scatter_div!, scatter_mean!, scatter!, # gather gather const IntOrTuple = Union{Integer,Tuple} const ops = [:add, :sub, :mul, :div, :max, :min, :mean] const name2op = Dict(:add => :+, :sub => :-, :mul => :*, :div => :/) include("scatter/densearray.jl") include("scatter/staticarray.jl") include("interfaces.jl") include("grad.jl") include("gather.jl") include("utils.jl") if CUDA.functional() using CUDA: @cuda const MAX_THREADS = 1024 include("cuda/cuarray.jl") include("cuda/grad.jl") include("cuda/gather.jl") else @warn "CUDA unavailable, not loading CUDA support" end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
975
""" Inverse operation of scatter """ function gather(input::AbstractArray{T,N}, index::AbstractArray{<:Integer,N}, dims::Integer) where {T,N} @assert dims <= N "Specified dimensions must lower or equal to the rank of input matrix." out = similar(index, T) @inbounds for x = CartesianIndices(out) tup = collect(Tuple(x)) tup[dims] = index[x] view(out, x) .= view(input, tup...) end return out end function gather(input::Matrix{T}, index::Array{Int}) where T out = Array{T}(undef, size(input,1), size(index)...) @inbounds for ind = CartesianIndices(index) view(out, :, ind) .= view(input, :, index[ind]) end return out end gather(input::Fill{T,2,<:Any}, index::Array{Int}) where T = gather(Matrix(input), index) function gather_indices(X::Array{T}) where T Y = DefaultDict{T,Vector{CartesianIndex}}(CartesianIndex[]) @inbounds for (ind, val) = pairs(X) push!(Y[val], ind) end Y end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
2577
@adjoint function scatter_add!(ys::AbstractArray, us::AbstractArray, xs::AbstractArray) ys_ = copy(ys) scatter_add!(ys_, us, xs) ys_, Δ -> (Δ, gather(Δ, xs), nothing) end @adjoint function scatter_sub!(ys::AbstractArray, us::AbstractArray, xs::AbstractArray) ys_ = copy(ys) scatter_sub!(ys_, us, xs) ys_, Δ -> (Δ, -gather(Δ, xs), nothing) end @adjoint function scatter_mul!(ys::Array{T}, us::Array{T}, xs::Array{<:IntOrTuple}) where {T<:Real} ys_ = copy(ys) scatter_mul!(ys_, us, xs) ys_, function (Δ) Δy = Δ .+ zero(ys) scatter_mul!(Δy, us, xs) rev_xs = gather_indices(xs) Δu = gather(ys, xs) .* gather(Δ, xs) @inbounds for ind = CartesianIndices(xs) inds = filter(x -> x != ind, rev_xs[xs[ind]]) for i = 1:size(us, 1) Δu[i, ind] *= prod(j -> us[i, j], inds) end end (Δy, Δu, nothing) end end @adjoint function scatter_div!(ys::Array{T}, us::Array{T}, xs::Array{<:IntOrTuple}) where {T<:Real} ys_ = copy(ys) scatter_div!(ys_, us, xs) ys_, function (Δ) Δy = Δ .+ zero(ys) scatter_div!(Δy, us, xs) rev_xs = gather_indices(xs) Δu = - gather(ys, xs) .* gather(Δ, xs) ./ us.^2 @inbounds for ind = CartesianIndices(xs) inds = filter(x -> x != ind, rev_xs[xs[ind]]) for i = 1:size(us, 1) Δu[i, ind] /= prod(j -> us[i, j], inds) end end (Δy, Δu, nothing) end end @adjoint function scatter_max!(ys::Array{T}, us::Array{T}, xs::Array{<:IntOrTuple}) where {T<:Real} max = copy(ys) scatter_max!(max, us, xs) max, function (Δ) Δy = (ys .== max) .* Δ Δu = (us .== gather(max, xs)) .* gather(Δ, xs) (Δy, Δu, nothing) end end @adjoint function scatter_min!(ys::Array{T}, us::Array{T}, xs::Array{<:IntOrTuple}) where {T<:Real} min = copy(ys) scatter_min!(min, us, xs) min, function (Δ) Δy = (ys .== min) .* Δ Δu = (us .== gather(min, xs)) .* gather(Δ, xs) (Δy, Δu, nothing) end end @adjoint function scatter_mean!(ys::AbstractArray, us::AbstractArray, xs::AbstractArray) ys_ = copy(ys) scatter_mean!(ys_, us, xs) ys_, function (Δ) Δu = gather(Δ, xs) counts = zero.(xs) @inbounds for i = 1:size(ys, 2) counts += sum(xs.==i) * (xs.==i) end @inbounds for ind = CartesianIndices(counts) view(Δu, :, ind) ./= counts[ind] end (Δ, Δu, nothing) end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
539
## API function scatter!(op::Symbol, ys::AbstractArray, us::AbstractArray, xs::AbstractArray) if op == :add return scatter_add!(ys, us, xs) elseif op == :sub return scatter_sub!(ys, us, xs) elseif op == :mul return scatter_mul!(ys, us, xs) elseif op == :div return scatter_div!(ys, us, xs) elseif op == :max return scatter_max!(ys, us, xs) elseif op == :min return scatter_min!(ys, us, xs) elseif op == :mean return scatter_mean!(ys, us, xs) end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
133
""" save_div(x, y) Savely divde `x` by `y`. If `y` is zero, return `x` directly. """ save_div(x, y) = ifelse(iszero(y), x, x/y)
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
4006
# Integer for op = [:add, :sub, :max, :min, :and, :or, :xor] fn = Symbol("scatter_$(op)!") atm_op = Symbol("atomic_$(op)!") @eval function $fn(ys::CuMatrix{T}, us::CuArray{T}, xs::CuArray{Int}) where {T<:Integer} function kernel!(ys, us, xs) li = threadIdx().y + (blockIdx().y - 1) * blockDim().y i = threadIdx().x + (blockIdx().x - 1) * blockDim().x @inbounds if li <= length(xs) && i <= size(ys, 1) ind = CartesianIndices(xs)[li] j = Base._to_linear_index(ys, i, xs[li]) CUDA.$atm_op(pointer(ys, j), us[i, ind]) end return end thread_x = min(MAX_THREADS, size(ys, 1)) thread_y = min(MAX_THREADS ÷ thread_x, length(xs)) threads = (thread_x, thread_y) blocks = ceil.(Int, (size(ys, 1), length(xs)) ./ threads) @cuda blocks=blocks threads=threads kernel!(ys, us, xs) return ys end @eval function $fn(ys::CuArray{T}, us::CuArray{T}, xs::CuArray{<:Tuple}) where {T<:Integer} function kernel!(ys, us, xs) li = threadIdx().y + (blockIdx().y - 1) * blockDim().y i = threadIdx().x + (blockIdx().x - 1) * blockDim().x @inbounds if li <= length(xs) && i <= size(ys, 1) ind = CartesianIndices(xs)[li] j = Base._to_linear_index(ys, i, xs[li]...) CUDA.$atm_op(pointer(ys, j), us[i, ind]) end return end thread_x = min(MAX_THREADS, size(ys, 1)) thread_y = min(MAX_THREADS ÷ thread_x, length(xs)) threads = (thread_x, thread_y) blocks = ceil.(Int, (size(ys, 1), length(xs)) ./ threads) @cuda blocks=blocks threads=threads kernel!(ys, us, xs) return ys end end # Floating point for op = [:add, :sub, :mul, :div, :max, :min] fn = Symbol("scatter_$(op)!") atm_op = Symbol("atomic_$(op)!") @eval function $fn(ys::CuMatrix{T}, us::CuArray{T}, xs::CuArray{Int}) where {T<:AbstractFloat} function kernel!(ys::CuDeviceArray{T}, us::CuDeviceArray{T}, xs) i = threadIdx().x + (blockIdx().x - 1) * blockDim().x j = threadIdx().y + (blockIdx().y - 1) * blockDim().y @inbounds if i <= size(ys, 1) && j <= length(xs) ind = CartesianIndices(xs)[j] k = Base._to_linear_index(ys, i, xs[j]) CUDA.$atm_op(pointer(ys, k), us[i, ind]) end return end thread_i = min(MAX_THREADS, size(ys, 1)) thread_j = min(MAX_THREADS ÷ thread_i, length(xs)) threads = (thread_i, thread_j) blocks = ceil.(Int, (size(ys, 1), length(xs)) ./ threads) @cuda blocks=blocks threads=threads kernel!(ys, us, xs) return ys end @eval function $fn(ys::CuArray{T}, us::CuArray{T}, xs::CuArray{<:Tuple}) where {T<:AbstractFloat} function kernel!(ys::CuDeviceArray{T}, us::CuDeviceArray{T}, xs) i = threadIdx().x + (blockIdx().x - 1) * blockDim().x j = threadIdx().y + (blockIdx().y - 1) * blockDim().y @inbounds if i <= size(ys, 1) && j <= length(xs) ind = CartesianIndices(xs)[j] k = Base._to_linear_index(ys, i, xs[j]...) CUDA.$atm_op(pointer(ys, k), us[i, ind]) end return end thread_i = min(MAX_THREADS, size(ys, 1)) thread_j = min(MAX_THREADS ÷ thread_i, length(xs)) threads = (thread_i, thread_j) blocks = ceil.(Int, (size(ys, 1), length(xs)) ./ threads) @cuda blocks=blocks threads=threads kernel!(ys, us, xs) return ys end end function scatter_mean!(ys::CuMatrix{T}, us::CuArray{T}, xs::CuArray{<:IntOrTuple}) where {T<:AbstractFloat} yt = CUDA.zero(ys) ot = CUDA.zero(ys) os = CUDA.one.(us) scatter_add!(ot, os, xs) scatter_add!(yt, us, xs) ys .+= save_div.(yt, ot) return ys end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
650
gather(input::AbstractArray{T}, index::CuArray{Int}) where T = gather(cu(Array(input)), index) function gather(input::CuMatrix{T}, index::CuArray{Int}) where T out = CUDA.zeros(T, size(input,1), size(index)...) @inbounds for ind = CartesianIndices(index) view(out, :, ind) .= view(input, :, index[ind]) end return out end function gather_indices(X::CuArray{T}) where T Y = gather_indices(Array(X)) cuY = Dict{T,CuVector}(k => cu(Tuple.(v)) for (k, v) in Y) cuY end function numerical_cmp(X::CuArray{T}, Y::CuArray) where T Z = map((x,y) -> sign(x - y)^2, X, Y) Z = map(x -> (one(T) - x)^2, Z) Z end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
2187
@adjoint function scatter_mul!(ys::CuArray{T}, us::CuArray{T}, xs::CuArray) where {T<:AbstractFloat} ys_ = copy(ys) scatter_mul!(ys_, us, xs) ys_, function (Δ) Δy = zero(ys) .+ Δ scatter_mul!(Δy, us, xs) rev_xs = gather_indices(xs) Δu = gather(ys, xs) .* gather(zero(Δ)+Δ, xs) @inbounds for ind = CartesianIndices(xs) ind = Tuple(ind) inds = filter(x -> x != ind, rev_xs[xs[ind...]]) for i = 1:size(us, 1) multiplier = one(T) for j = inds multiplier *= us[i, j...] end Δu[i, ind...] *= multiplier end end (Δy, Δu, nothing) end end @adjoint function scatter_div!(ys::CuArray{T}, us::CuArray{T}, xs::CuArray) where {T<:AbstractFloat} ys_ = copy(ys) scatter_div!(ys_, us, xs) ys_, function (Δ) Δy = zero(ys) .+ Δ scatter_div!(Δy, us, xs) rev_xs = gather_indices(xs) Δu = - gather(ys, xs) Δu .*= gather(zero(Δ)+Δ, xs) Δu ./= us.^2 @inbounds for ind = CartesianIndices(xs) ind = Tuple(ind) inds = filter(x -> x != ind, rev_xs[xs[ind...]]) for i = 1:size(us, 1) denom = one(T) for j = inds denom *= us[i, j...] end Δu[i, ind...] /= denom end end (Δy, Δu, nothing) end end @adjoint function scatter_max!(ys::CuArray{T}, us::CuArray{T}, xs::CuArray) where {T<:AbstractFloat} max = copy(ys) scatter_max!(max, us, xs) max, function (Δ) Δy = numerical_cmp(ys, max) .* Δ Δu = gather(max, xs) Δu = numerical_cmp(us, Δu) Δu .*= gather(zero(Δ)+Δ, xs) (Δy, Δu, nothing) end end @adjoint function scatter_min!(ys::CuArray{T}, us::CuArray{T}, xs::CuArray) where {T<:AbstractFloat} min = copy(ys) scatter_min!(min, us, xs) min, function (Δ) Δy = numerical_cmp(ys, min) .* Δ Δu = gather(min, xs) Δu = numerical_cmp(us, Δu) Δu .*= gather(zero(Δ)+Δ, xs) (Δy, Δu, nothing) end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
6767
## Scatter operations """ scatter_add!(ys, us, xs) Scatter addition operation. ys[:, xs[k]...] = ys[:, xs[k]...] .+ us[:, k...] # Arguments - `ys`: the destination for `us` to aggregate to. This argument will be mutated. - `us`: the source data for aggregating. - `xs`: the mapping for aggregation from source (index) to destination (value). The index of `xs` is corresponding to the index of `us` and the value of `xs` is corresponding to the index of `ys`. The value of `xs` can be `Int` or `Tuple` type. The dimension of `us` must equal to one plus dimension of `xs`. `ys`, `us` and `xs` must be supported array type and be the same type.`Array`, `StaticArray` and `CuArray` are currently supported. """ function scatter_add! end """ scatter_sub!(ys, us, xs) Scatter subtraction operation. ys[:, xs[k]...] = ys[:, xs[k]...] .- us[:, k...] # Arguments - `ys`: the destination for `us` to aggregate to. This argument will be mutated. - `us`: the source data for aggregating. - `xs`: the mapping for aggregation from source (index) to destination (value). The index of `xs` is corresponding to the index of `us` and the value of `xs` is corresponding to the index of `ys`. The value of `xs` can be `Int` or `Tuple` type. The dimension of `us` must equal to one plus dimension of `xs`. `ys`, `us` and `xs` must be supported array type and be the same type.`Array`, `StaticArray` and `CuArray` are currently supported. """ function scatter_sub! end """ scatter_mul!(ys, us, xs) Scatter multiplication operation. ys[:, xs[k]...] = ys[:, xs[k]...] .* us[:, k...] # Arguments - `ys`: the destination for `us` to aggregate to. This argument will be mutated. - `us`: the source data for aggregating. - `xs`: the mapping for aggregation from source (index) to destination (value). The index of `xs` is corresponding to the index of `us` and the value of `xs` is corresponding to the index of `ys`. The value of `xs` can be `Int` or `Tuple` type. The dimension of `us` must equal to one plus dimension of `xs`. `ys`, `us` and `xs` must be supported array type and be the same type.`Array`, `StaticArray` and `CuArray` are currently supported. """ function scatter_mul! end """ scatter_div!(ys, us, xs) Scatter division operation. ys[:, xs[k]...] = ys[:, xs[k]...] ./ us[:, k...] # Arguments - `ys`: the destination for `us` to aggregate to. This argument will be mutated. - `us`: the source data for aggregating. - `xs`: the mapping for aggregation from source (index) to destination (value). The index of `xs` is corresponding to the index of `us` and the value of `xs` is corresponding to the index of `ys`. The value of `xs` can be `Int` or `Tuple` type. The dimension of `us` must equal to one plus dimension of `xs`. `ys`, `us` and `xs` must be supported array type and be the same type.`Array`, `StaticArray` and `CuArray` are currently supported. """ function scatter_div! end for op = [:add, :sub, :mul, :div] fn = Symbol("scatter_$(op)!") @eval function $fn(ys::Array{T}, us::Array{T}, xs::Array{<:IntOrTuple}) where {T<:Real} @simd for k = 1:length(xs) k = CartesianIndices(xs)[k] ys_v = view(ys, :, xs[k]...) us_v = view(us, :, k) @inbounds ys_v .= $(name2op[op]).(ys_v, us_v) end ys end end """ scatter_max!(ys, us, xs) Scatter maximum operation. ys[:, xs[k]...] = max.(ys[:, xs[k]...], us[:, k...]) # Arguments - `ys`: the destination for `us` to aggregate to. This argument will be mutated. - `us`: the source data for aggregating. - `xs`: the mapping for aggregation from source (index) to destination (value). The index of `xs` is corresponding to the index of `us` and the value of `xs` is corresponding to the index of `ys`. The value of `xs` can be `Int` or `Tuple` type. The dimension of `us` must equal to one plus dimension of `xs`. `ys`, `us` and `xs` must be supported array type and be the same type.`Array`, `StaticArray` and `CuArray` are currently supported. """ function scatter_max!(ys::Array{T}, us::Array{T}, xs::Array{<:IntOrTuple}) where {T<:Real} @simd for k = 1:length(xs) k = CartesianIndices(xs)[k] ys_v = view(ys, :, xs[k]...) us_v = view(us, :, k) @inbounds view(ys, :, xs[k]...) .= max.(ys_v, us_v) end ys end """ scatter_min!(ys, us, xs) Scatter minimum operation. ys[:, xs[k]...] = min.(ys[:, xs[k]...], us[:, k...]) # Arguments - `ys`: the destination for `us` to aggregate to. This argument will be mutated. - `us`: the source data for aggregating. - `xs`: the mapping for aggregation from source (index) to destination (value). The index of `xs` is corresponding to the index of `us` and the value of `xs` is corresponding to the index of `ys`. The value of `xs` can be `Int` or `Tuple` type. The dimension of `us` must equal to one plus dimension of `xs`. `ys`, `us` and `xs` must be supported array type and be the same type.`Array`, `StaticArray` and `CuArray` are currently supported. """ function scatter_min!(ys::Array{T}, us::Array{T}, xs::Array{<:IntOrTuple}) where {T<:Real} @simd for k = 1:length(xs) k = CartesianIndices(xs)[k] ys_v = view(ys, :, xs[k]...) us_v = view(us, :, k) @inbounds ys_v .= min.(ys_v, us_v) end ys end """ scatter_mean!(ys, us, xs) Scatter mean operation. ys[:, xs[k]...] = mean.(ys[:, xs[k]...], us[:, k...]) # Arguments - `ys`: the destination for `us` to aggregate to. This argument will be mutated. - `us`: the source data for aggregating. - `xs`: the mapping for aggregation from source (index) to destination (value). The index of `xs` is corresponding to the index of `us` and the value of `xs` is corresponding to the index of `ys`. The value of `xs` can be `Int` or `Tuple` type. The dimension of `us` must equal to one plus dimension of `xs`. `ys`, `us` and `xs` must be supported array type and be the same type.`Array`, `StaticArray` and `CuArray` are currently supported. """ function scatter_mean!(ys::Array{T}, us::Array{T}, xs::Array{<:IntOrTuple}) where {T<:Real} Ns = zero(ys) ys_ = zero(ys) scatter_add!(Ns, one.(us), xs) scatter_add!(ys_, us, xs) ys .+= save_div.(ys_, Ns) return ys end # Support different types of array for op = ops fn = Symbol("scatter_$(op)!") @eval function $fn(ys::Array{T}, us::Array{S}, xs::Array{<:IntOrTuple}) where {T<:Real,S<:Real} PT = promote_type(T, S) $fn(PT.(ys), PT.(us), xs) end @eval function $fn(ys::StaticArray{<:Tuple,T}, us::StaticArray{<:Tuple,S}, xs::StaticArray{<:Tuple,<:IntOrTuple}) where {T<:Real,S<:Real} PT = promote_type(T, S) $fn(PT.(ys), PT.(us), xs) end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
1519
## Scatter operations for StaticArray for op = [:add, :sub, :mul, :div] fn = Symbol("scatter_$(op)!") @eval function $fn(ys::StaticArray{<:Tuple,T}, us::StaticArray{<:Tuple,T}, xs::StaticArray{<:Tuple,<:IntOrTuple}) where {T<:Real} @simd for k = 1:length(xs) k = CartesianIndices(xs)[k] ys_v = view(ys, :, xs[k]...) us_v = view(us, :, k) @inbounds ys_v .= $(name2op[op]).(ys_v, us_v) end ys end end function scatter_max!(ys::StaticArray{<:Tuple,T}, us::StaticArray{<:Tuple,T}, xs::StaticArray{<:Tuple,<:IntOrTuple}) where {T<:Real} @simd for k = 1:length(xs) k = CartesianIndices(xs)[k] ys_v = view(ys, :, xs[k]...) us_v = view(us, :, k) @inbounds ys_v .= max.(ys_v, us_v) end ys end function scatter_min!(ys::StaticArray{<:Tuple,T}, us::StaticArray{<:Tuple,T}, xs::StaticArray{<:Tuple,<:IntOrTuple}) where {T<:Real} @simd for k = 1:length(xs) k = CartesianIndices(xs)[k] ys_v = view(ys, :, xs[k]...) us_v = view(us, :, k) @inbounds ys_v .= min.(ys_v, us_v) end ys end function scatter_mean!(ys::StaticArray{<:Tuple,T}, us::StaticArray{<:Tuple,T}, xs::StaticArray{<:Tuple,<:IntOrTuple}) where {T<:Real} Ns = zero(ys) ys_ = zero(ys) scatter_add!(Ns, one.(us), xs) scatter_add!(ys_, us, xs) ys .+= save_div.(ys_, Ns) return ys end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
719
@testset "gather" begin @testset "3-argumented" begin X = [1 2 3; 4 5 6] ind1 = [1 2 2; 1 1 1] ind2 = [1 2; 3 1] for T = [Int8, Int16, Int32, Int64, Int128, Float16, Float32, Float64] @test gather(T.(X), ind1, 1) == T.([1 5 6; 1 2 3]) @test gather(T.(X), ind2, 2) == T.([1 2; 6 4]) end end @testset "2-argumented" begin input = [3 3 4 4 5; 5 5 6 6 7] index = [1 2 3 4; 4 2 1 3; 3 5 5 3] output = cat([3 4 4; 5 6 6], [3 3 5; 5 5 7], [4 3 5; 6 5 7], [4 4 4; 6 6 6], dims=3) @test gather(input, index) == output end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
2308
ys = [3. 3. 4. 4. 5.; 5. 5. 6. 6. 7.] us = 2*ones(2, 3, 4) xs = [1 2 3 4; 4 2 1 3; 3 5 5 3] ∇y_mul = [4. 4. 16. 4. 4.; 4. 4. 16. 4. 4.] ∇y_div = [.25 .25 .0625 .25 .25; .25 .25 .0625 .25 .25] ∇u_mean = cat([.5 .5 .25; .5 .5 .25], [.5 .5 .5; .5 .5 .5], [.25 .5 .5; .25 .5 .5], [.5 .25 .25; .5 .25 .25], dims=3) @testset "grad" begin @testset "scatter" begin @test Zygote.gradient(x -> sum(scatter_add!(x, us, xs)), ys) == (ones(2, 5),) @test Zygote.gradient(x -> sum(scatter_add!(copy(ys), x, xs)), us) == (ones(2, 3, 4),) @test Zygote.gradient(x -> sum(scatter_add!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_sub!(x, us, xs)), ys) == (ones(2, 5),) @test Zygote.gradient(x -> sum(scatter_sub!(copy(ys), x, xs)), us) == (-ones(2, 3, 4),) @test Zygote.gradient(x -> sum(scatter_sub!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_max!(x, us, xs)), ys) == (ones(2, 5),) @test Zygote.gradient(x -> sum(scatter_max!(copy(ys), x, xs)), us) == (zeros(2, 3, 4),) @test Zygote.gradient(x -> sum(scatter_max!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_min!(x, us, xs)), ys) == (zeros(2, 5),) @test Zygote.gradient(x -> sum(scatter_min!(copy(ys), x, xs)), us) == (ones(2, 3, 4),) @test Zygote.gradient(x -> sum(scatter_min!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_mul!(x, us, xs)), ys) == (∇y_mul,) @test Zygote.gradient(x -> sum(scatter_mul!(copy(ys), x, xs)), us) == (2048*gather(ys, xs),) @test Zygote.gradient(x -> sum(scatter_mul!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_div!(x, us, xs)), ys) == (∇y_div,) @test Zygote.gradient(x -> sum(scatter_div!(copy(ys), x, xs)), us) == (-gather(ys, xs)/8192,) @test Zygote.gradient(x -> sum(scatter_div!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_mean!(x, us, xs)), ys) == (ones(2, 5),) @test Zygote.gradient(x -> sum(scatter_mean!(copy(ys), x, xs)), us) == (∇u_mean,) @test Zygote.gradient(x -> sum(scatter_mean!(copy(ys), us, x)), xs) == (nothing,) end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
448
using ScatterNNlib using StaticArrays: @MMatrix, @MArray using Zygote using CUDA using Test cuda_tests = [ "cuda/cuarray", "cuda/grad", ] tests = [ "scatter/densearray", "scatter/staticarray", "grad", "gather", ] if CUDA.functional() append!(tests, cuda_tests) else @warn "CUDA unavailable, not testing CUDA support" end @testset "ScatterNNlib.jl" begin for t in tests include("$(t).jl") end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
5258
ys = cu([3 3 4 4 5; 5 5 6 6 7]) us = cu(ones(Int, 2, 3, 4)) xs = CuArray{Int64}([1 2 3 4; 4 2 1 3; 3 5 5 3]) xs_tup = CuArray([(1,) (2,) (3,) (4,); (4,) (2,) (1,) (3,); (3,) (5,) (5,) (3,)]) @testset "cuda/scatter" begin for T = [UInt32, UInt64, Int32, Int64] @testset "$(T)" begin @testset "add" begin ys_ = cu([5 5 8 6 7; 7 7 10 8 9]) @test scatter_add!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter!(:add, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_add!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter!(:add, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "sub" begin ys_ = cu([1 1 0 2 3; 3 3 2 4 5]) @test scatter_sub!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter!(:sub, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_sub!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter!(:sub, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "max" begin ys_ = cu([3 3 4 4 5; 5 5 6 6 7]) @test scatter_max!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter!(:max, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_max!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter!(:max, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "min" begin ys_ = cu([1 1 1 1 1; 1 1 1 1 1]) @test scatter_min!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter!(:min, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_min!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter!(:min, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end end end for T = [Float32, Float64] @testset "$(T)" begin @testset "add" begin ys_ = cu([5 5 8 6 7; 7 7 10 8 9]) @test scatter_add!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter!(:add, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_add!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter!(:add, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "sub" begin ys_ = cu([1 1 0 2 3; 3 3 2 4 5]) @test scatter_sub!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter!(:sub, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_sub!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter!(:sub, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "max" begin ys_ = cu([3 3 4 4 5; 5 5 6 6 7]) @test scatter_max!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter!(:max, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_max!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter!(:max, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "min" begin ys_ = cu([1 1 1 1 1; 1 1 1 1 1]) @test scatter_min!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter!(:min, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_min!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter!(:min, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "mul" begin ys_ = cu([3 3 4 4 5; 5 5 6 6 7]) @test scatter_mul!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter!(:mul, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_mul!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter!(:mul, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "div" begin us_div = us .* 2 ys_ = cu([0.75 0.75 0.25 1. 1.25; 1.25 1.25 0.375 1.5 1.75]) @test scatter_div!(T.(copy(ys)), T.(us_div), xs) == T.(ys_) @test scatter!(:div, T.(copy(ys)), T.(us_div), xs) == T.(ys_) @test scatter_div!(T.(copy(ys)), T.(us_div), xs_tup) == T.(ys_) @test scatter!(:div, T.(copy(ys)), T.(us_div), xs_tup) == T.(ys_) end @testset "mean" begin ys_ = cu([4 4 5 5 6; 6 6 7 7 8]) @test scatter_mean!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter!(:mean, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_mean!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter!(:mean, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end end end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
2370
ys = cu([3. 3. 4. 4. 5.; 5. 5. 6. 6. 7.]) us = cu(2*ones(2, 3, 4)) xs = CuArray{Int64}([1 2 3 4; 4 2 1 3; 3 5 5 3]) ∇y_mul = [4. 4. 16. 4. 4.; 4. 4. 16. 4. 4.] ∇y_div = [.25 .25 .0625 .25 .25; .25 .25 .0625 .25 .25] ∇u_mean = cat([.5 .5 .25; .5 .5 .25], [.5 .5 .5; .5 .5 .5], [.25 .5 .5; .25 .5 .5], [.5 .25 .25; .5 .25 .25], dims=3) @testset "cuda/grad" begin @testset "scatter" begin @test Zygote.gradient(x -> sum(scatter_add!(x, us, xs)), ys) == (ones(2, 5),) @test Zygote.gradient(x -> sum(scatter_add!(copy(ys), x, xs)), us) == (ones(2, 3, 4),) @test Zygote.gradient(x -> sum(scatter_add!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_sub!(x, us, xs)), ys) == (ones(2, 5),) @test Zygote.gradient(x -> sum(scatter_sub!(copy(ys), x, xs)), us) == (-ones(2, 3, 4),) @test Zygote.gradient(x -> sum(scatter_sub!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_max!(x, us, xs)), ys) == (ones(2, 5),) @test Zygote.gradient(x -> sum(scatter_max!(copy(ys), x, xs)), us) == (zeros(2, 3, 4),) @test Zygote.gradient(x -> sum(scatter_max!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_min!(x, us, xs)), ys) == (zeros(2, 5),) @test Zygote.gradient(x -> sum(scatter_min!(copy(ys), x, xs)), us) == (ones(2, 3, 4),) @test Zygote.gradient(x -> sum(scatter_min!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_mul!(x, us, xs)), ys) == (∇y_mul,) @test Zygote.gradient(x -> sum(scatter_mul!(copy(ys), x, xs)), us) == (2048*gather(ys, xs),) @test Zygote.gradient(x -> sum(scatter_mul!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_div!(x, us, xs)), ys) == (∇y_div,) @test Zygote.gradient(x -> sum(scatter_div!(copy(ys), x, xs)), us) == (-gather(ys, xs)/8192,) @test Zygote.gradient(x -> sum(scatter_div!(copy(ys), us, x)), xs) == (nothing,) @test Zygote.gradient(x -> sum(scatter_mean!(x, us, xs)), ys) == (ones(2, 5),) @test Zygote.gradient(x -> sum(scatter_mean!(copy(ys), x, xs)), us) == (∇u_mean,) @test Zygote.gradient(x -> sum(scatter_mean!(copy(ys), us, x)), xs) == (nothing,) end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
5744
ys = [3 3 4 4 5; 5 5 6 6 7] us = ones(Int, 2, 3, 4) xs = [1 2 3 4; 4 2 1 3; 3 5 5 3] xs_tup = [(1,) (2,) (3,) (4,); (4,) (2,) (1,) (3,); (3,) (5,) (5,) (3,)] types = [UInt8, UInt16, UInt32, UInt64, UInt128, Int8, Int16, Int32, Int64, Int128, BigInt, Float16, Float32, Float64, BigFloat, Rational] @testset "scatter/densearray" begin for T = types @testset "$T" begin PT = promote_type(T, Int) @testset "scatter_add!" begin ys_ = [5 5 8 6 7; 7 7 10 8 9] @test scatter_add!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_add!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_add!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:add, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_add!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_add!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_add!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:add, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "scatter_sub!" begin ys_ = [1 1 0 2 3; 3 3 2 4 5] @test scatter_sub!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_sub!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_sub!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:sub, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_sub!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_sub!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_sub!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:sub, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "scatter_max!" begin ys_ = [3 3 4 4 5; 5 5 6 6 7] @test scatter_max!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_max!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_max!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:max, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_max!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_max!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_max!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:max, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "scatter_min!" begin ys_ = [1 1 1 1 1; 1 1 1 1 1] @test scatter_min!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_min!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_min!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:min, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_min!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_min!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_min!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:min, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "scatter_mul!" begin ys_ = [3 3 4 4 5; 5 5 6 6 7] @test scatter_mul!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_mul!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_mul!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:mul, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_mul!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_mul!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_mul!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:mul, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end end end for T = [Float16, Float32, Float64, BigFloat, Rational] @testset "$T" begin PT = promote_type(T, Float64) @testset "scatter_div!" begin us_div = us .* 2 ys_ = [0.75 0.75 0.25 1. 1.25; 1.25 1.25 0.375 1.5 1.75] @test scatter_div!(T.(copy(ys)), T.(us_div), xs) == T.(ys_) @test scatter_div!(T.(copy(ys)), us_div, xs) == PT.(ys_) @test scatter_div!(copy(ys), T.(us_div), xs) == PT.(ys_) @test scatter!(:div, T.(copy(ys)), T.(us_div), xs) == T.(ys_) @test scatter_div!(T.(copy(ys)), T.(us_div), xs_tup) == T.(ys_) @test scatter_div!(T.(copy(ys)), us_div, xs_tup) == PT.(ys_) @test scatter_div!(copy(ys), T.(us_div), xs_tup) == PT.(ys_) @test scatter!(:div, T.(copy(ys)), T.(us_div), xs_tup) == T.(ys_) end @testset "scatter_mean!" begin ys_ = [4. 4. 5. 5. 6.; 6. 6. 7. 7. 8.] @test scatter_mean!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_mean!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_mean!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:mean, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_mean!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_mean!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_mean!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:mean, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end end end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
code
5616
ys = @MMatrix [3 3 4 4 5; 5 5 6 6 7] us = @MArray ones(Int, 2, 3, 4) xs = @MMatrix [1 2 3 4; 4 2 1 3; 3 5 5 3] xs_tup = @MMatrix [(1,) (2,) (3,) (4,); (4,) (2,) (1,) (3,); (3,) (5,) (5,) (3,)] types = [UInt8, UInt16, UInt32, UInt64, UInt128, Int8, Int16, Int32, Int64, Int128, Float16, Float32, Float64, Rational] @testset "scatter/staticarray" begin for T = types @testset "$T" begin PT = promote_type(T, Int) @testset "scatter_add!" begin ys_ = @MMatrix [5 5 8 6 7; 7 7 10 8 9] @test scatter_add!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_add!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_add!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:add, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_add!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_add!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_add!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:add, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "scatter_sub!" begin ys_ = @MMatrix [1 1 0 2 3; 3 3 2 4 5] @test scatter_sub!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_sub!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_sub!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:sub, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_sub!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_sub!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_sub!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:sub, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "scatter_max!" begin ys_ = @MMatrix [3 3 4 4 5; 5 5 6 6 7] @test scatter_max!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_max!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_max!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:max, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_max!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_max!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_max!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:max, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "scatter_min!" begin ys_ = @MMatrix [1 1 1 1 1; 1 1 1 1 1] @test scatter_min!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_min!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_min!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:min, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_min!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_min!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_min!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:min, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end @testset "scatter_mul!" begin ys_ = @MMatrix [3 3 4 4 5; 5 5 6 6 7] @test scatter_mul!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_mul!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_mul!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:mul, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_mul!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_mul!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_mul!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:mul, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end end end for T = [Float16, Float32, Float64, Rational] @testset "$T" begin PT = promote_type(T, Float64) @testset "scatter_div!" begin us_div = us .* 2 ys_ = @MMatrix [0.75 0.75 0.25 1. 1.25; 1.25 1.25 0.375 1.5 1.75] @test scatter_div!(T.(copy(ys)), T.(us_div), xs) == T.(ys_) @test scatter_div!(T.(copy(ys)), us_div, xs) == PT.(ys_) @test scatter_div!(copy(ys), T.(us_div), xs) == PT.(ys_) @test scatter!(:div, T.(copy(ys)), T.(us_div), xs) == T.(ys_) @test scatter_div!(T.(copy(ys)), T.(us_div), xs_tup) == T.(ys_) @test scatter_div!(T.(copy(ys)), us_div, xs_tup) == PT.(ys_) @test scatter_div!(copy(ys), T.(us_div), xs_tup) == PT.(ys_) @test scatter!(:div, T.(copy(ys)), T.(us_div), xs_tup) == T.(ys_) end @testset "scatter_mean!" begin ys_ = @MMatrix [4. 4. 5. 5. 6.; 6. 6. 7. 7. 8.] @test scatter_mean!(T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_mean!(T.(copy(ys)), us, xs) == PT.(ys_) @test scatter_mean!(copy(ys), T.(us), xs) == PT.(ys_) @test scatter!(:mean, T.(copy(ys)), T.(us), xs) == T.(ys_) @test scatter_mean!(T.(copy(ys)), T.(us), xs_tup) == T.(ys_) @test scatter_mean!(T.(copy(ys)), us, xs_tup) == PT.(ys_) @test scatter_mean!(copy(ys), T.(us), xs_tup) == PT.(ys_) @test scatter!(:mean, T.(copy(ys)), T.(us), xs_tup) == T.(ys_) end end end end
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
docs
563
# Changelog All notable changes to this project will be documented in this file. ## [0.1.7] - Support CUDA up to v2.6 - Support FillArrays v0.11 - Support Zygote v0.6 ## [0.1.6] - Support Julia v1.6 - Support StaticArrays v1.0 ## [0.1.5] - Support CUDA v2.2 and v2.3 ## [0.1.4] - Support CUDA v2.1 - Support FillArrays v0.10 ## [0.1.3] - Add doc page - Bump CUDA to v2.0 - Not support bool type ## [0.1.2] - Increase test coverage for dense array, static array and cuarray - Add benchmark ## [0.1.1] - Add CUDA utilities to fix computation on CUDA
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
docs
866
# ScatterNNlib.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://yuehhua.github.io/ScatterNNlib.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://yuehhua.github.io/ScatterNNlib.jl/dev) A scatter operation library for neural network ## Benchmark Scatter operations are fundamental to ScatterNNlib.jl and they are implemented in CPU and CUDA version. Benchmarks of scatter operations are done with scripts in benchmark folder. Statistics, includes max, min and mean, are shown in the following plots. ![](benchmark/pics/cpu_scatter.svg) ![](benchmark/pics/gpu_scatter.svg) Performance of scatter add operations in ScatterNNlib is better than Pytorch_scatter on cuda. > Version: > * CUDA 10.2 > * Python 3.7, Pytorch 1.6.0, Pytorch scatter 2.0.5 > * Julia v1.5.0, CUDA v1.2.1, Flux v0.11.0, ScatterNNlib v0.1.1
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
docs
116
```@meta CurrentModule = ScatterNNlib ``` # ScatterNNlib ```@index ``` ```@autodocs Modules = [ScatterNNlib] ```
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.1.7
aff60eb73e9fd0d230e39d4ea5a7100334986861
docs
211
# Scatter operations ```@docs scatter_add! ``` ```@docs scatter_sub! ``` ```@docs scatter_mul! ``` ```@docs scatter_div! ``` ```@docs scatter_max! ``` ```@docs scatter_min! ``` ```@docs scatter_mean! ```
ScatterNNlib
https://github.com/yuehhua/ScatterNNlib.jl.git
[ "MIT" ]
0.7.0
a84ae6da7e44400b4d1df7684ac85e98f06765f3
code
653
using Bumper open("Docstrings.md", "w+") do io println(io, "# Docstrings\n") println(io, "## User API\n") for s ∈ (Symbol("@no_escape"), Symbol("@alloc"), Symbol("@alloc_ptr"), :default_buffer, :SlabBuffer, :reset_buffer!, :with_buffer) println(io, Base.Docs.doc(Base.Docs.Binding(Bumper, s))) println(io, "---------------------------------------") end println(io, "## Allocator API\n") for s ∈ (:alloc_ptr!, :alloc!, :checkpoint_save, :checkpoint_restore!) println(io, Base.Docs.doc(Base.Docs.Binding(Bumper, s))) println(io, "---------------------------------------") end end
Bumper
https://github.com/MasonProtter/Bumper.jl.git
[ "MIT" ]
0.7.0
a84ae6da7e44400b4d1df7684ac85e98f06765f3
code
2269
module AllocBufferImpl import Bumper: alloc_ptr!, checkpoint_save, checkpoint_restore!, default_buffer, reset_buffer!, with_buffer const default_buffer_size = 1_048_576 """ AllocBuffer{StorageType} This is a simple bump allocator that could be used to store a fixed amount of memory of type `StorageType`, so long as `::StoreageType` supports `pointer`, and `sizeof`. Do not manually manipulate the fields of an AllocBuffer that is in use. """ mutable struct AllocBuffer{Store} buf::Store offset::UInt end AllocBuffer(max_size::Int) = AllocBuffer(Vector{UInt8}(undef, max_size), UInt(0)) AllocBuffer(storage) = AllocBuffer(storage, UInt(0)) """ AllocBuffer() -> AllocBuffer{Vector{UInt8}} Create an `AllocBuffer` which can hold at most $default_buffer_size bytes. """ AllocBuffer() = AllocBuffer(Vector{UInt8}(undef, UInt(default_buffer_size))) const default_buffer_key = gensym(:buffer) """ default_buffer(::Type{AllocBuffer}) -> AllocBuffer{Vector{UInt8}} Return the current task-local default `AllocBuffer`, if one does not exist in the current task, it will create one automatically. This currently can only create `AllocBuffer{Vector{UInt8}}`, and you cannot adjust the memory size it creates ($default_buffer_size bytes). """ function default_buffer(::Type{AllocBuffer}) get!(() -> AllocBuffer(), task_local_storage(), default_buffer_key)::AllocBuffer{Vector{UInt8}} end with_buffer(f, b::AllocBuffer{Vector{UInt8}}) = task_local_storage(f, default_buffer_key, b) function reset_buffer!(b::AllocBuffer = default_buffer()) b.offset = UInt(0) nothing end struct AllocCheckpoint{Store} buf::AllocBuffer{Store} offset::UInt end function checkpoint_save(buf::AllocBuffer) AllocCheckpoint(buf, buf.offset) end function checkpoint_restore!(cp::AllocCheckpoint) cp.buf.offset = cp.offset nothing end function alloc_ptr!(b::AllocBuffer, sz::Int)::Ptr{Cvoid} ptr = pointer(b.buf) + b.offset b.offset += sz b.offset > sizeof(b.buf) && oom_error() ptr end @noinline function oom_error() error("alloc: Buffer out of memory. This might be a sign of a memory leak. Use Bumper.reset_buffer!(b::AllocBuffer) to reclaim its memory.") end end # module AllocBufferImpl
Bumper
https://github.com/MasonProtter/Bumper.jl.git
[ "MIT" ]
0.7.0
a84ae6da7e44400b4d1df7684ac85e98f06765f3
code
5611
module Bumper export SlabBuffer, AllocBuffer, @alloc, @alloc_ptr, default_buffer, @no_escape, with_buffer using UnsafeArrays: UnsafeArrays, UnsafeArray """ @no_escape([buf=default_buffer()], expr) Record the current state of `buf` (which defaults to the `default_buffer()` if there is only one argument), and then run the code in `expr` and then reset `buf` back to the state it was in before the code ran. This allows us to allocate memory within the `expr` using `@alloc`, and then have those arrays be automatically de-allocated once the expression is over. This is a restrictive but highly efficient form of memory management. See also `Bumper.checkpoint_save`, and `Bumper.checkpoint_restore!`. Using `return`, `@goto`, and `@label` are not allowed inside of `@no_escape` block. Example: function f(x::Vector{Int}) # Set up a scope where memory may be allocated, and does not escape: @no_escape begin # Allocate a `UnsafeArray` from UnsafeArrays.jl using memory from the default buffer. y = @alloc(Int, length(x)) # Now do some stuff with that vector: y .= x .+ 1 sum(y) end end """ macro no_escape end """ @alloc(T, n::Int...) -> UnsafeArray{T, length(n)} This can be used inside a `@no_escape` block to allocate a `UnsafeArray` whose dimensions are determined by `n`. The memory used to allocate this array will come from the buffer associated with the enclosing `@no_escape` block. Do not allow any references to this array to escape the enclosing `@no_escape` block, and do not pass these arrays to concurrent tasks unless that task is guaranteed to terminate before the `@no_escape` block ends. Any array allocated in this way which is found outside of its parent `@no_escape` block has undefined contents, and writing to this pointer will have undefined behaviour. """ macro alloc(args...) error("The @alloc macro may only be used inside of a @no_escape block.") end """ @alloc_ptr(n::Integer) -> Ptr{Nothing} This can be used inside a `@no_escape` block to allocate a pointer which can hold `n` bytes. The memory used to allocate this pointer will come from the buffer associated with the enclosing `@no_escape` block. Do not allow any references to this pointer to escape the enclosing `@no_escape` block, and do not pass these pointers to concurrent tasks unless that task is guaranteed to terminate before the `@no_escape` block ends. Any pointer allocated in this way which is found outside of its parent `@no_escape` block has undefined contents, and writing to this pointer will have undefined behaviour. """ macro alloc_ptr(args...) error("The @alloc_ptr macro may only be used inside of a @no_escape block.") end function default_buffer end """ Bumper.alloc!(b, ::Type{T}, n::Int...) -> UnsafeArray{T, length(n)} Function-based alternative to `@alloc` which allocates onto a specified allocator `b`. You must obey all the rules from `@alloc`, but you can use this outside of the lexical scope of `@no_escape` for specific (but dangerous!) circumstances where you cannot avoid a scope barrier between the two. """ function alloc! end """ Bumper.alloc_ptr!(b, n::Int) -> Ptr{Nothing} Take a pointer which can store at least `n` bytes from the allocator `b`. """ function alloc_ptr! end """ with_buffer(f, buf) Execute the function `f()` in a context where `default_buffer()` will return `buf` instead of the normal `default_buffer`. This currently only works with `SlabBuffer{1_048_576}`, and `AllocBuffer{Vector{UInt8}}`. Example: julia> let b1 = default_buffer() b2 = SlabBuffer() with_buffer(b2) do @show default_buffer() == b2 end @show default_buffer() == b1 end default_buffer() == b2 = true default_buffer() == b1 = true true """ function with_buffer end allow_ptr_array_to_escape() = false """ Bumper.reset_buffer!(buf=default_buffer()) This resets a buffer to its default state, effectively making it like a freshly allocated buffer. This might be necessary to use if you accidentally over-allocate a buffer or screw up its state in some other way. """ function reset_buffer! end """ Bumper.checkpoint_save(buf = default_buffer()) Returns a checkpoint object `cp` which stores the state of a `buf` at a given point in a program. One can then use `Bumper.checkpoint_restore!(cp)` to later on restore the state of the buffer to it's earlier saved state, undoing any bump allocations which happened in the meantime on that buffer. Users should prefer to use `@no_escape` instead of `checkpoint_save` and `checkpoint_restore`, which is a safer and more structured way of doing the same thing. """ function checkpoint_save end """ Bumper.checkpoint_restore!(cp) Restore a buffer (the one used to create `cp`) to the state it was in when the checkpoint was created, undoing any bump allocations which happened in the meantime on that buffer. See also `Bumper.checkpoint_save` Users should prefer to use `@no_escape` instead of `checkpoint_save` and `checkpoint_restore`, which is a safer and more structured way of doing the same thing. """ function checkpoint_restore! end ## Private # ------------------------------------------------------ include("internals.jl") # module Internals ## Allocator implementations # ------------------------------------------------------ include("SlabBuffer.jl") import .SlabBufferImpl: SlabBuffer include("AllocBuffer.jl") import .AllocBufferImpl: AllocBuffer end # Bumper
Bumper
https://github.com/MasonProtter/Bumper.jl.git
[ "MIT" ]
0.7.0
a84ae6da7e44400b4d1df7684ac85e98f06765f3
code
6458
module SlabBufferImpl import Bumper: alloc_ptr!, checkpoint_save, checkpoint_restore!, reset_buffer!, default_buffer, with_buffer import Bumper.Internals: malloc, free const default_slab_size = 1_048_576 """ mutable struct SlabBuffer{SlabSize} A slab-based bump allocator which can dynamically grow to hold an arbitrary amount of memory. Small allocations live within a specific slab of memory, and if that slab fills up, a new slab is allocated and future allocations happen on that slab. Small allocations are stored in slabs of size `SlabSize` bytes, and the list of live slabs are tracked in the `slabs` field. Allocations which are too large to fit into one slab are stored and tracked in the `custom_slabs` field. The default slab size is $default_slab_size bytes. `SlabBuffer`s are nearly as fast as stack allocation (typically up to within a couple of nanoseconds) for typical use. One potential performance pitfall is if that `SlabBuffer`'s current position is at the end of a slab, then the next allocation will be slow because it requires a new slab to be created. This means that if you do something like buf = SlabBuffer{N}() @no_escape buf begin @alloc(Int8, N÷2 - 1) # Take up just under half the first slab @alloc(Int8, N÷2 - 1) # Take up another half of the first slab # Now buf should be practically out of room. for i in 1:1000 @no_escape buf begin y = @alloc(Int8, 10) # This will allocate a new slab because there's no room f(y) end # At the end of this block, we delete the new slab because it's not needed. end end then the inner loop will run slower than normal because at each iteration, a new slab of size `N` bytes must be freshly allocated. This should be a rare occurance, but is possible to encounter. Do not manipulate the fields of a SlabBuffer that is in use. """ mutable struct SlabBuffer{SlabSize} current ::Ptr{Cvoid} slab_end ::Ptr{Cvoid} slabs ::Vector{Ptr{Cvoid}} custom_slabs ::Vector{Ptr{Cvoid}} function SlabBuffer{_SlabSize}(; finalize::Bool=true) where {_SlabSize} SlabSize = convert(Int, _SlabSize) current = malloc(SlabSize) slab_end = current + SlabSize slabs = [current] custom_slabs = Ptr{Cvoid}[] buf = new{SlabSize}(current, slab_end, slabs, custom_slabs) finalize && finalizer(free, buf) buf end end @doc """ SlabBuffer{SlabSize}(;finalize::Bool = true) Create a slab allocator whose slabs are of size `SlabSize`. If you set the `finalize` keyword argument to `false`, then you will need to explicitly call `Bumper.free()` when you are done with a `SlabBuffer`. This is not recommended. """ SlabBuffer{SlabSize}() """ SlabBuffer(;finalize::Bool = true) Create a slab allocator whose slabs are of size $default_slab_size. If you set the `finalize` keyword argument to `false`, then you will need to explicitly call `Bumper.free()` when you are done with a `SlabBuffer`. This is not recommended. """ SlabBuffer(;finalize=true) = SlabBuffer{default_slab_size}(;finalize) function free(buf::SlabBuffer) for ptr ∈ buf.slabs free(ptr) end for ptr ∈ buf.custom_slabs free(ptr) end end const default_buffer_key = gensym(:slab_buffer) """ default_buffer(::Type{SlabBuffer}) -> SlabBuffer{$default_slab_size} Return the current task-local default `SlabBuffer`, if one does not exist in the current task, it will create one automatically. This currently can only create `SlabBuffer{$default_slab_size}`, and you cannot adjust the slab size it creates. """ function default_buffer(::Type{SlabBuffer}) get!(() -> SlabBuffer{default_slab_size}(), task_local_storage(), default_buffer_key)::SlabBuffer{default_slab_size} end """ default_buffer() -> SlabBuffer{$default_slab_size} Return the current task-local default `SlabBuffer`, if one does not exist in the current task, it will create one automatically. This currently only works with `SlabBuffer{$default_slab_size}`, and you cannot adjust the slab size it creates. """ default_buffer() = default_buffer(SlabBuffer) function alloc_ptr!(buf::SlabBuffer{SlabSize}, sz::Int)::Ptr{Cvoid} where {SlabSize} p = buf.current next = buf.current + sz if next > buf.slab_end p = add_new_slab!(buf, sz) else buf.current = next end p end @noinline function add_new_slab!(buf::SlabBuffer{SlabSize}, sz::Int)::Ptr{Cvoid} where {SlabSize} if sz >= SlabSize custom = malloc(sz) push!(buf.custom_slabs, custom) custom else new_slab = malloc(SlabSize) buf.current = new_slab + sz buf.slab_end = new_slab + SlabSize push!(buf.slabs, new_slab) new_slab end end struct SlabCheckpoint{SlabSize} buf::SlabBuffer{SlabSize} current::Ptr{Cvoid} slab_end::Ptr{Cvoid} slabs_length::Int custom_slabs_length::Int end function checkpoint_save(buf::SlabBuffer=default_buffer()) SlabCheckpoint(buf, buf.current, buf.slab_end, length(buf.slabs), length(buf.custom_slabs)) end function checkpoint_restore!(cp::SlabCheckpoint) buf = cp.buf slabs = buf.slabs custom = buf.custom_slabs if length(slabs) > cp.slabs_length restore_slabs!(cp) end if length(custom) > cp.custom_slabs_length restore_custom_slabs!(cp) end buf.current = cp.current buf.slab_end = cp.slab_end nothing end @noinline function restore_slabs!(cp) buf = cp.buf slabs = buf.slabs for i ∈ (cp.slabs_length+1):length(slabs) free(slabs[i]) end resize!(slabs, cp.slabs_length) nothing end @noinline function restore_custom_slabs!(cp) buf = cp.buf custom = buf.custom_slabs for i ∈ (cp.custom_slabs_length+1):length(custom) free(custom[i]) end resize!(custom, cp.custom_slabs_length) nothing end function reset_buffer!(buf::SlabBuffer{SlabSize}) where {SlabSize} buf.current = buf.slabs[1] buf.slab_end = buf.current + SlabSize for ptr ∈ @view buf.slabs[2:end] free(ptr) end for ptr ∈ buf.custom_slabs free(ptr) end resize!(buf.slabs, 1) resize!(buf.custom_slabs, 0) buf end with_buffer(f, b::SlabBuffer{default_slab_size}) = task_local_storage(f, default_buffer_key, b) end # module SlabBufferImpl
Bumper
https://github.com/MasonProtter/Bumper.jl.git
[ "MIT" ]
0.7.0
a84ae6da7e44400b4d1df7684ac85e98f06765f3
code
3450
module Internals using UnsafeArrays: UnsafeArrays, UnsafeArray import Bumper: @no_escape, alloc!, default_buffer, allow_ptr_array_to_escape, with_buffer, reset_buffer!, checkpoint_save, checkpoint_restore!, alloc_ptr! macro no_escape(b_ex, ex) _no_escape_macro(b_ex, ex, __module__) end macro no_escape(ex) _no_escape_macro(:($default_buffer()), ex, __module__) end get_task() = Base.current_task() isexpr(ex) = ex isa Expr isexpr(ex, head) = isexpr(ex) && ex.head == head function _no_escape_macro(b_ex, _ex, __module__) @gensym b offset tsk e_offset = esc(offset) # This'll be the variable labelling the active buffer e_b = esc(b) function recursive_handler(ex) if isexpr(ex) if isexpr(ex, :macrocall) if ex.args[1] == Symbol("@alloc") # replace calls to @alloc(T, size...) with alloc(T, buf, size...) where buf # is the current buffer in use. Expr(:block, :($tsk === $get_task() || $tsk_err()), Expr(:call, alloc!, b, recursive_handler.(ex.args[3:end])...)) elseif ex.args[1] == Symbol("@alloc_ptr") Expr(:block, :($tsk === $get_task() || $tsk_err()), Expr(:call, alloc_ptr!, b, recursive_handler.(ex.args[3:end])...)) elseif ex.args[1] == Symbol("@no_escape") # If we encounter nested @no_escape blocks, we'll leave them alone ex else # All other macros must be macroexpanded in case the user has a macro # in the body which has return or goto in it expanded = macroexpand(__module__, ex; recursive=false) recursive_handler(expanded) end elseif isexpr(ex, :return) error("The `return` keyword is not allowed to be used inside the `@no_escape` macro") elseif isexpr(ex, :symbolicgoto) error("`@goto` statements are not allowed to be used inside the `@no_escape` macro") elseif isexpr(ex, :symboliclabel) error("`@label` statements are not allowed to be used inside the `@no_escape` macro") else Expr(ex.head, recursive_handler.(ex.args)...) end else ex end end ex = recursive_handler(_ex) quote $e_b = $(esc(b_ex)) $(esc(tsk)) = get_task() local cp = checkpoint_save($e_b) local res = $(esc(ex)) checkpoint_restore!(cp) if res isa UnsafeArray && !(allow_ptr_array_to_escape()) esc_err() end res end end @noinline tsk_err() = error("Tried to use @alloc from a different task than its parent @no_escape block, that is not allowed for thread safety reasons. If you really need to do this, see Bumper.alloc instead of @alloc.") @noinline esc_err() = error("Tried to return a UnsafeArray from a `no_escape` block. If you really want to do this, evaluate Bumper.allow_ptrarray_to_escape() = true") function alloc!(buf, ::Type{T}, s::Vararg{Integer, N}) where {T, N} ptr::Ptr{T} = alloc_ptr!(buf, prod(s) * sizeof(T)) UnsafeArray(ptr, s) end malloc(n::Integer) = Libc.malloc(Int(n)) free(p::Ptr) = Libc.free(p) end
Bumper
https://github.com/MasonProtter/Bumper.jl.git
[ "MIT" ]
0.7.0
a84ae6da7e44400b4d1df7684ac85e98f06765f3
code
5286
using Test, Bumper function f(x, buf=default_buffer()) @no_escape buf begin y = @alloc(eltype(x), length(x)) y .= x .+ 1 sum(y) end end function g(x, buf) @no_escape buf begin y = Bumper.alloc!(buf, eltype(x), length(x)) y .= x .+ 1 sum(y) end end @testset "basic" begin v = [1,2,3] b = AllocBuffer(100) @test f(v) == 9 @test default_buffer().current == default_buffer().slabs[1] @test f(v, b) == 9 @test b.offset == 0 @test g(v, b) == 9 @test b.offset == 0 @test @allocated(f(v)) == 0 @test @allocated(f(v, b)) == 0 @test @allocated(g(v, b)) == 0 sb = SlabBuffer{16_384}() @no_escape sb begin p = sb.current e = sb.slab_end x = @alloc(Int8, 16_384 ÷ 2 - 1) x = @alloc(Int8, 16_384 ÷ 2 - 1) for i ∈ 1:5 @no_escape sb begin @test sb.current == p + 16_382 @test p <= sb.current <= e y = @alloc(Int, 10) @test !(p <= sb.current <= e) end end z = @alloc(Int, 100_000) @test sb.current == p + 16_382 @test sb.slab_end == e @test !(p <= pointer(z) <= e) @test pointer(z) == sb.custom_slabs[end] end @test isempty(sb.custom_slabs) @test sb.current == sb.slabs[1] @test sb.slab_end == sb.current + 16_384 @no_escape sb begin current = sb.current p = @alloc_ptr(10) @test p == current @test sb.current == p + 10 p2 = @alloc_ptr(100_000) @test p2 == sb.custom_slabs[end] end try @no_escape sb begin x = @alloc(Int8, 16_383) y = @alloc(Int8, 100_000) z = @alloc(Int8, 10) throw("Boo!") end catch e @test length(sb.custom_slabs) == 1 @test length(sb.slabs) == 2 @test sb.current == sb.slabs[2] + 10 Bumper.reset_buffer!(sb) @test isempty(sb.custom_slabs) @test length(sb.slabs) == 1 @test sb.current == sb.slabs[1] end @no_escape b begin y = @alloc(Int, length(v)) off1 = b.offset @no_escape b begin z = @alloc(Int, length(v)) @test pointer(z) != pointer(y) @test Int(pointer(z)) == Int(pointer(y)) + 8*length(v) @test b.offset == off1 + 8*length(v) end b2 = AllocBuffer(100) @no_escape b2 begin z = @alloc(Int, length(v)) @test pointer(z) == pointer(b2.buf) end @test b.offset == off1 end @test_throws Exception Bumper.alloc!(b, Int, 100000) Bumper.reset_buffer!(b) Bumper.reset_buffer!() @test_throws Exception @no_escape begin @alloc(Int, 10) end @test_throws Exception @no_escape begin @sync Threads.@spawn begin @alloc(Int, 10) end end end macro sneaky_return(ex) esc(:(return $ex)) end macro sneaky_goto(label) esc(:(@goto $label)) end @testset "trying to break out of no_escape blocks" begin # It is very tricky to properly deal with code which uses @goto or return inside # a @no_escape code block, because could bypass the mechanism for resetting the # buffer's offset after the block completes. # I played with some mechanisms for cleaning it up, but they were sometimes incorrect # if one nested multuple @no_escape blocks, so I decided that they should simply be # disabled, and throw an error at macroexpansion time. @test_throws Exception Bumper.Internals._no_escape_macro( :(default_buffer()), :(return sum(@alloc(Int, 10) .= 1)), @__MODULE__() ) @test_throws Exception Bumper.Internals._no_escape_macro( :(default_buffer()), :(@sneaky_return sum(@alloc(Int, 10) .= 1)), @__MODULE__() ) @test_throws Exception Bumper.Internals._no_escape_macro( :(default_buffer()), :(@goto lab), @__MODULE__() ) @test_throws Exception Bumper.Internals._no_escape_macro( :(default_buffer()), :(@sneaky_goto lab), @__MODULE__() ) @test_throws Exception Bumper.Internals._no_escape_macro( :(default_buffer()), :(@label lab), @__MODULE__() ) end @testset "tasks and buffer switching" begin let b1 = default_buffer(AllocBuffer) b2 = AllocBuffer(Vector{UInt8}(undef, 100)) with_buffer(b2) do @test default_buffer(AllocBuffer) == b2 end @test default_buffer(AllocBuffer) == b1 end let b2 = AllocBuffer(Vector{Int}(undef, 100)) @test_throws MethodError with_buffer(b2) do default_buffer() end end @test default_buffer() === default_buffer() @test default_buffer() !== fetch(@async default_buffer()) @test default_buffer() !== fetch(Threads.@spawn default_buffer()) @test default_buffer() !== with_buffer(default_buffer, SlabBuffer()) @test default_buffer(AllocBuffer) === default_buffer(AllocBuffer) @test default_buffer(AllocBuffer) !== with_buffer(() -> default_buffer(AllocBuffer), AllocBuffer()) end
Bumper
https://github.com/MasonProtter/Bumper.jl.git
[ "MIT" ]
0.7.0
a84ae6da7e44400b4d1df7684ac85e98f06765f3
docs
2355
# Changelog ## Version 0.6.0 + Removed the package extension which was added in v0.5.1, because we plan on making Bumper.jl a direct dependancy of StaticTools.jl ## Version 0.5.4 + Changed the default size heuristics for `SlabBuffer`, the default slab size is now 1 megabyte, and custom slabs are now created for allocations which are larger than *half* the slab size, rather than larger than the slab size. + Changed the default size heuristic for `AllocBuffer`. `AllocBuffer()` now creates a buffer of 1 megabyte capacity. ## Version 0.5.3 + Added `@alloc_ptr(n)` which is like `@alloc` except it returns an `n` byte pointer directly instead of an array. ## Version 0.5.2 ## Version 0.5.1 + Added a package extension (only works on julia versions 1.9+) which lets the `AllocBuffer` work under StaticCompiler.jl, and defines methods like `AllocBuffer(::Type{MallocVector}, n::Int)` and `free(AllocBuffer{<:MallocArray})` for convenience. ## Version 0.5.0 + The default allocator is now something known as a *slab* allocator `SlabBuffer`. This comes with a very *slight* performance hit relative to `AllocBuffer`, but the advantage is that it scales very well from handling small allocations all the way up to handling very large allocations. It will only run out of memory when your computer runs out of memory, but it also won't hog memory that's not in use. It is also be much faster to construct than the old default `AllocBuffer`. + `AllocBuffer` still exists, but now defaults to 128kb of storage instead of 1/8th of your computer's physical memory. This allocator is very slightly faster than the slab allocator, but will error if it runs out of memory. It also is more flexible in the kinds of types it can wrap to use as underlying storage. + There is now an API for hooking user-defined allocators into the `@no_escape` and `@alloc` machinery. + `alloc(::Type{T}, buffer, dims...)` is now `alloc!(buffer, ::Type{T}, dims...)` + `alloc_nothrow` and `@alloc_nothrow` have been removed. People who need this can instead create custom no-throw buffer types. ## Version 0.4.0 + `alloc` has been replaced with `@alloc`, a macro that can *only* be used inside of a `@no_escape` block, and always allocates memory from that specified block. `alloc` still exists, but it is not recommended, and has to be explicitly imported to use.
Bumper
https://github.com/MasonProtter/Bumper.jl.git
[ "MIT" ]
0.7.0
a84ae6da7e44400b4d1df7684ac85e98f06765f3
docs
8177
# Docstrings ## User API ``` @no_escape([buf=default_buffer()], expr) ``` Record the current state of `buf` (which defaults to the `default_buffer()` if there is only one argument), and then run the code in `expr` and then reset `buf` back to the state it was in before the code ran. This allows us to allocate memory within the `expr` using `@alloc`, and then have those arrays be automatically de-allocated once the expression is over. This is a restrictive but highly efficient form of memory management. See also `Bumper.checkpoint_save`, and `Bumper.checkpoint_restore!`. Using `return`, `@goto`, and `@label` are not allowed inside of `@no_escape` block. Example: ``` function f(x::Vector{Int}) # Set up a scope where memory may be allocated, and does not escape: @no_escape begin # Allocate a `UnsafeArray` from UnsafeArrays.jl using memory from the default buffer. y = @alloc(Int, length(x)) # Now do some stuff with that vector: y .= x .+ 1 sum(y) end end ``` --------------------------------------- ``` @alloc(T, n::Int...) -> UnsafeArray{T, length(n)} ``` This can be used inside a `@no_escape` block to allocate a `UnsafeArray` whose dimensions are determined by `n`. The memory used to allocate this array will come from the buffer associated with the enclosing `@no_escape` block. Do not allow any references to this array to escape the enclosing `@no_escape` block, and do not pass these arrays to concurrent tasks unless that task is guaranteed to terminate before the `@no_escape` block ends. Any array allocated in this way which is found outside of its parent `@no_escape` block has undefined contents, and writing to this pointer will have undefined behaviour. --------------------------------------- ``` @alloc_ptr(n::Integer) -> Ptr{Nothing} ``` This can be used inside a `@no_escape` block to allocate a pointer which can hold `n` bytes. The memory used to allocate this pointer will come from the buffer associated with the enclosing `@no_escape` block. Do not allow any references to this pointer to escape the enclosing `@no_escape` block, and do not pass these pointers to concurrent tasks unless that task is guaranteed to terminate before the `@no_escape` block ends. Any pointer allocated in this way which is found outside of its parent `@no_escape` block has undefined contents, and writing to this pointer will have undefined behaviour. --------------------------------------- ``` default_buffer(::Type{SlabBuffer}) -> SlabBuffer{1048576} ``` Return the current task-local default `SlabBuffer`, if one does not exist in the current task, it will create one automatically. This currently can only create `SlabBuffer{1048576}`, and you cannot adjust the slab size it creates. ``` default_buffer() -> SlabBuffer{1048576} ``` Return the current task-local default `SlabBuffer`, if one does not exist in the current task, it will create one automatically. This currently only works with `SlabBuffer{1048576}`, and you cannot adjust the slab size it creates. ``` default_buffer(::Type{AllocBuffer}) -> AllocBuffer{Vector{UInt8}} ``` Return the current task-local default `AllocBuffer`, if one does not exist in the current task, it will create one automatically. This currently can only create `AllocBuffer{Vector{UInt8}}`, and you cannot adjust the memory size it creates (1048576 bytes). --------------------------------------- ``` mutable struct SlabBuffer{SlabSize} ``` A slab-based bump allocator which can dynamically grow to hold an arbitrary amount of memory. Small allocations live within a specific slab of memory, and if that slab fills up, a new slab is allocated and future allocations happen on that slab. Small allocations are stored in slabs of size `SlabSize` bytes, and the list of live slabs are tracked in the `slabs` field. Allocations which are too large to fit into one slab are stored and tracked in the `custom_slabs` field. The default slab size is 1048576 bytes. `SlabBuffer`s are nearly as fast as stack allocation (typically up to within a couple of nanoseconds) for typical use. One potential performance pitfall is if that `SlabBuffer`'s current position is at the end of a slab, then the next allocation will be slow because it requires a new slab to be created. This means that if you do something like ``` buf = SlabBuffer{N}() @no_escape buf begin @alloc(Int8, N÷2 - 1) # Take up just under half the first slab @alloc(Int8, N÷2 - 1) # Take up another half of the first slab # Now buf should be practically out of room. for i in 1:1000 @no_escape buf begin y = @alloc(Int8, 10) # This will allocate a new slab because there's no room f(y) end # At the end of this block, we delete the new slab because it's not needed. end end ``` then the inner loop will run slower than normal because at each iteration, a new slab of size `N` bytes must be freshly allocated. This should be a rare occurance, but is possible to encounter. Do not manipulate the fields of a SlabBuffer that is in use. ``` SlabBuffer{SlabSize}(;finalize::Bool = true) ``` Create a slab allocator whose slabs are of size `SlabSize`. If you set the `finalize` keyword argument to `false`, then you will need to explicitly call `Bumper.free()` when you are done with a `SlabBuffer`. This is not recommended. ``` SlabBuffer(;finalize::Bool = true) ``` Create a slab allocator whose slabs are of size 1048576. If you set the `finalize` keyword argument to `false`, then you will need to explicitly call `Bumper.free()` when you are done with a `SlabBuffer`. This is not recommended. --------------------------------------- ``` Bumper.reset_buffer!(buf=default_buffer()) ``` This resets a buffer to its default state, effectively making it like a freshly allocated buffer. This might be necessary to use if you accidentally over-allocate a buffer or screw up its state in some other way. --------------------------------------- ``` with_buffer(f, buf) ``` Execute the function `f()` in a context where `default_buffer()` will return `buf` instead of the normal `default_buffer`. This currently only works with `SlabBuffer{1_048_576}`, and `AllocBuffer{Vector{UInt8}}`. Example: ``` julia> let b1 = default_buffer() b2 = SlabBuffer() with_buffer(b2) do @show default_buffer() == b2 end @show default_buffer() == b1 end default_buffer() == b2 = true default_buffer() == b1 = true true ``` --------------------------------------- ## Allocator API ``` Bumper.alloc_ptr!(b, n::Int) -> Ptr{Nothing} ``` Take a pointer which can store at least `n` bytes from the allocator `b`. --------------------------------------- ``` Bumper.alloc!(b, ::Type{T}, n::Int...) -> UnsafeArray{T, length(n)} ``` Function-based alternative to `@alloc` which allocates onto a specified allocator `b`. You must obey all the rules from `@alloc`, but you can use this outside of the lexical scope of `@no_escape` for specific (but dangerous!) circumstances where you cannot avoid a scope barrier between the two. --------------------------------------- ``` Bumper.checkpoint_save(buf = default_buffer()) ``` Returns a checkpoint object `cp` which stores the state of a `buf` at a given point in a program. One can then use `Bumper.checkpoint_restore!(cp)` to later on restore the state of the buffer to it's earlier saved state, undoing any bump allocations which happened in the meantime on that buffer. Users should prefer to use `@no_escape` instead of `checkpoint_save` and `checkpoint_restore`, which is a safer and more structured way of doing the same thing. --------------------------------------- ``` Bumper.checkpoint_restore!(cp) ``` Restore a buffer (the one used to create `cp`) to the state it was in when the checkpoint was created, undoing any bump allocations which happened in the meantime on that buffer. See also `Bumper.checkpoint_save` Users should prefer to use `@no_escape` instead of `checkpoint_save` and `checkpoint_restore`, which is a safer and more structured way of doing the same thing. ---------------------------------------
Bumper
https://github.com/MasonProtter/Bumper.jl.git
[ "MIT" ]
0.7.0
a84ae6da7e44400b4d1df7684ac85e98f06765f3
docs
15537
- [Basics](#basics) - [Important notes](#important-notes) - [Concurrency and parallelism](#concurrency-and-parallelism) - [Allocators provided by Bumper](#allocators-provided-by-bumper) - [Creating your own allocator types](#creating-your-own-allocator-types) - [Usage with StaticCompiler.jl](#usage-with-staticcompilerjl) - [Docstrings](Docstrings.md) # Bumper.jl Bumper.jl is a package that aims to make working with bump allocators (also known as arena allocators) easier and safer. You can dynamically allocate memory to these bump allocators, and reset them at the end of a code block, just like Julia's stack. Allocating to a bump allocator with Bumper.jl can be just as efficient as stack allocation. Bumper.jl is still a young package, and may have bugs. Let me know if you find any. If you use Bumper.jl, please consider submitting a sample of your use-case so I can include it in the test suite. ## Basics Bumper.jl has a task-local default allocator, using a *slab allocation strategy* which can dynamically grow to arbitary sizes. The simplest way to use Bumper is to rely on its default buffer implicitly like so: ``` julia using Bumper function f(x) # Set up a scope where memory may be allocated, and does not escape: @no_escape begin # Allocate a `UnsafeVector{eltype(x)}` (see UnsafeArrays.jl) using memory from the default buffer. y = @alloc(eltype(x), length(x)) # Now do some stuff with that vector: y .= x .+ 1 sum(y) # It's okay for the sum of y to escape the block, but references to y itself must not do so! end end f([1,2,3]) ``` ``` 9 ``` When you use `@no_escape`, you are promising that the code enclosed in the macro will not leak **any** memory created by `@alloc`. That is, you are *only* allowed to do intermediate `@alloc` allocations inside a `@no_escape` block, and the lifetime of those allocations is the block. **This is important.** Once a `@no_escape` block finishes running, it will reset its internal state to the position it had before the block started, potentially overwriting or freeing any arrays which were created in the block. In addition to `@alloc` for creating arrays, you can use `@alloc_ptr(n)` to get an `n`-byte pointer (of type `Ptr{Nothing}`) directly. Let's compare the performance of `f` to the equivalent with an intermediate heap allocation: ``` julia using BenchmarkTools @benchmark f(x) setup=(x = rand(1:10, 30)) ``` ``` BenchmarkTools.Trial: 10000 samples with 995 evaluations. Range (min … max): 28.465 ns … 49.843 ns ┊ GC (min … max): 0.00% … 0.00% Time (median): 28.718 ns ┊ GC (median): 0.00% Time (mean ± σ): 28.840 ns ± 0.833 ns ┊ GC (mean ± σ): 0.00% ± 0.00% ▃▄▂▇█▅▆▇▅▂▂▁▁▂▁ ▂ ██████████████████▆▇▅▄▅▅▅▆▃▄▄▁▃▄▄▃▄▃▁▁▁▁▁▃▁▁▁▄▅▅▅▅▄▄▃▄▁▃▃▃▄ █ 28.5 ns Histogram: log(frequency) by time 31.5 ns < Memory estimate: 0 bytes, allocs estimate: 0. ``` and ``` julia function g(x::Vector{Int}) y = x .+ 1 sum(y) end @benchmark g(x) setup=(x = rand(1:10, 30)) ``` ``` BenchmarkTools.Trial: 10000 samples with 993 evaluations. Range (min … max): 32.408 ns … 64.986 μs ┊ GC (min … max): 0.00% … 99.87% Time (median): 37.443 ns ┊ GC (median): 0.00% Time (mean ± σ): 55.929 ns ± 651.009 ns ┊ GC (mean ± σ): 14.68% ± 5.87% ▆█▅▃▁▁▁▁ ▁▁ ▁ ▂▁ ▁ ████████▇██▅▄▃▄▁▁▃▁▁▁▁▁▁▁▁▃▃▁▁██████▇▇▅▁▄▃▃▃▁▁▃▁▁▁▄▃▄▅▄▄▅▇██ █ 32.4 ns Histogram: log(frequency) by time 227 ns < Memory estimate: 304 bytes, allocs estimate: 1. ``` So, using Bumper.jl in this benchmark gives a slight speedup relative to regular julia `Vector`s, and a major increase in performance *consistency* due to the lack of heap allocations. However, we can actually go a little faster better if we're okay with manually passing around a buffer. The way I invoked `@no_escape` and `@alloc` implicitly used the task's default buffer, and fetching that default buffer is not as fast as using a `const` global variable, because Bumper.jl is trying to protect you against concurrency bugs (more on that later). If we provide the allocator to `f` explicitly, we go even faster: ``` julia function f(x, buf) @no_escape buf begin # <----- Notice I specified buf here y = @alloc(Int, length(x)) y .= x .+ 1 sum(y) end end @benchmark f(x, buf) setup = begin x = rand(1:10, 30) buf = default_buffer() end ``` ``` BenchmarkTools.Trial: 10000 samples with 997 evaluations. Range (min … max): 19.425 ns … 40.367 ns ┊ GC (min … max): 0.00% … 0.00% Time (median): 19.494 ns ┊ GC (median): 0.00% Time (mean ± σ): 19.620 ns ± 0.983 ns ┊ GC (mean ± σ): 0.00% ± 0.00% █▅ ▁ ██▅█▇▄▃▄▄▃▃▃▄▅▄▅▄▅▄▇▇▅▄▄▅▆▅▅▅▄▄▄▁▄▃▃▃▁▁▄▃▃▄▁▁▁▁▃▃▃▁▄▄▃▁▄▃▁▃ █ 19.4 ns Histogram: log(frequency) by time 25.3 ns < Memory estimate: 0 bytes, allocs estimate: 0. ``` If you manually specify a buffer like this, it is your responsibility to ensure that you don't have multiple concurrent tasks using that buffer at the same time. Running `default_buffer()` will give you the current task's default buffer. You can explicitly construct your own `N` byte buffer by calling `AllocBuffer(N)`, or you can create a buffer which can dynamically grow by calling `SlabBuffer()`. `AllocBuffer`s are *slightly* faster than `SlabBuffer`s, but will throw an error if you overfill them. ## Important notes - `@no_escape` blocks can be nested as much as you want, just don't let references outlive the specific block they were created in. - At the end of a `@no_escape` block, all memory allocations from inside that block are erased and the buffer is reset to its previous state - The `@alloc` marker can only be used directly inside of a `@no_escape` block, and it will always use the buffer that the corresponding `@no_escape` block uses. - You cannot use `@alloc` from a different concurrent task than its parent `@no_escape` block as this can cause concurrency bugs. - If for some reason you need to be able to use `@alloc` outside of the scope of the `@no_escape` block, there is a function =`Bumper.alloc!(bug, T, n...)`= which takes in an explicit buffer `buf` and uses it to allocate an array of element type `T`, and dimensions `n...`. Using this is not as safe as `@alloc` and not recommended. - Bumper.jl only supports `isbits` types. You cannot use it for allocating vectors containing mutable, abstract, or other pointer-backed objects. - As mentioned previously, *Do not allow any array which was initialized inside a* `@no_escape` *block to escape the block.* Doing so will cause incorrect results. - If you accidentally overfill a buffer, via e.g. a memory leak and need to reset the buffer, use `Bumper.reset_buffer!` to do this. - You are not allowed to use `return` or `@goto` inside a `@no_escape` block, since this could compromise the cleanup it performs after the block finishes. ## Concurrency and parallelism <details><summary>Click me!</summary> <p> Every task has its own *independent* default buffer. A task's buffer is only created if it is used, so this does not slow down the spawning of Julia tasks in general. Here's a demo showing that the default buffers are different: ``` julia using Bumper let b = default_buffer() # The default buffer on the main task t = @async default_buffer() # Get the default buffer on an asychronous task fetch(t) === b end ``` ``` false ``` Whereas if we don't spawn any tasks, there is no unnecessary buffer creation: ``` julia let b = default_buffer() b2 = default_buffer() b2 === b end ``` ``` true ``` Because of this, we don't have to worry about `@no_escape begin ... @alloc() ... end` blocks on different threads or tasks interfering with each other, so long as they are only operating on buffers local to that task or the `default_buffer()`. </details> </p> ## Allocators provided by Bumper <details><summary>Click me!</summary> <p> ### SlabBuffer `SlabBuffer` is a slab-based bump allocator which can dynamically grow to hold an arbitrary amount of memory. Small allocations from a `SlabBuffer` will live within a specific slab of memory, and if that slab fills up, a new slab is allocated and future allocations will then happen on that slab. Small allocations are stored in slabs of size `SlabSize` bytes (default 1 megabyte), and the list of live slabs are tracked in a field called `slabs`. Allocations which are too large to fit into one slab are stored and tracked in a field called `custom_slabs`. `SlabBuffer`s are nearly as fast as stack allocation (typically up to within a couple of nanoseconds) for typical use. One potential performance pitfall is if that `SlabBuffer`'s current position is at the end of a slab, then the next allocation will be slow because it requires a new slab to be created. This means that if you do something like ``` julia buf = SlabBuffer{N}() @no_escape buf begin @alloc(Int8, N÷2 - 1) # Take up just under half the first slab @alloc(Int8, N÷2 - 1) # Take up another half of the first slab # Now buf should be practically out of room. for i in 1:1000 @no_escape buf begin y = @alloc(Int8, 10) # This will allocate a new slab because there's no room f(y) end # At the end of this block, we delete the new slab because it's not needed. end end ``` then the inner loop will run slower than normal because at each iteration, a new slab of size `N` bytes must be freshly allocated. This should be a rare occurance, but is possible to encounter. Do not manipulate the fields of a SlabBuffer that is in use. ### AllocBuffer `AllocBuffer{StorageType}` is a very simple bump allocator that could be used to store a fixed amount of memory of type `StorageType`, so long as `::StoreageType` supports `pointer`, and `sizeof`. If it runs out of memory to allocate, an error will be thrown. By default, `AllocBuffer` stores a `Vector{UInt8}` of `1` megabyte. Allocations using `AllocBuffer`s should be just as fast as stack allocation. Do not manually manipulate the fields of an AllocBuffer that is in use. </details> </p> ## Creating your own allocator types <details><summary>Click me!</summary> <p> Bumper.jl's `SlabBuffer` type is very flexible and fast, and so should almost always be preferred, but you may have specific use-cases where you want to use a different design or make different tradeoffs, but want to be able to interoperate with Bumper.jl's other features. Hence, Bumper.jl provides an API for you to hook custom allocator types into it. When someone writes ``` julia @no_escape buf begin y = @alloc(T, n, m, o) f(y) end ``` this turns into the equivalent of ``` julia begin local cp = Bumper.checkpoint_save(buf) local result = begin y = Bumper.alloc!(buf, T, n, m, o) f(y) end Bumper.checkpoint_restore!(cp) result end ``` `checkpoint_save` should save the state of `buf`, `alloc!` should create an array using memory from `buf`, and `checkpoint_restor!` needs to reset `buf` to the state it was in when the checkpoint was created. Hence, in order to use your custom allocator with Bumper.jl, all you need to write is the following methods: + `Bumper.alloc_ptr!(::YourAllocator, n::Int)::Ptr{Nothing}` which returns a pointer that can hold up to `n` bytes, and should be created from memory supplied with your allocator type however you see fit. + Alternatively, you could implement `Bumper.alloc!(::YourAllocator, ::Type{T}, s::Vararg{Integer})` which should return a multidimensional array whose sizes are determined by `s...`, created from memory supplied by your custom allocator. The default implementation of this method calls `Bumper.alloc_ptr!`. + `Bumper.checkpoint_save(::YourAllocator)::YourAllocatorCheckpoint` which saves whatever information your allocator needs to save in order to later on deallocate all objects which were created after `checkpoint_save` was called. + `checkpoint_restore!(::YourAllocatorCheckpoint)` which resets the allocator back to the state it was in when the checkpoint was created. Let's look at a concrete example where we make our own simple copy of `AllocBuffer`: ``` julia mutable struct MyAllocBuffer buf::Vector{UInt8} # The memory chunk we'll use for allocations offset::UInt # A simple offset saying where the current position of the allocator is. #Default constructor MyAllocBuffer(n::Int) = new(Vector{UInt8}(undef, n), UInt(0)) end struct MyCheckpoint buf::MyAllocBuffer # The buffer we want to store offset::UInt # The buffer's offset when the checkpoint was created end function Bumper.alloc_ptr!(b::MyAllocBuffer, sz::Int)::Ptr{Cvoid} ptr = pointer(b.buf) + b.offset b.offset += sz b.offset > sizeof(b.buf) && error("alloc: Buffer out of memory.") ptr end function Bumper.checkpoint_save(buf::MyAllocBuffer) MyCheckpoint(buf, buf.offset) end function Bumper.checkpoint_restore!(cp::MyCheckpoint) cp.buf.offset = cp.offset nothing end ``` that's it! ``` julia julia> let x = [1, 2, 3], buf = MyAllocBuffer(100) @btime f($x, $buf) end 9.918 ns (0 allocations: 0 bytes) 9 ``` As a bonus, this isn't required, but if you want to have functionality like `default_buffer`, it can be simply implemented as follows: ``` julia #Some default size, say 16kb MyAllocBuffer() = MyAllocBuffer(16_000) const default_buffer_key = gensym(:my_buffer) function Bumper.default_buffer(::Type{MyAllocBuffer}) get!(() -> MyAllocBuffer(), task_local_storage(), default_buffer_key)::MyAllocBuffer end ``` You may also want to implemet `Bumper.reset_buffer!` for refreshing you allocator to a freshly initialized state. </details> </p> ## Usage with StaticCompiler.jl <details><summary>Click me!</summary> <p> Bumper.jl is in the process of becoming a dependancy of [StaticTools.jl](https://github.com/brenhinkeller/StaticTools.jl) (and thus [StaticCompiler.jl](https://github.com/tshort/StaticCompiler.jl)), which extends Bumper.jl with a new buffer type, `MallocSlabBuffer` which is like `SlabBuffer` but designed to work without needing Julia's runtime at all. This allows for code like the following ``` julia using Bumper, StaticTools function times_table(argc::Int, argv::Ptr{Ptr{UInt8}}) argc == 3 || return printf(c"Incorrect number of command-line arguments\n") rows = argparse(Int64, argv, 2) # First command-line argument cols = argparse(Int64, argv, 3) # Second command-line argument buf = MallocSlabBuffer() @no_escape buf begin M = @alloc(Int, rows, cols) for i=1:rows for j=1:cols M[i,j] = i*j end end printf(M) end free(buf) end using StaticCompiler filepath = compile_executable(times_table, (Int64, Ptr{Ptr{UInt8}}), "./") ``` giving ``` shell> ./times_table 12, 7 1 2 3 4 5 6 7 2 4 6 8 10 12 14 3 6 9 12 15 18 21 4 8 12 16 20 24 28 5 10 15 20 25 30 35 6 12 18 24 30 36 42 7 14 21 28 35 42 49 8 16 24 32 40 48 56 9 18 27 36 45 54 63 10 20 30 40 50 60 70 11 22 33 44 55 66 77 12 24 36 48 60 72 84 ``` </details> </p> ## Docstrings See the full list of docstrings [here](Docstrings.md).
Bumper
https://github.com/MasonProtter/Bumper.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
1189
using Quantica using Documenter DocMeta.setdocmeta!(Quantica, :DocTestSetup, :(using Quantica); recursive=true) makedocs(; modules=[Quantica], authors="Pablo San-Jose", repo="https://github.com/pablosanjose/Quantica.jl/blob/{commit}{path}#L{line}", sitename="Quantica.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://pablosanjose.github.io/Quantica.jl", assets=["assets/custom.css"], ), pages=[ "Home" => "index.md", "Tutorial" => [ "Welcome" => "tutorial/tutorial.md", "Glossary" => "tutorial/glossary.md", "Lattices" => "tutorial/lattices.md", "Models" => "tutorial/models.md", "Hamiltonians" => "tutorial/hamiltonians.md", "Bandstructures" => "tutorial/bandstructures.md", "GreenFunctions" => "tutorial/greenfunctions.md", "Observables" => "tutorial/observables.md", "Advanced topics" => "tutorial/advanced.md" ], "Examples" => "examples.md", "API" => "api.md", ] ) deploydocs(; repo="github.com/pablosanjose/Quantica.jl", )
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
1401
module QuanticaMakieExt using Makie using Quantica using Makie.GeometryBasics using Makie.GeometryBasics: Ngon using Quantica: Lattice, LatticeSlice, AbstractHamiltonian, Hamiltonian, OpenHamiltonian, ParametricHamiltonian, Harmonic, Bravais, SVector, GreenFunction, GreenSolution, argerror, harmonics, sublats, siterange, site, norm, normalize, nsites, nzrange, rowvals, nonzeros, sanitize_SVector, default_hamiltonian import Quantica: plotlattice, plotlattice!, plotbands, plotbands!, qplot, qplot!, qplotdefaults ## PlotArgumentTypes const PlotLatticeArgumentType{E} = Union{ Lattice{<:Any,E}, LatticeSlice{<:Any,E}, AbstractHamiltonian{<:Any,E}, GreenFunction{<:Any,E}, OpenHamiltonian{<:Any,E}} const PlotBandsArgumentType{E} = Union{Quantica.Bandstructure{<:Any,E}, Quantica.Subband{<:Any,E}, AbstractVector{<:Quantica.Subband{<:Any,E}}, Quantica.Mesh{<:Quantica.BandVertex{<:Any,E}}, AbstractVector{<:Quantica.Mesh{<:Quantica.BandVertex{<:Any,E}}}} const PlotArgumentType{E} = Union{PlotLatticeArgumentType{E},PlotBandsArgumentType{E}} ## Currying fallbacks Quantica.qplot(; kw...) = x -> Quantica.qplot(x; kw...) Quantica.qplot!(; kw...) = x -> Quantica.qplot!(x; kw...) include("plotlattice.jl") include("plotbands.jl") include("tools.jl") include("defaults.jl") include("docstrings.jl") end # module
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
4739
############################################################################################ # qplot defaults #region ## qplot defaults function qplotdefaults(; figure::Union{Missing,NamedTuple} = missing, axis2D::Union{Missing,NamedTuple} = missing, axis3D::Union{Missing,NamedTuple} = missing, lscene::Union{Missing,NamedTuple} = missing, inspector::Union{Missing,NamedTuple} = missing) ismissing(figure) || (global user_default_figure = figure) ismissing(axis2D) || (global user_default_axis2D = axis2D) ismissing(axis3D) || (global user_default_axis3D = axis3D) ismissing(lscene) || (global user_default_lscene = lscene) ismissing(inspector) || (global user_default_inspector = inspector) return (; user_default_figure, user_default_axis2D, user_default_axis3D, user_default_lscene, user_default_inspector) end qplotdefaults(defaults::NamedTuple) = qplotdefaults(; defaults...) user_default_figure = (;) user_default_axis2D = (;) user_default_axis3D = (;) user_default_lscene = (;) user_default_inspector = (;) # Choose used_default_axis for each given type of plotted object axis_defaults(::PlotArgumentType{3}, fancyaxis) = axis_defaults(fancyaxis) axis_defaults(::PlotArgumentType, fancyaxis) = user_default_axis2D axis_defaults(fancyaxis::Bool) = ifelse(fancyaxis, user_default_lscene, user_default_axis3D) empty_fig_axis(b::PlotArgumentType; kw...) = (checkplotdim(b); _empty_fig_axis(b; kw...)) _empty_fig_axis(::PlotLatticeArgumentType{3}; kw...) = empty_fig_axis_3D(plotlat_default_3D...; kw...) _empty_fig_axis(b::PlotLatticeArgumentType; kw...) = empty_fig_axis_2D(plotlat_default_2D...; kw...) _empty_fig_axis(::PlotBandsArgumentType{3}; kw...) = empty_fig_axis_3D(plotbands_default_3D...; kw...) _empty_fig_axis(b::PlotBandsArgumentType; kw...) = empty_fig_axis_2D(plotbands_default_2D...; kw...) function empty_fig_axis_2D(default_figure, default_axis2D; axis = user_default_axis2D, figure = user_default_figure, kw...) axis´ = merge(user_default_axis2D, axis) fig = Figure(; default_figure..., figure...) ax = Axis(fig[1,1]; default_axis2D..., axis´...) tight_ticklabel_spacing!(ax) # Workaround for Makie issue #3009 return fig, ax end function empty_fig_axis_3D(default_figure, default_axis3D, default_lscene; fancyaxis = true, axis = axis_defaults(fancyaxis), figure = user_default_figure, kw...) fig = Figure(; default_figure..., figure...) axis´ = merge(axis_defaults(fancyaxis), axis) ax = fancyaxis ? LScene(fig[1,1]; default_lscene..., axis´...) : Axis3(fig[1,1]; default_axis3D..., axis´...) return fig, ax end checkplotdim(::PlotArgumentType{E}) where {E} = E > 3 && argerror("Cannot represent a mesh in an $E-dimensional embedding space") ## plotlattice defaults const plotlat_default_figure = (; size = (870, 1200), fontsize = 20) const plotlat_default_axis3D = (; xlabel = "x", ylabel = "y", zlabel = "z", xticklabelcolor = :gray, yticklabelcolor = :gray, zticklabelcolor = :gray, xspinewidth = 0.2, yspinewidth = 0.2, zspinewidth = 0.2, xlabelrotation = 0, ylabelrotation = 0, zlabelrotation = 0, xticklabelsize = 18, yticklabelsize = 18, zticklabelsize = 18, xlabelsize = 25, ylabelsize = 25, zlabelsize = 25, xlabelfont = :italic, ylabelfont = :italic, zlabelfont = :italic, perspectiveness = 0.3, aspect = :data) const plotlat_default_axis2D = (; xlabel = "x", ylabel = "y", autolimitaspect = 1) const plotlat_default_lscene = (;) const plotlat_default_2D = (plotlat_default_figure, plotlat_default_axis2D) const plotlat_default_3D = (plotlat_default_figure, plotlat_default_axis3D, plotlat_default_lscene) ## plotbands defaults const plotbands_default_figure = (; size = (870, 1200), fontsize = 20) const plotbands_default_axis3D = (; xlabel = "ϕ₁", ylabel = "ϕ₂", zlabel = "ε", xticklabelcolor = :gray, yticklabelcolor = :gray, zticklabelcolor = :gray, xspinewidth = 0.2, yspinewidth = 0.2, zspinewidth = 0.2, xlabelrotation = 0, ylabelrotation = 0, zlabelrotation = 0, xticklabelsize = 18, yticklabelsize = 18, zticklabelsize = 18, xlabelsize = 25, ylabelsize = 25, zlabelsize = 25, xlabelfont = :italic, ylabelfont = :italic, zlabelfont = :italic, perspectiveness = 0.4, aspect = :data) const plotbands_default_axis2D = (; xlabel = "ϕ", ylabel = "ε", autolimitaspect = nothing) const plotbands_default_lscene = (;) const plotbands_default_2D = (plotbands_default_figure, plotbands_default_axis2D) const plotbands_default_3D = (plotbands_default_figure, plotbands_default_axis3D, plotbands_default_lscene) ## inspector defaults const default_inspector = (; fontsize = 15) #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
9728
""" qplot(object; figure = (;), axis = (;), fancyaxis = true, inspector = true, plotkw...) Render a plot of `object` using the `Makie` package. Supported `object`s and associated specialized plot recipes: - `object::Lattice` -> `plotlattice` (supports also `LatticeSlice`s) - `object::Hamiltonian` -> `plotlattice` (supports also `ParametricHamiltonian`) - `object::GreenFunction` -> `plotlattice` (supports also `OpenHamiltonian`, see below) - `object::Bandstructure` -> `plotbands` (supports also slices of `Bandstructure`) - `object::Subband` -> `plotbands` (supports also collections of `Subbands`) Supported `Makie` backends include `GLMakie`, `CairoMakie`, `WGLMakie`, etc. Instead of `using Makie`, load a specific backend directly, e.g. `using GLMakie`. qplot(g::Union{GreenFunction,OpenHamiltonian}; children = (plotkw₁::NamedTuple, plotkw₂::NamedTuple, ...), kw...) Render the parent Hamiltonian of `g`, along with a representation of each of `g`'s self-energies. Specific `plotkwᵢ` keywords for each self-energy can be given in `children`, cycling over them if necessary. ## Keywords - `figure`: keywords to pass onto the plot `Figure` (e.g. `size` or `fontsize`, see `Makie.Figure`) - `axis`: keywords to pass on to the plot axis (see `Makie.LScene`, `Makie.Axis3` or `Makie.Axis` for options) - `fancyaxis::Bool`: for 3D plots, whether to use `Makie.LScene` (supports zoom+pan) instead of `Makie.Axis3` - `inspector::Bool`: whether to enable interactive tooltips of plot elements - `plotkw`: additional keywords to pass on to `plotlattice` or `plotbands`, see their docstring for details. # See also `plotlattice`, `plotbands`, `qplotdefaults` """ qplot """ qplot!(object; plotkw...) Render `object` on the currently active scene using either `plotlattice!` (for lattice-based objects) or `plotbands!` (for bands-based object), and passing `plotkw` keywords along. See their respective docstrings for possible keywords. """ qplot! """ plotlattice(lat::Lattice; kw...) Render the lattice unit cell and its Bravais vectors. plotlattice(lat::LatticeSlice; kw...) Render a finite subset of sites in a lattice and its Bravais vectors. plotlattice(h::AbstractHamiltonian; kw...) Render the lattice on which `h` is defined, together with all hoppings in the form of inter-site links. plotlattice(h::GreenFunction; kw...) Render the lattice on which `h` is defined, together with all hoppings in the form of inter-site links, and a representation of contacts. ## Keywords - `flat = true`: whether to render sites and hops as flat circles and lines, or as 3D meshes - `force_transparency = false`: whether to disable occlusion of all non-transparent elements. Useful in case `inspector` tooltips are occluded. - `shellopacity = 0.07`: opacity of elements surrounding the unitcell or the set of selected sites (dubbed "shell") - `cellopacity = 0.03`: opacity of the unitcell's boundingbox - `cellcolor = RGBAf(0,0,1)`: color of the unitcell's boundingbox - `boundarycolor = RGBAf(1,0,0)`: color of boundary cells for GreenFunction plots - `boundaryopacity = 0.07`: opacity of boundary cells for GreenFunction plots - `sitecolor = missing`: color of sites, as a index in `sitecolormap`, a named color, a `Makie.Colorant`, a collection of either, or as a site shader (see below). If `missing`, cycle through `sitecolormap`. If a collection, cycle through that. - `sitecolormap = :Spectral_9`: colormap to use for `sitecolor` (see options in https://tinyurl.com/cschemes) - `siteopacity = missing`: opacity of sites, as a real between 0 and 1, or as a site shader (see below). If `missing`, obey `shellopacity`. - `siteradius = 0.25`: radius of sites as a real in units of lattice dimensions, or as a site shader (see below) - `minmaxsiteradius = (0.0, 0.5)`: if `sitedradius` is a shader, minimum and maximum site radius. - `siteoutline = 2`: thickness of the outline around flat sites - `siteoutlinedarken = 0.6`: darkening factor of the outline around flat sites - `sitedarken = 0.0`: darkening factor for sites - `hopcolor = missing`: color of hops, as a index in `hopcolormap`, a named color, a `Makie.Colorant`, a collection of either, or as a hop shader (see below). If `missing`, cycle through `sitecolormap`. If a collection, cycle through that. - `hopcolormap = :Spectral_9`: colormap to use for `hopcolor` (see options in https://tinyurl.com/cschemes) - `hopopacity = missing`: opacity of hops, as a real between 0 and 1, or as a hop shader (see below) - `hopradius = 0.03`: radius of hops as a real number in units of lattice dimensions, or as a hop shader (see below) - `hoppixels = 6`: if `flat = true` fixed hop linewidth in pixels, or maximum pixel linewidth if `hopradius` is a shader. - `minmaxhopradius = (0, 0.1)`: if `hopdradius` is a shader, minimum and maximum hop radius. - `hopdarken = 0.85`: darkening factor for hops - `selector = missing`: an optional `siteselector(; sites...)` to filter which sites are shown (see `siteselector`) - `hide = (:cell,)`: collection of elements to hide, to choose from `(:hops, :sites, :hops, :bravais, :cell, :axes, :shell, :boundary, :contacts, :all)`. It can also be an empty collection or `nothing` to show all elements. - `children = missing`: collection of `NamedTuple`s of any of the above keywords to be applied (cyclically) to contacts in GreenFunction plots ## Shaders The element properties in the list above that accept site shaders may take either of these options - `(i, r) -> Real`: a real function of site index `i::Int` and site position `r::SVector`. - `AbstractVector`: a real vector representing the shading for each plotted site - `AbstractMatrix`: a real matrix whose summed rows represent the shading for each plotted site - `LocalSpectralDensitySolution`: a generator of local density of states at a fixed energy (see `ldos`). It is evaluated at the site position. - `CurrentDensitySolution`: a generator of local current density at a fixed energy (see `current`). It is taken as the sum of currents along all hops connected to the site. Element properties marked as accepting hop shaders may take either of these options - `((src, dst), (r, dr)) -> Real`: a real function of site indices `(src, dst)` and hop coordinates `(r, dr)` (see `hopselector` for definition of hop coordinates) - `AbstractVector`: a real vector `v` such that `(v[i]+v[j])/2` represents the shading for each hopping `j => i` - `AbstractMatrix`: a real matrix `m` such that `m[i,j]` represents the shading for each hopping `j => i` - `LocalSpectralDensitySolution`: a generator of local density of states at a fixed energy (see `ldos`). It is evaluated as the average between connected sites. - `CurrentDensitySolution`: a generator of local current density at a fixed energy (see `current`). It is taken as the current along the hop. """ plotlattice """ plotlattice!(object; kw...) Render lattice-based `object` on currently active scene. See `plotlattice` for possible keywords `kw` """ plotlattice! """ plotbands(b::Bandstructure; kw...) plotbands(s::Subband; kw...) plotbands(ss::AbstractVector{<:Subbands}; kw...) Render a `Bandstructure` object, a single subband (e.g. `s = b[1]`) or a collection of subbands or subband slices (e.g. `ss = b[1:4]` or `ss = b[(:,0,:)]`). ## Keywords - `color = missing`: color of subbands, as a index in `colormap`, a named color, a `Makie.Colorant`, or as a band shader (see below). If `missing`, cycle through `colormap`. - `colormap = :Spectral_9`: colormap to use for `color` (see options in https://tinyurl.com/cschemes) - `opacity = 1.0`: opacity of subbands, as a real between 0 and 1 or as a band shader (see below) - `size = 2`: stroke thickness, in pixels, when plotting line-like features. May also be a band shader in 2D plots (see below) - `minmaxsize = (0, 6)`: if `size` is a shader, minimum and maximum stroke thickness, in pixels. - `nodesizefactor = 4`: relative size of nodes respect to subbands. - `nodedarken = 0.0`: darkening factor of nodes despect to subband color. - `hide = ()`: collection of elements to hide, to choose from `(:nodes, :bands, :wireframe)` ## Shaders The element properties in the list above that accept band shaders may take either of these options - `(ψ, ϵ, ϕs) -> Real`: a real function of the eigenstates `ψ::Matrix` in the subband, eigenenergy `ϵ`, and Bloch phases `ϕs::SVector`. """ plotbands """ plotbands!(object; kw...) Render bands-based `object` on currently active scene. See `plotbands` for possible keywords `kw` """ plotbands! """ qplotdefaults(; figure = missing, axis2D = missing, axis3D = missing, lscene = missing, inspector = missing) Define default values for the `figure` and `axis` keyword arguments of `qplot`. The `axis2D` defaults are applied to `axis` for 2D plots, while `lscene` or `axis3D` are applied to `axis` if `fancyaxis` is `true` or `false`, respectively. Similarly, the `inspector` defaults are passed to `DataInspector` if tooltips are activated. qplotdefaults(defaults::NamedTuple) Equivalent to `qplotdefaults(; defaults...)` # Examples ```jldoctest julia> qplotdefaults(figure = (size = (1000, 1000),)) (user_default_figure = (size = (1000, 1000),), user_default_axis2D = NamedTuple(), user_default_axis3D = NamedTuple(), user_default_lscene = NamedTuple(), user_default_inspector = NamedTuple()) julia> qplotdefaults(axis2D = (xlabel = "X",), inspector = (fontsize = 30,)) (user_default_figure = (size = (1000, 1000),), user_default_axis2D = (xlabel = "X",), user_default_axis3D = NamedTuple(), user_default_lscene = NamedTuple(), user_default_inspector = (fontsize = 30,)) ``` """ qplotdefaults
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
7851
############################################################################################ # plotlattice recipe #region @recipe(PlotBands) do scene Theme( colormap = :Spectral_9, color = missing, opacity = 1.0, size = 1, minmaxsize = (0, 6), nodesizefactor = 4, nodedarken = 0.0, hide = () # :nodes, :bands, :wireframe ) end #endregion ############################################################################################ # qplot # Supports plotting b::Bandstructure, but also b[...]::Vector{Subbands} and # slice(b, ...)::Vector{Mesh} #region function Quantica.qplot(b::PlotBandsArgumentType; fancyaxis = true, axis = axis_defaults(b, fancyaxis), figure = user_default_figure, inspector = true, plotkw...) fig, ax = empty_fig_axis(b; fancyaxis, axis, figure) plotbands!(ax, b; plotkw...) inspector && DataInspector(; default_inspector..., user_default_inspector...) return fig end Quantica.qplot!(b::PlotBandsArgumentType; kw...) = plotbands!(b; kw...) #endregion ############################################################################################ # PlotBands Primitives #region struct MeshPrimitives{E,S} verts::Vector{Point{E,Float32}} simps::Vector{Int} # flattened neighbor matrix hues::Vector{Float32} opacities::Vector{Float32} sizes::Vector{Float32} tooltips::Vector{String} colors::Vector{RGBAf} end #region ## Constructors ## MeshPrimitives{E,S}() where {E,S} = MeshPrimitives{E,S}(Point{E,Float32}[], Int[], Float32[], Float32[], Float32[], String[], RGBAf[]) function meshprimitives(meshes, plot) # function barrier opts = (plot[:color][], plot[:opacity][], plot[:size][]) E, S = Quantica.dims(first(meshes)) mp = MeshPrimitives{E,S}() for (s, mesh) in enumerate(meshes) bandprimitives!(mp, mesh, s, opts) end update_colors!(mp, plot) update_sizes!(mp, plot) return mp end function bandprimitives!(mp, mesh, s, (hue, opacity, size)) offset = length(mp.verts) append!(mp.simps, offset .+ reinterpret(Int, Quantica.simplices(mesh))) for (ivert, vert) in enumerate(Quantica.vertices(mesh)) ψ = Quantica.states(vert) kϵ = Quantica.coordinates(vert) k = Quantica.base_coordinates(vert) ϵ = Quantica.energy(vert) push!(mp.verts, kϵ) push_subbandhue!(mp, hue, ψ, ϵ, k, s) push_subbandopacity!(mp, opacity, ψ, ϵ, k, s) push_subbandsize!(mp, size, ψ, ϵ, k, s) push_subbandtooltip!(mp, ψ, ϵ, k, s, ivert) end return mp end #endregion #region ## API ## simplices_matrix(s::Quantica.Subband) = simplices_matrix(Quantica.mesh(s)) simplices_matrix(m::Quantica.Mesh) = reshape(reinterpret(Int, Quantica.simplices(m)), Quantica.embdim(m), length(Quantica.simplices(m)))' simplices_matrix(mp::MeshPrimitives{<:Any,S}) where {S} = reshape(mp.simps, S, length(mp.simps) ÷ S)' ## push! ## push_subbandhue!(mp, ::Missing, ψ, ϵ, k, s) = push!(mp.hues, s) push_subbandhue!(mp, hue::Real, ψ, ϵ, k, s) = push!(mp.hues, hue) push_subbandhue!(mp, hue::Function, ψ, ϵ, k, s) = push!(mp.hues, hue(ψ, ϵ, k)) push_subbandhue!(mp, ::Symbol, ψ, ϵ, k, s) = push!(mp.hues, 0f0) push_subbandhue!(mp, ::Makie.Colorant, ψ, ϵ, k, s) = push!(mp.hues, 0f0) push_subbandhue!(mp, hue, ψ, ϵ, k, s) = argerror("Unrecognized color") push_subbandopacity!(mp, opacity::Real, ψ, ϵ, k, s) = push!(mp.opacities, opacity) push_subbandopacity!(mp, opacity::Function, ψ, ϵ, k, s) = push!(mp.opacities, opacity(ψ, ϵ, k)) push_subbandopacity!(mp, opacity, ψ, ϵ, k, s) = argerror("Unrecognized opacity") push_subbandsize!(mp, size::Real, ψ, ϵ, k, s) = push!(mp.sizes, size) push_subbandsize!(mp, size::Function, ψ, ϵ, k, s) = push!(mp.sizes, size(ψ, ϵ, k)) push_subbandsize!(mp, size, ψ, ϵ, k, s) = argerror("Unrecognized size") push_subbandtooltip!(mp, ψ, ϵ, k, s, iv) = push!(mp.tooltips, "Subband $s, vertex $iv:\n k = $k\n ϵ = $ϵ\n degeneracy = $(size(ψ, 2))") ## update_color! ## function update_colors!(p::MeshPrimitives, plot) extremahues = safeextrema(p.hues) extremaops = safeextrema(p.opacities) color = plot[:color][] opacity = plot[:opacity][] colormap = Makie.ColorSchemes.colorschemes[plot[:colormap][]] # reuse update_colors! from plotlattice.jl return update_colors!(p, extremahues, extremaops, color, opacity, colormap, 0.0) end ## update_sizes! ## function update_sizes!(p::MeshPrimitives, plot) extremasizes = safeextrema(p.sizes) size = plot[:size][] minmaxsize = plot[:minmaxsize][] return update_sizes!(p, extremasizes, size, minmaxsize) # function barrier end # almost identical to update_radii! from plotlattice.jl function update_sizes!(p, extremasizes, size, minmaxsize) for (i, r) in enumerate(p.sizes) p.sizes[i] = primitive_size(normalize_range(r, extremasizes), size, minmaxsize) end return p end primitive_size(normr, size::Number, minmaxsize) = size primitive_size(normr, size, (mins, maxs)) = mins + (maxs - mins) * normr #endregion #endregion ############################################################################################ # PlotBands for 1D and 2D Bandstructure (2D and 3D embedding space) #region function Makie.plot!(plot::PlotBands{Tuple{S}}) where {S<:PlotBandsArgumentType} meshes = Quantica.meshes(to_value(plot[1])) mp = meshprimitives(meshes, plot) return plotmeshes!(plot, mp) end plotmeshes!(plot, mp::MeshPrimitives{<:Any,E}) where {E} = Quantica.argerror("Can only plot meshes in 2D and 3D space, got an $(E)D mesh") function plotmeshes!(plot, mp::MeshPrimitives{<:Any,2}) if !ishidden((:bands, :subbands), plot) verts = mp.verts[mp.simps] color = mp.colors[mp.simps] linewidth = mp.sizes[mp.simps] linesegments!(plot, verts; color, linewidth, inspectable = false) end if !ishidden((:nodes, :points, :vertices), plot) inspector_label = (self, i, r) -> mp.tooltips[i] markersize = mp.sizes .* plot[:nodesizefactor][] color´ = darken.(mp.colors, plot[:nodedarken][]) scatter!(plot, mp.verts; color = color´, markersize, inspector_label) end return plot end function plotmeshes!(plot, mp::MeshPrimitives{<:Any,3}) transparency = has_transparencies(plot[:opacity][]) if !ishidden((:bands, :subbands), plot) simps = simplices_matrix(mp) if !ishidden((:wireframe, :simplices), plot) color´ = darken.(mp.colors, plot[:nodedarken][]) poly!(plot, mp.verts, simps; color = mp.colors, inspectable = false, transparency, strokewidth = plot[:size][]) else mesh!(plot, mp.verts, simps; color = mp.colors, inspectable = false, transparency) end end if !ishidden((:nodes, :points, :vertices), plot) inspector_label = (self, i, r) -> mp.tooltips[i] markersize = mp.sizes .* plot[:nodesizefactor][] color´ = darken.(mp.colors, plot[:nodedarken][]) scatter!(plot, mp.verts; color = color´, markersize, transparency, inspector_label) end return plot end #endregion ############################################################################################ # convert_argments #region function Makie.convert_arguments(T::Type{<:Makie.Mesh}, s::Quantica.Subband{<:Any,3}) verts = [Point3f(Quantica.coordinates(v)) for v in Quantica.vertices(s)] simps = simplices_matrix(s) return convert_arguments(T, verts, simps) end function Makie.convert_arguments(::Type{<:LineSegments}, s::Quantica.Subband{<:Any,2}) verts = Quantica.vertices(s) simps = Quantica.simplices(s) segments = [Point2f(Quantica.coordinates(verts[i])) for s in simps for i in s] return (segments,) end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
30351
############################################################################################ # plotlattice recipe #region @recipe(PlotLattice) do scene Theme( flat = true, force_transparency = false, shellopacity = 0.07, cellopacity = 0.03, cellcolor = RGBAf(0,0,1), boundarycolor = RGBAf(1,0,0), boundaryopacity = 0.07, sitecolor = missing, # accepts (i, r) -> float, IndexableObservable siteopacity = missing, # accepts (i, r) -> float, IndexableObservable minmaxsiteradius = (0.0, 0.5), siteradius = 0.2, # accepts (i, r) -> float, IndexableObservable siteradiusfactor = 1.0, # independent multiplier to apply to siteradius siteoutline = 2, siteoutlinedarken = 0.6, sitedarken = 0.0, sitecolormap = :Spectral_9, hopcolor = missing, # accepts ((i,j), (r,dr)) -> float, IndexableObservable hopopacity = missing, # accepts ((i,j), (r,dr)) -> float, IndexableObservable minmaxhopradius = (0.0, 0.1), hopradius = 0.01, # accepts ((i,j), (r,dr)) -> float, IndexableObservable hopdarken = 0.85, hopcolormap = :Spectral_9, hoppixels = 2, selector = missing, hide = :cell, # :hops, :sites, :bravais, :cell, :axes, :shell, :boundary, :contacts, :all isAxis3 = false, # for internal use, to fix marker scaling marker = :auto, children = missing ) end #endregion ############################################################################################ # qplot #region function Quantica.qplot(h::PlotLatticeArgumentType; fancyaxis = true, axis = axis_defaults(h, fancyaxis), figure = user_default_figure, inspector = true, plotkw...) fig, ax = empty_fig_axis(h; fancyaxis, axis, figure) plotkw´ = (isAxis3 = ax isa Axis3, inspector, plotkw...) # isAxis3 necessary to fix marker scaling plotlattice!(ax, h; plotkw´...) inspector && DataInspector(; default_inspector..., user_default_inspector...) return fig end Quantica.qplot!(x::PlotLatticeArgumentType; kw...) = plotlattice!(x; kw...) #endregion ############################################################################################ # PlotLattice Primitives #region struct SitePrimitives{E} centers::Vector{Point{E,Float32}} indices::Vector{Int} hues::Vector{Float32} opacities::Vector{Float32} radii::Vector{Float32} tooltips::Vector{String} colors::Vector{RGBAf} end struct HoppingPrimitives{E} centers::Vector{Point{E,Float32}} vectors::Vector{Vec{E,Float32}} indices::Vector{Tuple{Int,Int}} hues::Vector{Float32} opacities::Vector{Float32} radii::Vector{Float32} tooltips::Vector{String} colors::Vector{RGBAf} end const ColorOrSymbol = Union{Symbol, Makie.Colorant} const ColorsPerSublat = Union{NTuple{<:Any,ColorOrSymbol}, AbstractVector{<:ColorOrSymbol}} #region ## Constructors ## SitePrimitives{E}() where {E} = SitePrimitives(Point{E,Float32}[], Int[], Float32[], Float32[], Float32[], String[], RGBAf[]) HoppingPrimitives{E}() where {E} = HoppingPrimitives(Point{E,Float32}[], Vec{E,Float32}[], Tuple{Int,Int}[], Float32[], Float32[], Float32[], String[], RGBAf[]) function siteprimitives(ls, h, plot, is_shell) # function barrier opts = (plot[:sitecolor][], plot[:siteopacity][], plot[:shellopacity][], plot[:siteradius][]) opts´ = maybe_evaluate_observable.(opts, Ref(ls)) return _siteprimitives(ls, h, opts´, is_shell) end function _siteprimitives(ls::LatticeSlice{<:Any,E}, h, opts, is_shell) where {E} sp = SitePrimitives{E}() lat = parent(ls) for (i´, cs) in enumerate(Quantica.cellsites(ls)) ni = Quantica.cell(cs) i = Quantica.siteindex(cs) # in case opts contains some array over latslice (from an observable) opts´ = maybe_getindex.(opts, i´) push_siteprimitive!(sp, opts´, lat, i, ni, view(h, cs), is_shell) end return sp end function hoppingprimitives(ls, ls´, h, siteradii, plot) # function barrier opts = (plot[:hopcolor][], plot[:hopopacity][], plot[:shellopacity][], plot[:hopradius][], plot[:flat][]) opts´ = maybe_evaluate_observable.(opts, Ref(ls)) return _hoppingprimitives(ls, ls´, h, opts´, siteradii) end function _hoppingprimitives(ls::LatticeSlice{<:Any,E}, ls´, h, opts, siteradii) where {E} hp = HoppingPrimitives{E}() hp´ = HoppingPrimitives{E}() lat = parent(ls) sdict = Quantica.siteindexdict(ls) sdict´ = Quantica.siteindexdict(ls´) for (j´, csj) in enumerate(Quantica.cellsites(ls)) nj = Quantica.cell(csj) j = Quantica.siteindex(csj) siteradius = isempty(siteradii) ? Float32(0) : siteradii[j´] for har in harmonics(h) dn = Quantica.dcell(har) ni = nj + dn mat = Quantica.matrix(har) rows = rowvals(mat) for ptr in nzrange(mat, j) i = rows[ptr] Quantica.isonsite((i, j), dn) && continue csi = sites(ni, i) i´ = get(sdict, csi, nothing) if i´ === nothing # dst is not in latslice if haskey(sdict´, csi) # dst is in latslice´ opts´ = maybe_getindex.(opts, j´) push_hopprimitive!(hp´, opts´, lat, (i, j), (ni, nj), siteradius, view(h, csi, csj), false) end else opts´ = maybe_getindex.(opts, i´, j´) push_hopprimitive!(hp, opts´, lat, (i, j), (ni, nj), siteradius, view(h, csi, csj), true) end end end end return hp, hp´ end maybe_evaluate_observable(o::Quantica.IndexableObservable, ls) = o[ls] maybe_evaluate_observable(x, ls) = x maybe_getindex(v::AbstractVector{<:Number}, i) = v[i] maybe_getindex(m::AbstractMatrix{<:Number}, i) = sum(view(m, i, :)) maybe_getindex(m::Quantica.AbstractSparseMatrixCSC{<:Number}, i) = sum(view(nonzeros(m), nzrange(m, i))) maybe_getindex(v, i) = v maybe_getindex(v::AbstractVector{<:Number}, i, j) = 0.5*(v[i] + v[j]) maybe_getindex(m::AbstractMatrix{<:Number}, i, j) = m[i, j] maybe_getindex(v, i, j) = v ## push! ## # sitecolor here could be a color, a symbol, a vector/tuple of either, a number, a function, or missing function push_siteprimitive!(sp, (sitecolor, siteopacity, shellopacity, siteradius), lat, i, ni, matii, is_shell) r = Quantica.site(lat, i, ni) s = Quantica.sitesublat(lat, i) push!(sp.centers, r) push!(sp.indices, i) push_sitehue!(sp, sitecolor, i, r, s) push_siteopacity!(sp, siteopacity, shellopacity, i, r, is_shell) push_siteradius!(sp, siteradius, i, r) push_sitetooltip!(sp, i, r, matii) return sp end push_sitehue!(sp, ::Union{Missing,ColorsPerSublat}, i, r, s) = push!(sp.hues, s) push_sitehue!(sp, sitecolor::Real, i, r, s) = push!(sp.hues, sitecolor) push_sitehue!(sp, sitecolor::Function, i, r, s) = push!(sp.hues, sitecolor(i, r)) push_sitehue!(sp, ::Symbol, i, r, s) = push!(sp.hues, 0f0) push_sitehue!(sp, ::Makie.Colorant, i, r, s) = push!(sp.hues, 0f0) push_sitehue!(sp, sitecolor, i, r, s) = argerror("Unrecognized sitecolor") push_siteopacity!(sp, ::Missing, shellopacity, i, r, is_shell) = push!(sp.opacities, is_shell ? 1.0 : shellopacity) push_siteopacity!(sp, ::Missing, ::Missing, i, r, is_shell) = push!(sp.opacities, 1.0) push_siteopacity!(sp, siteopacity::Real, shellopacity, i, r, is_shell) = push!(sp.opacities, is_shell ? siteopacity : shellopacity) push_siteopacity!(sp, siteopacity::Function, shellopacity, i, r, is_shell) = push!(sp.opacities, is_shell ? siteopacity(i, r) : shellopacity) push_siteopacity!(sp, siteopacity, shellopacity, i, r, is_shell) = argerror("Unrecognized siteradius") push_siteradius!(sp, siteradius::Real, i, r) = push!(sp.radii, siteradius) push_siteradius!(sp, siteradius::Function, i, r) = push!(sp.radii, siteradius(i, r)) push_siteradius!(sp, siteradius, i, r) = argerror("Unrecognized siteradius") push_sitetooltip!(sp, i, r, mat) = push!(sp.tooltips, matrixstring(i, mat)) push_sitetooltip!(sp, i, r) = push!(sp.tooltips, positionstring(i, r)) # hopcolor here could be a color, a symbol, a vector/tuple of either, a number, a function, or missing function push_hopprimitive!(hp, (hopcolor, hopopacity, shellopacity, hopradius, flat), lat, (i, j), (ni, nj), radius, matij, is_shell) src, dst = Quantica.site(lat, j, nj), Quantica.site(lat, i, ni) # If end site is opaque (not in outer shell), dst is midpoint, since the inverse hop will be plotted too # otherwise it is shifted by radius´ = radius minus hopradius correction if flat = false, and src also radius´ = flat ? radius : sqrt(max(0, radius^2 - hopradius^2)) unitvec = normalize(dst - src) dst = is_shell ? (src + dst)/2 : dst - unitvec * radius´ src = src + unitvec * radius´ r, dr = (src + dst)/2, (dst - src) sj = Quantica.sitesublat(lat, j) push!(hp.centers, r) push!(hp.vectors, dr) push!(hp.indices, (i, j)) push_hophue!(hp, hopcolor, (i, j), (r, dr), sj) push_hopopacity!(hp, hopopacity, shellopacity, (i, j), (r, dr), is_shell) push_hopradius!(hp, hopradius, (i, j), (r, dr)) push_hoptooltip!(hp, (i, j), matij) return hp end push_hophue!(hp, ::Union{Missing,ColorsPerSublat}, ij, rdr, s) = push!(hp.hues, s) push_hophue!(hp, hopcolor::Real, ij, rdr, s) = push!(hp.hues, hopcolor) push_hophue!(hp, hopcolor::Function, ij, rdr, s) = push!(hp.hues, hopcolor(ij, rdr)) push_hophue!(hp, ::Symbol, ij, rdr, s) = push!(hp.hues, 0f0) push_hophue!(hp, ::Makie.Colorant, ij, rdr, s) = push!(hp.hues, 0f0) push_hophue!(hp, hopcolor, ij, rdr, s) = argerror("Unrecognized hopcolor") push_hopopacity!(hp, ::Missing, shellopacity, ij, rdr, is_shell) = push!(hp.opacities, is_shell ? 1.0 : shellopacity) push_hopopacity!(hp, ::Missing, ::Missing, ij, rdr, is_shell) = push!(hp.opacities, 1.0) push_hopopacity!(hp, hopopacity::Real, shellopacity, ij, rdr, is_shell) = push!(hp.opacities, hopopacity) push_hopopacity!(hp, hopopacity::Function, shellopacity, ij, rdr, is_shell) = push!(hp.opacities, hopopacity(ij, rdr)) push_hopopacity!(hp, hopopacity, shellopacity, ij, rdr, is_shell) = argerror("Unrecognized hopradius") push_hopradius!(hp, hopradius::Real, ij, rdr) = push!(hp.radii, hopradius) push_hopradius!(hp, hopradius::Function, ij, rdr) = push!(hp.radii, hopradius(ij, rdr)) push_hopradius!(hp, hopradius, ij, rdr) = argerror("Unrecognized hopradius") push_hoptooltip!(hp, (i, j), mat) = push!(hp.tooltips, matrixstring(i, j, mat)) #endregion #region ## API ## embdim(p::SitePrimitives{E}) where {E} = E embdim(p::HoppingPrimitives{E}) where {E} = E ## update_color! ## update_colors!(p::Union{SitePrimitives,HoppingPrimitives}, plot) = update_colors!(p, plot, safeextrema(p.hues), safeextrema(p.opacities)) update_colors!(p::SitePrimitives, plot, extremahues, extremaops) = update_colors!(p, extremahues, extremaops, plot[:sitecolor][], plot[:siteopacity][], Makie.ColorSchemes.colorschemes[plot[:sitecolormap][]], plot[:sitedarken][]) update_colors!(p::HoppingPrimitives, plot, extremahues, extremaops) = update_colors!(p, extremahues, extremaops, plot[:hopcolor][], plot[:hopopacity][], Makie.ColorSchemes.colorschemes[plot[:hopcolormap][]], plot[:hopdarken][]) function update_colors!(p, extremahues, extremaops, pcolor, popacity, colormap, pdarken) resize!(p.colors, length(p.hues)) for (i, (c, α)) in enumerate(zip(p.hues, p.opacities)) p.colors[i] = transparent( darken(primitive_color(c, extremahues, colormap, pcolor), pdarken), primitite_opacity(α, extremaops, popacity)) end return p end # color == missing means sublat color primitive_color(colorindex, extrema, colormap, ::Missing) = RGBAf(colormap[mod1(round(Int, colorindex), length(colormap))]) primitive_color(colorindex, extrema, colormap, colorname::Symbol) = parse_color(colorname) primitive_color(colorindex, extrema, colormap, pcolor::Makie.Colorant) = parse_color(pcolor) primitive_color(colorindex, extrema, colormap, colors::ColorsPerSublat) = parse_color(colors[mod1(round(Int, colorindex), length(colors))]) primitive_color(colorindex, extrema, colormap, _) = parse_color(colormap[normalize_range(colorindex, extrema)]) parse_color(colorname::Symbol) = parse(RGBAf, colorname) parse_color(color::Makie.Colorant) = convert(RGBAf, color) # opacity::Function should be scaled primitite_opacity(α, extrema, ::Function) = normalize_range(α, extrema) # otherwise (opacity::Union{Missing,Real}) we leave it fixed primitite_opacity(α, extrema, _) = α ## update_radii! ## update_radii!(p, plot) = update_radii!(p, plot, safeextrema(p.radii)) function update_radii!(p::SitePrimitives, plot, extremarads) siteradius = plot[:siteradius][] minmaxsiteradius = plot[:minmaxsiteradius][] return update_radii!(p, extremarads, siteradius, minmaxsiteradius) end function update_radii!(p::HoppingPrimitives, plot, extremarads) hopradius = plot[:hopradius][] minmaxhopradius = plot[:minmaxhopradius][] return update_radii!(p, extremarads, hopradius, minmaxhopradius) end function update_radii!(p, extremarads, radius, minmaxradius) for (i, r) in enumerate(p.radii) p.radii[i] = primitive_radius(normalize_range(r, extremarads), radius, minmaxradius) end return p end primitive_radius(normr, radius::Number, minmaxradius) = radius primitive_radius(normr, radius, (minr, maxr)) = minr + (maxr - minr) * normr ## primitive_scales ## function primitive_scales(p::HoppingPrimitives, plot) hopradius = plot[:hopradius][] minmaxhopradius = plot[:minmaxhopradius][] scales = Vec3f[] for (r, v) in zip(p.radii, p.vectors) push!(scales, primitive_scale(r, v, hopradius, minmaxhopradius)) end return scales end primitive_scale(normr, v, hopradius::Number, minmaxhopradius) = Vec3f(hopradius, hopradius, norm(v)/2) function primitive_scale(normr, v, hopradius, (minr, maxr)) hopradius´ = minr + (maxr - minr) * normr return Vec3f(hopradius´, hopradius´, norm(v)/2) end ## primitive_segments ## function primitive_segments(p::HoppingPrimitives{E}, plot) where {E} segments = Point{E,Float32}[] for (r, dr) in zip(p.centers, p.vectors) push!(segments, r - dr/2) push!(segments, r + dr/2) end return segments end ## primitive_linewidths ## function primitive_linewidths(p::HoppingPrimitives{E}, plot) where {E} hoppixels = plot[:hoppixels][] hopradius = plot[:hopradius][] linewidths = Float32[] for r in p.radii linewidth = primitive_linewidth(r, hopradius, hoppixels) append!(linewidths, (linewidth, linewidth)) end return linewidths end primitive_linewidth(normr, hopradius::Number, hoppixels) = hoppixels primitive_linewidth(normr, hopradius, hoppixels) = hoppixels * normr #endregion #endregion ############################################################################################ # PlotLattice for different arguments #region function Makie.plot!(plot::PlotLattice{Tuple{L}}) where {L<:Lattice} lat = to_value(plot[1]) h = Quantica.hamiltonian(lat) return plotlattice!(plot, h; plot.attributes...) end function Makie.plot!(plot::PlotLattice{Tuple{L}}) where {L<:LatticeSlice} ls = to_value(plot[1]) lat = Quantica.parent(ls) h = Quantica.hamiltonian(lat) return plotlattice!(plot, h, ls; plot.attributes...) end function Makie.plot!(plot::PlotLattice{Tuple{L}}) where {L<:ParametricHamiltonian} ph = to_value(plot[1]) h = ph() return plotlattice!(plot, h; plot.attributes...) end function Makie.plot!(plot::PlotLattice{Tuple{H}}) where {H<:Hamiltonian} h = to_value(plot[1]) lat = Quantica.lattice(h) sel = sanitize_selector(plot[:selector][], lat) latslice = lat[sel] return plotlattice!(plot, h, latslice; plot.attributes...) end # For E < 2 Hamiltonians, promote to 2D function Makie.plot!(plot::PlotLattice{Tuple{H}}) where {H<:Hamiltonian{<:Any,1}} h = Hamiltonian{2}(to_value(plot[1])) return plotlattice!(plot, h; plot.attributes...) end function Makie.plot!(plot::PlotLattice{Tuple{H,S}}) where {H<:Hamiltonian{<:Any,1},S<:LatticeSlice} h = Hamiltonian{2}(to_value(plot[1])) lat = Quantica.lattice(h) l = Quantica.unsafe_replace_lattice(to_value(plot[2]), lat) return plotlattice!(plot, h, l; plot.attributes...) end function Makie.plot!(plot::PlotLattice{Tuple{H,S,S´}}) where {H<:Hamiltonian{<:Any,1},S<:LatticeSlice,S´<:LatticeSlice} h = Hamiltonian{2}(to_value(plot[1])) lat = Quantica.lattice(h) l = Quantica.unsafe_replace_lattice(to_value(plot[2]), lat) l´ = Quantica.unsafe_replace_lattice(to_value(plot[3]), lat) return plotlattice!(plot, h, l, l´; plot.attributes...) end function Makie.plot!(plot::PlotLattice{Tuple{H,S}}) where {H<:Hamiltonian,S<:LatticeSlice} h = to_value(plot[1]) latslice = to_value(plot[2]) latslice´ = Quantica.growdiff(latslice, h) return plotlattice!(plot, h, latslice, latslice´; plot.attributes...) end function Makie.plot!(plot::PlotLattice{Tuple{H,S,S´}}) where {H<:Hamiltonian,S<:LatticeSlice,S´<:LatticeSlice} h = to_value(plot[1]) latslice = to_value(plot[2]) # selected sites latslice´ = to_value(plot[3]) # shell around sites lat = Quantica.lattice(h) # if e.g. `plot[:sitecolor][] == :hopcolor`, replace with `plot[:hopcolor][]` resolve_cross_references!(plot) hidesites = ishidden((:sites, :all), plot) hidehops = ishidden((:hops, :hoppings, :links, :all), plot) hidebravais = ishidden((:bravais, :all), plot) hideshell = ishidden((:shell, :all), plot) || iszero(Quantica.latdim(h)) # plot bravais axes if !hidebravais plotbravais!(plot, lat, latslice) end # collect sites if !hidesites sp = siteprimitives(latslice, h, plot, true) # latslice if hideshell update_colors!(sp, plot) update_radii!(sp, plot) else sp´ = siteprimitives(latslice´, h, plot, false) # boundary shell around latslice joint_colors_radii_update!(sp, sp´, plot) end end # collect hops if !hidehops radii = hidesites ? () : sp.radii hp, hp´ = hoppingprimitives(latslice, latslice´, h, radii, plot) if hideshell update_colors!(hp, plot) update_radii!(hp, plot) else joint_colors_radii_update!(hp, hp´, plot) end end # plot hops if !hidehops hopopacity = plot[:hopopacity][] transparency = plot[:force_transparency][] || has_transparencies(hopopacity) if !plot[:flat][] plothops_shaded!(plot, hp, transparency) hideshell || plothops_shaded!(plot, hp´, true) else plothops_flat!(plot, hp, transparency) hideshell || plothops_flat!(plot, hp´, true) end end # plot sites if !hidesites siteopacity = plot[:siteopacity][] transparency = plot[:force_transparency][] || has_transparencies(siteopacity) if !plot[:flat][] plotsites_shaded!(plot, sp, transparency) hideshell || plotsites_shaded!(plot, sp´, true) else plotsites_flat!(plot, sp, transparency) hideshell || plotsites_flat!(plot, sp´, true) end end return plot end function Makie.plot!(plot::PlotLattice{Tuple{G}}) where {G<:GreenFunction} g = to_value(plot[1]) gsel = haskey(plot, :selector) && plot[:selector][] !== missing ? plot[:selector][] : green_selector(g) h = hamiltonian(g) latslice = lattice(h)[gsel] latslice´ = Quantica.growdiff(latslice, h) L = Quantica.latdim(h) squaremarker = !plot[:flat][] ? Rect3f(Vec3f(-0.5), Vec3f(1)) : Rect2 # plot boundary as cells if !ishidden((:boundary, :boundaries), plot) bsel = boundary_selector(g) blatslice = latslice[bsel] blatslice´ = latslice´[bsel] if L > 1 bkws = (; plot.attributes..., hide = (:axes, :sites, :hops), cellcolor = :boundarycolor, cellopacity = :boundaryopacity) isempty(blatslice) || plotlattice!(plot, blatslice; bkws...) isempty(blatslice´) || plotlattice!(plot, blatslice´; bkws...) end hideB = Quantica.tupleflatten(:bravais, plot[:hide][]) bkws´ = (; plot.attributes..., hide = hideB, sitecolor = :boundarycolor, siteopacity = :boundaryopacity, siteradiusfactor = sqrt(2), marker = squaremarker) isempty(blatslice) || plotlattice!(plot, blatslice; bkws´...) isempty(blatslice´) || plotlattice!(plot, blatslice´; bkws´...) end # plot cells plotlattice!(plot, h, latslice, latslice´; plot.attributes...) # plot contacts if !ishidden((:contact, :contacts), plot) Σkws = Iterators.cycle(parse_children(plot[:children])) Σs = Quantica.selfenergies(Quantica.contacts(g)) hideΣ = Quantica.tupleflatten(:bravais, plot[:hide][]) for (Σ, Σkw) in zip(Σs, Σkws) Σplottables = Quantica.selfenergy_plottables(Σ) for Σp in Σplottables plottables, kws = get_plottables_and_kws(Σp) plotlattice!(plot, plottables...; plot.attributes..., hide = hideΣ, marker = squaremarker, kws..., Σkw...) end end end return plot end parse_children(::Missing) = (NamedTuple(),) parse_children(p::Tuple) = p parse_children(p::NamedTuple) = (p,) parse_children(p::Attributes) = parse_children(NamedTuple(p)) parse_children(p::Observable) = parse_children(p[]) sanitize_selector(::Missing, lat) = Quantica.siteselector(; cells = Quantica.zerocell(lat)) sanitize_selector(s::Quantica.SiteSelector, lat) = s sanitize_selector(s, lat) = argerror("Specify a site selector with `selector = siteselector(; kw...)`") function joint_colors_radii_update!(p, p´, plot) hext, oext = jointextrema(p.hues, p´.hues), jointextrema(p.opacities, p´.opacities) update_colors!(p, plot, hext, oext) update_colors!(p´, plot, hext, oext) rext = jointextrema(p.radii, p´.radii) update_radii!(p, plot, rext) update_radii!(p´, plot, rext) return nothing end ############################################################################################ # green_selector and boundary_selector: sites plotted for green functions #region function green_selector(g) mincell, maxcell = green_bounding_box(g) s = siteselector(cells = n -> all(mincell .<= n .<= maxcell)) return s end boundary_selector(g) = siteselector(cells = n -> isboundarycell(n, g)) function green_bounding_box(g) L = Quantica.latdim(hamiltonian(g)) return isempty(Quantica.contacts(g)) ? boundary_bounding_box(Val(L), Quantica.boundaries(g)...) : broaden_bounding_box(Quantica.boundingbox(g), Quantica.boundaries(g)...) end function broaden_bounding_box((mincell, maxcell)::Tuple{SVector{N},SVector{N}}, (dir, cell), bs...) where {N} isfinite(cell) || return (mincell, maxcell) mincell´ = SVector(ntuple(i -> i == dir ? min(mincell[i], cell + 1) : mincell[i], Val(N))) maxcell´ = SVector(ntuple(i -> i == dir ? max(maxcell[i], cell - 1) : maxcell[i], Val(N))) return broaden_bounding_box((mincell´, maxcell´), bs...) end broaden_bounding_box(mm::Tuple) = mm boundary_bounding_box(::Val{0}) = (SVector{0,Int}(), SVector{0,Int}()) function boundary_bounding_box(::Val{L}, (dir, cell), bs...) where {L} cell´ = isfinite(cell) ? cell + 1 : 0 m = SVector(ntuple(i -> i == dir ? cell´ : 0, Val(L))) return broaden_bounding_box((m, m), bs...) end isboundarycell(n, g) = any(((dir, cell),) -> n[dir] == cell, Quantica.boundaries(g)) get_plottables_and_kws(Σp::Tuple) = (Σp, NamedTuple()) get_plottables_and_kws(Σp::Quantica.FrankenTuple) = (Tuple(Σp), NamedTuple(Σp)) get_plottables_and_kws(Σp) = ((Σp,), NamedTuple()) #endregion ############################################################################################ # core plotting methods #region function plotsites_shaded!(plot::PlotLattice, sp::SitePrimitives, transparency) inspector_label = (self, i, r) -> sp.tooltips[i] sizefactor = plot[:siteradiusfactor][] if plot[:marker][] == :auto # circle markers marker = (;) else marker = (; marker = plot[:marker][]) sizefactor *= sqrt(2) end markersize = sizefactor * sp.radii meshscatter!(plot, sp.centers; color = sp.colors, markersize, marker..., space = :data, transparency, inspector_label) return plot end function plotsites_flat!(plot::PlotLattice, sp::SitePrimitives{E}, transparency) where {E} inspector_label = (self, i, r) -> sp.tooltips[i] sizefactor = ifelse(plot[:isAxis3][] && plot[:flat][], 0.5, sqrt(2)) * plot[:siteradiusfactor][] if plot[:marker][] == :auto # default circular markers marker = (;) else marker = (; marker = plot[:marker][]) sizefactor *= 0.5 end markersize = 2*sp.radii*sizefactor scatter!(plot, sp.centers; markersize, marker..., color = sp.colors, markerspace = :data, strokewidth = plot[:siteoutline][], strokecolor = darken.(sp.colors, Ref(plot[:siteoutlinedarken][])), transparency, inspector_label) return plot end function plothops_shaded!(plot::PlotLattice, hp::HoppingPrimitives, transparency) inspector_label = (self, i, r) -> hp.tooltips[i] scales = primitive_scales(hp, plot) cyl = Cylinder(Point3f(0., 0., -1), Point3f(0., 0, 1), Float32(1)) vectors = Quantica.sanitize_SVector.(SVector{3,Float32}, hp.vectors) # convert to 3D meshscatter!(plot, hp.centers; color = hp.colors, rotations = vectors, markersize = scales, marker = cyl, transparency, inspector_label) return plot end function plothops_flat!(plot::PlotLattice, hp::HoppingPrimitives, transparency) inspector_label = (self, i, r) -> (hp.tooltips[(i+1) ÷ 2]) colors = hp.colors segments = primitive_segments(hp, plot) linewidths = primitive_linewidths(hp, plot) linesegments!(plot, segments; space = :data, color = colors, linewidth = linewidths, transparency, inspector_label) return plot end function plotbravais!(plot::PlotLattice, lat::Lattice{<:Any,E,L}, latslice) where {E,L} iszero(L) && return plot bravais = Quantica.bravais(lat) vs = Point{E,Float32}.(Quantica.bravais_vectors(bravais)) vtot = sum(vs) r0 = Point{E,Float32}(Quantica.mean(Quantica.sites(lat))) - 0.5 * vtot if !ishidden(:axes, plot) for (v, color) in zip(vs, (:red, :green, :blue)) arrows!(plot, [r0], [v]; color, inspectable = false) end end if !ishidden((:cell, :cells), plot) && L > 1 cellcolor = parse(RGBAf, plot[:cellcolor][]) colface = transparent(cellcolor, plot[:cellopacity][]) coledge = transparent(cellcolor, 5 * plot[:cellopacity][]) rect = Rect{L,Int}(Point{L,Int}(0), Point{L,Int}(1)) mrect0 = GeometryBasics.mesh(rect, pointtype=Point{L,Float32}, facetype=QuadFace{Int}) vertices0 = mrect0.position mat = Quantica.bravais_matrix(bravais) for sc in Quantica.cellsdict(latslice) cell = Quantica.cell(sc) mrect = GeometryBasics.mesh(rect, pointtype=Point{E,Float32}, facetype=QuadFace{Int}) vertices = mrect.position vertices .= Ref(r0) .+ Ref(mat) .* (vertices0 .+ Ref(cell)) mesh!(plot, mrect; color = colface, transparency = true, shading = NoShading, inspectable = false) wireframe!(plot, mrect; color = coledge, transparency = true, strokewidth = 1, inspectable = false) end end return plot end #endregion ############################################################################################ # tooltip strings #region positionstring(i, r) = string("Site[$i] : ", vectorstring(r)) function vectorstring(r::SVector) rs = repr("text/plain", r) pos = findfirst(isequal('\n'), rs) return pos === nothing ? rs : rs[pos:end] end matrixstring(row, x) = string("Onsite[$row] : ", matrixstring(x)) matrixstring(row, col, x) = string("Hopping[$row, $col] : ", matrixstring(x)) function matrixstring(s::AbstractMatrix) ss = repr("text/plain", s) pos = findfirst(isequal('\n'), ss) return pos === nothing ? ss : ss[pos:end] end numberstring(x) = isreal(x) ? string(" ", real(x)) : isimag(x) ? string(" ", imag(x), "im") : string(" ", x) isreal(x) = all(o -> imag(o) ≈ 0, x) isimag(x) = all(o -> real(o) ≈ 0, x) #endregion ############################################################################################ # convert_arguments #region Makie.convert_arguments(::PointBased, lat::Lattice, sublat = missing) = (Point.(Quantica.sites(lat, sublat)),) Makie.convert_arguments(p::PointBased, lat::Lattice{<:Any,1}, sublat = missing) = Makie.convert_arguments(p, Quantica.lattice(lat, dim = Val(2)), sublat) Makie.convert_arguments(p::PointBased, h::Union{AbstractHamiltonian,GreenFunction,GreenSolution}, sublat = missing) = Makie.convert_arguments(p, Quantica.lattice(h), sublat) Makie.convert_arguments(p::Type{<:LineSegments}, g::Union{GreenFunction,GreenSolution}, sublat = missing) = Makie.convert_arguments(p, Quantica.hamiltonian(g), sublat) function Makie.convert_arguments(::Type{<:LineSegments}, h::AbstractHamiltonian{<:Any,E}, sublat = missing) where {E} segments = Point{max(E,2),Float32}[] lat = Quantica.lattice(h) for har in harmonics(h) colrng = sublat === missing ? axes(h, 2) : siterange(lat, sublat) mat = Quantica.unflat(har) dn = Quantica.dcell(har) for col in colrng, ptr in nzrange(mat, col) row = rowvals(mat)[ptr] row == col && continue append!(segments, (site(lat, col, zero(dn)), site(lat, row, dn))) end end return (segments,) end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
2057
############################################################################################ # tools #region function darken(rgba::RGBAf, v = 0.66) r = max(0, min(rgba.r * (1 - v), 1)) g = max(0, min(rgba.g * (1 - v), 1)) b = max(0, min(rgba.b * (1 - v), 1)) RGBAf(r,g,b,rgba.alpha) end darken(colors::Vector, v = 0.66) = darken.(colors, Ref(v)) transparent(rgba::RGBAf, v = 0.5) = RGBAf(rgba.r, rgba.g, rgba.b, clamp(rgba.alpha * v, 0f0, 1f0)) maybedim(color, dn, dimming) = iszero(dn) ? color : transparent(color, 1 - dimming) dnshell(::Lattice{<:Any,<:Any,L}, span = -1:1) where {L} = sort!(vec(SVector.(Iterators.product(ntuple(_ -> span, Val(L))...))), by = norm) ishidden(s, plot::Union{PlotLattice,PlotBands}) = ishidden(s, plot[:hide][]) ishidden(s, ::Nothing) = false ishidden(s, ::Pair) = false # for cellsites => function ishidden(s::Symbol, hide::Symbol) = s === hide ishidden(s::Symbol, hides::Tuple) = s in hides ishidden(ss, hides) = any(s -> ishidden(s, hides), ss) normalize_range(c::T, (min, max)) where {T} = min ≈ max ? T(c) : T((c - min)/(max - min)) jointextrema(v, v´) = min(minimum(v; init = 0f0), minimum(v´; init = 0f0)), max(maximum(v; init = 0f0), maximum(v´; init = 0f0)) safeextrema(v::Missing) = (Float32(0), Float32(1)) safeextrema(v) = isempty(v) ? (Float32(0), Float32(1)) : extrema(v) has_transparencies(x::Real) = !(x ≈ 1) has_transparencies(::Missing) = false has_transparencies(x) = true function resolve_cross_references!(plot::PlotLattice) names = (:shellopacity, :siteopacity, :hopopacity, :cellcolor, :cellopacity, :boundarycolor, :boundaryopacity, :sitecolor, :hopcolor, :siteradius, :hopradius) for name in names property = plot[name][] if property isa Symbol && property in names plot[name][] = plot[property][] end end foreach(names) do name property = plot[name][] property isa Symbol && property in names && argerror("Cyclic reference in plot properties") end return plot end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
2543
module Quantica const REPOISSUES = "https://github.com/pablosanjose/Quantica.jl/issues" using Base.Threads: Iterators using StaticArrays using NearestNeighbors using SparseArrays using SparseArrays: getcolptr, AbstractSparseMatrix, AbstractSparseMatrixCSC using LinearAlgebra using Dictionaries using ProgressMeter using Random using SuiteSparse using FunctionWrappers: FunctionWrapper using ExprTools using IntervalTrees using FrankenTuples using Statistics: mean using QuadGK using SpecialFunctions using DelimitedFiles export sublat, bravais_matrix, lattice, sites, supercell, hamiltonian, hopping, onsite, @onsite, @hopping, @onsite!, @hopping!, pos, ind, cell, position, plusadjoint, neighbors, siteselector, hopselector, diagonal, unflat, torus, transform, translate, combine, spectrum, energies, states, bands, subdiv, greenfunction, selfenergy, attach, plotlattice, plotlattice!, plotbands, plotbands!, qplot, qplot!, qplotdefaults, conductance, josephson, ldos, current, transmission, densitymatrix, OrbitalSliceArray, OrbitalSliceVector, OrbitalSliceMatrix, orbaxes export LatticePresets, LP, RegionPresets, RP, HamiltonianPresets, HP, ExternalPresets, EP export EigenSolvers, ES, GreenSolvers, GS export @SMatrix, @SVector, SMatrix, SVector, SA export ishermitian, tr, I, norm, dot, diag, det export ftuple # Types include("types.jl") # Preamble include("iterators.jl") include("builders.jl") include("tools.jl") include("docstrings.jl") # API include("specialmatrices.jl") include("selectors.jl") include("lattice.jl") include("slices.jl") include("models.jl") include("hamiltonian.jl") include("supercell.jl") include("transform.jl") include("mesh.jl") include("bands.jl") include("greenfunction.jl") include("observables.jl") # Plumbing include("apply.jl") include("show.jl") include("convert.jl") include("sanitizers.jl") # Solvers include("solvers/eigen.jl") include("solvers/green.jl") include("solvers/selfenergy.jl") # Presets include("presets/regions.jl") include("presets/lattices.jl") include("presets/hamiltonians.jl") include("presets/external.jl") include("presets/docstrings.jl") # include("precompile.jl") # Extension stubs for QuanticaMakieExt function plotlattice end function plotlattice! end function plotbands end function plotbands! end function qplot end function qplot! end function qplotdefaults end qplot(args...; kw...) = argerror("No plotting backend found or unexpected argument. Forgot to do e.g. `using GLMakie`?") end
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
13644
# apply: takes generic user input (model/selector/modifier/etc), and specializes it # to a given object (Lattice/Hamiltonian/etc), performing some preprocessing task on the # input that allows to use it on that object (it gets transformed into an AppliedInput) # Example: a HopSelector input with a `range = neighbors(1)` gets applied onto a lattice # by computing the actual range for nearest neighbors in that lattice. ############################################################################################ # apply selector #region apply(s::Union{SiteSelector,HopSelector}, l::LatticeSlice) = apply(s, parent(l), cells(l)) function apply(s::SiteSelector, lat::Lattice{T,E,L}, cells...) where {T,E,L} region = r -> applied_region(r, s.region) intsublats = recursive_apply(name -> sublatindex_or_zero(lat, name), s.sublats) sublats = recursive_push!(Int[], intsublats) cells = recursive_push!(SVector{L,Int}[], sanitize_cells(s.cells, Val(L)), cells...) unique!(sort!(sublats)) unique!(sort!(cells)) # isnull: to distinguish in a type-stable way between s.cells === missing and no-selected-cells # and the same for sublats isnull = (s.cells !== missing && isempty(cells)) || (s.sublats !== missing && isempty(sublats)) return AppliedSiteSelector{T,E,L}(lat, region, sublats, cells, isnull) end function apply(s::HopSelector, lat::Lattice{T,E,L}, cells...) where {T,E,L} rmin, rmax = sanitize_minmaxrange(s.range, lat) L > 0 && s.dcells === missing && rmax === missing && throw(ErrorException("Tried to apply an infinite-range HopSelector on an unbounded lattice")) sign = ifelse(s.adjoint, -1, 1) region = (r, dr) -> applied_region((r, sign*dr), s.region) intsublats = recursive_apply(names -> sublatindex_or_zero(lat, names), s.sublats) sublats = recursive_push!(Pair{Int,Int}[], intsublats) dcells = recursive_push!(SVector{L,Int}[], sanitize_cells(s.dcells, Val(L)), cells...) unique!(sublats) unique!(dcells) if s.adjoint sublats .= reverse.(sublats) dcells .*= -1 end isnull = (s.dcells !== missing && isempty(dcells)) || (s.sublats !== missing && isempty(sublats)) return AppliedHopSelector{T,E,L}(lat, region, sublats, dcells, (rmin, rmax), isnull) end sublatindex_or_zero(lat, ::Missing) = missing sublatindex_or_zero(lat, i::Integer) = ifelse(1 <= i <= nsublats(lat), Int(i), 0) function sublatindex_or_zero(lat, name::Symbol) i = sublatindex(lat, name) return ifelse(i === nothing, 0, Int(i)) end sanitize_minmaxrange(r, lat) = sanitize_minmaxrange((zero(numbertype(lat)), r), lat) sanitize_minmaxrange((rmin, rmax)::Tuple{Any,Any}, lat) = padrange(applyrange(rmin, lat), -1), padrange(applyrange(rmax, lat), 1) sanitize_cells(cell::Number, ::Val{1}) = (sanitize_SVector(SVector{1,Int}, cell),) sanitize_cells(cell::Union{NTuple{L,<:Integer},SVector{L,<:Number}}, ::Val{L´}) where {L,L´} = argerror("Dimension $L of `cells` does not match lattice dimension $(L´)") sanitize_cells(cell::Union{NTuple{L,<:Integer},SVector{L,<:Number}}, ::Val{L}) where {L} = (sanitize_SVector(SVector{L,Int}, cell),) sanitize_cells(::Missing, ::Val{L}) where {L} = missing sanitize_cells(f::Function, ::Val{L}) where {L} = f sanitize_cells(cells, ::Val{L}) where {L} = sanitize_SVector.(SVector{L,Int}, cells) applyrange(r::Neighbors, lat) = nrange(Int(r), lat) applyrange(r::Real, lat) = r padrange(r::Real, m) = isfinite(r) ? float(r) + m * sqrt(eps(float(r))) : float(r) applied_region(r, ::Missing) = true applied_region((r, dr)::Tuple{SVector,SVector}, region::Function) = ifelse(region(r, dr), true, false) applied_region(r::SVector, region::Function) = ifelse(region(r), true, false) recursive_apply(f, t::Tuple) = recursive_apply.(f, t) recursive_apply(f, t::AbstractVector) = recursive_apply.(f, t) recursive_apply(f, (a,b)::Pair) = recursive_apply(f, a) => recursive_apply(f, b) recursive_apply(f, x) = f(x) recursive_push!(v::Vector, ::Missing) = v recursive_push!(v::Vector{T}, x::T) where {T} = push!(v, x) recursive_push!(v::Vector{S}, x::NTuple{<:Any,Integer}) where {S<:SVector} = push!(v, S(x)) recursive_push!(v::Vector{S}, x::Number) where {S<:SVector{1}} = push!(v, S(x)) recursive_push!(v::Vector{Pair{T,T}}, x::T) where {T} = push!(v, x => x) recursive_push!(v::Vector{Pair{T,T}}, (x, y)::Tuple{T,T}) where {T} = push!(v, x => y) recursive_push!(v::Vector{Pair{T,T}}, x::Pair{T,T}) where {T} = push!(v, x) function recursive_push!(v::Vector, xs) foreach(x -> recursive_push!(v, x), xs) return v end function recursive_push!(v::Vector{Pair{T,T}}, (xs, ys)::Pair) where {T} for (x, y) in Iterators.product(xs, ys) push!(v, x => y) end return v end # for cells::Function without list of cells function recursive_push!(v::Vector{SVector{L,Int}}, fcell::Function) where {L} iter = BoxIterator(zero(SVector{L,Int})) keepgoing = true for cell in iter found = fcell(cell) if found || keepgoing acceptcell!(iter, cell) if found push!(v, cell) keepgoing = false end end end return v end # for cells::Function with a list of cells (from a LatticeSlice) function recursive_push!(v::Vector{SVector{L,Int}}, fcell::Function, cells) where {L} for cell in cells fcell(cell) && push!(v, cell) end return v end recursive_push!(v::Vector, f, cells) = recursive_push!(v, f) #endregion ############################################################################################ # apply model terms #region function apply(o::OnsiteTerm, (lat, os)::Tuple{Lattice{T,E,L},OrbitalBlockStructure{B}}) where {T,E,L,B} f = (r, orbs) -> mask_block(B, o(r), (orbs, orbs)) asel = apply(selector(o), lat) return AppliedOnsiteTerm{T,E,L,B}(f, asel) # f gets wrapped in a FunctionWrapper end function apply(t::HoppingTerm, (lat, os)::Tuple{Lattice{T,E,L},OrbitalBlockStructure{B}}) where {T,E,L,B} f = (r, dr, orbs) -> mask_block(B, t(r, dr), orbs) asel = apply(selector(t), lat) return AppliedHoppingTerm{T,E,L,B}(f, asel) # f gets wrapped in a FunctionWrapper end apply(m::TightbindingModel, latos) = TightbindingModel(apply.(terms(m), Ref(latos))) apply(t::ParametricOnsiteTerm, lat::Lattice) = ParametricOnsiteTerm(functor(t), apply(selector(t), lat), coefficient(t), is_spatial(t)) apply(t::ParametricHoppingTerm, lat::Lattice) = ParametricHoppingTerm(functor(t), apply(selector(t), lat), coefficient(t), is_spatial(t)) apply(m::ParametricModel, lat) = ParametricModel(apply.(terms(m), Ref(lat))) #endregion ############################################################################################ # apply parametric modifiers # shifts allows to transform lattice(h) sites into the sites of some originating lattice # unit cell: shifts = [bravais * dn] for each site in lattice(h) # shifts is useful for supercell, where we want to keep the r, dr of original lat #region # Any means it could be wrapped in Intrablock or Interblock apply(m::BlockModifier, h::Hamiltonian, shifts = missing) = apply(parent(m), h, shifts, block(m, blockstructure(h))) function apply(m::OnsiteModifier, h::Hamiltonian, shifts = missing, oblock = missing) f = parametric_function(m) sel = selector(m) asel = apply(sel, lattice(h)) ptrs = pointers(h, asel, shifts, oblock) B = blocktype(h) spatial = is_spatial(m) return AppliedOnsiteModifier(sel, B, f, ptrs, spatial) end function apply(m::HoppingModifier, h::Hamiltonian, shifts = missing, oblock = missing) f = parametric_function(m) sel = selector(m) asel = apply(sel, lattice(h)) ptrs = pointers(h, asel, shifts, oblock) B = blocktype(h) spatial = is_spatial(m) return AppliedHoppingModifier(sel, B, f, ptrs, spatial) end function pointers(h::Hamiltonian{T,E,L,B}, s::AppliedSiteSelector{T,E,L}, shifts, oblock) where {T,E,L,B} isempty(cells(s)) || argerror("Cannot constrain cells in an onsite modifier, cell periodicity is assumed.") ptrs = Tuple{Int,SVector{E,T},CellSitePos{T,E,L,B},Int}[] isnull(s) && return ptrs lat = lattice(h) har0 = first(harmonics(h)) dn0 = zerocell(lat) umat = unflat(har0) rows = rowvals(umat) norbs = norbitals(h) for scol in sublats(lat), col in siterange(lat, scol) isinblock(col, oblock) || continue for p in nzrange(umat, col) row = rows[p] col == row || continue r = site(lat, col) r = apply_shift(shifts, r, col) if (scol, r) in s n = norbs[scol] sp = CellSitePos(dn0, col, r, B) push!(ptrs, (p, r, sp, n)) end end end return ptrs end function pointers(h::Hamiltonian{T,E,L,B}, s::AppliedHopSelector{T,E,L}, shifts, oblock) where {T,E,L,B} hars = harmonics(h) ptrs = [Tuple{Int,SVector{E,T},SVector{E,T},CellSitePos{T,E,L,B},CellSitePos{T,E,L,B},Tuple{Int,Int}}[] for _ in hars] isnull(s) && return ptrs lat = lattice(h) dn0 = zerocell(lat) norbs = norbitals(h) for (har, ptrs) in zip(hars, ptrs) mh = unflat(har) rows = rowvals(mh) for scol in sublats(lat), col in siterange(lat, scol), p in nzrange(mh, col) row = rows[p] isinblock(row, col, oblock) || continue srow = sitesublat(lat, row) dn = dcell(har) rcol = site(lat, col, dn0) rrow = site(lat, row, dn) r, dr = rdr(rcol => rrow) r = apply_shift(shifts, r, col) if (scol => srow, (r, dr), dn) in s ncol = norbs[scol] nrow = norbs[srow] srow, scol = CellSitePos(dn, row, rrow, B), CellSitePos(dn0, col, rcol, B) push!(ptrs, (p, r, dr, srow, scol, (nrow, ncol))) end end end return ptrs end apply_shift(::Missing, r, _) = r apply_shift(shifts, r, i) = r - shifts[i] #endregion ############################################################################################ # apply AbstractEigenSolver #region function apply(solver::AbstractEigenSolver, h::AbstractHamiltonian, ::Type{S}, mapping, transform) where {T<:Real,S<:SVector{<:Any,T}} h´ = minimal_callsafe_copy(h) # Some solvers (e.g. ES.LinearAlgebra) only accept certain matrix types # so this mat´ could be an alias of the call! output, or an unaliased conversion mat´ = ES.input_matrix(solver, h´) function sfunc(φs) φs´ = apply_map(mapping, φs) # this can be a FrankenTuple mat = call!(h´, φs´) mat´ === mat || copy!(mat´, mat) # mat´ could be dense, while mat is sparse, so if not egal, we copy # the solver always receives the type of matrix mat´ declared by ES.input_matrix eigen = solver(mat´) apply_transform!(eigen, transform) return eigen end # issue #235: for some reason, unless this is called, h´ may be GC'ed despite the # asolver closure in some systems, leading to segfaults. TODO: why this is needed? @static (Sys.ARCH === :x86_64 && !Sys.iswindows() && v"1.10" <= VERSION < v"1.11.0-alpha1" && sfunc(zero(S))) asolver = AppliedEigenSolver(FunctionWrapper{EigenComplex{T},Tuple{S}}(sfunc)) return asolver end function apply(solver::AbstractEigenSolver, hf::Function, ::Type{S}, mapping, transform) where {T<:Real,S<:SVector{<:Any,T}} function sfunc(φs) φs´ = apply_map(mapping, φs) # can be a FrankenTuple, should be accepted by hf mat = hf(φs´) eigen = solver(mat) apply_transform!(eigen, transform) return eigen end asolver = AppliedEigenSolver(FunctionWrapper{EigenComplex{T},Tuple{S}}(sfunc)) return asolver end apply(solver::AbstractEigenSolver, h, S, mapping, transform) = argerror("Encountered an unexpected type as argument to an eigensolver. Are your mesh vertices real?") apply_transform!(eigen, ::Missing) = eigen function apply_transform!(eigen, transform) ϵs = first(eigen) map!(transform, ϵs, ϵs) return eigen end apply_map(::Missing, φs) = φs apply_map(mapping, φs) = mapping(Tuple(φs)...) function apply_map(mapping, h::AbstractHamiltonian{T}, ::Type{S}) where {T,S<:SVector} function sfunc(φs) h´ = minimal_callsafe_copy(h) φs´ = apply_map(mapping, φs) # can be a FrankenTuple mat = call!(h´, φs´) return mat end return FunctionWrapper{SparseMatrixCSC{Complex{T},Int},Tuple{S}}(sfunc) end function apply_map(mapping, hf::Function, ::Type{S}) where {T,S<:SVector{<:Any,T}} function sfunc(φs) φs´ = apply_map(mapping, φs) # can be a FrankenTuple, should be accepted by hf mat = hf(φs´) return mat end return FunctionWrapper{SparseMatrixCSC{Complex{T},Int},Tuple{S}}(sfunc) end #endregion ############################################################################################ # apply CellSites #region apply(c::AnyCellSite, ::Lattice{<:Any,<:Any,L}) where {L} = c apply(c::CellSites{L,Vector{Int}}, ::Lattice{<:Any,<:Any,L}) where {L} = c apply(c::CellSites{L,Colon}, l::Lattice{<:Any,<:Any,L}) where {L} = CellSites(cell(c), collect(siterange(l))) apply(c::CellSites{L}, l::Lattice{<:Any,<:Any,L}) where {L} = CellSites(cell(c), [i for i in siteindices(c) if i in siterange(l)]) apply(::CellSites{L}, l::Lattice{<:Any,<:Any,L´}) where {L,L´} = argerror("Cell sites must have $(L´)-dimensional cell indices") #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
31417
############################################################################################ # spectrum #region function spectrum(h::AbstractHamiltonian{T}, φs; solver = ES.LinearAlgebra(), transform = missing, kw...) where {T} os = blockstructure(h) mapping = (φ...) -> ftuple(φ...; kw...) φs´ = sanitize_SVector(T, φs) S = typeof(φs´) asolver = apply(solver, h, S, mapping, transform) eigen = asolver(φs´) return Spectrum(eigen, os) end spectrum(h::AbstractHamiltonian{T,<:Any,0}; kw...) where {T} = spectrum(h, SVector{0,T}(); kw...) function spectrum(b::Bandstructure, φs;) os = blockstructure(b) solver = first(solvers(b)) eigen = solver(φs) return Spectrum(eigen, os) end #endregion ############################################################################################ # Spectrum indexing #region Base.first(s::Spectrum) = energies(s) Base.last(s::Spectrum) = states(s) Base.iterate(s::Spectrum) = first(s), Val(:states) Base.iterate(s::Spectrum, ::Val{:states}) = last(s), Val(:done) Base.iterate(::Spectrum, ::Val{:done}) = nothing Base.Tuple(s::Spectrum) = (first(s), last(s)) Base.getindex(s::Spectrum, i...; around = missing) = get_around(Tuple(s), around, i...) get_around((es, ss), ε0::Missing, i) = (es[i], ss[:,i]) get_around(s, ε0::Number) = get_around(s, ε0, 1) get_around(s, ε0::Number, i::Integer) = get_around(s, ε0, i:i) function get_around((es, ss), ε0::Number, inds) # Get indices of eachindex(es) such that if sorted by `by` will occupy `inds` positions if inds isa Union{Integer,OrdinalRange} rngs = partialsort(eachindex(es), inds, by = rng -> abs(es[rng] - ε0)) return (es[rngs], ss[:, rngs]) else # generic inds (cannot use partialsort) rngs = sort(eachindex(es), by = rng -> abs(es[rng] - ε0)) return (es[view(rngs, inds)], ss[:, view(rngs, inds)]) end end #endregion ############################################################################################ # bands(h, points...; kw...) # h can be an AbstractHamiltonian or a Function(vertex) -> AbstractMatrix #region bands(rng, rngs...; kw...) = h -> bands(h, rng, rngs...; kw...) bands(h::Function, rng, rngs...; kw...) = bands(h, mesh(rng, rngs...); kw...) bands(h::AbstractHamiltonian{T}, rng, rngs::Vararg{Any,L´}; kw...) where {T,L´} = bands(h, convert(Mesh{SVector{L´+1,T}}, mesh(rng, rngs...)); kw...) bands(h::AbstractHamiltonian{<:Any,<:Any,L}; kw...) where {L} = bands(h, default_band_ticks(Val(L))...; kw...) default_band_ticks(::Val{L}) where {L} = ntuple(Returns(subdiv(-π, π, 49)), Val(L)) function bands(h::AbstractHamiltonian, mesh::Mesh{S}; solver = ES.LinearAlgebra(), transform = missing, mapping = missing, kw...) where {S<:SVector} mapping´ = sanitize_mapping(mapping, h) solvers = eigensolvers_thread_pool(solver, h, S, mapping´, transform) hf = apply_map(mapping´, h, S) ss = subbands(hf, solvers, mesh; kw...) os = blockstructure(h) return Bandstructure(ss, solvers, os) end function bands(h::Function, mesh::Mesh{S}; solver = ES.LinearAlgebra(), transform = missing, mapping = missing, kw...) where {S<:SVector} mapping´ = sanitize_mapping(mapping, h) solvers = eigensolvers_thread_pool(solver, h, S, mapping´, transform) hf = apply_map(mapping´, h, S) ss = subbands(hf, solvers, mesh; kw...) return ss end function eigensolvers_thread_pool(solver, h, S, mapping, transform) # if h::Function we cannot be sure it is thread-safe nsolvers = ES.is_thread_safe(solver) && h isa AbstractHamiltonian ? Threads.nthreads() : 1 solvers = [apply(solver, h, S, mapping, transform) for _ in 1:nsolvers] return solvers end function subbands(hf, solvers, basemesh::Mesh{SVector{L,T}}; showprogress = true, defects = (), patches = 0, degtol = missing, split = true, warn = true, projectors = false) where {T,L} defects´ = sanitize_Vector_of_SVectors(SVector{L,T}, defects) degtol´ = degtol isa Number ? degtol : sqrt(eps(real(T))) subbands = subbands_precompilable(hf, solvers, basemesh, showprogress, defects´, patches, degtol´, split, warn, projectors) return subbands end sanitize_mapping(mapping, ::AbstractHamiltonian{<:Any,<:Any,L}) where {L} = sanitize_mapping(mapping, Val(L)) sanitize_mapping(mapping::Union{Missing,Function}, ::Function) = mapping sanitize_mapping(_, ::Function) = argerror("Cannot apply this mapping with a function input") sanitize_mapping(::Missing, ::Val) = missing sanitize_mapping(f::Function, ::Val) = f sanitize_mapping(pts::NTuple{N,Any}, ::Val{L}) where {N,L} = sanitize_mapping(ntuple(i -> i-1, Val(N)) => parsenode.(pts, Val(L)), Val(L)) sanitize_mapping((xs, nodes)::Pair, ::Val{L}) where {L} = polygonpath(xs, parsenode.(nodes, Val(L))) sanitize_mapping((xs, nodes)::Pair{X,S}, ::Val{L}) where {N,L,T,X<:NTuple{N,Real},S<:NTuple{N,SVector{L,T}}} = polygonpath(xs, nodes) function subbands_precompilable(hf::FunctionWrapper, solvers::Vector{A}, basemesh::Mesh{SVector{L,T}}, showprogress, defects, patches, degtol, split, warn, projectors) where {T,L,A<:AppliedEigenSolver{T,L}} basemesh = copy(basemesh) # will become part of Band, possibly refined eigens = Vector{EigenComplex{T}}(undef, length(vertices(basemesh))) bandverts = BandVertex{T,L+1}[] bandneighs = Vector{Int}[] bandneideg = similar(bandneighs) coloffsets = Int[] crossed = NTuple{6,Int}[] frustrated = similar(crossed) subbands = Subband{T,L+1}[] data = (; hf, solvers, basemesh, eigens, bandverts, bandneighs, bandneideg, coloffsets, L, crossed, frustrated, subbands, defects, patches, showprogress, degtol, split, warn, projectors) # Step 1 - Diagonalize: # Uses multiple SpectrumSolvers (one per Julia thread) to diagonalize h at each # vertex of basemesh. Then, it collects each of the produced Spectrum (aka "columns") # into a bandverts::Vector{BandVertex}, recording the coloffsets for each column blasthreads = BLAS.get_num_threads() Threads.nthreads() == 1 || BLAS.set_num_threads(1) # One BLASthread if JULIAthreads > 1 subbands_diagonalize!(data) BLAS.set_num_threads(blasthreads) # Restore BLAS threads # Step 2 - Knit seams: # Each base vertex holds a column of subspaces. Each subspace s of degeneracy d will # connect to other subspaces s´ in columns of a neighboring base vertex. Connections are # possible if the projector ⟨s'|s⟩ has any singular value greater than 1/2 subbands_knit!(data) # Step 3 - Patch seams: # Dirac points and other topological band defects will usually produce dislocations in # mesh connectivity that results in missing simplices. insert_defects!(data) if L>1 subbands_patch!(data) end # Step 4 - Split subbands: # Split disconnected subgraphs, rebuild their neighbor lists and convert to Subbands. # As part of the Subband conversion, subband simplices are computed. subbands_split!(data) # Step 5 - Compute projectors: # Each simplex s has a continuous matrix Fₛ(k) = ψₛ(k)ψₛ(k)⁺ that interpolates between # the Fₛ(kᵢ) at each vertex i. We compute Pˢᵢ such that F(kᵢ) = φₛ(kᵢ)*Pˢᵢ*φₛ(kᵢ)⁺ for # any vertex i of s with a degenerate eigenbasis φ(kᵢ). Non-degenerate vertices have P=1 # Required to use a Bandstructure as a GreenSolver subband_projectors!(data) return subbands end #endregion ############################################################################################ # parsenode #region parsenode(pt::SVector, ::Val{L}) where {L} = padright(pt, Val(L)) parsenode(pt::Tuple, val) = parsenode(SVector(float.(pt)), val) function parsenode(node::Symbol, val) pt = get(BZpoints, node, missing) pt === missing && throw(ArgumentError("Unknown Brillouin zone point $pt, use one of $(keys(BZpoints))")) pt´ = parsenode(pt, val) return pt´ end const BZpoints = ( Γ = (0,) , X = (pi,) , Y = (0, pi) , Z = (0, 0, pi) , K = (2pi/3, -2pi/3) , K´ = (4pi/3, 2pi/3) , M = (pi, 0) ) #endregion ############################################################################################ # polygonpath #region polygonpath(xs, nodes) = polygonpath(sanitize_polygonpath(xs), sanitize_polygonpath(nodes)) function polygonpath(xs::AbstractVector, nodes::AbstractVector) sanitize_polygonpath!(xs, nodes) minx, maxx = extrema(xs) mapping = x -> begin x´ = clamp(only(x), minx, maxx) i = argmin(i -> ifelse(x´ <= xs[i], Inf, x´ - xs[i]), eachindex(xs)) p = nodes[i] + (nodes[i+1] - nodes[i]) * (x´ - xs[i]) / (xs[i+1] - xs[i]) return p end return mapping end sanitize_polygonpath(xs::AbstractVector) = xs sanitize_polygonpath(xs::Tuple) = collect(xs) function sanitize_polygonpath!(xs, nodes) if !issorted(xs) p = sortperm(xs) permute!(xs, p) permute!(nodes, p) end return nothing end #endregion ############################################################################################ # subdiv #region subdiv(nodes, pts::Integer) = subdiv(nodes, [pts for _ in 1:length(nodes)-1]) subdiv(x1, x2, pts) = collect(range(x1, x2, length = pts)) function subdiv(nodes, pts) length(pts) == length(nodes) - 1 || argerror("`subdiv(nodes, pts)` requires `length(pts) == length(nodes) - 1` or pts::Integer") rng = [x for (n, pt) in enumerate(pts) for x in range(nodes[n], nodes[n+1], length = pt) if x != nodes[n+1]] push!(rng, last(nodes)) return rng end #endregion ############################################################################################ # subbands_diagonalize! #region function subbands_diagonalize!(data) baseverts = vertices(data.basemesh) meter = Progress(length(baseverts); desc = "Step 1 - Diagonalizing: ") push!(data.coloffsets, 0) # first element if length(data.solvers) > 1 Threads.@threads :static for i in eachindex(baseverts) vert = baseverts[i] solver = data.solvers[Threads.threadid()] data.eigens[i] = solver(vert) data.showprogress && ProgressMeter.next!(meter) end else solver = first(data.solvers) for i in eachindex(baseverts) vert = baseverts[i] data.eigens[i] = solver(vert) data.showprogress && ProgressMeter.next!(meter) end end # Collect band vertices and store column offsets for (basevert, eigen) in zip(baseverts, data.eigens) append_bands_column!(data, basevert, eigen) end ProgressMeter.finish!(meter) end const degeneracy_warning = 16 # collect eigen into a band column (vector of BandVertices for equal base vertex) function append_bands_column!(data, basevert, eigen) T = eltype(basevert) energies, states = eigen subs = collect(approxruns(energies, data.degtol)) for (i, rng) in enumerate(subs) deg = length(rng) data.warn && data.projectors && deg > degeneracy_warning && @warn "Encountered a highly degenerate point in bandstructure (deg = $deg), which will likely slow down the computation of projectors" state = orthonormalize!(view(states, :, rng)) energy = mean(i -> energies[i], rng) push!(data.bandverts, BandVertex(basevert, energy, state)) end push!(data.coloffsets, length(data.bandverts)) foreach(_ -> push!(data.bandneideg, Int[]), length(data.bandneideg)+1:length(data.bandverts)) foreach(_ -> push!(data.bandneighs, Int[]), length(data.bandneighs)+1:length(data.bandverts)) return data end # Gram-Schmidt but with column normalization only when norm^2 >= threshold (otherwise zero!) function orthonormalize!(m::AbstractMatrix, threshold = 0) @inbounds for j in axes(m, 2) col = view(m, :, j) for j´ in 1:j-1 col´ = view(m, :, j´) norm2´ = dot(col´, col´) iszero(norm2´) && continue r = dot(col´, col)/norm2´ col .-= r .* col´ end norm2 = real(dot(col, col)) factor = ifelse(norm2 < threshold, zero(norm2), 1/sqrt(norm2)) col .*= factor end return m end #endregion ############################################################################################ # subbands_knit! # Take two eigenpair columns connected on basemesh, and add edges between closest # eigenpair using projections (svd). #region function subbands_knit!(data) meter = Progress(length(data.eigens); desc = "Step 2 - Knitting: ") for isrcbase in eachindex(data.eigens) for idstbase in neighbors_forward(data.basemesh, isrcbase) knit_seam!(data, isrcbase, idstbase) end data.showprogress && ProgressMeter.next!(meter) end ProgressMeter.finish!(meter) return data end # Take two intervals (srcrange, dstrange) of bandverts (linked by base mesh) # and fill bandneighs with their connections, using the projector colproj function knit_seam!(data, ib, jb) srcrange = column_range(data, ib) dstrange = column_range(data, jb) _, statesib = data.eigens[ib] _, statesjb = data.eigens[jb] colproj = statesjb' * statesib for i in srcrange src = data.bandverts[i] for j in dstrange dst = data.bandverts[j] proj = view(colproj, parentcols(dst), parentcols(src)) connections = connection_rank(proj) if connections > 0 push!(data.bandneighs[i], j) push!(data.bandneighs[j], i) push!(data.bandneideg[i], connections) push!(data.bandneideg[j], connections) # populate crossed with all crossed links if lattice dimension > 1 if data.L > 1 for i´ in first(srcrange):i-1, j´ in data.bandneighs[i´] j´ in dstrange || continue # if crossed, push! with ordered i´ < i, j´ > j j´ > j && push!(data.crossed, (ib, jb, i´, i, j´, j)) end end end end end return data end # Number of singular values greater than √min_squared_overlap in proj = ψj'*ψi # Fast rank-1 |svd|^2 is r = tr(proj'proj). For higher ranks and r > 0 we must compute and # count singular values. The min_squared_overlap is arbitrary, and is fixed heuristically to # a high enough value to connect in the coarsest base lattices function connection_rank(proj) min_squared_overlap = 0.5 rankf = sum(abs2, proj) # = tr(proj'proj) fastrank = ifelse(rankf > min_squared_overlap, 1, 0) # For rank=1 proj: upon doubt, connect if iszero(fastrank) || size(proj, 1) == 1 || size(proj, 2) == 1 return fastrank else sv = svdvals(proj) return count(s -> abs2(s) > min_squared_overlap, sv) end end column_range(data, ibase) = data.coloffsets[ibase]+1:data.coloffsets[ibase+1] #endregion ############################################################################################ # subbands_patch! # Remove dislocations in mesh edges by edge splitting (adding patches) #region function subbands_patch!(data) data.patches > 0 || return data queue_frustrated!(data) data.warn && isempty(data.defects) && @warn "Trying to patch $(length(data.frustrated)) band dislocations without a list `defects` of defect positions." meter = data.patches < Inf ? Progress(data.patches; desc = "Step 3 - Patching: ") : ProgressUnknown(; desc = "Step 3 - Patching: ") newcols = 0 done = false while !isempty(data.frustrated) && !done (ib, jb, i, i´, j, j´) = pop!(data.frustrated) # check edge has not been previously split jb in neighbors(data.basemesh, ib) || continue newcols += 1 done = newcols == data.patches # new vertex k = crossing(data, (ib, jb, i´, i, j´, j)) # insert and connect a new column into band insert_column!(data, (ib, jb), k) # From the added crossings, remove all that are non-frustrated queue_frustrated!(data) data.showprogress && ProgressMeter.next!(meter) end # If we added new columns, base edges will have split -> rebuild base simplices newcols > 0 && rebuild_cliques!(data.basemesh) data.showprogress && ProgressMeter.finish!(meter) ndefects = length(data.frustrated) data.warn && !iszero(ndefects) && @warn("Warning: Band with $ndefects dislocation defects. Consider specifying topological defect locations with `defects` (or adjusting mesh) and/or increasing `patches`") return data end function insert_defects!(data) # insert user-provided defects as new columns in band foreach(k -> insert_defect_column!(data, k), data.defects) # detect possible defects in band and append them to data.defects mindeg = minimum(degeneracy, data.bandverts) for (v, ns) in zip(data.bandverts, data.bandneighs) k = base_coordinates(v) d = degeneracy(v) # exclude v if v does not increase degeneracy over minimum degeneracy(v) == mindeg && continue # only select vertices that have greater degeneracy than all its neighbors any(n -> degeneracy(data.bandverts[n]) >= d, ns) && continue # exclude v if it is already in data.defects any(kd -> kd ≈ k, data.defects) && continue push!(data.defects, base_coordinates(v)) end return data end function insert_defect_column!(data, kdefect) base = data.basemesh for k in vertices(base) k ≈ kdefect && return data end (ib, jb) = find_closest_edge(kdefect, base) insert_column!(data, (ib, jb), kdefect) return data end function find_closest_edge(kdefect::SVector{1}, base) kx = only(kdefect) for i in eachindex(vertices(base)), j in neighbors(base, i) only(vertices(base, i)) < kx < only(vertices(base, j)) && return (i, j) end argerror("Defects in 1D lattices should be contained inside the lattice, but the provided $kdefect is not") return (0, 0) end function find_closest_edge(kdefect, base) (ib, jb) = argmin(((i, j) for i in eachindex(vertices(base)) for j in neighbors(base, i))) do (i, j) sum(abs2, 0.5*(vertices(base, i) + vertices(base, j)) - kdefect) end return (ib, jb) end function insert_column!(data, (ib, jb), k) solver = first(data.solvers) # remove all bandneighs in this seam delete_seam!(data, ib, jb) # create new vertex in basemesh by splitting the edge, and connect to neighbors split_edge!(data.basemesh, (ib, jb), k) # compute spectrum at new vertex spectrum = solver(k) push!(data.eigens, spectrum) # collect spectrum into a set of new band vertices append_bands_column!(data, k, spectrum) # knit all new seams newbasevertex = length(vertices(data.basemesh)) # index of new base vertex newbaseneighs = neighbors(data.basemesh, newbasevertex) jb´ = newbasevertex # destination of all new edges for ib´ in newbaseneighs # neighbors of new vertex are new edge sources knit_seam!(data, ib´, jb´) # also pushes new crossings into data.crossed end return data end # queue frustrated crossings and sort decreasing distance between crossing and defects function queue_frustrated!(data) # we must check all crossed each time, as their frustration can change at any point for c in data.crossed is_frustrated_crossing(data, c) && !in(c, data.frustrated) && push!(data.frustrated, c) end isempty(data.defects) || reverse!(sort!(data.frustrated, by = i -> distance_to_defects(data, i))) return data end function distance_to_defects(data, ic) kc = crossing(data, ic) return minimum(d -> sum(abs2, kc - d), data.defects) end is_frustrated_crossing(data, (ib, jb, i, i´, j, j´)) = is_frustrated_link(data, (ib, jb, i, j)) || is_frustrated_link(data, (ib, jb, i´, j´)) function is_frustrated_link(data, (ib, jb, i, j)) deg = degeneracy_link(data, i, j) for kb in neighbors(data.basemesh, ib), kb´ in neighbors(data.basemesh, jb) kb == kb´ || continue count = 0 for k in data.bandneighs[i], k´ in data.bandneighs[j] k == k´ && k in column_range(data, kb) || continue count += min(degeneracy_link(data, i, k), degeneracy_link(data, j, k)) end count < deg && return true end return false end function degeneracy_link(data, i, j) for (k, d) in zip(data.bandneighs[i], data.bandneideg[i]) k == j && return d end return 0 end function crossing(data, (ib, jb, i, i´, j, j´)) εi, εi´, εj, εj´ = real.(energy.(getindex.(Ref(data.bandverts), (i, i´, j, j´)))) ki, kj = vertices(data.basemesh, ib), vertices(data.basemesh, jb) λ = (εi - εi´) / (εj´ - εi´ - εj + εi) k = ki + λ * (kj - ki) return k end function delete_seam!(data, isrcbase, idstbase) srcrange = column_range(data, isrcbase) dstrange = column_range(data, idstbase) for isrc in srcrange fast_setdiff!((data.bandneighs[isrc], data.bandneideg[isrc]), dstrange) end for idst in dstrange fast_setdiff!((data.bandneighs[idst], data.bandneideg[idst]), srcrange) end return data end #endregion ############################################################################################ # subbands_split! # We have vertex neighbors (data.bandneighs). Now we need to use these to cluster vertices # into disconnected subbands (i.e. vertex `subsets`). Once we have these, split vertices # into separate lists and rebuild neighbors using indices of these new lists #region function subbands_split!(data) if data.split # vsinds are the subband index of each vertex index # svinds is lists of band vertex indices that belong to the same subband vsinds, svinds = subsets(data.bandneighs) meter = Progress(length(svinds); desc = "Step 4 - Splitting: ") new2old = sortperm(vsinds) old2new = invperm(new2old) offset = 0 for subset in svinds # avoid subbands with no simplices if length(subset) > data.L sverts = data.bandverts[subset] sneighs = [ [old2new[dstold] - offset for dstold in data.bandneighs[srcold]] for srcold in subset] sband = Subband(sverts, sneighs) isempty(sband) || push!(data.subbands, sband) end offset += length(subset) data.showprogress && ProgressMeter.next!(meter) end else sband = Subband(data.bandverts, data.bandneighs) isempty(sband) || push!(data.subbands, sband) end return data end #endregion ############################################################################################ # subband_projectors!(s::Subband, hf::Function) # Fill dictionary of projector matrices for each degenerate vertex in each simplex of s # Dict([(simp_index, vert_index) => φᵢ * P]) # such that P = U PD U'. U columns are eigenstates of φᵢ hf(k_av) φᵢ⁺, i = vert_index, # φᵢ are vertex eigenstate matrices, k_av is the basecoordinate at the center of the # simplex, and PD is a Diagonal{Bool} that filters out M columns of U, so that only # deg_simplex = minimum(deg_verts) remain. The criterion to filter out the required # eigenstates is to order them is decreasing energy distance between their eigenvalue ε_av # and the simplex mean energy mean(ε_j). No φᵢ overlap criterion is used because we need # to fix the exact number of eliminations. #region function subband_projectors!(data) nsimps = sum(s -> length(simplices(s)), data.subbands) meter = Progress(nsimps; desc = "Step 5 - Projectors: ") if data.projectors for s in data.subbands subband_projectors!(s, data.hf, meter, data.showprogress) end end return data end function subband_projectors!(s::Subband{T}, hf, meter, showprogress) where {T} projstates = projected_states(s) isempty(projstates) || return s verts = vertices(s) simps = simplices(s) # a random symmetry-breaking perturbation common to all simplices perturbation = Complex{T}[] for (sind, simp) in enumerate(simps) degs = degeneracy.(getindex.(Ref(verts), simp)) if any(>(1), degs) kav = mean(i -> base_coordinates(verts[i]), simp) εav = mean(i -> energy(verts[i]), simp) hkav = hf(kav) nzs = nonzeros(hkav) nnzs = length(nzs) nnzs == length(perturbation) || resize_perturbation!(perturbation, nnzs) nzs .+= perturbation # in-place allowed since hkav gets updated on each call mindeg = minimum(degs) for (vind, deg) in zip(simp, degs) if deg > 1 # diagonalize vertex even if all degs are equal and > 1 φP = simplex_projector(hkav, verts, vind, εav, mindeg) projstates[(sind, vind)] = φP end end end showprogress && ProgressMeter.next!(meter) end return projstates end function resize_perturbation!(p::Vector{C}, n) where {C} l = length(p) @assert n > l # perturbation length should not decrease resize!(p, n) η = sqrt(eps(real(C))) # makes the perturbation small for i in l+1:n p[i] = η * rand(C) end return p end function simplex_projector(hkav, verts, vind, εav, mindeg) φ = states(verts[vind]) hproj = φ' * hkav * φ _, P = maybe_eigen!(Hermitian(hproj), sortby = ε -> abs(ε - εav)) Pthin = view(P, :, 1:mindeg) return φ * Pthin end maybe_eigen!(A::AbstractMatrix{<:LinearAlgebra.BlasComplex}; kw...) = eigen!(A; kw...) maybe_eigen!(A; kw...) = eigen(A; kw...) # generic fallback for e.g. Complex16 #endregion ############################################################################################ # Subband slicing and indexing # Example: in a 2D lattice, subband[(kx,ky,:)] is a vertical slice at fixed momentum kx, ky #region Base.getindex(b::Bandstructure, i) = subbands(b, i) Base.getindex(b::Bandstructure, xs::Tuple) = [s[xs] for s in subbands(b)] Base.getindex(s::Subband, xs::Tuple) = Subband(slice(s, xs, Val(true))) Base.lastindex(b::Bandstructure, args...) = lastindex(subbands(b), args...) slice(b::Bandstructure, xs) = [slice(s, xs) for s in subbands(b)] slice(s::Subband, xs::Tuple) = slice(s, xs, Val(false)) # getindex default (Val{true}): mesh with reduced embedding dimension = simplex length + 1 slice(s::Subband, xs::Tuple, ::Val{true}) = slice(s, perp_axes(s, xs...), slice_axes(s, xs...)) # slice default (Val{false}): mesh with same embedding dimension as subband and smaller simplex length slice(s::Subband, xs::Tuple, ::Val{false}) = slice(s, perp_axes(s, xs...), all_axes(s)) function slice(subband::Subband{<:Any,E}, paxes::NTuple{N}, saxes::Tuple) where {E,N} isempty(saxes) && argerror("The slice must have at least one unconstrained axis") isempty(paxes) && return mesh(subband) maximum(first, paxes) <= embdim(subband) && maximum(saxes) <= embdim(subband) || argerror("Cannot slice subband along more than $(embdim(subband)) axes") V = slice_vertex_type(subband, saxes) S = slice_skey_type(paxes) verts = V[] neighs = Vector{Int}[] vinds = Dict{S,Int}() vindstemp = Int[] subtemp = Int[] data = (; subband, paxes, saxes, verts, neighs, vinds, vindstemp, subtemp) foreach_simplex(subband, paxes) do sind simp = simplices(subband, sind) slice_simplex!(data, simp) end return Mesh{E-N}(verts, neighs) end perp_axes(::Subband{T}, xs...) where {T} = perp_axes(T, 1, xs...) perp_axes(T::Type, dim, ::Colon, xs...) = perp_axes(T, dim + 1, xs...) perp_axes(T::Type, dim, x::Number, xs...) = ((dim, T(x)), perp_axes(T, dim + 1, xs...)...) perp_axes(T::Type, dim) = () slice_axes(::Subband{<:Any,E}, xs...) where {E} = slice_axes(1, padtuple(xs, :, Val(E))...) slice_axes(dim::Int, ::Number, xs...) = slice_axes(dim + 1, xs...) slice_axes(dim::Int, ::Colon, xs...) = (dim, slice_axes(dim + 1, xs...)...) slice_axes(dim::Int) = () all_axes(::Subband{<:Any,E}) where {E} = ntuple(identity, Val(E)) slice_vertex_type(::Subband{T,<:Any}, ::NTuple{N}) where {T,N} = BandVertex{T,N} slice_skey_type(::NTuple{N}) where {N} = SVector{N+1,Int} function slice_simplex!(data, simp) empty!(data.vindstemp) perpaxes = SVector(first.(data.paxes)) paraxes = SVector(data.saxes) k = SVector(last.(data.paxes)) sub = data.subtemp for sub´ in Combinations(length(simp), length(perpaxes) + 1) # subsimplex must have minimal degeneracy on first vertex copy!(sub, sub´) # cannot modify sub´ because it also acts as state in Combinations sort!(sub, by = i -> degeneracy(vertices(data.subband, simp[i]))) key = vindskey(data.paxes, simp, sub) if !haskey(data.vinds, key) kε0, edgemat = vertmat_simplex(data.paxes, vertices(data.subband), simp, sub) dvper = edgemat[perpaxes, :] λs = dvper \ (k - kε0[perpaxes]) sum(λs) < 1 && all(>=(0), λs) || continue dvpar = edgemat[paraxes, :] kε = kε0[paraxes] + dvpar * λs φ = interpolate_state_along_edges(λs, vertices(data.subband), simp, sub) push!(data.verts, BandVertex(kε, φ)) push!(data.neighs, Int[]) vind = length(data.verts) data.vinds[key] = vind push!(data.vindstemp, vind) else vind = data.vinds[key] push!(data.vindstemp, vind) end end # all-to-all among new vertices for i in data.vindstemp, j in data.vindstemp i == j || push!(data.neighs[i], j) end return data end # a sorted SVector of the N+1 parent vertex indices is = simp[sub] (N = num perp slice axes) # identifying each distinct vertex in slice -> then, vinds[is] = new vertex index vindskey(::NTuple{N}, simp, sub) where {N} = sort(SVector(ntuple(i -> simp[sub[i]], Val(N+1)))) function vertmat_simplex(::NTuple{N}, vs, simp, sub) where {N} kε0 = coordinates(vs[simp[sub[1]]]) mat = hcat(ntuple(i -> coordinates(vs[simp[sub[i+1]]]) - kε0, Val(N))...) return kε0, mat end # we assume that sub is ordered and that simp is sorted so that the first vertex has minimal # degeneracy within the simplex (note that orient_simplices! preserves first vertex) function interpolate_state_along_edges(λs, vs, simp, sub) v0 = vs[simp[sub[1]]] φ0 = states(v0) deg0 = degeneracy(v0) φ = copy(φ0) φ .*= 1 - sum(λs) for (i, λi) in enumerate(λs) vi = vs[simp[sub[i+1]]] φi = states(vi) degi = degeneracy(vi) if degi == deg0 φ .+= λi .* φi elseif degi > deg0 proj = φi'φ0 # size(proj) == (degi, deg0) Q = qr!(proj).Q * Matrix(I, degi, deg0) mul!(φ, φi, Q, λi, 1) else throw(ErrorException("Unexpected simplex ordering: first should be minimal degeneracy")) end end return φ end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
9526
############################################################################################ # IJV sparse matrix builders #region struct IJV{B} i::Vector{Int} j::Vector{Int} v::Vector{B} end function IJV{B}(nnzguess = missing) where {B} i, j, v = Int[], Int[], B[] if nnzguess isa Integer sizehint!(i, nnzguess) sizehint!(j, nnzguess) sizehint!(v, nnzguess) end return IJV(i, j, v) end Base.push!(ijv::IJV, (i, j, v)) = (push!(ijv.i, i); push!(ijv.j, j); push!(ijv.v, v)) Base.append!(ijv::IJV, (is, js, vs)) = (append!(ijv.i, is); append!(ijv.j, js); append!(ijv.v, vs)) Base.isempty(s::IJV) = length(s) == 0 Base.length(s::IJV) = length(s.v) # cannot combine these two due to ambiguity with sparse(I, J, v::Number) SparseArrays.sparse(c::IJV, m::Integer, n::Integer) = sparse(c.i, c.j, c.v, m, n) SparseArrays.sparse(c::IJV) = sparse(c.i, c.j, c.v) #endregion ############################################################################################ # CSC sparse matrix builder #region mutable struct CSC{B} # must be mutable to update counters colptr::Vector{Int} rowval::Vector{Int} nzval::Vector{B} colcounter::Int rowvalcounter::Int cosorter::CoSort{Int,B} end function CSC{B}(cols = missing, nnzguess = missing) where {B} colptr = [1] rowval = Int[] nzval = B[] if cols isa Integer sizehint!(colptr, cols + 1) end if nnzguess isa Integer sizehint!(nzval, nnzguess) sizehint!(rowval, nnzguess) end colcounter = 1 rowvalcounter = 0 cosorter = CoSort(rowval, nzval) return CSC(colptr, rowval, nzval, colcounter, rowvalcounter, cosorter) end function pushtocolumn!(s::CSC, row::Int, x, skipdupcheck::Bool = true) if skipdupcheck || !isintail(row, s.rowval, s.colptr[s.colcounter]) push!(s.rowval, row) push!(s.nzval, x) s.rowvalcounter += 1 end return s end function appendtocolumn!(s::CSC, firstrow::Int, vals, skipdupcheck::Bool = true) len = length(vals) if skipdupcheck || !any(i->isintail(firstrow + i - 1, s.rowval, s.colptr[s.colcounter]), 1:len) append!(s.rowval, firstrow:firstrow+len-1) append!(s.nzval, vals) s.rowvalcounter += len end return s end function isintail(element, container, start::Int) for i in start:length(container) container[i] == element && return true end return false end function sync_columns!(s::CSC, col) missing_cols = col - s.colcounter for _ in 1:missing_cols finalizecolumn!(s) end return nothing end function finalizecolumn!(s::CSC, sortcol::Bool = true) if sortcol s.cosorter.offset = s.colptr[s.colcounter] - 1 sort!(s.cosorter) isgrowing(s.cosorter) || internalerror("finalizecolumn!: repeated rows") end s.colcounter += 1 push!(s.colptr, s.rowvalcounter + 1) return nothing end function completecolptr!(colptr, cols, lastrowptr) colcounter = length(colptr) if colcounter < cols + 1 resize!(colptr, cols + 1) for col in (colcounter + 1):(cols + 1) colptr[col] = lastrowptr + 1 end end return colptr end function SparseArrays.sparse(s::CSC, m::Integer, n::Integer) completecolptr!(s.colptr, n, s.rowvalcounter) rows, cols = isempty(s.rowval) ? 0 : maximum(s.rowval), length(s.colptr) - 1 rows <= m && cols == n || internalerror("sparse: matrix size $((rows, cols)) is inconsistent with lattice size $((m, n))") return SparseMatrixCSC(m, n, s.colptr, s.rowval, s.nzval) end Base.isempty(s::CSC) = length(s) == 0 Base.length(s::CSC) = length(s.nzval) #endregion ############################################################################################ # IJVBuilder and CSCBuilder <: AbstractHamiltonianBuilder #region abstract type AbstractHarmonicBuilder{L,B} end abstract type AbstractHamiltonianBuilder{T,E,L,B} end struct IJVHarmonic{L,B} <: AbstractHarmonicBuilder{L,B} dn::SVector{L,Int} collector::IJV{B} end struct CSCHarmonic{L,B} <: AbstractHarmonicBuilder{L,B} dn::SVector{L,Int} collector::CSC{B} end struct IJVBuilder{T,E,L,B,M<:Union{Missing,Vector{Any}}} <: AbstractHamiltonianBuilder{T,E,L,B} lat::Lattice{T,E,L} blockstruct::OrbitalBlockStructure{B} harmonics::Vector{IJVHarmonic{L,B}} kdtrees::Vector{KDTree{SVector{E,T},Euclidean,T}} modifiers::M end struct CSCBuilder{T,E,L,B} <: AbstractHamiltonianBuilder{T,E,L,B} lat::Lattice{T,E,L} blockstruct::OrbitalBlockStructure{B} harmonics::Vector{CSCHarmonic{L,B}} end const IJVBuilderWithModifiers = IJVBuilder{<:Any,<:Any,<:Any,<:Any,Vector{Any}} ## Constructors ## function CSCBuilder(lat::Lattice{<:Any,<:Any,L}, blockstruct::OrbitalBlockStructure{B}) where {L,B} harmonics = CSCHarmonic{L,B}[] return CSCBuilder(lat, blockstruct, harmonics) end IJVBuilder(lat::Lattice{T}, orbitals, modifiers = missing) where {T} = IJVBuilder(lat, OrbitalBlockStructure(T, orbitals, sublatlengths(lat)), modifiers) function IJVBuilder(lat::Lattice{T,E,L}, blockstruct::OrbitalBlockStructure{B}, modifiers = missing) where {E,T,L,B} harmonics = IJVHarmonic{L,B}[] kdtrees = Vector{KDTree{SVector{E,T},Euclidean,T}}(undef, nsublats(lat)) return IJVBuilder(lat, blockstruct, harmonics, kdtrees, modifiers) end # with no modifiers function IJVBuilder(lat::Lattice{T}, hams::Hamiltonian...) where {T} bs = blockstructure(lat, hams...) builder = IJVBuilder(lat, bs) push_ijvharmonics!(builder, hams...) return builder end # with some modifiers function IJVBuilder(lat::Lattice{T}, hams::AbstractHamiltonian...) where {T} bs = blockstructure(lat, hams...) builder = IJVBuilderWithModifiers(lat, bs) push_ijvharmonics!(builder, hams...) mss = modifiers.(hams) bis = blockindices(hams) unapplied_block_modifiers = ((ms, bi) -> intrablock.(parent.(ms), Ref(bi))).(mss, bis) push!(builder, tupleflatten(unapplied_block_modifiers...)...) return builder end (::Type{IJVBuilderWithModifiers})(lat, orbitals) = IJVBuilder(lat, orbitals, Any[]) push_ijvharmonics!(builder, ::OrbitalBlockStructure) = builder push_ijvharmonics!(builder, hars::Vector{<:IJVHarmonic}) = copy!(builder.harmonics, hars) push_ijvharmonics!(builder) = builder function push_ijvharmonics!(builder::IJVBuilder, hs::AbstractHamiltonian...) offset = 0 B = blocktype(builder) for h in hs for har in harmonics(h) ijv = builder[dcell(har)] hmat = unflat(matrix(har)) I,J,V = findnz(hmat) V´ = maybe_mask_blocks(B, V) append!(ijv, (I .+ offset, J .+ offset, V´)) end offset += nsites(lattice(h)) end return builder end maybe_mask_blocks(::Type{B}, V::Vector{B}) where {B} = V maybe_mask_blocks(::Type{B}, V::Vector) where {B} = mask_block.(B, V) empty_harmonic(b::CSCBuilder{<:Any,<:Any,L,B}, dn) where {L,B} = CSCHarmonic{L,B}(dn, CSC{B}(nsites(b.lat))) empty_harmonic(::IJVBuilder{<:Any,<:Any,L,B}, dn) where {L,B} = IJVHarmonic{L,B}(dn, IJV{B}()) builder(; kw...) = lat -> builder(lat; kw...) builder(lat::Lattice; orbitals = Val(1)) = IJVBuilderWithModifiers(lat, orbitals) ## API ## collector(har::AbstractHarmonicBuilder) = har.collector # for IJVHarmonic and CSCHarmonic dcell(har::AbstractHarmonicBuilder) = har.dn kdtrees(b::IJVBuilder) = b.kdtrees modifiers(b::IJVBuilderWithModifiers) = b.modifiers finalizecolumn!(b::CSCBuilder, x...) = foreach(har -> finalizecolumn!(collector(har), x...), b.harmonics) nsites(b::AbstractHamiltonianBuilder) = nsites(lattice(b)) ncells(b::AbstractHamiltonianBuilder) = length(harmonics(b)) Base.isempty(h::IJVHarmonic) = isempty(collector(h)) Base.isempty(s::CSCHarmonic) = isempty(collector(s)) lattice(b::AbstractHamiltonianBuilder) = b.lat blockstructure(b::AbstractHamiltonianBuilder) = b.blockstruct blocktype(::AbstractHamiltonianBuilder{<:Any,<:Any,<:Any,B}) where {B} = B harmonics(b::AbstractHamiltonianBuilder) = b.harmonics Base.length(b::AbstractHarmonicBuilder) = length(collector(b)) Base.push!(b::IJVBuilderWithModifiers, ms::AnyModifier...) = push!(b.modifiers, ms...) Base.pop!(b::IJVBuilderWithModifiers) = pop!(b.modifiers) Base.empty!(b::IJVBuilderWithModifiers) = (empty!(b.harmonics); empty!(b.modifiers); b) Base.empty!(b::IJVBuilder) = (empty!(b.harmonics); b) function Base.getindex(b::AbstractHamiltonianBuilder{<:Any,<:Any,L}, dn::SVector{L,Int}) where {L} hars = b.harmonics for har in hars dcell(har) == dn && return collector(har) end har = empty_harmonic(b, dn) push!(hars, har) return collector(har) end function SparseArrays.sparse(builder::AbstractHamiltonianBuilder{T,<:Any,L,B}) where {T,L,B} HT = Harmonic{T,L,B} b = blockstructure(builder) n = nsites(builder) hars = HT[sparse(b, har, n, n) for har in harmonics(builder) if !isempty(har)] return hars end function SparseArrays.sparse(b::OrbitalBlockStructure{B}, har::AbstractHarmonicBuilder{L,B}, m::Integer, n::Integer) where {L,B} s = sparse(har, m, n) return Harmonic(dcell(har), HybridSparseMatrix(b, s)) end # cannot combine these two due to ambiguity with sparse(I, J, v::Number) SparseArrays.sparse(har::AbstractHarmonicBuilder, n::Integer, m::Integer) = sparse(collector(har), m, n) SparseArrays.sparse(har::AbstractHarmonicBuilder) = sparse(collector(har)) #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
3204
# In v0.7+ the idea is that `convert`` is a shortcut to a "safe" subset of the constructors # for a type, that guarantees the resulting type. The constructor is the central machinery # to instantiate types and convert between instances. (For parametric types, unless overridden, # you get an implicit internal constructor without parameters, so no need to define that externally) Base.convert(::Type{T}, l::T) where T<:SMatrixView = l Base.convert(::Type{T}, l::SMatrixView) where T<:SMatrixView = T(parent(l)) Base.convert(::Type{T}, l::T) where T<:Sublat = l Base.convert(::Type{T}, l::Sublat) where T<:Sublat = T(l) Base.convert(::Type{T}, l::T) where T<:CellSites = l Base.convert(::Type{T}, l::CellSites) where T<:CellSites = T(l) Base.convert(::Type{T}, l::T) where T<:AbstractHamiltonian = l Base.convert(::Type{T}, l::AbstractHamiltonian) where T<:AbstractHamiltonian = T(l) Base.convert(::Type{T}, l::T) where T<:Mesh = l Base.convert(::Type{T}, l::Mesh) where T<:Mesh = T(l) # Constructors for conversion Sublat{T,E}(s::Sublat, name = s.name) where {T<:AbstractFloat,E} = Sublat{T,E}([sanitize_SVector(SVector{E,T}, site) for site in sites(s)], name) CellSites{L,V}(c::CellSites) where {L,V} = CellIndices(convert(SVector{L,Int}, cell(c)), convert(V, siteindices(c)), SiteLike()) CellSites{L,V}(c::CellSite) where {L,V<:Vector} = CellIndices(convert(SVector{L,Int}, cell(c)), convert(V, [siteindices(c)]), SiteLike()) function Hamiltonian{E}(h::Hamiltonian) where {E} lat = lattice(h) lat´ = lattice(lat, dim = Val(E)) bs = blockstructure(h) hs = harmonics(h) b = bloch(h) return Hamiltonian(lat´, bs, hs, b) end function ParametricHamiltonian{E}(ph::ParametricHamiltonian) where {E} hparent = Hamiltonian{E}(parent(ph)) h = Hamiltonian{E}(hamiltonian(ph)) ms = modifiers(ph) ptrs = pointers(ph) pars = parameters(ph) return ParametricHamiltonian(hparent, h, ms, ptrs, pars) end Mesh{S}(m::Mesh) where {S} = Mesh(convert(Vector{S}, vertices(m)), neighbors(m), simplices(m)) # We need this to promote different sublats into common dimensionality and type to combine # into a lattice Base.promote(ss::Sublat{T,E}...) where {T,E} = ss function Base.promote_rule(::Type{Sublat{T1,E1}}, ::Type{Sublat{T2,E2}}) where {T1,T2,E1,E2} E = max(E1, E2) T = float(promote_type(T1, T2)) return Sublat{T,E} end # Block type promotion, for use in e.g. combine const HBtype{B} = AbstractHamiltonian{<:Any,<:Any,<:Any,B} const SMatrixOrView{N,M,T,NM} = Union{SMatrix{N,M,T,NM}, SMatrixView{N,M,T,NM}} Base.promote_rule(::Type{<:HBtype{S}}, ::Type{<:HBtype{S}}) where {S} = HBtype{S} Base.promote_rule(::Type{<:HBtype{C}}, ::Type{<:HBtype{C´}}) where {C<:Complex,C´<:Complex} = HBtype{promote_type(C,C´)} Base.promote_rule(::Type{<:HBtype{C´}}, ::Type{<:HBtype{S}}) where {C´<:Complex,C,N,NN,S<:SMatrixOrView{N,N,C,NN}} = HBtype{SMatrixView{N,N,promote_type(C,C´),NN}} function Base.promote_rule(::Type{<:HBtype{S1}}, ::Type{<:HBtype{S2}}) where {N1,C1,S1<:SMatrixOrView{N1,N1,C1},N2,C2,S2<:SMatrixOrView{N2,N2,C2}} N = max(N1,N2) C = promote_type(C1, C2) return HBtype{SMatrixView{N,N,C,N*N}} end
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
85744
""" `LatticePresets` is a Quantica submodule containing several pre-defined lattices. The alias `LP` can be used in place of `LatticePresets`. Currently supported lattices are LP.linear(; a0 = 1, kw...) # linear lattice in 1D LP.square(; a0 = 1, kw...) # square lattice in 2D LP.triangular(; a0 = 1, kw...) # triangular lattice in 2D LP.honeycomb(; a0 = 1, kw...) # honeycomb lattice in 2D LP.cubic(; a0 = 1, kw...) # cubic lattice in 3D LP.fcc(; a0 = 1, kw...) # face-centered-cubic lattice in 3D LP.bcc(; a0 = 1, kw...) # body-centered-cubic lattice in 3D LP.hcp(; a0 = 1, kw...) # hexagonal-closed-packed lattice in 3D In all cases `a0` denotes the lattice constant, and `kw...` are extra keywords forwarded to `lattice`. # Examples ```jldoctest julia> LatticePresets.honeycomb(names = (:C, :D)) Lattice{Float64,2,2} : 2D lattice in 2D space Bravais vectors : [[0.5, 0.866025], [-0.5, 0.866025]] Sublattices : 2 Names : (:C, :D) Sites : (1, 1) --> 2 total per unit cell julia> LatticePresets.cubic(bravais = ((1, 0), (0, 2))) Lattice{Float64,3,2} : 2D lattice in 3D space Bravais vectors : [[1.0, 0.0, 0.0], [0.0, 2.0, 0.0]] Sublattices : 1 Names : (:A,) Sites : (1,) --> 1 total per unit cell ``` # See also `RegionPresets`, `HamiltonianPresets`, `ExternalPresets` """ LatticePresets """ `HamiltonianPresets` is a Quantica submodule containing several pre-defined Hamiltonians. The alias `HP` can be used in place of `HamiltonianPresets`. Currently supported hamiltonians are HP.graphene(; kw...) HP.twisted_bilayer_graphene(; kw...) For details on the keyword arguments `kw` see the corresponding docstring ```jldoctest julia> HamiltonianPresets.twisted_bilayer_graphene(twistindices = (30, 1)) Hamiltonian{Float64,3,2}: Hamiltonian on a 2D Lattice in 3D space Bloch harmonics : 7 Harmonic size : 11164 × 11164 Orbitals : [1, 1, 1, 1] Element type : scalar (ComplexF64) Onsites : 0 Hoppings : 315684 Coordination : 28.27696 ``` # See also `LatticePresets`, `RegionPresets`, `ExternalPresets` """ HamiltonianPresets """ `RegionPresets` is a Quantica submodule containing several pre-defined regions of type `Region{E}`, where `E` is the space dimension. The alias `RP` can be used in place of `RegionPresets`. Supported regions are RP.circle(radius = 10, center = (0, 0)) # 2D RP.ellipse((rx, ry) = (10, 15), center = (0, 0)) # 2D RP.square(side = 10, center = (0, 0)) # 2D RP.rectangle((sx, sy) = (10, 15), center = (0, 0)) # 2D RP.sphere(radius = 10, center = (0, 0, 0)) # 3D RP.spheroid((rx, ry, rz) = (10, 15, 20), center = (0, 0, 0)) # 3D RP.cube(side = 10, center = (0, 0, 0)) # 3D RP.cuboid((sx, sy, sz) = (10, 15, 20), center = (0, 0, 0)) # 3D Calling a `f::Region{E}` object on a `r::Tuple` or `r::SVector` with `f(r)` or `f(r...)` returns `true` or `false` if `r` is inside the region or not. Note that only the first `E` coordinates of `r` will be checked. Arbitrary boolean functions can also be wrapped in `Region{E}` to create custom regions, e.g. `f = Region{2}(r -> r[1]^2 < r[2])`. Boolean combinations of `Regions` are supported using `&`, `|`, `xor` and `!` operators, such as `annulus = RP.circle(10) & !RP.circle(5)`. # Examples ```jldoctest julia> RegionPresets.circle(10)(20, 0, 0) false julia> RegionPresets.circle(10)(0, 0, 20) true ``` # See also `LatticePresets`, `HamiltonianPresets`, `ExternalPresets` """ RegionPresets """ `ExternalPresets` is a Quantica submodule containing utilities to import objects from external applications The alias `EP` can be used in place of `ExternalPresets`. Currently supported importers are EP.wannier90(args...; kw...) For details on the arguments `args` and keyword arguments `kw` see the docstring for the corresponding function. # See also `LatticePresets`, `RegionPresets`, `HamiltonianPresets` """ ExternalPresets """ sublat(sites...; name::Symbol = :A) sublat(sites::AbstractVector; name::Symbol = :A) Create a `Sublat{E,T}` that adds a sublattice, of name `name`, with sites at positions `sites` in `E` dimensional space. Sites positions can be entered as `Tuple`s or `SVector`s. # Examples ```jldoctest julia> sublat((0.0, 0), (1, 1), (1, -1), name = :A) Sublat{2,Float64} : sublattice of Float64-typed sites in 2D space Sites : 3 Name : :A ``` """ sublat """ bravais_matrix(lat::Lattice) bravais_matrix(h::AbstractHamiltonian) Return the Bravais matrix of lattice `lat` or AbstractHamiltonian `h`, with Bravais vectors as its columns. # Examples ```jldoctest julia> lat = lattice(sublat((0,0)), bravais = ((1.0, 2), (3, 4))); julia> bravais_matrix(lat) 2×2 SMatrix{2, 2, Float64, 4} with indices SOneTo(2)×SOneTo(2): 1.0 3.0 2.0 4.0 ``` # See also `lattice` """ bravais_matrix """ lattice(sublats::Sublat...; bravais = (), dim, type, names) lattice(sublats::AbstractVector{<:Sublat}; bravais = (), dim, type, names) Create a `Lattice{T,E,L}` from sublattices `sublats`, where `L` is the number of Bravais vectors given by `bravais`, `T = type` is the `AbstractFloat` type of spatial site coordinates, and `dim = E` is the spatial embedding dimension. lattice(lat::Lattice; bravais = missing, dim = missing, type = missing, names = missing) Create a new lattice by applying any non-missing keywords to `lat`. lattice(x) Return the parent lattice of object `x`, of type e.g. `LatticeSlice`, `Hamiltonian`, etc. ## Keywords - `bravais`: a collection of one or more Bravais vectors of type NTuple{E} or SVector{E}. It can also be an `AbstractMatrix` of dimension `E×L`. The default `bravais = ()` corresponds to a bounded lattice with no Bravais vectors. - `names`: a collection of Symbols. Can be used to rename `sublats`. Any repeated names will be replaced if necessary by `:A`, `:B` etc. to ensure that all sublattice names are unique. ## Indexing lat[kw...] lat[siteselector(; kw...)] Indexing into a lattice `lat` with keywords returns `LatticeSlice` representing a finite collection of sites selected by `siteselector(; kw...)`. See `siteselector` for details on possible `kw`, and `sites` to obtain site positions. lat[] Special case equivalent to `lat[cells = (0,...)]` that returns a `LatticeSlice` of the zero-th unitcell. lat[i::CellSites] With an `i` of type `CellSites` contructed with `sites([cell,] indices)`, return a `LatticeSlice` of the corresponding sites. # Examples ```jldoctest julia> lat = lattice(sublat((0, 0)), sublat((0, 1)); bravais = (1, 0), type = Float32, dim = 3, names = (:up, :down)) Lattice{Float32,3,1} : 1D lattice in 3D space Bravais vectors : Vector{Float32}[[1.0, 0.0, 0.0]] Sublattices : 2 Names : (:up, :down) Sites : (1, 1) --> 2 total per unit cell julia> lattice(lat; type = Float64, names = (:A, :B), dim = 2) Lattice{Float64,2,1} : 1D lattice in 2D space Bravais vectors : [[1.0, 0.0]] Sublattices : 2 Names : (:A, :B) Sites : (1, 1) --> 2 total per unit cell ``` # See also `LatticePresets`, `sublat`, `sites`, `supercell` """ lattice """ sites(lat::Lattice[, sublat]) Return a collection of site positions in the unit cell of lattice `lat`. If a `sublat::Symbol` or `sublat::Int` is specified, only sites for the specified sublattice are returned. sites(ls::LatticeSlice) Return a collection of positions of a LatticeSlice, generally obtained by indexing a lattice `lat[sel...]` with some `siteselector` keywords `sel`. See also `lattice`. Note: the returned collections can be of different types (vectors, generators, views...) sites(cell_index, site_indices) sites(site_indices) Construct a simple selector of sites, of type `CellSites`, with given `site_indices` in a given cell at `cell_index`. Here, `site_indices` can be an index, a collection of integers or `:` (for all sites), and `cell_index` should be a collection of `L` integers, where `L` is the lattice dimension. If omitted, `cell_index` defaults to the zero-th cell `(0,...)`. `CellSites` produced with `sites` can be used to index `Lattice`s, `AbstractHamiltonian`s, `GreenFunction`s, `GreenSlice`s, `OrbitalSliceArray`s, etc. Note that selecting sites based on cell and site indices requires finding the indices beforehand, which can be done e.g. through plotting the system with `qplot`. This is lower level and potentially more fragile than using `siteselector`s, as indices are chosen freely by Quantica in an unspecified way, but it does have a smaller overhead. # Examples ```jldoctest julia> sites(LatticePresets.honeycomb(), :A) 1-element view(::Vector{SVector{2, Float64}}, 1:1) with eltype SVector{2, Float64}: [0.0, -0.2886751345948129] ``` # See also `lattice`, `siteselector` """ sites """ position(b::ExternalPresets.WannierBuilder) Returns the position operator in the Wannier basis. It is given as a `r::BarebonesOperator` object, which can be indexed as `r[s, s´]` to obtain matrix elements `⟨s|R|s´⟩` of the position operator `R` (a vector). Here `s` and `s´` represent site indices, constructed with `sites(cell, inds)`. To obtain the matrix between cells separated by `dn::SVector{L,Int}`, do `r[dn]`. The latter will throw an error if the `dn` harmonic is not present. # See also `current`, `sites` """ position """ supercell(lat::Lattice{E,L}, v::NTuple{L,Integer}...; seed = missing, kw...) supercell(lat::Lattice{E,L}, uc::SMatrix{L,L´,Int}; seed = missing, kw...) Generate a new `Lattice` from an `L`-dimensional lattice `lat` with a larger unit cell, such that its Bravais vectors are `br´= br * uc`. Here `uc::SMatrix{L,L´,Int}` is the integer supercell matrix, with the `L´` vectors `v`s as its columns. If no `v` are given, the new lattice will have no Bravais vectors (i.e. it will be bounded, with its shape determined by keywords `kw...`). Likewise, if `L´ < L`, the resulting lattice will be bounded along `L´ - L` directions, as dictated by `kw...`. Only sites selected by `siteselector(; kw...)` will be included in the supercell (see `siteselector` for details on the available keywords `kw`). If no keyword `region` is given in `kw`, a single Bravais unit cell perpendicular to the `v` axes will be selected along the `L-L´` bounded directions. supercell(lattice::Lattice{E,L}, factors::Integer...; seed = missing, kw...) Call `supercell` with different scaling along each Bravais vector, so that supercell matrix `uc` is `Diagonal(factors)`. If a single `factor` is given, `uc = SMatrix{L,L}(factor * I)` supercell(h::Hamiltonian, v...; mincoordination = 0, seed = missing, kw...) Transform the `Lattice` of `h` to have a larger unit cell, while expanding the Hamiltonian accordingly. ## Keywords - `seed::NTuple{L,Integer}`: starting cell index to perform search of included sites. By default `seed = missing`, which makes search start from the zero-th cell. - `mincoordination::Integer`: minimum number of nonzero hopping neighbors required for sites to be included in the supercell. Sites with less coordination will be removed recursively, until all remaining sites satisfy `mincoordination`. ## Currying lat_or_h |> supercell(v...; kw...) Curried syntax, equivalent to `supercell(lat_or_h, v...; kw...)` # Examples ```jldoctest julia> LatticePresets.square() |> supercell((1, 1), region = r -> 0 < r[1] < 5) Lattice{Float64,2,1} : 1D lattice in 2D space Bravais vectors : [[1.0, 1.0]] Sublattices : 1 Names : (:A,) Sites : (8,) --> 8 total per unit cell julia> LatticePresets.honeycomb() |> supercell(3) Lattice{Float64,2,2} : 2D lattice in 2D space Bravais vectors : [[1.5, 2.598076], [-1.5, 2.598076]] Sublattices : 2 Names : (:A, :B) Sites : (9, 9) --> 18 total per unit cell ``` # See also `supercell`, `siteselector` """ supercell """ reverse(lat_or_h::Union{Lattice,AbstractHamiltonian}) Build a new lattice or hamiltonian with the orientation of all Bravais vectors reversed. # See also `reverse!`, `transform` """ Base.reverse """ reverse!(lat_or_h::Union{Lattice,AbstractHamiltonian}) In-place version of `reverse`, inverts all Bravais vectors of `lat_or_h`. # See also `reverse`, `transform` """ Base.reverse! """ transform(lat_or_h::Union{Lattice,AbstractHamiltonian}, f::Function) Build a new lattice or hamiltonian transforming each site positions `r` into `f(r)`. ## Currying x |> transform(f::Function) Curried version of `transform`, equivalent to `transform(f, x)` Note: Unexported `Quantica.transform!` is also available for in-place transforms. Use with care, as aliasing (i.e. several objects sharing the modified one) can produce unexpected results. # Examples ```jldoctest julia> LatticePresets.square() |> transform(r -> 3r) Lattice{Float64,2,2} : 2D lattice in 2D space Bravais vectors : [[3.0, 0.0], [0.0, 3.0]] Sublattices : 1 Names : (:A,) Sites : (1,) --> 1 total per unit cell ``` # See also `translate`, `reverse`, `reverse!` """ transform """ translate(lat::Lattice, δr) Build a new lattice translating each site positions from `r` to `r + δr`, where `δr` can be a `NTuple` or an `SVector` in embedding space. ## Currying x |> translate(δr) Curried version of `translate`, equivalent to `translate(x, δr)` Note: Unexported `Quantica.translate!` is also available for in-place translations. Use with care, as aliasing (i.e. several objects sharing the modified one) can produce unexpected results. # Examples ```jldoctest julia> LatticePresets.square() |> translate((3,3)) |> sites 1-element Vector{SVector{2, Float64}}: [3.0, 3.0] ``` # See also `transform`, `reverse`, `reverse!` """ translate """ combine(lats::Lattice...) If all `lats` have compatible Bravais vectors, combine them into a single lattice. If necessary, sublattice names are renamed to remain unique. combine(hams::Hamiltonians...; coupling = TighbindingModel()) Combine a collection `hams` of Hamiltonians into one by combining their corresponding lattices, and optionally by adding a coupling between them, given by the hopping terms in `coupling`. Note that the `coupling` model will be applied to the combined lattice (which may have renamed sublattices to avoid name collissions). However, only hopping terms between different `hams` blocks will be applied. ## Limitations Currently, `combine` only works with `Lattice{T}` `AbstractHamiltonians{T}` with the same `T`. Furthermore, if any of the `hams` is a `ParametricHamiltonian` or `coupling` is a `ParametricModel`, the sublattice names of all `hams` must be distinct. This ensures that parametric models, which get applied through `Modifiers` after construction of the `ParametricHamiltonian`, are not applied to the wrong sublattice, since sublattice names could be renamed by `combine` if they are not unique. Therefore, be sure to choose unique sublattice names upon construction for all the `hams` to be combined (see `lattice`). # Examples ```jldoctest julia> # Building Bernal-stacked bilayer graphene julia> hbot = HP.graphene(a0 = 1, dim = 3, names = (:A,:B)); julia> htop = translate(HP.graphene(a0 = 1, dim = 3, names = (:C,:D)), (0, 1/√3, 1/√3)); julia> h2 = combine(hbot, htop; coupling = hopping(1, sublats = :B => :C) |> plusadjoint) Hamiltonian{Float64,3,2}: Hamiltonian on a 2D Lattice in 3D space Bloch harmonics : 5 Harmonic size : 4 × 4 Orbitals : [1, 1, 1, 1] Element type : scalar (ComplexF64) Onsites : 0 Hoppings : 14 Coordination : 3.5 ``` # See also `hopping` """ combine """ siteselector(; region = missing, sublats = missing, cells = missing) Return a `SiteSelector` object that can be used to select a finite set of sites in a lattice. Sites at position `r::SVector{E}`, belonging to a cell of index `n::SVector{L,Int}` and to a sublattice with name `s::Symbol` will be selected only if `region(r) && s in sublats && n in cells` Any missing `region`, `sublat` or `cells` will not be used to constraint the selection. ## Generalization While `sublats` and `cells` are usually collections of `Symbol`s and `SVector`s, respectively, they also admit other possibilities: - If either `cells` or `sublats` are a single cell or sublattice, they will be treated as single-element collections - If `sublat` is a collection of `Integer`s, it will refer to sublattice numbers. - If `cells` is an `i::Integer`, it will be converted to an `SVector{1}` - If `cells` is a collection, each element will be converted to an `SVector`. - If `cells` is a boolean function, `n in cells` will be the result of `cells(n)` ## Usage Although the constructor `siteselector(; kw...)` is exported, the end user does not usually need to call it directly. Instead, the keywords `kw` are input into different functions that allow filtering sites, which themselves call `siteselector` internally as needed. Some of these functions are - getindex(lat::Lattice; kw...) : return a LatticeSlice with sites specified by `kw` (also `lat[kw...]`) - supercell(lat::Lattice; kw...) : returns a bounded lattice with the sites specified by `kw` - onsite(...; kw...) : onsite model term to be applied to sites specified by `kw` - @onsite!(...; kw...) : onsite modifier to be applied to sites specified by `kw` # See also `hopselector`, `lattice`, `supercell`, `onsite`, `@onsite`, `@onsite!` """ siteselector """ hopselector(; range = neighbors(1), dcells = missing, sublats = missing, region = missing) Return a `HopSelector` object that can be used to select a finite set of hops between sites in a lattice. Hops between two sites at positions `r₁ = r - dr/2` and `r₂ = r + dr`, belonging to unit cells with a cell distance `dn::SVector{L,Int}` and to a sublattices with names `s₁::Symbol` and `s₂::Symbol` will be selected only if `region(r, dr) && (s₁ => s₂ in sublats) && (dcell in dcells) && (norm(dr) <= range)` If any of these is `missing` it will not be used to constraint the selection. ## Generalization While `range` is usually a `Real`, and `sublats` and `dcells` are usually collections of `Pair{Symbol}`s and `SVector`s, respectively, they also admit other possibilities: sublats = :A # Hops from :A to :A sublats = :A => :B # Hops from :A to :B sublattices, but not from :B to :A sublats = (:A => :B,) # Same as above sublats = (:A => :B, :C => :D) # Hopping from :A to :B or :C to :D sublats = (:A, :C) .=> (:B, :D) # Broadcasted pairs, same as above sublats = (:A, :C) => (:B, :D) # Direct product, (:A=>:B, :A=>:D, :C=>:B, :C=>D) sublats = 1 => 2 # Hops from 1st to 2nd sublat. All the above patterns also admit Ints sublats = (spec₁, spec₂, ...) # Hops matching any of the specs with any of the above forms dcells = dn::SVector{L,Integer} # Hops between cells separated by `dn` dcells = dn::NTuple{L,Integer} # Hops between cells separated by `SVector(dn)` dcells = f::Function # Hops between cells separated by `dn` such that `f(dn) == true` range = neighbors(n) # Hops within the `n`-th nearest neighbor distance in the lattice range = (min, max) # Hops at distance inside the `[min, max]` closed interval (bounds can also be `neighbors(n)`) ## Usage Although the constructor `hopselector(; kw...)` is exported, the end user does not usually need to call it directly. Instead, the keywords `kw` are input into different functions that allow filtering hops, which themselves call `hopselector` internally as needed. Some of these functions are - hopping(...; kw...) : hopping model term to be applied to site pairs specified by `kw` - @hopping(...; kw...) : parametric hopping model term to be applied to site pairs specified by `kw` - @hopping!(...; kw...) : hopping modifier to be applied to site pairs specified by `kw` # Examples ```jldoctest julia> h = LP.honeycomb() |> hamiltonian(hopping(1, range = neighbors(2), sublats = (:A, :B) .=> (:A, :B))) Hamiltonian{Float64,2,2}: Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 7 Harmonic size : 2 × 2 Orbitals : [1, 1] Element type : scalar (ComplexF64) Onsites : 0 Hoppings : 12 Coordination : 6.0 julia> h = LP.honeycomb() |> hamiltonian(hopping(1, range = (neighbors(2), neighbors(3)), sublats = (:A, :B) => (:A, :B))) Hamiltonian{Float64,2,2}: Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 9 Harmonic size : 2 × 2 Orbitals : [1, 1] Element type : scalar (ComplexF64) Onsites : 0 Hoppings : 18 Coordination : 9.0 ``` # See also `siteselector`, `lattice`, `hopping`, `@hopping`, `@hopping!` """ hopselector """ neighbors(n::Int) Create a `Neighbors(n)` object that represents a hopping range to distances corresponding to the n-th nearest neighbors in a given lattice, irrespective of their sublattice. Neighbors at equal distance do not count towards `n`. neighbors(n::Int, lat::Lattice) Obtain the actual nth-nearest-neighbot distance between sites in lattice `lat`. # See also `hopping` """ neighbors """ hamiltonian(lat::Lattice, model; orbitals = 1) Create an `AbstractHamiltonian` (i.e. an `Hamiltonian` or `ParametricHamiltonian`) by applying `model` to the lattice `lat` (see `onsite`, `@onsite`, `hopping` and `@hopping` for details on building parametric and non-parametric tight-binding models). hamiltonian(lat::Lattice, model, modifiers...; orbitals = 1) Create a `ParametricHamiltonian` where all onsite and hopping terms in `model` can be parametrically modified through the provided parametric `modifiers` (see `@onsite!` and `@hopping!` for details on defining modifiers). hamiltonian(h::AbstractHamiltonian, modifier, modifiers...) Add modifiers to an existing `AbstractHamiltonian`. hamiltonian(h::ParametricHamiltonian) Return the base (non-parametric) `Hamiltonian` of `h`, with all modifiers and parametric model terms removed (see `@onsite`, `@hopping`, `@onsite!`, `@hopping!`). ## Keywords - `orbitals`: number of orbitals per sublattice. If an `Integer` (or a `Val{<:Integer}` for type-stability), all sublattices will have the same number of orbitals. A collection of values indicates the orbitals on each sublattice. ## Currying lat |> hamiltonian(model[, modifiers...]; kw...) Curried form of `hamiltonian` equivalent to `hamiltonian(lat, model, modifiers...; kw...)`. lat |> model Alternative and less general curried form equivalent to `hamiltonian(lat, model)`. h |> modifier Alternative and less general curried form equivalent to `hamiltonian(h, modifier)`. ## Indexing h[dn::SVector{L,Int}] h[dn::NTuple{L,Int}] Return the Bloch harmonic of an `h::AbstractHamiltonian` in the form of a `SparseMatrixCSC` with complex scalar `eltype`. This matrix is "flat", in the sense that it contains matrix elements between individual orbitals, not sites. This distinction is only relevant for multiorbital Hamiltonians. To access the non-flattened matrix use `h[unflat(dn)]` (see also `unflat`). h[()] Special syntax equivalent to `h[(0...)]`, which access the fundamental Bloch harmonic. h[i::CellSites, j::CellSites = i] With `i` and `j` of type `CellSites` and constructed with `sites([cell,] indices)`, return a `SparseMatrixCSC` block of `h` between the sites with the corresponding `indices` and in the given `cell`s. Alternatively, one can also use `view(h, i, j = i)`, which should be non-allocating for `AbstractHamiltonian`s with uniform number of orbitals. h[srow::SiteSelector, scol::SiteSelector = srow] h[kwrow::NamedTuple, kwcol::NamedTuple = kwrow] Return an `OrbitalSliceMatrix` of `h` between row and column sites selected by `srow` and `scol`, or by `siteselector(; kwrow...)` and `siteselector(; kwcol...)` Note: `CellSites` and `SiteSelector`s can be mixed when indexing, in which case the matrix block will be returned as a `SparseMatrixCSC`, instead of an `OrbitalSliceMatrix`. ## Call syntax ph(; params...) Return a `h::Hamiltonian` from a `ph::ParametricHamiltonian` by applying specific values to its parameters `params`. If `ph` is a non-parametric `Hamiltonian` instead, this is a no-op. h(φs; params...) Return the flat, sparse Bloch matrix of `h::AbstractHamiltonian` at Bloch phases `φs`, with applied parameters `params` if `h` is a `ParametricHamiltonian`. The Bloch matrix is defined as H = ∑_dn exp(-im φs⋅dn) H_dn where `H_dn = h[dn]` is the `dn` flat Bloch harmonic of `h`, and `φs[i] = k⋅aᵢ` in terms of the wavevector `k` and the Bravais vectors `aᵢ`. # Examples ```jldoctest julia> h = hamiltonian(LP.honeycomb(), hopping(SA[0 1; 1 0], range = 1/√3), orbitals = 2) Hamiltonian{Float64,2,2}: Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 5 Harmonic size : 2 × 2 Orbitals : [2, 2] Element type : 2 × 2 blocks (ComplexF64) Onsites : 0 Hoppings : 6 Coordination : 3.0 julia> h((0,0)) 4×4 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 8 stored entries: ⋅ ⋅ 0.0+0.0im 3.0+0.0im ⋅ ⋅ 3.0+0.0im 0.0+0.0im 0.0+0.0im 3.0+0.0im ⋅ ⋅ 3.0+0.0im 0.0+0.0im ⋅ ⋅ julia> h[sites(1), sites(2)] 2×2 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 4 stored entries: 0.0+0.0im 1.0+0.0im 1.0+0.0im 0.0+0.0im julia> ph = h |> @hopping!((t; p = 3) -> p*t); ph[region = RP.square(1)] 4×4 OrbitalSliceMatrix{SparseArrays.SparseMatrixCSC{ComplexF64, Int64}}: 0.0+0.0im 0.0+0.0im 0.0+0.0im 3.0+0.0im 0.0+0.0im 0.0+0.0im 3.0+0.0im 0.0+0.0im 0.0+0.0im 3.0+0.0im 0.0+0.0im 0.0+0.0im 3.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im ``` # See also `lattice`, `onsite`, `hopping`, `@onsite`, `@hopping`, `@onsite!`, `@hopping!`, `ishermitian`, `OrbitalSliceMatrix` """ hamiltonian """ ishermitian(h::Hamiltonian) Check whether `h` is Hermitian. This is not supported for `h::ParametricHamiltonian`, as the result can depend of the specific values of its parameters. """ ishermitian """ onsite(o; sites...) onsite(r -> o(r); sites...) Build a `TighbindingModel` representing a uniform or a position-dependent onsite potential, respectively, on sites selected by `siteselector(; sites...)` (see `siteselector` for details). Site positions are `r::SVector{E}`, where `E` is the embedding dimension of the lattice. The onsite potential `o` can be a `Number` (for single-orbital sites), a `UniformScaling` (e.g. `2I`) or an `AbstractMatrix` (use `SMatrix` for performance) of dimensions matching the number of orbitals in the selected sites. Models may be applied to a lattice `lat` to produce a `Hamiltonian` with `hamiltonian(lat, model; ...)`, see `hamiltonian`. Position dependent models are forced to preserve the periodicity of the lattice. onsite(m::{TighbindingModel,ParametricModel}; sites...) Convert `m` into a new model with just onsite terms acting on `sites`. ## Model algebra Models can be combined using `+`, `-` and `*`, or conjugated with `'`, e.g. `onsite(1) - 2 * hopping(1)'`. # Examples ```jldoctest julia> model = onsite(r -> norm(r) * SA[0 1; 1 0]; sublats = :A) - hopping(I; range = 2) TightbindingModel: model with 2 terms OnsiteTerm{Function}: Region : any Sublattices : A Cells : any Coefficient : 1 HoppingTerm{LinearAlgebra.UniformScaling{Bool}}: Region : any Sublattice pairs : any Cell distances : any Hopping range : 2.0 Reverse hops : false Coefficient : -1 julia> LP.cubic() |> supercell(4) |> hamiltonian(model, orbitals = 2) Hamiltonian{Float64,3,3}: Hamiltonian on a 3D Lattice in 3D space Bloch harmonics : 27 Harmonic size : 64 × 64 Orbitals : [2] Element type : 2 × 2 blocks (ComplexF64) Onsites : 64 Hoppings : 2048 Coordination : 32.0 ``` # See also `hopping`, `@onsite`, `@hopping`, `@onsite!`, `@hopping!`, `hamiltonian` """ onsite """ hopping(t; hops...) hopping((r, dr) -> t(r, dr); hops...) Build a `TighbindingModel` representing a uniform or a position-dependent hopping amplitude, respectively, on hops selected by `hopselector(; hops...)` (see `hopselector` for details). Hops from a site at position `r₁` to another at `r₂` are described using the hop center `r = (r₁ + r₂)/2` and the hop vector `dr = r₂ - r₁`. Hopping amplitudes `t` can be a `Number` (for hops between single-orbital sites), a `UniformScaling` (e.g. `2I`) or an `AbstractMatrix` (use `SMatrix` for performance) of dimensions matching the number of orbitals in the selected sites. Models may be applied to a lattice `lat` to produce an `Hamiltonian` with `hamiltonian(lat, model; ...)`, see `hamiltonian`. Position dependent models are forced to preserve the periodicity of the lattice. hopping(m::Union{TighbindingModel,ParametricModel}; hops...) Convert `m` into a new model with just hopping terms acting on `hops`. ## Model algebra Models can be combined using `+`, `-` and `*`, or conjugated with `'`, e.g. `onsite(1) - 2 * hopping(1)'`. # Examples ```jldoctest julia> model = hopping((r, dr) -> cis(dot(SA[r[2], -r[1]], dr)); dcells = (0,0)) + onsite(r -> rand()) TightbindingModel: model with 2 terms HoppingTerm{Function}: Region : any Sublattice pairs : any Cell distances : (0, 0) Hopping range : Neighbors(1) Reverse hops : false Coefficient : 1 OnsiteTerm{Function}: Region : any Sublattices : any Cells : any Coefficient : 1 julia> LP.honeycomb() |> supercell(2) |> hamiltonian(model) Hamiltonian{Float64,2,2}: Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 1 Harmonic size : 8 × 8 Orbitals : [1, 1] Element type : scalar (ComplexF64) Onsites : 8 Hoppings : 16 Coordination : 2.0 ``` # See also `onsite`, `@onsite`, `@hopping`, `@onsite!`, `@hopping!`, `hamiltonian`, `plusadjoint` """ hopping """ @onsite((; params...) -> o(; params...); sites...) @onsite((r; params...) -> o(r; params...); sites...) Build a `ParametricModel` representing a uniform or a position-dependent onsite potential, respectively, on sites selected by `siteselector(; sites...)` (see `siteselector` for details). Site positions are `r::SVector{E}`, where `E` is the embedding dimension of the lattice. The onsite potential `o` can be a `Number` (for single-orbital sites), a `UniformScaling` (e.g. `2I`) or an `AbstractMatrix` (use `SMatrix` for performance) of dimensions matching the number of orbitals in the selected sites. Parametric models may be applied to a lattice `lat` to produce a `ParametricHamiltonian` with `hamiltonian(lat, model; ...)`, see `hamiltonian`. Position dependent models are forced to preserve the periodicity of the lattice. The difference between regular and parametric tight-binding models (see `onsite` and `hopping`) is that parametric models may depend on arbitrary parameters, specified by the `params` keyword arguments. These are inherited by `h::ParametricHamiltonian`, which can then be evaluated very efficiently for different parameter values by callling `h(; params...)`, to obtain a regular `Hamiltonian` without reconstructing it from scratch. @onsite((ω; params...) -> Σᵢᵢ(ω; params...); sites...) @onsite((ω, r; params...) -> Σᵢᵢ(ω, r; params...); sites...) Special form of a parametric onsite potential meant to model a self-energy (see `attach`). @onsite((i; params...) --> ...; sites...) @onsite((ω, i; params...) --> ...; sites...) The `-->` syntax allows to treat the argument `i` as a site index, instead of a position. In fact, the type of `i` is `CellSitePos`, so they can be used to index `OrbitalSliceArray`s (see doctrings for details). The functions `pos(i)`, `cell(i)` and `ind(i)` yield the position, cell and site index of the site. This syntax is useful to implement models that depend on observables (in the form of `OrbitalSliceArray`s), like in self-consistent mean field calculations. ## Model algebra Parametric models can be combined using `+`, `-` and `*`, or conjugated with `'`, e.g. `@onsite((; o=1) -> o) - 2 * hopping(1)'`. The combined parametric models can share parameters. # Examples ```jldoctest julia> model = @onsite((r; dμ = 0) -> (r[1] + dμ) * I; sublats = :A) + @onsite((; dμ = 0) -> - dμ * I; sublats = :B) ParametricModel: model with 2 terms ParametricOnsiteTerm{ParametricFunction{1}} Region : any Sublattices : A Cells : any Coefficient : 1 Argument type : spatial Parameters : [:dμ] ParametricOnsiteTerm{ParametricFunction{0}} Region : any Sublattices : B Cells : any Coefficient : 1 Argument type : spatial Parameters : [:dμ] julia> LP.honeycomb() |> supercell(2) |> hamiltonian(model, orbitals = 2) ParametricHamiltonian{Float64,2,2}: Parametric Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 1 Harmonic size : 8 × 8 Orbitals : [2, 2] Element type : 2 × 2 blocks (ComplexF64) Onsites : 8 Hoppings : 0 Coordination : 0.0 Parameters : [:dμ] ``` # See also `onsite`, `hopping`, `@hopping`, `@onsite!`, `@hopping!`, `attach`, `hamiltonian`, `OrbitalSliceArray` """ macro onsite end """ @hopping((; params...) -> t(; params...); hops...) @hopping((r, dr; params...) -> t(r; params...); hops...) Build a `ParametricModel` representing a uniform or a position-dependent hopping amplitude, respectively, on hops selected by `hopselector(; hops...)` (see `hopselector` for details). Hops from a site at position `r₁` to another at `r₂` are described using the hop center `r = (r₁ + r₂)/2` and the hop vector `dr = r₂ - r₁`. Hopping amplitudes `t` can be a `Number` (for hops between single-orbital sites), a `UniformScaling` (e.g. `2I`) or an `AbstractMatrix` (use `SMatrix` for performance) of dimensions matching the number of site orbitals in the selected sites. Parametric models may be applied to a lattice `lat` to produce a `ParametricHamiltonian` with `hamiltonian(lat, model; ...)`, see `hamiltonian`. Position dependent models are forced to preserve the periodicity of the lattice. The difference between regular and parametric tight-binding models (see `onsite` and `hopping`) is that parametric models may depend on arbitrary parameters, specified by the `params` keyword arguments. These are inherited by `h::ParametricHamiltonian`, which can then be evaluated very efficiently for different parameter values by callling `h(; params...)`, to obtain a regular `Hamiltonian` without reconstructing it from scratch. @hopping((ω; params...) -> Σᵢⱼ(ω; params...); hops...) @hopping((ω, r, dr; params...) -> Σᵢⱼ(ω, r, dr; params...); hops...) Special form of a parametric hopping amplitude meant to model a self-energy (see `attach`). @hopping((i, j; params...) --> ...; sites...) @hopping((ω, i, j; params...) --> ...; sites...) The `-->` syntax allows to treat the arguments `i, j` as a site indices, instead of a positions. Here `i` is the destination (row) and `j` the source (column) site. In fact, the type of `i` and `j` is `CellSitePos`, so they can be used to index `OrbitalSliceArray`s (see doctrings for details). The functions `pos(i)`, `cell(i)` and `ind(i)` yield the position, cell and site index of the site. This syntax is useful to implement models that depend on observables (in the form of `OrbitalSliceArray`s), like in self-consistent mean field calculations. ## Model algebra Parametric models can be combined using `+`, `-` and `*`, or conjugated with `'`, e.g. `@onsite((; o=1) -> o) - 2 * hopping(1)'`. The combined parametric models can share parameters. # Examples ```jldoctest julia> model = @hopping((r, dr; t = 1, A = Returns(SA[0,0])) -> t * cis(-dr' * A(r))) ParametricModel: model with 1 term ParametricHoppingTerm{ParametricFunction{2}} Region : any Sublattice pairs : any Cell distances : any Hopping range : Neighbors(1) Reverse hops : false Coefficient : 1 Argument type : spatial Parameters : [:t, :A] julia> LP.honeycomb() |> supercell(2) |> hamiltonian(model) ParametricHamiltonian{Float64,2,2}: Parametric Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 5 Harmonic size : 8 × 8 Orbitals : [1, 1] Element type : scalar (ComplexF64) Onsites : 0 Hoppings : 24 Coordination : 3.0 Parameters : [:A, :t] ``` # See also `onsite`, `hopping`, `@onsite`, `@onsite!`, `@hopping!`, `attach`, `hamiltonian`, `OrbitalSliceArray` """ macro hopping end """ @onsite!((o; params...) -> o´(o; params...); sites...) @onsite!((o, r; params...) -> o´(o, r; params...); sites...) Build a uniform or position-dependent onsite term modifier, respectively, acting on sites selected by `siteselector(; sites...)` (see `siteselector` for details). Site positions are `r::SVector{E}`, where `E` is the embedding dimension of the lattice. The original onsite potential is `o`, and the modified potential is `o´`, which is a function of `o` and possibly `r`. It may optionally also depend on parameters, enconded in `params`. Modifiers are meant to be applied to an `h:AbstractHamiltonian` to obtain a `ParametricHamiltonian` (with `hamiltonian(h, modifiers...)` or `hamiltonian(lat, model, modifiers...)`, see `hamiltonian`). Modifiers will affect only pre-existing model terms. In particular, if no onsite model has been applied to a specific site, its onsite potential will be zero, and will not be modified by any `@onsite!` modifier. Conversely, if an onsite model has been applied, `@onsite!` may modify the onsite potential even if it is zero. The same applies to `@hopping!`. @onsite((o, i; params...) --> ...; sites...) The `-->` syntax allows to treat the argument `i` as a site index, instead of a position. In fact, the type of `i` is `CellSitePos`, so they can be used to index `OrbitalSliceArray`s (see doctrings for details). The functions `pos(i)`, `cell(i)` and `ind(i)` yield the position, cell and site index of the site. This syntax is useful to implement models that depend on observables (in the form of `OrbitalSliceArray`s), like in self-consistent mean field calculations. # Examples ```jldoctest julia> model = onsite(0); disorder = @onsite!((o; W = 0) -> o + W * rand()) OnsiteModifier{ParametricFunction{1}}: Region : any Sublattices : any Cells : any Argument type : spatial Parameters : [:W] julia> LP.honeycomb() |> hamiltonian(model) |> supercell(10) |> hamiltonian(disorder) ParametricHamiltonian{Float64,2,2}: Parametric Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 1 Harmonic size : 200 × 200 Orbitals : [1, 1] Element type : scalar (ComplexF64) Onsites : 200 Hoppings : 0 Coordination : 0.0 Parameters : [:W] ``` # See also `onsite`, `hopping`, `@onsite`, `@hopping`, `@hopping!`, `hamiltonian`, `OrbitalSliceArray` """ macro onsite! end """ @hopping!((t; params...) -> t´(t; params...); hops...) @hopping!((t, r, dr; params...) -> t´(t, r, dr; params...); hops...) Build a uniform or position-dependent hopping term modifier, respectively, acting on hops selected by `hopselector(; hops...)` (see `hopselector` for details). Hops from a site at position `r₁` to another at `r₂` are described using the hop center `r = (r₁ + r₂)/2` and the hop vector `dr = r₂ - r₁`. The original hopping amplitude is `t`, and the modified hopping is `t´`, which is a function of `t` and possibly `r, dr`. It may optionally also depend on parameters, enconded in `params`. Modifiers are meant to be applied to an `h:AbstractHamiltonian` to obtain a `ParametricHamiltonian` (with `hamiltonian(h, modifiers...)` or `hamiltonian(lat, model, modifiers...)`, see `hamiltonian`). Modifiers will affect only pre-existing model terms. In particular, if no onsite model has been applied to a specific site, its onsite potential will be zero, and will not be modified by any `@onsite!` modifier. Conversely, if an onsite model has been applied, `@onsite!` may modify the onsite potential even if it is zero. The same applies to `@hopping!`. @hopping!((t, i, j; params...) --> ...; sites...) The `-->` syntax allows to treat the arguments `i, j` as a site indices, instead of a positions. Here `i` is the destination (row) and `j` the source (column) site. In fact, the type of `i` and `j` is `CellSitePos`, so they can be used to index `OrbitalSliceArray`s (see doctrings for details). The functions `pos(i)`, `cell(i)` and `ind(i)` yield the position, cell and site index of the site. This syntax is useful to implement models that depend on observables (in the form of `OrbitalSliceArray`s), like in self-consistent mean field calculations. # Examples ```jldoctest julia> model = hopping(1); peierls = @hopping!((t, r, dr; A = r -> SA[0,0]) -> t * cis(-dr' * A(r))) HoppingModifier{ParametricFunction{3}}: Region : any Sublattice pairs : any Cell distances : any Hopping range : Inf Reverse hops : false Argument type : spatial Parameters : [:A] julia> LP.honeycomb() |> hamiltonian(model) |> supercell(10) |> hamiltonian(peierls) ParametricHamiltonian{Float64,2,2}: Parametric Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 5 Harmonic size : 200 × 200 Orbitals : [1, 1] Element type : scalar (ComplexF64) Onsites : 0 Hoppings : 600 Coordination : 3.0 Parameters : [:A] ``` # See also `onsite`, `hopping`, `@onsite`, `@hopping`, `@onsite!`, `hamiltonian`, `OrbitalSliceArray` """ macro hopping! end """ plusadjoint(t::Model) Returns a model `t + t'`. This is a convenience function analogous to the `+ h.c.` notation. # Example ```jldoctest julia> model = hopping(im, sublats = :A => :B) |> plusadjoint TightbindingModel: model with 2 terms HoppingTerm{Complex{Bool}}: Region : any Sublattice pairs : :A => :B Cell distances : any Hopping range : Neighbors(1) Reverse hops : false Coefficient : 1 HoppingTerm{Complex{Int64}}: Region : any Sublattice pairs : :A => :B Cell distances : any Hopping range : Neighbors(1) Reverse hops : true Coefficient : 1 julia> h = hamiltonian(LP.honeycomb(), model) Hamiltonian{Float64,2,2}: Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 5 Harmonic size : 2 × 2 Orbitals : [1, 1] Element type : scalar (ComplexF64) Onsites : 0 Hoppings : 6 Coordination : 3.0 julia> h((0,0)) 2×2 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 2 stored entries: ⋅ 0.0-3.0im 0.0+3.0im ⋅ ``` """ plusadjoint """ torus(h::AbstractHamiltonian, (ϕ₁, ϕ₂,...)) For an `h` of lattice dimension `L` and a set of `L` Bloch phases `ϕ = (ϕ₁, ϕ₂,...)`, contruct a new `h´::AbstractHamiltonian` on a bounded torus, i.e. with all Bravais vectors eliminated by stitching the lattice onto itself along the corresponding Bravais vector. Intercell hoppings along stitched directions will pick up a Bloch phase `exp(-iϕ⋅dn)`. If a number `L´` of phases `ϕᵢ` are `:` instead of numbers, the corresponding Bravais vectors will not be stitched, and the resulting `h´` will have a finite lattice dimension `L´`. ## Currying h |> torus((ϕ₁, ϕ₂,...)) Currying syntax equivalent to `torus(h, (ϕ₁, ϕ₂,...))`. # Examples ```jldoctest julia> h2D = HP.graphene(); h1D = torus(h2D, (:, 0.2)) Hamiltonian{Float64,2,1}: Hamiltonian on a 1D Lattice in 2D space Bloch harmonics : 3 Harmonic size : 2 × 2 Orbitals : [1, 1] Element type : scalar (ComplexF64) Onsites : 0 Hoppings : 4 Coordination : 2.0 julia> h2D((0.3, 0.2)) ≈ h1D(0.3) true ``` # See also `hamiltonian`, `supercell` """ torus """ unflat(dn) Construct an `u::Unflat` object wrapping some indices `dn`. This object is meant to be used to index into a `h::AbstractHamiltonian` as `h[u]`, which returns an non-flattened version of the Bloch harmonic `h[dn]`. Each element in the matrix `h[u]` is an `SMatrix` block representing onsite or hoppings between whole sites, in contrast to `h[dn]` where they are scalars representing single orbitals. This is only relevant for multi-orbital Hamiltonians `h`. unflat() Equivalent to `unflat(())` # Examples ``` julia> h = HP.graphene(orbitals = 2); h[unflat(0,0)] 2×2 SparseArrays.SparseMatrixCSC{SMatrix{2, 2, ComplexF64, 4}, Int64} with 2 stored entries: ⋅ [2.7+0.0im 0.0+0.0im; 0.0+0.0im 2.7+0.0im] [2.7+0.0im 0.0+0.0im; 0.0+0.0im 2.7+0.0im] ⋅ ``` """ unflat """ `EigenSolvers` is a Quantica submodule containing several pre-defined eigensolvers. The alias `ES` can be used in place of `EigenSolvers`. Currently supported solvers are ES.LinearAlgebra(; kw...) # Uses `eigen(mat; kw...)` from the `LinearAlgebra` package ES.Arpack(; kw...) # Uses `eigs(mat; kw...)` from the `Arpack` package (WARNING: Arpack is not thread-safe) ES.KrylovKit(params...; kw...) # Uses `eigsolve(mat, params...; kw...)` from the `KrylovKit` package ES.ArnoldiMethod(; kw...) # Uses `partialschur(mat; kw...)` from the `ArnoldiMethod` package Additionally, to compute interior eigenvalues, we can use a shift-invert method around energy `ϵ0` (uses `LinearMaps` and a `LinearSolve.lu` factorization), combined with any solver `s` from the list above: ES.ShiftInvert(s, ϵ0) # Perform a lu-based shift-invert with solver `s` If the required packages are not already available, they will be automatically loaded when calling these solvers. # Examples ``` julia> h = HP.graphene(t0 = 1) |> supercell(10); julia> spectrum(h, (0,0); solver = ES.ShiftInvert(ES.ArnoldiMethod(nev = 4), 0.0)) |> energies 4-element Vector{ComplexF64}: -0.3819660112501042 + 2.407681231060336e-16im -0.6180339887498942 - 2.7336317916863215e-16im 0.6180339887498937 - 1.7243387890744497e-16im 0.3819660112501042 - 1.083582785131051e-16im ``` # See also `spectrum`, `bands` """ EigenSolvers """ spectrum(h::AbstractHamiltonian, ϕs; solver = EigenSolvers.LinearAlgebra(), transform = missing, params...) Compute the `Spectrum` of the Bloch matrix `h(ϕs; params...)` using the specified eigensolver, with `transform` applied to the resulting eigenenergies, if not `missing`. Eigenpairs are sorted by the real part of their energy. See `EigenSolvers` for available solvers and their options. spectrum(h::AbstractHamiltonian; kw...) For a 0D `h`, equivalent to `spectrum(h, (); kw...)` spectrum(m::AbstractMatrix; solver = EigenSolvers.LinearAlgebra()], transform = missing) Compute the `Spectrum` of matrix `m` using `solver` and `transform`. spectrum(b::Bandstructure, ϕs) Compute the `Spectrum` corresponding to slicing the bandstructure `b` at point `ϕs` of its base mesh (see `bands` for details). ## Indexing and destructuring Eigenenergies `ϵs::Tuple` and eigenstates `ψs::Matrix` can be extracted from a spectrum `sp` using any of the following ϵs, ψs = sp ϵs = first(sp) ϵs = energies(sp) ψs = last(sp) ψs = states(sp) In addition, one can extract the `n` eigenpairs closest (in real energy) to a given energy `ϵ₀` with ϵs, ψs = sp[1:n, around = ϵ₀] More generally, `sp[inds, around = ϵ₀]` will take the eigenpairs at position given by `inds` after sorting by increasing distance to `ϵ₀`, or the closest eigenpair in `inds` is missing. If `around` is omitted, the ordering in `sp` is used. # Examples ```jldoctest julia> h = HP.graphene(t0 = 1); spectrum(h, (0,0)) Spectrum{Float64,ComplexF64} : Energies: 2-element Vector{ComplexF64}: -2.9999999999999982 + 0.0im 2.9999999999999982 + 0.0im States: 2×2 Matrix{ComplexF64}: -0.707107+0.0im 0.707107+0.0im 0.707107+0.0im 0.707107+0.0im ``` # See also `EigenSolvers`, `bands` """ spectrum """ energies(sp::Spectrum) Returns the energies in `sp` as a vector of Numbers (not necessarily real). Equivalent to `first(sp)`. # See also `spectrum`, `bands` """ energies """ states(sp::Spectrum) Returns the eigenstates in `sp` as columns of a matrix. Equivalent to `last(sp)`. # See also `spectrum`, `bands` """ states """ bands(h::AbstractHamiltonian, xcolᵢ...; kw...) Construct a `Bandstructure` object, which contains in particular a collection of continuously connected `Subband`s of `h`, obtained by diagonalizing the matrix `h(ϕs; params...)` on an `M`-dimensional mesh of points `(x₁, x₂, ..., xₘ)`, where each `xᵢ` takes values in the collection `xcolᵢ`. The mapping between points in the mesh points and values of `(ϕs; params...)` is defined by keyword `mapping` (`identity` by default, see Keywords). Diagonalization is multithreaded and will use all available Julia threads (start session with `julia -t N` to have `N` threads). bands(f::Function, xcolᵢ...; kw...) Like the above using `f(ϕs)::AbstractMatrix` in place of `h(ϕs; params...)`, and returning a `Vector{<:Subband}` instead of a `Bandstructure` object. This is provided as a lower level driver without the added slicing functionality of a full `Bandstructure` object, see below. bands(h::AbstractHamiltonian; kw...) Equivalent to `bands(h::AbstractHamiltonian, xcolᵢ...; kw...)` with a default `xcolᵢ = subdiv(-π, π, 49)`. ## Keywords - `solver`: eigensolver to use for each diagonalization (see `Eigensolvers`). Default: `ES.LinearAlgebra()` - `mapping`: a function of the form `(x, y, ...) -> ϕs` or `(x, y, ...) -> ftuple(ϕs...; params...)` that translates points `(x, y, ...)` in the mesh to Bloch phases `ϕs` or phase+parameter FrankenTuples `ftuple(ϕs...; params...)`. See also linecuts below. Default: `identity` - `transform`: function to apply to each eigenvalue after diagonalization. Default: `identity` - `degtol::Real`: maximum distance between to nearby eigenvalue so that they are classified as degenerate. Default: `sqrt(eps)` - `split::Bool`: whether to split bands into disconnected subbands. Default: `true` - `projectors::Bool`: whether to compute interpolating subspaces in each simplex (for use as GreenSolver). Default: `true` - `warn::Bool`: whether to emit warning when band dislocations are encountered. Default: `true` - `showprogress::Bool`: whether to show or not a progress bar. Default: `true` - `defects`: (experimental) a collection of extra points to add to the mesh, typically the location of topological band defects such as Dirac points, so that interpolation avoids creating dislocation defects in the bands. You need to also increase `patches` to repair the subband dislocations using the added defect vertices. Default: `()` - `patches::Integer`: (experimental) if a dislocation is encountered, attempt to patch it by searching for the defect recursively to a given order, or using the provided `defects` (preferred). Default: `0` ## Currying h |> bands(xcolᵢ...; kw...) Curried form of `bands` equivalent to `bands(h, xcolᵢ...; kw...)` ## Band linecuts To do a linecut of a bandstructure along a polygonal path in the `L`-dimensional Brillouin zone, mapping a set of 1D points `xs` to a set of `nodes`, with `pts` interpolation points in each segment, one can use the following convenient syntax bands(h, subdiv(xs, pts); mapping = (xs => nodes)) Here `nodes` can be a collection of `SVector{L}` or of named Brillouin zone points from the list (`:Γ`,`:K`, `:K´`, `:M`, `:X`, `:Y`, `:Z`). If `mapping = nodes`, then `xs` defaults to `0:length(nodes)-1`. See also `subdiv` for its alternative methods. ## Indexing and slicing b[i] Extract `i`-th subband from `b::Bandstructure`. `i` can also be a `Vector`, an `AbstractRange` or any other argument accepted by `getindex(subbands::Vector, i)` b[slice::Tuple] Compute a section of `b::Bandstructure` with a "plane" defined by `slice = (ϕ₁, ϕ₂,..., ϕₗ[, ϵ])`, where each `ϕᵢ` or `ϵ` can be a real number (representing a fixed momentum or energy) or a `:` (unconstrained along that dimension). For bands of an `L`-dimensional lattice, `slice` will be padded to an `L+1`-long tuple with `:` if necessary. The result is a collection of of sliced `Subband`s. # Examples ``` julia> phis = range(0, 2pi, length = 50); h = LP.honeycomb() |> hamiltonian(@hopping((; t = 1) -> t)); julia> bands(h(t = 1), phis, phis) Bandstructure{Float64,3,2}: 3D Bandstructure over a 2-dimensional parameter space of type Float64 Subbands : 1 Vertices : 5000 Edges : 14602 Simplices : 9588 julia> bands(h, phis, phis; mapping = (x, y) -> ftuple(0, x; t = y/2π)) Bandstructure{Float64,3,2}: 3D Bandstructure over a 2-dimensional parameter space of type Float64 Subbands : 1 Vertices : 4950 Edges : 14553 Simplices : 9604 julia> bands(h(t = 1), subdiv((0, 2, 3), (20, 30)); mapping = (0, 2, 3) => (:Γ, :M, :K)) Bandstructure{Float64,2,1}: 2D Bandstructure over a 1-dimensional parameter space of type Float64 Subbands : 1 Vertices : 97 Edges : 96 Simplices : 96 ``` # See also `spectrum`, `subdiv` """ bands """ subdiv((x₁, x₂, ..., xₙ), (p₁, p₂, ..., pₙ₋₁)) Build a vector of values between `x₁` and `xₙ` containing all `xᵢ` such that in each interval `[xᵢ, xᵢ₊₁]` there are `pᵢ` equally space values. subdiv((x₁, x₂, ..., xₙ), p) Same as above with all `pᵢ = p` subdiv(x₁, x₂, p) Equivalent to `subdiv((x₁, x₂), p) == collect(range(x₁, x₂, length = p))` """ subdiv """ attach(h::AbstractHamiltonian, args..; sites...) attach(h::OpenHamiltonian, args...; sites...) Build an `h´::OpenHamiltonian` by attaching (adding) a `Σ::SelfEnergy` to a finite number of sites in `h` specified by `siteselector(; sites...)`. This also defines a "contact" on said sites that can be referred to (with index `i::Integer` for the i-th attached contact) when slicing Green functions later. Self-energies are taken into account when building the Green function `g(ω) = (ω - h´ - Σ(ω))⁻¹` of the resulting `h´`, see `greenfunction`. ## Self-energy forms The different forms of `args` yield different types of self-energies `Σ`. Currently supported forms are: attach(h, gs::GreenSlice, coupling::AbstractModel; transform = missing, sites...) Adds a generic self-energy `Σ(ω) = V´⋅gs(ω)⋅V` on `h`'s `sites`, where `V` and `V´` are couplings (given by `coupling`) between said `sites` and the `LatticeSlice` in `gs` (after applying `transform` to the latter). Allowed forms of `gs` include both `g[bath_sites...]` and `g[contactind::Integer]` where `g` is any `GreenFunction`. attach(h, model::ParametricModel; sites...) Add self-energy `Σᵢⱼ(ω)` defined by a `model` composed of parametric terms (`@onsite` and `@hopping`) with `ω` as first argument, as in e.g. `@onsite((ω, r) -> Σᵢᵢ(ω, r))` and `@hopping((ω, r, dr) -> Σᵢⱼ(ω, r, dr))` attach(h, nothing; sites...) Add a `nothing` contact with a null self-energy `Σᵢⱼ(ω) = 0` on selected sites, which in effect simply amounts to labeling those sites with a contact number, but does not lead to any dressing the Green function. This is useful for some `GreenFunction` solvers such as `GS.KPM` (see `greenfunction`), which need to know the sites of interest beforehand (the contact sites in this case). attach(h, g1D::GreenFunction; reverse = false, transform = identity, sites...) Add a self-energy `Σ(ω) = h₋₁⋅g1D(ω)[surface]⋅h₁` corresponding to a semi-infinite 1D lead (i.e. with a finite `boundary`, see `greenfunction`), where `h₁` and `h₋₁` are intercell couplings, and `g1D` is the lead `GreenFunction`. The `g1D(ω)` is taken at the `suface` unitcell, either adjacent to the `boundary` on its positive side (if `reverse = false`) or on its negative side (if `reverse = true`). Note that `reverse` only flips the direction we extend the lattice to form the lead, but does not flip the unit cell (use `transform` for that). The positions of the selected `sites` in `h` must match, modulo an arbitrary displacement, those of the left or right unit cell surface of the lead (i.e. sites coupled to the adjacent unit cells), after applying `transform` to the latter. If they don't match, use the `attach` syntax below. Advanced: If the `g1D` does not have any self-energies, the produced self-energy is in fact an `ExtendedSelfEnergy`, which is numerically more stable than a naive implementation of `RegularSelfEnergy`'s, since `g1D(ω)[surface]` is never actually computed. Conversely, if `g1D` has self-energies attached, a `RegularSelfEnergy` is produced. attach(h, g1D::GreenFunction, coupling::AbstractModel; reverse = false, transform = identity, sites...) Add a self-energy `Σ(ω) = V´⋅g1D(ω)[surface]⋅V` corresponding to a 1D lead (semi-infinite or infinite), but with couplings `V` and `V´`, defined by `coupling`, between `sites` and the `surface` lead unitcell (or the one with index zero if there is no boundary) . See also Advanced note above. ## Currying h |> attach(args...; sites...) Curried form equivalent to `attach(h, args...; sites...)`. # Examples ```jldoctest julia> # A graphene flake with two out-of-plane cubic-lattice leads julia> g1D = LP.cubic(names = :C) |> hamiltonian(hopping(1)) |> supercell((0,0,1), region = RP.square(4)) |> greenfunction(GS.Schur(boundary = 0)); julia> coupling = hopping(1, range = 2); julia> gdisk = HP.graphene(a0 = 1, dim = 3) |> supercell(region = RP.circle(10)) |> attach(g1D, coupling; region = RP.square(4)) |> attach(g1D, coupling; region = RP.square(4), reverse = true) |> greenfunction; ``` # See also `greenfunction`, `GreenSolvers` """ attach """ greenfunction(h::Union{AbstractHamiltonian,OpenHamiltonian}, solver::AbstractGreenSolver) Build a `g::GreenFunction` of Hamiltonian `h` using `solver`. See `GreenSolvers` for available solvers. If `solver` is not provided, a default solver is chosen automatically based on the type of `h`. ## Currying h |> greenfunction(solver) Curried form equivalent to `greenfunction(h, solver)`. ## Partial evaluation `GreenFunction`s allow independent, partial evaluation of their positions (producing a `GreenSlice`) and energy/parameters (producing a `GreenSolution`). Depending on the solver, this may avoid repeating calculations unnecesarily when sweeping over either of these with the other fixed. g[ss] g[siteselector(; ss...)] Build a `gs::GreenSlice` that represents a Green function at arbitrary energy and parameter values, but at specific sites on the lattice defined by `siteselector(; ss...)`, with `ss::NamedTuple` (see `siteselector`). g[contact_index::Integer] Build a `GreenSlice` equivalent to `g[contact_sites...]`, where `contact_sites...` correspond to sites in contact number `contact_index` (must have `1<= contact_index <= number_of_contacts`). See `attach` for details on attaching contacts to a Hamiltonian. g[:] Build a `GreenSlice` over all contacts. g[dst, src] Build a `gs::GreenSlice` between sites specified by `src` and `dst`, which can take any of the forms above. Therefore, all the previous single-index slice forms correspond to a diagonal block `g[i, i]`. g[diagonal(i, kernel = missing)] If `kernel = missing`, efficiently construct `diag(g[i, i])`. If `kernel` is a matrix, return `tr(g[site, site] * kernel)` over each site encoded in `i`. Note that if there are several orbitals per site, these will have different length (i.e. number of orbitals vs number of sites). See also `diagonal`. g(ω; params...) Build a `gω::GreenSolution` that represents a retarded Green function at arbitrary points on the lattice, but at fixed energy `ω` and system parameter values `param`. If `ω` is complex, the retarded or advanced Green function is returned, depending on `sign(imag(ω))`. If `ω` is `Real`, a small, positive imaginary part is automatically added internally to produce the retarded `g`. gω[i] gω[i, j] gs(ω; params...) For any `gω::GreenSolution` or `gs::GreenSlice`, build the Green function matrix fully evaluated at fixed energy, parameters and positions. The matrix is a dense `m::OrbitalSliceMatrix` with scalar element type, so that any orbital structure on each site is flattened. Note that the resulting `m` can itself be indexed over collections of sites with `m[i, j]`, where `i, j` are `siteselector(; ss...)` or `ss::NamedTuple`. view(gω, i::C, j::C == i) For any `gω::GreenSolution` and `C<:Union{Colon,Integer}`, obtain a view (of type `SubArray`, not `OrbitalSliceMatrix`) of the corresponding intra or inter-contact propagator `gω[i, j]` with minimal allocations. g(; params...) For any `g::Union{GreenFunction,GreenSlice}`, produce a new `GreenFunction` or `GreenSlice` with all parameters fixed to `params` (or to their default values if not provided). # Example ```jldoctest julia> g = LP.honeycomb() |> hamiltonian(@hopping((; t = 1) -> t)) |> supercell(region = RP.circle(10)) |> greenfunction(GS.SparseLU()) GreenFunction{Float64,2,0}: Green function of a Hamiltonian{Float64,2,0} Solver : AppliedSparseLUGreenSolver Contacts : 0 Contact solvers : () Contact sizes : () ParametricHamiltonian{Float64,2,0}: Parametric Hamiltonian on a 0D Lattice in 2D space Bloch harmonics : 1 Harmonic size : 726 × 726 Orbitals : [1, 1] Element type : scalar (ComplexF64) Onsites : 0 Hoppings : 2098 Coordination : 2.88981 Parameters : [:t] julia> gω = g(0.1; t = 2) GreenSolution{Float64,2,0}: Green function at arbitrary positions, but at a fixed energy julia> ss = (; region = RP.circle(2), sublats = :B); julia> gs = g[ss] GreenSlice{Float64,2,0}: Green function at arbitrary energy, but at a fixed lattice positions julia> gω[ss] == gs(0.1; t = 2) true ``` # See also `GreenSolvers`, `diagonal`, `ldos`, `conductance`, `current`, `josephson` """ greenfunction """ `GreenSolvers` is a Quantica submodule containing several pre-defined Green function solvers. The alias `GS` can be used in place of `GS`. Currently supported solvers and their possible keyword arguments are - `GS.SparseLU()` : Direct inversion solver for 0D Hamiltonians using a `SparseArrays.lu(hmat)` factorization - `GS.Spectrum(; spectrum_kw...)` : Diagonalization solver for 0D Hamiltonians using `spectrum(h; spectrum_kw...)` - `spectrum_kw...` : keyword arguments passed on to `spectrum` - This solver does not accept ParametricHamiltonians. Convert to Hamiltonian with `h(; params...)` first. Contact self-energies that depend on parameters are supported. - `GS.Schur(; boundary = Inf)` : Solver for 1D Hamiltonians based on a deflated, generalized Schur factorization - `boundary` : 1D cell index of a boundary cell, or `Inf` for no boundaries. Equivalent to removing that specific cell from the lattice when computing the Green function. - `GS.KPM(; order = 100, bandrange = missing, kernel = I)` : Kernel polynomial method solver for 0D Hamiltonians - `order` : order of the expansion in Chebyshev polynomials `Tₙ(h)` of the Hamiltonian `h` (lowest possible order is `n = 0`). - `bandrange` : a `(min_energy, max_energy)::Tuple` interval that encompasses the full band of the Hamiltonian. If `missing`, it is computed automatically. - `kernel` : generalization that computes momenta as `μₙ = Tr[Tₙ(h)*kernel]`, so that the local density of states (see `ldos`) becomes the density of the `kernel` operator. - This solver does not allow arbitrary indexing of the resulting `g::GreenFunction`, only on contacts `g[contact_ind::Integer]`. If the system has none, we can add a dummy contact using `attach(h, nothing; sites...)`, see `attach`. - `GS.Bands(bands_arguments; boundary = missing, bands_kw...)`: solver based on the integration of bandstructure simplices - `bands_arguments`: positional arguments passed on to `bands` - `bands_kw`: keyword arguments passed on to `bands` - `boundary`: either `missing` (no boundary), or `dir => cell_pos` (single boundary), where `dir::Integer` is the Bravais vector normal to the boundary, and `cell_pos::Integer` the value of cell indices `cells[dir]` that define the boundary (i.e. `cells[dir] <= cell_pos` are vaccum) - This solver only allows zero or one boundary. WARNING: if a boundary is used, the algorithm may become unstable for very fine band meshes. """ GreenSolvers """ diagonal(i; kernel = missing) Wrapper over site or orbital indices (used to index into a `g::GreenFunction` or `g::GreenSolution`) that represent purely diagonal entries. Here `i` can be any index accepted in `g[i,i]`, e.g. `i::Integer` (contact index), `i::Colon` (merged contacts), `i::SiteSelector` (selected sites), etc. diagonal(kernel = missing, sites...) Equivalent to `diagonal(siteselector(; sites...); kernel)` ## Keywords - `kernel`: if missing, all orbitals in the diagonal `g[i, i]` are returned when indexing `g[diagonal(i)]`. Otherwise, `tr(g[site, site]*kernel)` for each site included in `i` is returned. See also `ldos` # Example ```jldoctest julia> g = HP.graphene(orbitals = 2) |> attach(nothing, cells = (0,0)) |> greenfunction(); julia> g(1)[diagonal(:)] # g diagonal on all contact orbitals 4-element Vector{ComplexF64}: -0.10919028168061964 - 0.08398577667508965im -0.10919028168734393 - 0.08398577667508968im -0.10919028169083328 - 0.08398577667508969im -0.109190281684109 - 0.08398577667508969im julia> g(1)[diagonal(:, kernel = SA[1 0; 0 -1])] # σz spin spectral density at ω = 1 2-element Vector{ComplexF64}: 6.724287793247186e-12 + 2.7755575615628914e-17im -6.724273915459378e-12 + 0.0im ``` # See also `greenfunction`, `ldos` """ """ ldos(gs::GreenSlice; kernel = I) Build `ρs::LocalSpectralDensitySlice`, a partially evaluated object representing the local density of states `ρᵢ(ω)` at specific sites `i` but at arbitrary energy `ω`. ldos(gω::GreenSolution; kernel = I) Build `ρω::LocalSpectralDensitySolution`, as above, but for `ρᵢ(ω)` at a fixed `ω` and arbitrary sites `i`. See also `greenfunction` for details on building a `GreenSlice` and `GreenSolution`. The local density of states is defined here as ``ρᵢ(ω) = -Tr(gᵢᵢ(ω))/π``, where `gᵢᵢ(ω)` is the retarded Green function at a given site `i`. ## Keywords - `kernel` : for multiorbital sites, `kernel` allows to compute a generalized `ldos` `ρᵢ(ω) = -Tr(gᵢᵢ(ω) * kernel)/π`, where `gᵢᵢ(ω)` is the retarded Green function at site `i` and energy `ω`. If `kernel = missing`, the complete, orbital-resolved `ldos` is returned. ## Full evaluation ρω[sites...] ρs(ω; params...) Given a partially evaluated `ρω::LocalSpectralDensitySolution` or `ρs::LocalSpectralDensitySlice`, build an `OrbitalSliceVector` `[ρ₁(ω), ρ₂(ω)...]` of fully evaluated local densities of states. See `OrbitalSliceVector` for further details. # Example ``` julia> g = HP.graphene(a0 = 1, t0 = 1) |> supercell(region = RP.circle(20)) |> attach(nothing, region = RP.circle(1)) |> greenfunction(GS.KPM(order = 300, bandrange = (-3.1, 3.1))) GreenFunction{Float64,2,0}: Green function of a Hamiltonian{Float64,2,0} Solver : AppliedKPMGreenSolver Contacts : 1 Contact solvers : (SelfEnergyEmptySolver,) Contact sizes : (6,) Hamiltonian{Float64,2,0}: Hamiltonian on a 0D Lattice in 2D space Bloch harmonics : 1 Harmonic size : 2898 × 2898 Orbitals : [1, 1] Element type : scalar (ComplexF64) Onsites : 0 Hoppings : 8522 Coordination : 2.94065 julia> ldos(g(0.2))[1] 6-element OrbitalSliceVector{Vector{Float64}}: 0.036802204179316955 0.034933055722650375 0.03493305572265026 0.03493305572265034 0.03493305572265045 0.036802204179317045 julia> ldos(g(0.2))[1] == -imag.(g[diagonal(1; kernel = I)](0.2)) ./ π true ``` # See also `greenfunction`, `diagonal`, `current`, `conductance`, `josephson`, `transmission`, `OrbitalSliceVector` """ ldos """ densitymatrix(gs::GreenSlice; opts...) Compute a `ρ::DensityMatrix` at thermal equilibrium on sites encoded in `gs`. The actual matrix for given system parameters `params`, and for a given chemical potential `mu` and temperature `kBT` is obtained by calling `ρ(mu = 0, kBT = 0; params...)`. The algorithm used is specialized for the GreenSolver used, if available. In this case, `opts` are options for said algorithm. densitymatrix(gs::GreenSlice, (ωmin, ωmax); opts..., quadgk_opts...) densitymatrix(gs::GreenSlice, (ωpoints...); opts..., quadgk_opts...) As above, but using a generic algorithm that relies on numerical integration along a contour in the complex plane, between points `(ωmin, ωmax)` (or along a polygonal path connecting `ωpoints`), which should be chosen so as to encompass the full system bandwidth. Keywords `quadgk_opts` are passed to the `QuadGK.quadgk` integration routine. See below for additiona `opts`. densitymatrix(gs::GreenSlice, ωmax::Number; opts...) As above with `ωmin = -ωmax`. ## Full evaluation ρ(μ = 0, kBT = 0; params...) # where ρ::DensityMatrix Evaluate the density matrix at chemical potential `μ` and temperature `kBT` (in the same units as the Hamiltonian) for the given `g` parameters `params`, if any. The result is given as an `OrbitalSliceMatrix`, see its docstring for further details. ## Algorithms and keywords The generic integration algorithm allows for the following `opts` (see also `josephson`): - `omegamap`: a function `ω -> (; params...)` that translates `ω` at each point in the integration contour to a set of system parameters. Useful for `ParametricHamiltonians` which include terms `Σ(ω)` that depend on a parameter `ω` (one would then use `omegamap = ω -> (; ω)`). Default: `ω -> (;)`, i.e. no mapped parameters. - `imshift`: a small imaginary shift to add to the integration contour. Default: `sqrt(eps)` for the relevant number type. - `post`: a function to apply to the result of the integration. Default: `identity`. - `slope`: the integration contour is a sawtooth path connecting `(ωmin, ωmax)`, or more generally `ωpoints`, which are usually real numbers encompasing the system's bandwidth. Between each pair of points the path increases and then decreases linearly with the given `slope`. Default: `1.0`. Currently, the following GreenSolvers implement dedicated densitymatrix algorithms: - `GS.Spectrum`: based on summation occupation-weigthed eigenvectors. No `opts`. - `GS.KPM`: based on the Chebyshev expansion of the Fermi function. Currently only works for zero temperature and only supports `nothing` contacts (see `attach`). No `opts`. # Example ``` julia> g = HP.graphene(a0 = 1) |> supercell(region = RP.circle(10)) |> greenfunction(GS.Spectrum()); julia> ρ = densitymatrix(g[region = RP.circle(0.5)]) DensityMatrix: density matrix on specified sites with solver of type DensityMatrixSpectrumSolver julia> ρ() # with mu = kBT = 0 by default 2×2 OrbitalSliceMatrix{Matrix{ComplexF64}}: 0.5+0.0im -0.262865+0.0im -0.262865+0.0im 0.5+0.0im ``` """ densitymatrix """ current(h::AbstractHamiltonian; charge = -I, direction = 1) Build an `Operator` object that behaves like a `ParametricHamiltonian` in regards to calls and getindex, but whose matrix elements are hoppings ``im*(rⱼ-rᵢ)[direction]*charge*tⱼᵢ``, where `tᵢⱼ` are the hoppings in `h`. This operator is equal to ``∂h/∂Aᵢ``, where `Aᵢ` is a gauge field along `direction = i`. current(gs::GreenSlice; charge = -I, direction = missing) Build `Js::CurrentDensitySlice`, a partially evaluated object representing the equilibrium local current density `Jᵢⱼ(ω)` at arbitrary energy `ω` from site `j` to site `i`, both taken from a specific lattice slice. The current is computed along a given `direction` (see Keywords). current(gω::GreenSolution; charge = -I, direction = missing) Build `Jω::CurrentDensitySolution`, as above, but for `Jᵢⱼ(ω)` at a fixed `ω` and arbitrary sites `i, j`. See also `greenfunction` for details on building a `GreenSlice` and `GreenSolution`. The local current density is defined here as ``Jᵢⱼ(ω) = (2/h) rᵢⱼ Re Tr[(Hᵢⱼgⱼᵢ(ω) - gᵢⱼ(ω)Hⱼᵢ) * charge]``, with the integrated local current given by ``Jᵢⱼ = ∫ f(ω) Jᵢⱼ(ω) dω``. Here `Hᵢⱼ` is the hopping from site `j` at `rⱼ` to `i` at `rᵢ`, `rᵢⱼ = rᵢ - rⱼ`, `charge` is the charge of carriers in orbital space (see Keywords), and `gᵢⱼ(ω)` is the retarded Green function between said sites. ## Keywords - `charge` : for multiorbital sites, `charge` can be a general matrix, which allows to compute arbitrary currents, such as spin currents. - `direction`: as defined above, `Jᵢⱼ(ω)` is a vector. If `direction` is `missing` the norm `|Jᵢⱼ(ω)|` is returned. If it is an `u::Union{SVector,Tuple}`, `u⋅Jᵢⱼ(ω)` is returned. If an `n::Integer`, `Jᵢⱼ(ω)[n]` is returned. ## Full evaluation Jω[sites...] Js(ω; params...) Given a partially evaluated `Jω::CurrentDensitySolution` or `ρs::CurrentDensitySlice`, build a sparse matrix `Jᵢⱼ(ω)` along the specified `direction` of fully evaluated local current densities. Note: Evaluating the current density returns a `SparseMatrixCSC` currently, instead of a `OrbitalSliceMatrix`, since the latter is designed for dense arrays. # Example ``` julia> # A semi-infinite 1D lead with a magnetic field `B` julia> g = LP.square() |> supercell((1,0), region = r->-2<r[2]<2) |> hamiltonian(@hopping((r, dr; B = 0.1) -> cis(B * dr' * SA[r[2],-r[1]]))) |> greenfunction(GS.Schur(boundary = 0)); julia> J = current(g[cells = SA[1]]) CurrentDensitySlice{Float64} : current density at a fixed location and arbitrary energy charge : LinearAlgebra.UniformScaling{Int64}(-1) direction : missing julia> J(0.2; B = 0.1) 3×3 SparseArrays.SparseMatrixCSC{Float64, Int64} with 4 stored entries: ⋅ 0.0290138 ⋅ 0.0290138 ⋅ 0.0290138 ⋅ 0.0290138 ⋅ julia> J(0.2; B = 0.0) 3×3 SparseArrays.SparseMatrixCSC{Float64, Int64} with 4 stored entries: ⋅ 7.77156e-16 ⋅ 7.77156e-16 ⋅ 5.55112e-16 ⋅ 5.55112e-16 ⋅ ``` # See also `greenfunction`, `ldos`, `conductance`, `josephson`, `transmission` """ current """ conductance(gs::GreenSlice; nambu = false) Given a slice `gs = g[i::Integer, j::Integer]` of a `g::GreenFunction`, build a partially evaluated object `G::Conductance` representing the zero-temperature, linear, differential conductance `Gᵢⱼ = dIᵢ/dVⱼ` between contacts `i` and `j` at arbitrary bias `ω = eV` in units of `e^2/h`. `Gᵢⱼ` is given by Gᵢⱼ = e^2/h × Tr{[im*δᵢⱼ(gʳ-gᵃ)Γⁱ-gʳΓⁱgᵃΓʲ]} (nambu = false) Gᵢⱼ = e^2/h × Tr{[im*δᵢⱼ(gʳ-gᵃ)Γⁱτₑ-gʳΓⁱτ₃gᵃΓʲτₑ]} (nambu = true) Here `gʳ = g(ω)` and `gᵃ = (gʳ)' = g(ω')` are the retarded and advanced Green function of the system, and `Γⁱ = im * (Σⁱ - Σⁱ')` is the decay rate at contact `i`. For Nambu systems (`nambu = true`), the matrices `τₑ=[I 0; 0 0]` and `τ₃ = [I 0; 0 -I]` ensure that charge reversal in Andreev reflections is properly taken into account. For normal systems (`nambu = false`), the total current at finite bias and temperatures is given by ``Iᵢ = e/h × ∫ dω ∑ⱼ [fᵢ(ω) - fⱼ(ω)] Gᵢⱼ(ω)``, where ``fᵢ(ω)`` is the Fermi distribution in lead `i`. ## Keywords - `nambu` : whether to consider the Hamiltonian of the system is written in a Nambu basis, each site containing `N` electron orbitals followed by `N` hole orbitals. ## Full evaluation G(ω; params...) Compute the conductance at the specified contacts. # Examples ```jldoctest julia> # A central system g0 with two 1D leads and transparent contacts julia> glead = LP.square() |> hamiltonian(hopping(1)) |> supercell((1,0), region = r->-2<r[2]<2) |> greenfunction(GS.Schur(boundary = 0)); julia> g0 = LP.square() |> hamiltonian(hopping(1)) |> supercell(region = r->-2<r[2]<2 && r[1]≈0) |> attach(glead, reverse = true) |> attach(glead) |> greenfunction; julia> G = conductance(g0[1]) Conductance{Float64}: Zero-temperature conductance dIᵢ/dVⱼ from contacts i,j, in units of e^2/h Current contact : 1 Bias contact : 1 julia> G(0.2) ≈ 3 true ``` # See also `greenfunction`, `ldos`, `current`, `josephson`, `transmission` """ conductance """ transmission(gs::GreenSlice) Given a slice `gs = g[i::Integer, j::Integer]` of a `g::GreenFunction`, build a partially evaluated object `T::Transmission` representing the normal transmission probability `Tᵢⱼ(ω)` from contact `j` to `i` at energy `ω`. It can be written as ``Tᵢⱼ = Tr{gʳΓⁱgᵃΓʲ}``. Here `gʳ = g(ω)` and `gᵃ = (gʳ)' = g(ω')` are the retarded and advanced Green function of the system, and `Γⁱ = im * (Σⁱ - Σⁱ')` is the decay rate at contact `i` ## Full evaluation T(ω; params...) Compute the transmission `Tᵢⱼ(ω)` at a given `ω` and for the specified `params` of `g`. # Examples ```jldoctest julia> # A central system g0 with two 1D leads and transparent contacts julia> glead = LP.square() |> hamiltonian(hopping(1)) |> supercell((1,0), region = r->-2<r[2]<2) |> greenfunction(GS.Schur(boundary = 0)); julia> g0 = LP.square() |> hamiltonian(hopping(1)) |> supercell(region = r->-2<r[2]<2 && r[1]≈0) |> attach(glead, reverse = true) |> attach(glead) |> greenfunction; julia> T = transmission(g0[2, 1]) Transmission: total transmission between two different contacts From contact : 1 To contact : 2 julia> T(0.2) ≈ 3 # The difference from 3 is due to the automatic `im*sqrt(eps(Float64))` added to `ω` false julia> T(0.2 + 1e-10im) ≈ 3 true ``` # See also `greenfunction`, `conductance`, `ldos`, `current`, `josephson` """ transmission """ josephson(gs::GreenSlice, ωmax; omegamap = ω -> (;), phases = missing, imshift = missing, slope = 1, post = real, atol = 1e-7, quadgk_opts...) For a `gs = g[i::Integer]` slice of the `g::GreenFunction` of a hybrid junction, build a `J::Josephson` object representing the equilibrium (static) Josephson current `I_J` flowing into `g` through contact `i`, integrated from `-ωmax` to `ωmax`. The result of `I_J` is given in units of `qe/h` (`q` is the dimensionless carrier charge). `I_J` can be written as ``I_J = Re ∫ dω f(ω) j(ω)``, where ``j(ω) = (qe/h) × 2Tr[(ΣʳᵢGʳ - GʳΣʳᵢ)τz]``. ## Full evaluation J(kBT = 0; params...) # where J::Josephson Evaluate the current `I_J` at temperature `kBT` (in the same units as the Hamiltonian) for the given `g` parameters `params`, if any. ## Keywords - `omegamap`: a function `ω -> (; params...)` that translates `ω` at each point in the integration contour to a set of system parameters. Useful for `ParametricHamiltonians` which include terms `Σ(ω)` that depend on a parameter `ω` (one would then use `omegamap = ω -> (; ω)`). Default: `ω -> (;)`, i.e. no mapped parameters. - `phases` : collection of superconducting phase biases to apply to the contact, so as to efficiently compute the full current-phase relation `[I_J(ϕ) for ϕ in phases]`. Note that each phase bias `ϕ` is applied by a `[cis(-ϕ/2) 0; 0 cis(ϕ/2)]` rotation to the self energy, which is almost free. If `missing`, a single `I_J` is returned. - `imshift`: if `missing` the initial and final integration points `± ωmax` are shifted by `im * sqrt(eps(ωmax))`, to avoid the real axis. Otherwise a shift `im*imshift` is applied (may be zero if `ωmax` is greater than the bandwidth). - `slope`: if non-zero, the integration will be performed along a piecewise-linear path in the complex plane `(-ωmax, -ωmax/2 * (1+slope*im), 0, ωmax/2 * (1+slope*im), ωmax)`, taking advantage of the holomorphic integrand `f(ω) j(ω)` and the Cauchy Integral Theorem for faster convergence. - `post`: function to apply to the result of `∫ dω f(ω) j(ω)` to obtain the result, `post = real` by default. - `atol`: absolute integration tolerance. The default `1e-7` is chosen to avoid excessive integration times when the current is actually zero. - `quadgk_opts` : extra keyword arguments (other than `atol`) to pass on to the function `QuadGK.quadgk` that is used for the integration. # Examples ``` julia> glead = LP.square() |> hamiltonian(@onsite((; ω = 0) -> 0.0005 * SA[0 1; 1 0] + im*ω*I) + hopping(SA[1 0; 0 -1]), orbitals = 2) |> supercell((1,0), region = r->-2<r[2]<2) |> greenfunction(GS.Schur(boundary = 0)); julia> g0 = LP.square() |> hamiltonian(hopping(SA[1 0; 0 -1]), orbitals = 2) |> supercell(region = r->-2<r[2]<2 && r[1]≈0) |> attach(glead, reverse = true) |> attach(glead) |> greenfunction; julia> J = josephson(g0[1], 4; omegamap = ω -> (;ω), phases = subdiv(0, pi, 10)) Josephson: equilibrium Josephson current at a specific contact using solver of type JosephsonIntegratorSolver julia> J(0.0) 10-element Vector{Float64}: 7.060440509787806e-18 0.0008178484258721882 0.0016108816082772972 0.002355033150366814 0.0030277117620820513 0.003608482493380227 0.004079679643085058 0.004426918320990192 0.004639358112465513 2.2618383948099795e-12 ``` # See also `greenfunction`,`ldos`, `current`, `conductance`, `transmission` """ josephson """ OrbitalSliceArray <: AbstractArray A type of `AbstractArray` defined over a set of orbitals (see also `orbaxes`). It wraps a regular array that can be obtained with `parent(::OrbitalSliceArray)`, and supports all the general AbstractArray interface. In addition, it also supports indexing using `siteselector`s and `cellindices`. `OrbitalSliceVector` and `OrbitalSliceMatrix` are special cases of `OrbitalSliceArray` of dimension 1 and 2 respectively. This is the common output type produced by `GreenFunctions` and most observables. Note that for `m::OrbitalSliceMatrix`, `mat[i]` is equivalent to `mat[i,i]`, and `mat[; sel...]` is equivalent to `mat[(; sel...), (; sel...)]`. # `siteselector` indexing mat[(; rowsites...), (; colsites...)] mat[rowsel::SiteSelector, colsel::SiteSelector] If we index an `OrbitalSliceMatrix` with `s::NamedTuple` or a `siteselector(; s...)`, we obtain a new `OrbitalSliceMatrix` over the orbitals of the selected sites. # `sites` indexing mat[sites(cell_index, site_indices)] mat[sites(row_cell_index, row_site_indices), sites(col_cell_index, col_site_indices)] If we index an `OrbitalSliceMatrix` with `sites`, we obtain an unwrapped `Matrix` over the sites with `site_indices` within cell with `cell_index`. Here `site_indices` can be an `Int`, a container of `Int`, or a `:` (for all sites in the unit cell). If any of the specified sites are not already in `orbaxes(mat)`, indexing will throw an error. Note that in this case we do not obtain a new `OrbitalSliceMatrix`. This behavior is required for performance, as re-wrapping in a new `OrbitalSliceMatrix` requires recomputing and allocating the new `orbaxes`. view(mat, rows::CellSites, cols::Cellsites = rows) Like the above, but returns a view instead of a copy of the indexed orbital matrix. Note: `diagonal` indexing is currently not supported by `OrbitalSliceArray`. # Examples ``` julia> g = LP.linear() |> hamiltonian(hopping(SA[0 1; 1 0]) + onsite(I), orbitals = 2) |> supercell(4) |> greenfunction; julia> mat = g(0.2)[region = r -> 2<=r[1]<=4] 6×6 OrbitalSliceMatrix{Matrix{ComplexF64}}: -1.93554e-9-0.545545im 0.0-0.0im 0.0-0.0im -0.5+0.218218im 0.4+0.37097im 0.0+0.0im 0.0-0.0im -1.93554e-9-0.545545im -0.5+0.218218im 0.0-0.0im 0.0+0.0im 0.4+0.37097im 0.0-0.0im -0.5+0.218218im -1.93554e-9-0.545545im 0.0-0.0im 0.0+0.0im -0.5+0.218218im -0.5+0.218218im 0.0-0.0im 0.0-0.0im -1.93554e-9-0.545545im -0.5+0.218218im 0.0+0.0im 0.4+0.37097im 0.0+0.0im 0.0+0.0im -0.5+0.218218im -1.93554e-9-0.545545im 0.0-0.0im 0.0+0.0im 0.4+0.37097im -0.5+0.218218im 0.0+0.0im 0.0-0.0im -1.93554e-9-0.545545im julia> mat[(; cells = SA[1]), (; cells = SA[0])] 2×4 OrbitalSliceMatrix{Matrix{ComplexF64}}: 0.4+0.37097im 0.0+0.0im 0.0+0.0im -0.5+0.218218im 0.0+0.0im 0.4+0.37097im -0.5+0.218218im 0.0+0.0im julia> mat[sites(SA[1], 1)] 2×2 Matrix{ComplexF64}: -1.93554e-9-0.545545im 0.0-0.0im 0.0-0.0im -1.93554e-9-0.545545im ``` # See also `siteselector`, `cellindices`, `orbaxes` """ OrbitalSliceArray, OrbitalSliceVector, OrbitalSliceMatrix """ diagonal(args...) Wrapper over indices `args` used to obtain the diagonal of a `gω::GreenSolution`. If `d = diagonal(sel)`, then `gω[d] = diag(gω[sel, sel])`, although in most cases the computation is done more efficiently internally. """ diagonal
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
22386
############################################################################################ # greenfunction #region greenfunction(s::AbstractGreenSolver) = oh -> greenfunction(oh, s) greenfunction() = h -> greenfunction(h) greenfunction(h::AbstractHamiltonian, args...) = greenfunction(OpenHamiltonian(h), args...) function greenfunction(oh::OpenHamiltonian, s::AbstractGreenSolver = default_green_solver(hamiltonian(oh))) cs = Contacts(oh) h = hamiltonian(oh) as = apply(s, h, cs) return GreenFunction(h, as, cs) end default_green_solver(::AbstractHamiltonian0D) = GS.SparseLU() default_green_solver(::AbstractHamiltonian1D) = GS.Schur() default_green_solver(::AbstractHamiltonian) = GS.Bands() #endregion ############################################################################################ # Contacts call! API #region function call!(c::Contacts, ω; params...) Σblocks = selfenergyblocks(c) call!.(c.selfenergies, Ref(ω); params...) # updates matrices in Σblocks return Σblocks end call!_output(c::Contacts) = selfenergyblocks(c) #endregion ############################################################################################ # GreenFuntion call! API #region (g::GreenFunction)(ω; params...) = minimal_callsafe_copy(call!(g, ω; params...)) (g::GreenSlice)(ω; params...) = copy(call!(g, ω; params...)) call!(g::G, ω; params...) where {T,G<:Union{GreenFunction{T},GreenSlice{T}}} = call!(g, real_or_complex_convert(T, ω); params...) function call!(g::GreenFunction{T}, ω::T; params...) where {T} ω´ = retarded_omega(ω, solver(g)) return call!(g, ω´; params...) end function call!(g::GreenFunction{T}, ω::Complex{T}; params...) where {T} h = parent(g) # not hamiltonian(h). We want the ParametricHamiltonian if it exists. contacts´ = contacts(g) call!(h; params...) Σblocks = call!(contacts´, ω; params...) corbs = contactorbitals(contacts´) slicer = solver(g)(ω, Σblocks, corbs) return GreenSolution(g, slicer, Σblocks, corbs) end call!(g::GreenSlice{T}, ω::T; params...) where {T} = call!(g, retarded_omega(ω, solver(parent(g))); params...) call!(g::GreenSlice{T}, ω::Complex{T}; params...) where {T} = call!(greenfunction(g), ω; params...)[orbinds_or_contactinds(g)...] real_or_complex_convert(::Type{T}, ω::Real) where {T<:Real} = convert(T, ω) real_or_complex_convert(::Type{T}, ω::Complex) where {T<:Real} = convert(Complex{T}, ω) retarded_omega(ω::T, s::AppliedGreenSolver) where {T<:Real} = ω + im * sqrt(eps(float(T))) * needs_omega_shift(s) # fallback, may be overridden needs_omega_shift(s::AppliedGreenSolver) = true #endregion ############################################################################################ # FixedParamGreenSolver # support for g(; params...) --> GreenFunction (not a wrapper, completely independent) # FixedParamGreenSolver doesn't need to implement the AppliedGreenSolver API, since it # forwards to its parent #region struct FixedParamGreenSolver{P,G<:GreenFunction} <: AppliedGreenSolver gparent::G params::P end Base.parent(s::FixedParamGreenSolver) = s.gparent parameters(s::FixedParamGreenSolver) = s.params function (g::GreenFunction)(; params...) h´ = minimal_callsafe_copy(parent(g)) c´ = minimal_callsafe_copy(contacts(g)) s´ = minimal_callsafe_copy(solver(g), h´, c´) gparent = GreenFunction(h´, s´, c´) return GreenFunction(h´, FixedParamGreenSolver(gparent, params), c´) end (g::GreenSlice)(; params...) = GreenSlice(parent(g)(; params...), greenindices(g)...) # params are ignored, solver.params are used instead. T required to disambiguate. function call!(g::GreenFunction{T,<:Any,<:Any,<:FixedParamGreenSolver}, ω::Complex{T}; params...) where {T} s = solver(g) return call!(s.gparent, ω; s.params...) end function minimal_callsafe_copy(s::FixedParamGreenSolver, parentham, parentcontacts) solver´ = minimal_callsafe_copy(solver(s.gparent), parentham, parentcontacts) gparent = GreenFunction(parentham, solver´, parentcontacts) s´ = FixedParamGreenSolver(gparent, s.params) return s´ end default_hamiltonian(g::GreenFunction{<:Any,<:Any,<:Any,<:FixedParamGreenSolver}) = default_hamiltonian(parent(g); parameters(solver(g))...) #endregion ############################################################################################ # GreenSolution indexing # We convert any index down to cellorbs to pass to slicer, except contacts (Int, Colon) #region Base.getindex(g::GreenFunction, i, j = i) = GreenSlice(g, i, j) Base.getindex(g::GreenFunction; kw...) = g[siteselector(; kw...)] Base.getindex(g::GreenFunction, kw::NamedTuple) = g[siteselector(; kw...)] Base.getindex(g::GreenSolution; kw...) = g[getindex(lattice(g); kw...)] # g[::Integer, ::Integer] and g[:, :] - intra and inter contacts Base.view(g::GreenSolution, i::CT, j::CT = i) where {CT<:Union{Integer,Colon}} = view(slicer(g), i, j) # fastpath for intra and inter-contact Base.getindex(g::GreenSolution, i::CT, j::CT = i) where {CT<:Union{Integer,Colon}} = OrbitalSliceMatrix(copy(view(g, i, j)), sites_to_orbs.((i,j), Ref(g))) # conversion down to CellOrbitals. See sites_to_orbs in slices.jl Base.getindex(g::GreenSolution, i, j) = getindex(g, sites_to_orbs(i, g), sites_to_orbs(j, g)) Base.getindex(g::GreenSolution, i) = (i´ = sites_to_orbs(i, g); getindex(g, i´, i´)) # wrapped matrix for end user consumption Base.getindex(g::GreenSolution, i::OrbitalSliceGrouped, j::OrbitalSliceGrouped) = OrbitalSliceMatrix( mortar((g[si, sj] for si in cellsdict(i), sj in cellsdict(j))), (i, j)) Base.getindex(g::GreenSolution, i::AnyOrbitalSlice, j::AnyOrbitalSlice) = mortar((g[si, sj] for si in cellsdict(i), sj in cellsdict(j))) Base.getindex(g::GreenSolution, i::AnyOrbitalSlice, j::AnyCellOrbitals) = mortar((g[si, sj] for si in cellsdict(i), sj in (j,))) Base.getindex(g::GreenSolution, i::AnyCellOrbitals, j::AnyOrbitalSlice) = mortar((g[si, sj] for si in (i,), sj in cellsdict(j))) Base.getindex(g::GreenSolution, i::AnyCellOrbitals, j::AnyCellOrbitals) = slicer(g)[sanitize_cellorbs(i), sanitize_cellorbs(j)] # fallback conversion to CellOrbitals Base.getindex(s::GreenSlicer, i::AnyCellOrbitals, j::AnyCellOrbitals = i) = getindex(s, sanitize_cellorbs(i), sanitize_cellorbs(j)) # fallback, for GreenSlicers that forgot to implement getindex Base.getindex(s::GreenSlicer, ::CellOrbitals, ::CellOrbitals) = argerror("getindex of $(nameof(typeof(s))) not implemented") # fallback, for GreenSlicers that don't implement view Base.view(g::GreenSlicer, args...) = argerror("GreenSlicer of type $(nameof(typeof(g))) doesn't implement view for these arguments") # must ensure that orbindices is not a scalar, to consistently obtain a Matrix sanitize_cellorbs(c::CellOrbitals) = c sanitize_cellorbs(c::CellOrbital) = CellOrbitals(cell(c), orbindex(c):orbindex(c)) sanitize_cellorbs(c::CellOrbitalsGrouped) = CellOrbitals(cell(c), orbindices(c)) #endregion ############################################################################################ # GreenSolution diagonal indexing # returns a vector of AbstractMatrices or scalars, one per site #region Base.getindex(gω::GreenSolution{T}, i::DiagIndices, ::DiagIndices = i) where {T} = append_diagonal!(Complex{T}[], gω, parent(i), kernel(i)) |> maybe_OrbitalSliceArray(sites_to_orbs(i, gω)) # If i::Union{SiteSlice,CellSites}, convert to orbitals append_diagonal!(d, gω, i, kernel; kw...) = append_diagonal!(d, gω, sites_to_orbs(i, gω), kernel; kw...) append_diagonal!(d, gω, s::OrbitalSlice, kernel; kw...) = append_diagonal!(d, gω, cellsdict(s), kernel; kw...) # no OrbitalSliceVector here append_diagonal!(d, gω, s::AnyOrbitalSlice, kernel; kw...) = append_diagonal!(d, gω, cellsdict(s), kernel; kw...) function append_diagonal!(d, gω, s::AnyCellOrbitalsDict, kernel; kw...) sizehint!(d, length(s)) for sc in s append_diagonal!(d, gω, sc, kernel; kw...) end return d end function append_diagonal!(d, gω, o::Union{AnyCellOrbitals,Integer,Colon}, kernel; post = identity) gblock = diagonal_slice(gω, o) rngs = orbranges_or_allorbs(kernel, o, gω) for rng in rngs push!(d, post(apply_kernel(kernel, view_or_scalar(gblock, rng)))) end return d end # fallback, may be overloaded for gω's that know how to do this more efficiently # it should include all diagonal blocks for each site, not just the orbital diagonal diagonal_slice(gω, o) = gω[o, o] # If no kernel is provided, we return the whole diagonal orbranges_or_allorbs(kernel::Missing, o::AnyCellOrbitals, gω) = eachindex(orbindices(o)) orbranges_or_allorbs(kernel::Missing, o::Colon, gω) = 1:norbitals(contactorbitals(gω)) orbranges_or_allorbs(kernel::Missing, i::Integer, gω) = 1:norbitals(contactorbitals(gω), i) orbranges_or_allorbs(kernel, o, gω) = orbranges_or_allorbs(o, gω) orbranges_or_allorbs(contact::Integer, gω) = orbranges(contactorbitals(gω), contact) orbranges_or_allorbs(::Colon, gω) = orbranges(contactorbitals(gω)) orbranges_or_allorbs(o::CellOrbitalsGrouped, gω) = orbranges(o) view_or_scalar(gblock, rng::UnitRange) = view(gblock, rng, rng) view_or_scalar(gblock, i::Integer) = gblock[i, i] apply_kernel(kernel::Missing, v::Number) = v apply_kernel(kernel::AbstractMatrix, v) = tr(kernel * v) apply_kernel(kernel::UniformScaling, v) = kernel.λ * tr(v) apply_kernel(kernel::Number, v) = kernel * tr(v) apply_kernel(kernel::Diagonal, v::AbstractMatrix) = sum(i -> kernel[i] * v[i, i], eachindex(kernel)) apply_kernel(kernel::Diagonal, v::Number) = only(kernel) * v maybe_scalarize(s::OrbitalSliceGrouped, kernel::Missing) = s maybe_scalarize(s::OrbitalSliceGrouped, kernel) = scalarize(s) #endregion ############################################################################################ # selfenergy(::GreenSolution, contactinds::Int...; onlyΓ = false) # if no contactinds are provided, all are returned. Otherwise, a view of Σ over contacts. # selfenergy!(Σ::AbstractMatrix, ::GreenSolution, cinds...) # add blocks from cinds selfenergies to Σ (or all), and return a view over them # similar_contactΣ(g) # Matrix to hold MatrixBlocks of any self-energy # similar_contactΣ(g, cind) # Matrix that can hold a view of one self-energy #region selfenergy(g::GreenSolution, cinds::Int...; kw...) = selfenergy!(similar_contactΣ(g), g, cinds...; kw...) # we support also the case for one contact, but it is only used elsewhere function similar_contactΣ(g::Union{GreenFunction{T},GreenSolution{T}}, cind...) where {T} n = norbitals(contactorbitals(g), cind...) Σ = zeros(Complex{T}, n, n) return Σ end function maybe_selfenergy_view(Σ, g, cind, cinds...) inds = copy(contactinds(g, cind)) foreach(i -> append!(inds, contactinds(g, i)), cinds) isempty(cinds) || unique!(sort!(inds)) Σv = view(Σ, inds, inds) return Σv end maybe_selfenergy_view(Σ, g) = Σ function selfenergy!(Σ::AbstractMatrix{T}, g::GreenSolution, cinds...; onlyΓ = false) where {T} fill!(Σ, zero(T)) addselfenergy!(Σ, g, cinds...) onlyΓ && extractΓ!(Σ) # faster to do this on Σ than on Σv Σv = maybe_selfenergy_view(Σ, g, cinds...) return Σv end addselfenergy!(Σ, g::GreenSolution, cind::Int, cinds...) = addselfenergy!(addselfenergy!(Σ, selfenergies(g)[cind]), g, cinds...) addselfenergy!(Σ, ::GreenSolution) = Σ # RegularSelfEnergy case function addselfenergy!(Σ, b::MatrixBlock) v = view(Σ, blockrows(b), blockcols(b)) v .+= blockmat(b) return Σ end # ExtendedSelfEnergy case function addselfenergy!(Σ, (V´, g⁻¹, V)::NTuple{<:Any,MatrixBlock}) v = view(Σ, blockrows(V´), blockcols(V)) Vd = denseblockmat(V) copy!(Vd, blockmat(V)) ldiv!(lu(blockmat(g⁻¹)), Vd) mul!(v, blockmat(V´), Vd, 1, 1) return Σ end function extractΓ!(Σ) Σ .-= Σ' Σ .*= im return Σ end #endregion ############################################################################################ # selfenergyblocks # Build MatrixBlocks from contacts, including extended inds for ExtendedSelfEnergySolvers #region function selfenergyblocks(contacts::Contacts) Σs = selfenergies(contacts) solvers = solver.(Σs) extoffset = norbitals(contactorbitals(contacts)) cinds = contactinds(contacts) Σblocks = selfenergyblocks(extoffset, cinds, 1, (), solvers...) return Σblocks end # extoffset: current offset where extended indices start # contactinds: orbital indices for all selfenergies in contacts # ci: auxiliary index for current selfenergy being processed # blocks: tuple accumulating all MatrixBlocks from all selfenergies # solvers: selfenergy solvers that will update the MatrixBlocks selfenergyblocks(extoffset, contactinds, ci, blocks) = blocks function selfenergyblocks(extoffset, contactinds, ci, blocks, s::RegularSelfEnergySolver, ss...) c = contactinds[ci] Σblock = MatrixBlock(call!_output(s), c, c) return selfenergyblocks(extoffset, contactinds, ci + 1, (blocks..., Σblock), ss...) end function selfenergyblocks(extoffset, contactinds, ci, blocks, s::ExtendedSelfEnergySolver, ss...) Vᵣₑ, gₑₑ⁻¹, Vₑᵣ = shiftedmatblocks(call!_output(s), contactinds[ci], extoffset) extoffset += size(gₑₑ⁻¹, 1) # there is no minus sign here! return selfenergyblocks(extoffset, contactinds, ci + 1, (blocks..., (Vᵣₑ, gₑₑ⁻¹, Vₑᵣ)), ss...) end function shiftedmatblocks((Vᵣₑ, gₑₑ⁻¹, Vₑᵣ)::NTuple{3,AbstractArray}, cinds, shift) extsize = size(gₑₑ⁻¹, 1) Vᵣₑ´ = MatrixBlock(Vᵣₑ, cinds, shift+1:shift+extsize) # adds denseblock for selfenergy ldiv Vₑᵣ´ = MatrixBlock(Vₑᵣ, shift+1:shift+extsize, cinds, Matrix(Vₑᵣ)) gₑₑ⁻¹´ = MatrixBlock(gₑₑ⁻¹, shift+1:shift+extsize, shift+1:shift+extsize) return Vᵣₑ´, gₑₑ⁻¹´, Vₑᵣ´ end #endregion ############################################################################################ # ContactOrbitals constructors # Build a ContactOrbitals from a Hamiltonian and a set of latslices #region ContactOrbitals(h::AbstractHamiltonian{<:Any,<:Any,L}) where {L} = ContactOrbitals{L}() ContactOrbitals(h::AbstractHamiltonian, os, oss...) = ContactOrbitals(blockstructure(h), os, oss...) # probably unused, since oss comes from SelfEnergy, so it is already OrbitalSliceGrouped ContactOrbitals(bs::OrbitalBlockStructure, oss...) = ContactOrbitals(bs, sites_to_orbs.(oss, Ref(bs))...) function ContactOrbitals(bs::OrbitalBlockStructure, oss::OrbitalSliceGrouped...) codicts = cellsdict.(oss) codictall = combine(codicts...) contactinds = Vector{Int}[] corb_to_ind = dictionary(corb => ind for (ind, corb) in enumerate(cellorbs(codictall))) for codict in codicts i = [corb_to_ind[co] for co in cellorbs(codict)] push!(contactinds, i) end offsets = lengths_to_offsets(length, codictall) corbs = ContactOrbitals(codictall, [codicts...], contactinds, offsets) return corbs end #endregion ############################################################################################ # TMatrixSlicer <: GreenSlicer # Given a slicer that works without any contacts, implement slicing with contacts through # a T-Matrix equation g(i, j) = g0(i, j) + g0(i, k)T(k,k')g0(k', j), and T = (1-Σ*g0)⁻¹*Σ #region struct TMatrixSlicer{C,L,V<:AbstractArray{C},S} <: GreenSlicer{C} g0slicer::S tmatrix::V gcontacts::V contactorbs::ContactOrbitals{L} end struct NothingSlicer{C} <: GreenSlicer{C} end #region ## Constructors ## # if there are no Σblocks, return g0slicer. Otherwise build TMatrixSlicer. maybe_TMatrixSlicer(g0slicer::GreenSlicer, Σblocks::Tuple{}, contactorbs) = g0slicer maybe_TMatrixSlicer(g0slicer, Σblocks, contactorbs) = TMatrixSlicer(g0slicer, Σblocks, contactorbs) # Uses getindex(g0slicer) to construct g0contacts function TMatrixSlicer(g0slicer::GreenSlicer{C}, Σblocks, contactorbs) where {C} if isempty(Σblocks) tmatrix = gcontacts = view(zeros(C, 0, 0), 1:0, 1:0) else nreg = norbitals(contactorbs) g0contacts = zeros(C, nreg, nreg) off = offsets(contactorbs) for (j, sj) in enumerate(cellsdict(contactorbs)), (i, si) in enumerate(cellsdict(contactorbs)) irng = off[i]+1:off[i+1] jrng = off[j]+1:off[j+1] g0view = view(g0contacts, irng, jrng) copy!(g0view, g0slicer[si, sj]) end Σblocks´ = tupleflatten(Σblocks...) tmatrix, gcontacts = t_g_matrices(g0contacts, contactorbs, Σblocks´...) end return TMatrixSlicer(g0slicer, tmatrix, gcontacts, contactorbs) end # Takes a precomputed g0contacts (for dummy g0slicer that doesn't implement indexing) function TMatrixSlicer(g0contacts::AbstractMatrix{C}, Σblocks, contactorbs) where {C} tmatrix, gcontacts = t_g_matrices(g0contacts, contactorbs, Σblocks...) g0slicer = NothingSlicer{C}() return TMatrixSlicer(g0slicer, tmatrix, gcontacts, contactorbs) end # empty Σblocks function t_g_matrices(g0contacts::AbstractMatrix{C}, contactorbs) where {C} tmatrix = gcontacts = view(zeros(C, 0, 0), 1:0, 1:0) return tmatrix, gcontacts end # Check whether Σblocks are all spzeros, and if not, compute G and T function t_g_matrices(g0contacts::AbstractMatrix{C}, contactorbs, Σblocks::MatrixBlock...) where {C} if isspzeros(Σblocks) gcontacts = g0contacts tmatrix = zero(g0contacts) else tmatrix, gcontacts = t_g_matrices!(copy(g0contacts), contactorbs, Σblocks...) end return tmatrix, gcontacts end # rewrites g0contacts function t_g_matrices!(g0contacts::AbstractMatrix{C}, contactorbs, Σblocks::MatrixBlock...) where {C} nreg = norbitals(contactorbs) # number of regular orbitals n = max(nreg, maxrows(Σblocks), maxcols(Σblocks)) # includes extended orbitals Σmatext = Matrix{C}(undef, n, n) Σbm = BlockMatrix(Σmatext, Σblocks) update!(Σbm) # updates Σmat with Σblocks Σmatᵣᵣ = view(Σmatext, 1:nreg, 1:nreg) Σmatₑᵣ = view(Σmatext, nreg+1:n, 1:nreg) Σmatᵣₑ = view(Σmatext, 1:nreg, nreg+1:n) Σmatₑₑ = view(Σmatext, nreg+1:n, nreg+1:n) Σmat = copy(Σmatᵣᵣ) Σmat´ = ldiv!(lu!(Σmatₑₑ), Σmatₑᵣ) mul!(Σmat, Σmatᵣₑ, Σmat´, 1, 1) # Σmat = Σmatᵣᵣ + ΣmatᵣₑΣmatₑₑ⁻¹ Σmatₑᵣ den = Matrix{C}(I, nreg, nreg) mul!(den, Σmat, g0contacts, -1, 1) # den = 1-Σ*g0 luden = lu!(den) tmatrix = ldiv!(luden, Σmat) # tmatrix = (1 - Σ*g0)⁻¹Σ gcontacts = rdiv!(g0contacts, luden) # gcontacts = g0 * (1 - Σ*g0)⁻¹ return tmatrix, gcontacts end #endregion #region ## API ## Base.view(s::TMatrixSlicer, i::Integer, j::Integer) = view(s.gcontacts, contactinds(s.contactorbs, i), contactinds(s.contactorbs, j)) Base.view(s::TMatrixSlicer, ::Colon, ::Colon) = view(s.gcontacts, :, :) function Base.getindex(s::TMatrixSlicer, i::CellOrbitals, j::CellOrbitals) g0 = s.g0slicer g0ij = ensure_mutable_matrix(g0[i, j]) tkk´ = s.tmatrix isempty(tkk´) && return g0ij k = s.contactorbs g0ik = mortar((g0[si, sk] for si in (i,), sk in cellsdict(k))) g0k´j = mortar((g0[sk´, sj] for sk´ in cellsdict(k), sj in (j,))) gij = mul!(g0ij, g0ik, tkk´ * g0k´j, 1, 1) # = g0ij + g0ik * tkk´ * g0k´j return gij end ensure_mutable_matrix(m::SMatrix) = Matrix(m) ensure_mutable_matrix(m::AbstractMatrix) = m minimal_callsafe_copy(s::TMatrixSlicer, parentham, parentcontacts) = TMatrixSlicer( minimal_callsafe_copy(s.g0slicer, parentham, parentcontacts), s.tmatrix, s.gcontacts, s.contactorbs) Base.view(::NothingSlicer, i::Union{Integer,Colon}...) = internalerror("view(::NothingSlicer): unreachable reached") Base.getindex(::NothingSlicer, i::CellOrbitals...) = argerror("Slicer does not support generic indexing") minimal_callsafe_copy(s::NothingSlicer, parentham, parentcontacts) = s #endregion #endregion ############################################################################################ # GreenSolutionCache # Cache that memoizes columns of GreenSolution[ci,cj] on columns of single CellSite{L} # It does not support more general indices, but upon creation, the cache includes the data # already computed for the intra-contacts Green function (with noncontact sites as undefs) #region struct GreenSolutionCache{T,L,G<:GreenSolution{T,<:Any,L}} gω::G cache::Dict{Tuple{SVector{L,Int},SVector{L,Int},Int},Matrix{Complex{T}}} end function GreenSolutionCache(gω::GreenSolution{T,<:Any,L}) where {T,L} cache = Dict{Tuple{SVector{L,Int},SVector{L,Int},Int},Matrix{Complex{T}}}() # if contacts exists, we preallocate columns for each of their sites if ncontacts(gω) > 0 gmat = gω[:] g = parent(gω) h = hamiltonian(g) bs = blockstructure(h) co = contactorbitals(g) corngs = collect(orbranges(co)) cls = latslice(g, :) nrows = flatsize(h) j = 0 for colsc in cellsdict(cls) nj = cell(colsc) for j´ in siteindices(colsc) j += 1 jrng = corngs[j] i = 0 for rowsc in cellsdict(cls) ni = cell(rowsc) undefs = Matrix{Complex{T}}(undef, nrows, length(jrng)) for i´ in siteindices(rowsc) i += 1 irng = corngs[i] irng´ = flatrange(bs, i´) copy!(view(undefs, irng´, :), view(gmat, irng, jrng)) end push!(cache, (ni, nj, j´) => undefs) end end end end return GreenSolutionCache(gω, cache) end function Base.getindex(c::GreenSolutionCache{<:Any,L}, ci::CellSite, cj::CellSite) where {L} ci´, cj´ = sanitize_cellindices(ci, Val(L)), sanitize_cellindices(cj, Val(L)) ni, i = cell(ci´), siteindex(ci´) nj, j = cell(cj´), siteindex(cj´) if haskey(c.cache, (ni, nj, j)) gs = c.cache[(ni, nj, j)] else gs = c.gω[sites(ni, :), cj] push!(c.cache, (ni, nj, j) => gs) end h = hamiltonian(c.gω) rows = flatrange(h, i) return view(gs, rows, :) end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
24295
############################################################################################ # add!(::IJVBuilder, ...) # add matrix elements to a builder before assembly into a (Parametric)Hamiltonian #region add!(m::TightbindingModel) = b -> add!(b, m) # direct site indexing function add!(b::IJVBuilder, val, c::CellSites, d::CellSites) c´, d´ = sanitize_cellindices(c, b), sanitize_cellindices(d, b) ijv = b[cell(d´) - cell(c´)] B = blocktype(b) val´ = mask_block(B, val) # Warning: we don't check matrix size here, just conversion to B add!(ijv, val´, siteindices(c´), siteindices(d´)) return b end function add!(b::IJVBuilder, val, c::CellSites) c´ = sanitize_cellindices(c, b) ijv = b[zero(cell(c´))] B = blocktype(b) val´ = mask_block(B, val) # Warning: we don't check matrix size here, just conversion to B add!(ijv, val´, siteindices(c´)) return b end add!(ijv::IJV, v, i::Integer, j::Integer = i) = push!(ijv, (i, j, v)) function add!(ijv::IJV, v, is, js) foreach(Iterators.product(is, js)) do (i, j) push!(ijv, (i, j, v)) end return ijv end function add!(ijv::IJV, v, is) foreach(is) do i push!(ijv, (i, i, v)) end return ijv end # block may be a tuple of row-col index ranges, to restrict application of model function add!(b::IJVBuilder, model::TightbindingModel, block = missing) lat = lattice(b) bs = blockstructure(b) amodel = apply(model, (lat, bs)) addterm!.(Ref(b), Ref(block), terms(amodel)) return b end function add!(b::IJVBuilderWithModifiers, model::ParametricModel, block = missing) m0 = basemodel(model) ms = modifier.(terms(model)) add!(b, m0, block) push!(b, ms...) return b end function addterm!(builder, block, term::AppliedOnsiteTerm) sel = selector(term) isempty(cells(sel)) || argerror("Cannot constrain cells in an onsite term, cell periodicity is assumed.") lat = lattice(builder) dn0 = zerocell(lat) ijv = builder[dn0] bs = blockstructure(builder) bsizes = blocksizes(bs) foreach_site(sel, dn0) do s, i, r isinblock(i, block) || return nothing n = bsizes[s] # conventional terms are never non-spatial, only modifiers can be vr = term(r, n) push!(ijv, (i, i, vr)) end return nothing end function addterm!(builder, block, term::AppliedHoppingTerm) trees = kdtrees(builder) sel = selector(term) bs = blockstructure(builder) bsizes = blocksizes(bs) foreach_cell(sel) do dn ijv = builder[dn] found = foreach_hop(sel, trees, dn) do (si, sj), (i, j), (r, dr) isinblock(i, j, block) || return nothing ni = bsizes[si] nj = bsizes[sj] # conventional terms are never non-spatial, only modifiers can be vr = term(r, dr, (ni, nj)) push!(ijv, (i, j, vr)) end return found end return nothing end # If block is not Missing, restrict to ranges # Interblock isinblock(i, j, ::Missing) = true function isinblock(i, j, rngs::Tuple) for (jr, rng´) in enumerate(rngs), (ir, rng) in enumerate(rngs) jr == ir && continue isinblock(i, rng) && isinblock(j, rng´) && return true end return false end # Intrablock isinblock(i, j, rng) = isinblock(i, rng) && isinblock(j, rng) isinblock(i, ::Missing) = true isinblock(i, rng) = i in rng #endregion ############################################################################################ # hamiltonian #region (model::AbstractModel)(lat::Lattice) = hamiltonian(lat, model) (modifier::Modifier)(h::AbstractHamiltonian) = hamiltonian(h, modifier) hamiltonian(args...; kw...) = lat -> hamiltonian(lat, args...; kw...) hamiltonian(h::AbstractHamiltonian, m::AbstractModifier, ms::AbstractModifier...) = parametric(h, m, ms...) hamiltonian(lat::Lattice, m0::TightbindingModel, m::Modifier, ms::Modifier...; kw...) = parametric(hamiltonian(lat, m0; kw...), m, ms...) hamiltonian(lat::Lattice, m0::ParametricModel, ms::Modifier...; kw...) = parametric(hamiltonian(lat, basemodel(m0); kw...), modifier.(terms(m0))..., ms...) hamiltonian(lat::Lattice, m::Modifier, ms::Modifier...; kw...) = parametric(hamiltonian(lat; kw...), m, ms...) hamiltonian(lat::Lattice, m::Interblock{<:TightbindingModel}; kw...) = hamiltonian(lat, parent(m), block(m); kw...) hamiltonian(lat::Lattice, m::Interblock{<:ParametricModel}; kw...) = parametric( hamiltonian(lat, basemodel(parent(m)), block(m); kw...), modifier.(terms(parent(m)))...) function hamiltonian(lat::Lattice{T}, m::TightbindingModel = TightbindingModel(), block = missing; orbitals = Val(1)) where {T} b = IJVBuilder(lat, orbitals) add!(b, m, block) return hamiltonian(b) end hamiltonian(b::IJVBuilder) = Hamiltonian(lattice(b), blockstructure(b), sparse(b)) hamiltonian(b::IJVBuilderWithModifiers) = maybe_parametric(Hamiltonian(lattice(b), blockstructure(b), sparse(b)), modifiers(b)...) maybe_parametric(h) = h maybe_parametric(h, m, ms...) = parametric(h, m, ms...) #endregion ############################################################################################ # parametric #region function parametric(hparent::Hamiltonian) modifiers = () allparams = Symbol[] allptrs = [Int[] for _ in harmonics(hparent)] # We must decouple hparent from the result, which will modify h in various ways h = minimal_callsafe_copy(hparent) return ParametricHamiltonian(hparent, h, modifiers, allptrs, allparams) end # Any means perhaps wrapped in Intrablock or Interblock parametric(h::Hamiltonian, m::AnyAbstractModifier, ms::AnyAbstractModifier...) = parametric!(parametric(h), m, ms...) parametric(p::ParametricHamiltonian, ms::AnyAbstractModifier...) = parametric!(copy(p), ms...) # This should not be exported, because it doesn't modify p in place (because of modifiers) function parametric!(p::ParametricHamiltonian, ms::AnyModifier...) ams = apply.(ms, Ref(parent(p))) return parametric!(p, ams...) end function parametric!(p::ParametricHamiltonian, ms::AppliedModifier...) hparent = parent(p) h = hamiltonian(p) allmodifiers = (modifiers(p)..., ms...) allparams = parameters(p) merge_parameters!(allparams, ms...) allptrs = pointers(p) merge_pointers!(allptrs, ms...) return ParametricHamiltonian(hparent, h, allmodifiers, allptrs, allparams) end merge_pointers!(p, m, ms...) = merge_pointers!(_merge_pointers!(p, m), ms...) function merge_pointers!(p) for pn in p unique!(sort!(pn)) end return p end function _merge_pointers!(p, m::AppliedOnsiteModifier) p0 = first(p) for (ptr, _) in pointers(m) push!(p0, ptr) end return p end function _merge_pointers!(p, m::AppliedHoppingModifier) for (pn, pm) in zip(p, pointers(m)), (ptr, _) in pm push!(pn, ptr) end return p end #endregion ############################################################################################ # Hamiltonian call API # call!(::AbstractHamiltonian; params...) returns a Hamiltonian with params applied # call!(::AbstractHamiltonian, ϕs; params...) returns a HybridSparseMatrix with Bloch phases # ϕs and params applied # h(...; ...) is a copy decoupled from future call!'s #region (h::Hamiltonian)(phi...; params...) = copy(call!(h, phi...; params...)) call!(h::Hamiltonian; params...) = flat_sync!(h) # mimic partial call!(p::ParametricHamiltonian; params...) call!(h::Hamiltonian, φ1::Number, φ2::Number, φs::Number...; params...) = argerror("To obtain the (flat) Bloch matrix of `h` use `h(ϕs)`, where `ϕs` is a collection of `L=$(latdim(lattice(h)))` Bloch phases") call!(h::Hamiltonian{T}, φs; params...) where {T} = flat_bloch!(h, sanitize_SVector(T, φs)) call!(h::Hamiltonian{<:Any,<:Any,0}, ::Tuple{}; params...) = h[()] call!(h::Hamiltonian, ft::FrankenTuple) = call!(h, Tuple(ft)) # shortcut (see call!_output further below) flat_bloch!(h::Hamiltonian{<:Any,<:Any,0}, ::SVector{0}, axis = missing) = h[()] # returns a flat sparse matrix function flat_bloch!(h::Hamiltonian{T}, φs::SVector, axis = missing) where {T} hbloch = bloch(h) needs_initialization(hbloch) && initialize_bloch!(hbloch, harmonics(h)) fbloch = flat(hbloch) fill!(fbloch, zero(Complex{T})) # This preserves sparsity structure addblochs!(fbloch, h, φs, axis) return fbloch end function addblochs!(dst::SparseMatrixCSC, h::Hamiltonian, φs, axis) checkbloch(h, φs) hars = harmonics(h) isvelocity = axis isa Integer for har in hars iszero(dcell(har)) && isvelocity && continue e⁻ⁱᵠᵈⁿ = cis(-dot(φs, dcell(har))) isvelocity && (e⁻ⁱᵠᵈⁿ *= - im * dcell(har)[axis]) merged_mul!(dst, matrix(har), e⁻ⁱᵠᵈⁿ, 1, 1) # see tools.jl end return dst end function initialize_bloch!(bloch, hars) fbloch = flat_unsafe(bloch) fbloch´ = merge_sparse(flat.(matrix.(hars))) copy!(fbloch, fbloch´) ubloch = unflat_unsafe(bloch) ubloch === fbloch || copy!(ubloch, unflat(blockstructure(bloch), fbloch)) needs_no_sync!(bloch) update_nnz!(bloch) return bloch end @noinline checkbloch(::AbstractHamiltonian{<:Any,<:Any,L}, ::SVector{L´}) where {L,L´} = L == L´ || throw(ArgumentError("Need $L Bloch phases, got $(L´)")) # ouput of a call!(h, ϕs) call!_output(h::Hamiltonian) = flat_unsafe(bloch(h)) call!_output(h::Hamiltonian{<:Any,<:Any,0}) = flat_unsafe(h[hybrid()]) #endregion ############################################################################################ # ParametricHamiltonian call API #region (p::ParametricHamiltonian)(; kw...) = copy(call!(p; kw...)) (p::ParametricHamiltonian)(phis; kw...) = copy(call!(call!(p; kw...), phis)) call!(p::ParametricHamiltonian, phi; kw...) = call!(call!(p; kw...), phi) call!(p::ParametricHamiltonian, ft::FrankenTuple) = call!(p, Tuple(ft); NamedTuple(ft)...) function call!(ph::ParametricHamiltonian; kw...) reset_to_parent!(ph) h = hamiltonian(ph) applymodifiers!(h, modifiers(ph)...; kw...) flat_sync!(h) # modifiers are applied to unflat, need to be synced to flat return h end function reset_to_parent!(ph) h = hamiltonian(ph) hparent = parent(ph) nnzfraction = 0.3 # threshold to revert to full copyto! for (har, har´, ptrs) in zip(harmonics(h), harmonics(hparent), pointers(ph)) m, m´ = matrix(har), matrix(har´) nz = nonzeros(needs_initialization(m) ? unflat(m) : unflat_unsafe(m)) nz´ = nonzeros(unflat(m´)) if length(ptrs) < length(nz) * nnzfraction for ptr in ptrs nz[ptr] = nz´[ptr] end else copyto!(nz, nz´) end needs_flat_sync!(m) end return ph end applymodifiers!(h; kw...) = h applymodifiers!(h, m, m´, ms...; kw...) = applymodifiers!(applymodifiers!(h, m; kw...), m´, ms...; kw...) applymodifiers!(h, m::Modifier; kw...) = applymodifiers!(h, apply(m, h); kw...) function applymodifiers!(h, m::AppliedOnsiteModifier; kw...) nz = nonzeros(unflat(first(harmonics(h)))) if is_spatial(m) # Branch outside loop @simd for p in pointers(m) (ptr, r, s, norbs) = p @inbounds nz[ptr] = m(nz[ptr], r, norbs; kw...) # @inbounds too risky? end else @simd for p in pointers(m) (ptr, r, s, norbs) = p @inbounds nz[ptr] = m(nz[ptr], s, norbs; kw...) end end return h end function applymodifiers!(h, m::AppliedOnsiteModifier{B}; kw...) where {B<:SMatrixView} nz = nonzeros(unflat(first(harmonics(h)))) if is_spatial(m) # Branch outside loop @simd for p in pointers(m) (ptr, r, s, norbs) = p val = view(nz[ptr], 1:norbs, 1:norbs) # this might be suboptimal - do we need view? @inbounds nz[ptr] = m(val, r, norbs; kw...) # @inbounds too risky? end else @simd for p in pointers(m) (ptr, r, s, norbs) = p val = view(nz[ptr], 1:norbs, 1:norbs) @inbounds nz[ptr] = m(val, s, norbs; kw...) end end return h end function applymodifiers!(h, m::AppliedHoppingModifier; kw...) for (har, ptrs) in zip(harmonics(h), pointers(m)) nz = nonzeros(unflat(har)) if is_spatial(m) # Branch outside loop @simd for p in ptrs (ptr, r, dr, si, sj, orborb) = p @inbounds nz[ptr] = m(nz[ptr], r, dr, orborb; kw...) end else @simd for p in ptrs (ptr, r, dr, si, sj, orborb) = p @inbounds nz[ptr] = m(nz[ptr], si, sj, orborb; kw...) end end end return h end function applymodifiers!(h, m::AppliedHoppingModifier{B}; kw...) where {B<:SMatrixView} for (har, ptrs) in zip(harmonics(h), pointers(m)) nz = nonzeros(unflat(har)) if is_spatial(m) # Branch outside loop @simd for p in ptrs (ptr, r, dr, si, sj, (oi, oj)) = p val = view(nz[ptr], 1:oi, 1:oj) # this might be suboptimal - do we need view? @inbounds nz[ptr] = m(val, r, dr, (oi, oj); kw...) end else @simd for p in ptrs (ptr, r, dr, si, sj, (oi, oj)) = p val = view(nz[ptr], 1:oi, 1:oj) @inbounds nz[ptr] = m(val, si, sj, (oi, oj); kw...) end end end return h end # ouput of a *full* call!(p, ϕs; kw...) call!_output(p::ParametricHamiltonian) = call!_output(hamiltonian(p)) #endregion ############################################################################################ # indexing into AbstractHamiltonian - see also slices.jl #region # Extraction of Harmonics Base.getindex(h::AbstractHamiltonian, dn::Union{Tuple,Integer,SVector,AbstractVector}) = flat(h[hybrid(dn)]) Base.getindex(h::AbstractHamiltonian, dn::UnflatInds) = unflat(h[hybrid(parent(dn))]) Base.getindex(h::AbstractHamiltonian, dn::HybridInds{<:Union{Integer,Tuple}}) = h[hybrid(SVector(parent(dn)))] Base.getindex(h::AbstractHamiltonian{<:Any,<:Any,L}, ::HybridInds{Tuple{}}) where {L} = h[hybrid(zero(SVector{L,Int}))] Base.getindex(h::ParametricHamiltonian{<:Any,<:Any,L}, dn::HybridInds{SVector{L,Int}}) where {L} = getindex(hamiltonian(h), dn) function Base.getindex(h::Hamiltonian{<:Any,<:Any,L}, dn::HybridInds{SVector{L,Int}}) where {L} for har in harmonics(h) parent(dn) == dcell(har) && return matrix(har) end @boundscheck(boundserror(harmonics(h), parent(dn))) # this is unreachable, but avoids allocations by having non-Union return type return matrix(first(harmonics(h))) end Base.isassigned(h::AbstractHamiltonian, dn::Tuple) = isassigned(h, SVector(dn)) function Base.isassigned(h::AbstractHamiltonian{<:Any,<:Any,L}, dn::SVector{L,Int}) where {L} for har in harmonics(h) dn == dcell(har) && return true end return false end # SiteSelector indexing - replicates GreenSolution indexing - see GreenFunctions.jl Base.getindex(h::ParametricHamiltonian; kw...) = getindex(call!(h); kw...) Base.getindex(h::Hamiltonian; kw...) = h[siteselector(; kw...)] # conversion down to CellOrbitals. See sites_to_orbs in slices.jl Base.getindex(h::ParametricHamiltonian, i, j) = getindex(call!(h), i, j) Base.getindex(h::Hamiltonian, i, j) = getindex(h, sites_to_orbs(i, h), sites_to_orbs(j, h)) # we need AbstractHamiltonian here to avoid ambiguities with dn above Base.getindex(h::AbstractHamiltonian, i) = (i´ = sites_to_orbs(i, h); getindex(h, i´, i´)) # wrapped matrix for end user consumption Base.getindex(h::Hamiltonian, i::OrbitalSliceGrouped, j::OrbitalSliceGrouped) = OrbitalSliceMatrix( mortar((h[si, sj] for si in cellsdict(i), sj in cellsdict(j))), (i, j)) Base.getindex(h::Hamiltonian, i::AnyOrbitalSlice, j::AnyOrbitalSlice) = mortar((h[si, sj] for si in cellsdict(i), sj in cellsdict(j))) Base.getindex(h::Hamiltonian, i::AnyOrbitalSlice, j::AnyCellOrbitals) = mortar((h[si, sj] for si in cellsdict(i), sj in (j,))) Base.getindex(h::Hamiltonian, i::AnyCellOrbitals, j::AnyOrbitalSlice) = mortar((h[si, sj] for si in (i,), sj in cellsdict(j))) function Base.getindex(h::Hamiltonian{T}, i::AnyCellOrbitals, j::AnyCellOrbitals) where {T} dn = cell(i) - cell(j) oi, oj = orbindices(i), orbindices(j) mat = isassigned(h, dn) ? h[dn][oi, oj] : spzeros(Complex{T}, length(oi), length(oj)) return mat end Base.view(h::ParametricHamiltonian, i::CellSites, j::CellSites = i) = view(call!(h), i, j) function Base.view(h::Hamiltonian, i::CellSites, j::CellSites = i) oi, oj = sites_to_orbs_nogroups(i, h), sites_to_orbs_nogroups(j, h) dn = cell(oi) - cell(oj) return view(h[dn], orbindices(oi), orbindices(oj)) end #endregion ############################################################################################ # coordination #region function nhoppings(h::AbstractHamiltonian) count = 0 for har in harmonics(h) umat = unflat(matrix(har)) count += iszero(dcell(har)) ? (nnz(umat) - nnzdiag(umat)) : nnz(umat) end return count end nonsites(h::Hamiltonian) = nnzdiag(h[unflat()]) # avoid call!, since params can have no default nonsites(h::ParametricHamiltonian) = nonsites(hamiltonian(h)) coordination(h::AbstractHamiltonian) = iszero(nhoppings(h)) ? 0.0 : round(nhoppings(h) / nsites(lattice(h)), digits = 5) #endregion ############################################################################################ # unitcell_hamiltonian # Builds the intra-unitcell 0D Hamiltonian. If parent is p::ParametricHamiltonian, the # obtained uh::Hamiltonian is aliased with p, so call!(p,...) also updates uh #region function unitcell_hamiltonian(h::Hamiltonian) lat = lattice(lattice(h); bravais = ()) bs = blockstructure(h) hars = [Harmonic(SVector{0,Int}(), matrix(first(harmonics(h))))] return Hamiltonian(lat, bs, hars) end unitcell_hamiltonian(ph::ParametricHamiltonian) = unitcell_hamiltonian(hamiltonian(ph)) #endregion ############################################################################################ # combine # type-stable with Hamiltonians, but not with ParametricHamiltonians, as the field # builder.modifiers isa Vector{Any} in that case. #region function combine(hams::AbstractHamiltonian...; coupling::AbstractModel = TightbindingModel()) check_unique_names(coupling, hams...) lat = combine(lattice.(hams)...) builder = IJVBuilder(lat, hams...) interblockmodel = interblock(coupling, hams...) model´, blocks´ = parent(interblockmodel), block(interblockmodel) add!(builder, model´, blocks´) return hamiltonian(builder) end # No need to have unique names if nothing is parametric check_unique_names(::TightbindingModel, ::Hamiltonian...) = nothing function check_unique_names(::AbstractModel, hs::AbstractHamiltonian...) names = tupleflatten(sublatnames.(lattice.(hs))...) allunique(names) || argerror("Cannot combine ParametricHamiltonians with non-unique sublattice names, since modifiers could be tied to the original names. Assign unique names on construction.") return nothing end function check_unique_names(::AbstractModel, hs::Hamiltonian...) names = tupleflatten(sublatnames.(lattice.(hs))...) allunique(names) || argerror("Cannot combine Hamiltonians with non-unique sublattice names using a ParametricModel, since modifiers could be tied to the original names. Assign unique names on construction.") return nothing end #endregion ############################################################################################ # torus(::Hamiltonian, phases) #region torus(phases) = h -> torus(h, phases) function torus(h::Hamiltonian{<:Any,<:Any,L}, phases) where {L} check_torus_phases(phases, L) wa, ua = split_axes(phases) # indices for wrapped and unwrapped axes iszero(length(wa)) && return minimal_callsafe_copy(h) lat = lattice(h) b´ = bravais_matrix(lat)[:, SVector(ua)] lat´ = lattice(lat; bravais = b´) bs´ = blockstructure(h) bloch´ = copy_matrices(bloch(h)) hars´ = stitch_harmonics(harmonics(h), phases, wa, ua) return Hamiltonian(lat´, bs´, hars´, bloch´) end check_torus_phases(phases, L) = length(phases) == L || argerror("Expected $L `torus` phases, got $(length(phases))") split_axes(phases) = split_axes((), (), 1, phases...) split_axes(wa, ua, n, x::Colon, xs...) = split_axes(wa, (ua..., n), n+1, xs...) split_axes(wa, ua, n, x, xs...) = split_axes((wa..., n), ua, n+1, xs...) split_axes(wa, ua, n) = wa, ua function stitch_harmonics(hars, phases, wa::NTuple{W}, ua::NTuple{U}) where {W,U} phases_w = SVector(phases)[SVector(wa)] dcells_u = SVector{U,Int}[dcell(har)[SVector(ua)] for har in hars] dcells_w = SVector{W,Int}[dcell(har)[SVector(wa)] for har in hars] unique_dcells_u = unique!(sort(dcells_u, by = norm)) groups = [findall(==(dcell), dcells_u) for dcell in unique_dcells_u] hars´ = [summed_harmonic(inds, hars, phases_w, dcells_u, dcells_w) for inds in groups] return hars´ end function summed_harmonic(inds, hars::Vector{<:Harmonic{<:Any,<:Any,B}}, phases_w, dcells_u, dcells_w) where {B} I,J,V = Int[], Int[], B[] for i in inds I´, J´, V´ = findnz(unflat(matrix(hars[i]))) dn_w = dcells_w[i] e⁻ⁱᵠᵈⁿ = cis(-dot(phases_w, dn_w)) V´ .*= e⁻ⁱᵠᵈⁿ append!(I, I´) append!(J, J´) append!(V, V´) end dn_u = dcells_u[first(inds)] bs = blockstructure(matrix(hars[first(inds)])) n = unflatsize(bs) mat = sparse(I, J, V, n, n) return Harmonic(dn_u, HybridSparseMatrix(bs, mat)) end #endregion ############################################################################################ # torus(::ParametricHamiltonian, phases) #region function torus(p::ParametricHamiltonian, phases) wa, ua = split_axes(phases) # indices for wrapped and unwrapped axes iszero(length(wa)) && return minimal_callsafe_copy(p) h = parent(p) h´ = torus(h, phases) ams = modifiers(p) L = latdim(lattice(h)) S = SMatrix{L,L,Int}(I)[SVector(ua), :] # dnnew = S * dnold ptrmap = pointer_map(h, h´, S) # [[(ptr´ of har´[S*dn]) for ptr in har] for har in h] harmap = harmonics_map(h, h´, S) # [(index of har´[S*dn]) for har in h] ams´ = stitch_modifier.(ams, Ref(ptrmap), Ref(harmap)) p´ = hamiltonian(h´, ams´...) return p´ end pointer_map(h, h´, S) = [pointer_map(har, first(harmonic_index(h´, S*dcell(har)))) for har in harmonics(h)] function pointer_map(har, har´) ptrs´ = Int[] mat, mat´ = unflat(matrix(har)), unflat(matrix(har´)) rows, rows´ = rowvals(mat), rowvals(mat´) for col in axes(mat, 2), ptr in nzrange(mat, col) row = rows[ptr] for ptr´ in nzrange(mat´, col) if row == rows´[ptr´] push!(ptrs´, ptr´) break end end end return ptrs´ end harmonics_map(h, h´, S) = [last(harmonic_index(h´, S*dcell(har))) for har in harmonics(h)] function stitch_modifier(m::AppliedOnsiteModifier, ptrmap, _) ptrs´ = first(ptrmap) p´ = [(ptrs´[ptr], r, s, orbs) for (ptr, r, s, orbs) in pointers(m)] return AppliedOnsiteModifier(m, p´) end function stitch_modifier(m::AppliedHoppingModifier, ptrmap, harmap) ps = pointers(m) ps´ = [similar(first(ps), 0) for _ in 1:maximum(harmap)] for (i, p) in enumerate(ps), (ptr, r, dr, si, sj, orborbs) in p i´ = harmap[i] ptrs´ = ptrmap[i] push!(ps´[i´], (ptrs´[ptr], r, dr, si, sj, orborbs)) end sort!.(ps´) check_ptr_duplicates(first(ps´)) return AppliedHoppingModifier(m, ps´) end function check_ptr_duplicates(h0ptrs) has_duplicates_ptrs = !allunique(first(p) for p in h0ptrs) has_duplicates_ptrs && @warn "The wrapped ParametricHamiltonian has a modifier on hoppings that are the sum of intra- and intercell hoppings. The modifier will be applied to the sum, which may lead to unexpected results for position-dependent modifiers." return nothing end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
8335
####################################################################### # BoxIterator #region """ BoxIterator(seed::SVector{N,Int}; maxiterations = TOOMANYITERS) Cartesian iterator `iter` over `SVector{N,Int}`s (`cell`s) that starts at `seed` and grows outwards in the form of a box of increasing sides (not necesarily equal) until it encompasses a certain N-dimensional region. To signal that a cell is in the desired region the user calls `acceptcell!(iter, cell)`. """ struct BoxIterator{N} seed::SVector{N,Int} maxiter::Int dimdir::MVector{2,Int} nmoves::MVector{N,Bool} pmoves::MVector{N,Bool} npos::MVector{N,Int} ppos::MVector{N,Int} end const TOOMANYITERS = 10^8 Base.IteratorSize(::Type{BoxIterator}) = Base.SizeUnknown() Base.IteratorEltype(::Type{BoxIterator}) = Base.HasEltype() Base.eltype(::Type{BoxIterator{N}}) where {N} = SVector{N,Int} Base.CartesianIndices(b::BoxIterator) = CartesianIndices(UnitRange.(Tuple(b.npos), Tuple(b.ppos))) eldim(::BoxIterator{N}) where {N} = N function BoxIterator(seed::SVector{N}; maxiterations = TOOMANYITERS) where {N} BoxIterator(seed, maxiterations, MVector(1, 2), ones(MVector{N,Bool}), ones(MVector{N,Bool}), MVector{N,Int}(seed), MVector{N,Int}(seed)) end struct BoxIteratorState{N} range::CartesianIndices{N, NTuple{N,UnitRange{Int}}} rangestate::CartesianIndex{N} iteration::Int end Base.iterate(b::BoxIterator{0}) = (SVector{0,Int}(), nothing) Base.iterate(b::BoxIterator{0}, state) = nothing function Base.iterate(b::BoxIterator) N = eldim(b) range = CartesianIndices(ntuple(i -> b.seed[i]:b.seed[i], Val(N))) itrange = iterate(range) if itrange === nothing return nothing else (cell, rangestate) = itrange return (SVector(Tuple(cell)), BoxIteratorState(range, rangestate, 1)) end end function Base.iterate(b::BoxIterator, s::BoxIteratorState) itrange = iterate(s.range, s.rangestate) facedone = itrange === nothing if facedone alldone = !any(b.pmoves) && !any(b.nmoves) || checkmaxiter(b, s) if alldone # Last shells in all directions were empty, trim from boundingboxcorners b.npos .+= 1 b.ppos .-= 1 return nothing else newrange = nextface!(b) # newrange === nothing && return nothing itrange = iterate(newrange) # itrange === nothing && return nothing (cell, rangestate) = itrange return (SVector(Tuple(cell)), BoxIteratorState(newrange, rangestate, s.iteration + 1)) end else (cell, rangestate) = itrange return (SVector(Tuple(cell)), BoxIteratorState(s.range, rangestate, s.iteration + 1)) end end @noinline function checkmaxiter(b::BoxIterator, s::BoxIteratorState) exceeded = isless(b.maxiter, s.iteration) exceeded && @warn("Region seems unbounded after $(b.maxiter) iterations") return exceeded end function nextface!(b::BoxIterator) N = eldim(b) @inbounds for i in 1:2N nextdimdir!(b) newdim, newdir = Tuple(b.dimdir) if newdir == 1 if b.nmoves[newdim] b.npos[newdim] -= 1 b.nmoves[newdim] = false return newrangeneg(b, newdim) end else if b.pmoves[newdim] b.ppos[newdim] += 1 b.pmoves[newdim] = false return newrangepos(b, newdim) end end end return nothing end function nextdimdir!(b::BoxIterator) N = eldim(b) dim, dir = Tuple(b.dimdir) if dim < N dim += 1 else dim = 1 dir = ifelse(dir == 1, 2, 1) end b.dimdir[1] = dim b.dimdir[2] = dir return nothing end @inline function newrangeneg(b::BoxIterator, dim) N = eldim(b) return CartesianIndices(ntuple( i -> b.npos[i]:(i == dim ? b.npos[i] : b.ppos[i]), Val(N))) end @inline function newrangepos(b::BoxIterator, dim) N = eldim(b) return CartesianIndices(ntuple( i -> (i == dim ? b.ppos[i] : b.npos[i]):b.ppos[i], Val(N))) end function acceptcell!(b::BoxIterator, cell) N = eldim(b) dim, dir = Tuple(b.dimdir) if dir == 1 @inbounds for i in 1:N (cell[i] == b.ppos[i]) && (b.pmoves[i] = true) (i == dim || cell[i] == b.npos[i]) && (b.nmoves[i] = true) end else @inbounds for i in 1:N (i == dim || cell[i] == b.ppos[i]) && (b.pmoves[i] = true) (cell[i] == b.npos[i]) && (b.nmoves[i] = true) end end return nothing end # Fallback for non-BoxIterators acceptcell!(b, cell) = nothing #endregion ####################################################################### # CoSort #region struct CoSortTup{T,T´} x::T y::T´ end mutable struct CoSort{T,T´} <: AbstractVector{CoSortTup{T,T´}} sortvector::Vector{T} covector::Vector{T´} offset::Int function CoSort{T,T´}(sortvector, covector, offset) where {T,T´} length(covector) >= length(sortvector) ? new(sortvector, covector, offset) : throw(DimensionMismatch("Coarray length should exceed sorting array")) end end CoSort(sortvector::Vector{T}, covector::Vector{T´}) where {T,T´} = CoSort{T,T´}(sortvector, covector, 0) function cosort!(s, c) cs = CoSort(s, c) sort!(cs) return cs.sortvector, cs.covector end Base.size(c::CoSort) = (size(c.sortvector, 1) - c.offset,) Base.getindex(c::CoSort, i) = CoSortTup(getindex(c.sortvector, i + c.offset), getindex(c.covector, i + c.offset)) Base.setindex!(c::CoSort, t::CoSortTup, i) = (setindex!(c.sortvector, t.x, i + c.offset); setindex!(c.covector, t.y, i + c.offset); c) Base.isless(a::CoSortTup, b::CoSortTup) = isless(a.x, b.x) Base.Sort.defalg(v::C) where {T<:Union{Number, Missing}, C<:CoSort{T}} = Base.DEFAULT_UNSTABLE isgrowing(c::CoSort) = isgrowing(c.sortvector, c.offset + 1) function isgrowing(vs::AbstractVector, i0 = 1) i0 > length(vs) && return true vprev = vs[i0] for i in i0 + 1:length(vs) v = vs[i] v <= vprev && return false vprev = v end return true end #endregion ####################################################################### # Combinations -- gratefully borrowed from Combinatorics.jl #region struct Combinations n::Int t::Int end @inline function Base.iterate(c::Combinations, s = [min(c.t - 1, i) for i in 1:c.t]) if c.t == 0 # special case to generate 1 result for t==0 isempty(s) && return (s, [1]) return end # for i in c.t:-1:1 for ii in 1:c.t i = c.t + 1 - ii s[i] += 1 if s[i] > (c.n - (c.t - i)) continue end for j in i+1:c.t s[j] = s[j-1] + 1 end break end s[1] > c.n - c.t + 1 && return (s, s) end Base.length(c::Combinations) = binomial(c.n, c.t) Base.eltype(::Type{Combinations}) = Vector{Int} Base.IteratorSize(::Type{Combinations}) = Base.HasLength() Base.IteratorEltype(::Type{Combinations}) = Base.HasEltype() ####################################################################### # Runs #region # iteration yields ranges of subsequent xs elements such that istogether of consecutive pairs gives true struct Runs{T,F} xs::Vector{T} istogether::F end equalruns(xs) = Runs(xs, ==) approxruns(xs::Vector{T}, atol = sqrt(eps(real(T)))) where {T<:Number} = Runs(xs, (x, y) -> isapprox(x, y; atol)) function Base.iterate(s::Runs, frst = 1) xs = s.xs frst > length(xs) && return nothing # find first element in run for frst´ in frst:length(xs) xj´ = xs[frst´] if s.istogether(xj´, xj´) frst = frst´ break elseif frst´ == length(xs) return nothing end end # find last element in run, which is at least xs[frst] lst = frst for lst´ in frst+1:length(xs) if !s.istogether(xs[lst´-1], xs[lst´]) lst = lst´-1 break else lst = lst´ end end return frst:lst, lst + 1 end Base.IteratorSize(::Runs) = Base.SizeUnknown() Base.IteratorEltype(::Runs) = Base.HasEltype() Base.eltype(::Runs) = UnitRange{Int} #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
6275
############################################################################################ # sublat #region sublat(sites::Union{Number,Tuple,SVector,AbstractVector{<:Number}}...; name = :A) = Sublat([float.(promote(sanitize_SVector.(sites)...))...], Symbol(name)) function sublat(sites::AbstractVector; name = :A) T = foldl((x, y) -> promote_type(x, eltype(sanitize_SVector(y))), sites; init = Bool) return Sublat(sanitize_SVector.(float(T), sites), Symbol(name)) end #endregion ############################################################################################ # lattice #region lattice(s::Sublat, ss::Sublat...; kw...) = _lattice(promote(s, ss...)...; kw...) lattice(ss::AbstractVector{<:Sublat}; kw...) = _lattice(ss; kw...) # Start with an empty list of nranges, to be filled as they are requested Lattice(b::Bravais{T}, u::Unitcell{T}) where {T} = Lattice(b, u, Tuple{Int,T}[]) _lattice(ss::Sublat{T,E}...; bravais = (), dim = Val(E), type::Type{T´} = T, names = sublatname.(ss)) where {T,E,T´} = _lattice(ss, bravais, dim, type, names) _lattice(ss::AbstractVector{S}; bravais = (), dim = Val(E), type::Type{T´} = T, names = sublatname.(ss)) where {T,E,T´,S<:Sublat{T,E}} = _lattice(ss, bravais, dim, type, names) _lattice(ss, bravais, dim, type, names) = Lattice(Bravais(type, dim, bravais), unitcell(ss, names, postype(dim, type))) function lattice(lat::Lattice{T,E}; bravais = bravais_matrix(lat), dim = Val(E), type::Type{T´} = T, names = sublatnames(lat)) where {T,E,T´} u = unitcell(unitcell(lat), names, postype(dim, type)) b = Bravais(type, dim, bravais) return Lattice(b, u) end postype(dim, type) = SVector{dim,type} postype(::Val{E}, type) where {E} = SVector{E,type} function unitcell(sublats, names, postype::Type{S}) where {S<:SVector} sites´ = S[] offsets´ = [0] # length(offsets) == length(sublats) + 1 for s in eachindex(sublats) for site in sites(sublats[s]) push!(sites´, sanitize_SVector(S, site)) end push!(offsets´, length(sites´)) end return Unitcell(sites´, names, offsets´) end function unitcell(u::Unitcell{T´,E´}, names, postype::Type{S}) where {T´,E´,S<:SVector} sites´ = sanitize_SVector.(S, sites(u)) offsets´ = offsets(u) Unitcell(sites´, names, offsets´) end # with simple rename, don't copy sites unitcell(u::Unitcell{T,E}, names, postype::Type{S}) where {T,E,S<:SVector{E,T}} = Unitcell(sites(u), names, offsets(u)) #endregion ############################################################################################ # combine lattices - combine sublats, rename if equal name #region function combine(lats::Lattice{T,E,L}...) where {T,E,L} isapprox_modulo_shuffle(bravais_matrix.(lats)...) || throw(ArgumentError("To combine lattices they must all share the same Bravais matrix. They read $(bravais_matrix.(lats))")) bravais´ = bravais(first(lats)) unitcell´ = combine(unitcell.(lats)...) return Lattice(bravais´, unitcell´) end # without <:Any here, this method overwrites the one above combine(lats::Lattice{<:Any}...) = argerror("Tried to combine lattices with different type or different dimension or embedding dimension") function combine(ucells::Unitcell...) names´ = vcat(sublatnames.(ucells)...) sites´ = vcat(sites.(ucells)...) offsets´ = combined_offsets(offsets.(ucells)...) return Unitcell(sites´, names´, offsets´) end isapprox_modulo_shuffle() = true function isapprox_modulo_shuffle(s::AbstractMatrix, ss::AbstractMatrix...) for s´ in ss, c´ in eachcol(s´) any(c -> c ≈ c´ || c ≈ -c´, eachcol(s)) || return false end return true end combined_offsets(offsets...) = lengths_to_offsets(Iterators.flatten(diff.(offsets))) #endregion ############################################################################################ # neighbors # TODO: may be simplified/optimized #region function nrange(n, lat) for (n´, r) in nranges(lat) n == n´ && return r end r = compute_nrange(n, lat) push!(nranges(lat), (n, r)) return r end function compute_nrange(n, lat::Lattice{T}) where {T} latsites = sites(lat) dns = BoxIterator(zerocell(lat)) br = bravais_matrix(lat) # 128 is a heuristic cutoff for kdtree vs brute-force search if length(latsites) <= 128 dists = fill(T(Inf), n) for dn in dns iszero(dn) || ispositive(dn) || continue for (i, ri) in enumerate(latsites), (j, rj) in enumerate(latsites) j <= i && iszero(dn) && continue r = ri - rj + br * dn update_dists!(dists, r'r) end isfinite(last(dists)) || acceptcell!(dns, dn) end dist = sqrt(last(dists)) else tree = KDTree(latsites) dist = T(Inf) for dn in dns iszero(dn) || ispositive(dn) || continue for r0 in latsites r = r0 + br * dn dist = min(dist, compute_nrange(n, tree, r, nsites(lat))) end isfinite(dist) || acceptcell!(dns, dn) end end return dist end function update_dists!(dists, dist) len = length(dists) for (n, d) in enumerate(dists) isapprox(dist, d) && break if dist < d dists[n+1:len] .= dists[n:len-1] dists[n] = dist break end end return dists end function compute_nrange(n, tree, r::AbstractVector, nmax) for m in n:nmax _, dists = knn(tree, r, 1 + m, true) popfirst!(dists) unique_sorted_approx!(dists) length(dists) == n && return maximum(dists) end return convert(eltype(r), Inf) end function unique_sorted_approx!(v::AbstractVector) i = 1 xprev = first(v) for j in 2:length(v) if v[j] ≈ xprev xprev = v[j] else i += 1 xprev = v[i] = v[j] end end resize!(v, i) return v end function ispositive(ndist) result = false for i in ndist i == 0 || (result = i > 0; break) end return result end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
4698
############################################################################################ # mesh methods #region # Marching Tetrahedra mesh function mesh(rngs::Vararg{Any,L}) where {L} vmat = [SVector(pt) for pt in Iterators.product(rngs...)] verts = vec(vmat) cinds = CartesianIndices(vmat) neighs = marching_neighbors(cinds) # sorted neighbors of i, with n[i][j] > i return Mesh{L+1}(verts, neighs) end # forward neighbors, cind is a CartesianRange over vertices function marching_neighbors(cinds) linds = LinearIndices(cinds) matrix = [Int[] for _ in cinds] for cind in cinds forward = max(cind, first(cinds)):min(cind + oneunit(cind), last(cinds)) for cind´ in forward cind === cind´ && continue push!(matrix[cind], linds[cind´]) push!(matrix[cind´], linds[cind]) end end neighs = vec(matrix) return neighs end # simplices are not recomputed for performance function split_edge!(m, (i, j), k) i == j && return m if i > j i, j = j, i end delete_edge!(m, (i, j)) verts = vertices(m) push!(verts, k) push!(neighbors(m), Int[]) dst = length(verts) newneighs = intersect(neighbors(m, i), neighbors(m, j)) push!(newneighs, i, j) sort!(newneighs) for src in newneighs push!(neighbors(m, src), dst) push!(neighbors(m, dst), src) end return m end function delete_edge!(m, (i, j)) i == j && return m if i > j i, j = j, i end fast_setdiff!(neighbors(m, i), j) fast_setdiff!(neighbors(m, j), i) return m end # delete elements in c if it is not in rng function fast_setdiff!(c::Vector, rng) i = 0 for x in c x in rng && continue i += 1 c[i] = x end resize!(c, i) return c end # delete elements in c and d if the one in c is not in rng function fast_setdiff!((c, d)::Tuple{Vector,Vector}, rng) i = 0 for (i´, x) in enumerate(c) x in rng && continue i += 1 c[i] = x d[i] = d[i´] end resize!(c, i) resize!(d, i) return (c, d) end # groups of n all-to-all connected neighbors, sorted build_cliques(neighs, ::Val{N}) where {N} = rebuild_cliques!(NTuple{N,Int}[], neighs) rebuild_cliques!(mesh::Mesh) = rebuild_cliques!(simplices(mesh), neighbors(mesh)) function rebuild_cliques!(cliques::Vector{NTuple{N,Int}}, neighs) where {N} empty!(cliques) for (src, dsts) in enumerate(neighs) dsts_f = filter(>(src), dsts) # indexable forward neighbors for ids in Combinations(length(dsts_f), N - 1) if all_adjacent(ids, dsts_f, neighs) # clique = (src, dsts_f[ids]...), but non-allocating clique = ntuple(i -> i == 1 ? src : dsts_f[ids[i - 1]], Val(N)) push!(cliques, clique) end end end return cliques end # Check whether dsts_f[ids] are all mutual neighbors. ids are a total of nverts-1 indices # of dsts_f = neighbor_forward(neighs, src) function all_adjacent(ids, dsts_f, neighs) nids = length(ids) for (n, id) in enumerate(ids), n´ in n+1:nids dst = dsts_f[ids[n´]] dst in neighs[dsts_f[id]] || return false end return true end # ensure simplex orientation has normals pointing towards positive z function orient_simplices!(simplices, vertices::Vector{B}) where {E,B<:BandVertex{<:Any,E}} E <= 2 && return simplices for (s, simplex) in enumerate(simplices) if E > 2 k0 = base_coordinates(vertices[simplex[1]]) edges = ntuple(i -> base_coordinates(vertices[simplex[i+1]])-k0, Val(E-1)) volume = det(hcat(edges...)) if volume < 0 simplices[s] = switchlast(simplex) end end end return simplices end switchlast(s::NTuple{N}) where {N} = ntuple(i -> i < N-1 ? s[i] : s[2N-i-1], Val(N)) # Computes connected subsets from a list of neighbors, in the form of a (vsinds, svinds) # vsinds::Vector{Int} is the subset index for each band vertex # svinds::Vector{Vector{Int}} is a list of vertex indices for each subset function subsets(neighs::Vector{Vector{Int}}) vsinds = zeros(Int, length(neighs)) svinds = Vector{Int}[] sidx = 0 vidx = 1 while vidx !== nothing sidx += 1 sv = [vidx] push!(svinds, sv) vsinds[vidx] = sidx for i in sv, j in neighs[i] iszero(vsinds[j]) || continue vsinds[j] = sidx push!(sv, j) end sort!(sv) vidx = findfirst(iszero, vsinds) end return vsinds, svinds end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
8185
############################################################################################ # onsite and hopping #region onsite(o; kw...) = onsite(o, siteselector(; kw...)) onsite(o, sel::SiteSelector) = TightbindingModel(OnsiteTerm(o, sel, 1)) hopping(t; kw...) = hopping(t, hopselector(; kw...)) hopping(t, sel::HopSelector) = TightbindingModel(HoppingTerm(t, sel, 1)) plusadjoint(t) = t + t' ## filtering models, and modifying their selectors onsite(m::AbstractModel; kw...) = reduce(+, (_onsite(t; kw...) for t in allterms(m) if t isa Union{OnsiteTerm,ParametricOnsiteTerm}); init = TightbindingModel()) hopping(m::AbstractModel; kw...) = reduce(+, (_hopping(t; kw...) for t in allterms(m) if t isa Union{HoppingTerm,ParametricHoppingTerm}); init = TightbindingModel()) _onsite(o::OnsiteTerm; kw...) = TightbindingModel(OnsiteTerm(functor(o), siteselector(selector(o); kw...), coefficient(o))) _hopping(t::HoppingTerm; kw...) = TightbindingModel(HoppingTerm(functor(t), hopselector(selector(t); kw...), coefficient(t))) _onsite(o::ParametricOnsiteTerm; kw...) = ParametricModel(ParametricOnsiteTerm(functor(o), siteselector(selector(o); kw...), coefficient(o), is_spatial(o))) _hopping(t::ParametricHoppingTerm; kw...) = ParametricModel(ParametricHoppingTerm(functor(t), hopselector(selector(t); kw...), coefficient(t), is_spatial(t))) #endregion ############################################################################################ # @onsite, @hopping, @onsite! and @hopping! - Parametric models and model modifiers #region # Macros are needed to read out number of f arguments (N) and kwarg names (params). # A kw... is appended to kwargs in the actual function method definition to skip # non-applicable kwargs. # An alternative based on internals (m = first(methods(f)), Base.kwarg_decl(m) and m.nargs) # has been considered, but decided against due to its fragility and slow runtime ## Parametric models ## macro onsite(x, ys...) kw, f, N, params, spatial = parse_term("@onsite", x, ys...) return esc(:(Quantica.ParametricModel(Quantica.ParametricOnsiteTerm( Quantica.ParametricFunction{$N}($f, $(params)), Quantica.siteselector($kw), 1, $(spatial))))) end macro hopping(x, ys...) kw, f, N, params, spatial = parse_term("@hopping", x, ys...) return esc(:(Quantica.ParametricModel(Quantica.ParametricHoppingTerm( Quantica.ParametricFunction{$N}($f, $(params)), Quantica.hopselector($kw), 1, $(spatial))))) end ## Model modifiers ## macro onsite!(x, ys...) kw, f, N, params, spatial = parse_term("@onsite!", x, ys...) return esc(:(Quantica.OnsiteModifier(Quantica.ParametricFunction{$N}($f, $(params)), Quantica.siteselector($kw), $(spatial)))) end macro hopping!(x, ys...) kw, f, N, params, spatial = parse_term("@hopping!", x, ys...) # Since the default hopping range is neighbors(1), we need change the default to Inf for @hopping! return esc(:(Quantica.HoppingModifier(Quantica.ParametricFunction{$N}($f, $(params)), Quantica.hopselector_infrange($kw), $(spatial)))) end function parse_term(macroname, x, ys...) if x isa Expr && x.head == :parameters kw = x f, N, params, spatial = parse_term_body(macroname, only(ys)) else kw = parse_term_parameters(ys...) f, N, params, spatial = parse_term_body(macroname, x) end return kw, f, N, params, spatial end # parse keywords after a comma as if they were keyword arguments function parse_term_parameters(exs...) exs´ = maybe_kw.(exs) paramex = Expr(:parameters, exs´...) return paramex end maybe_kw(ex::Expr) = Expr(:kw, ex.args...) maybe_kw(ex::Symbol) = ex # Extracts normalized f, number of arguments and kwarg names from an anonymous function f function parse_term_body(macroname, f) if !(f isa Expr && (f.head == :-> || f.head == :-->)) msg = "Only $(macroname)(args -> body; kw...) syntax supported (or with -->). Received $(macroname)($f, ...) instead." throw(ArgumentError(msg)) end # change --> to -> and record change in spatial spatial = f.head == :-> !spatial && (f.head = :->) d = ExprTools.splitdef(f) # process keyword arguments, add splat kwargs = convert(Vector{Any}, get!(d, :kwargs, [])) d[:kwargs] = kwargs # in case it wasn't Vector{Any} originally if isempty(kwargs) params = Symbol[] push!(kwargs, :(_...)) # normalization : append _... to kwargs else params = get_kwname.(kwargs) if !isempty(params) && last(params) == :... params = params[1:end-1] # drop _... kwarg from params else push!(kwargs, :(_...)) # normalization : append _... to kwargs end end N = haskey(d, :args) ? length(d[:args]) : 0 f´ = ExprTools.combinedef(d) return f´, N, params, spatial end get_kwname(x::Symbol) = x get_kwname(x::Expr) = x.head === :kw ? x.args[1] : x.head # x.head == :... hopselector_infrange(; kw...) = hopselector(; range = Inf, kw...) #endregion ############################################################################################ # @onsite, @hopping conversions # each ParametricTerm gets converted, using `basemodel` and `modifier`, into two pieces #region zero_model(term::ParametricOnsiteTerm) = OnsiteTerm(r -> 0I, selector(term), coefficient(term)) zero_model(term::ParametricHoppingTerm) = HoppingTerm((r, dr) -> 0I, selector(term), coefficient(term)) function modifier(term::ParametricOnsiteTerm{N}) where {N} f = (o, args...; kw...) -> o + term(args...; kw...) pf = ParametricFunction{N+1}(f, parameters(term)) return OnsiteModifier(pf, selector(term), is_spatial(term)) end function modifier(term::ParametricHoppingTerm{N}) where {N} f = (t, args...; kw...) -> t + term(args...; kw...) pf = ParametricFunction{N+1}(f, parameters(term)) return HoppingModifier(pf, selector(term), is_spatial(term)) end basemodel(m::ParametricModel) = nonparametric(m) + TightbindingModel(zero_model.(terms(m))) # transforms the first argument in each model term to a parameter named pname model_ω_to_param(model::ParametricModel) = ParametricModel(nonparametric(model), model_ω_to_param.(terms(model))) model_ω_to_param(model::TightbindingModel) = model_ω_to_param(ParametricModel(model)) function model_ω_to_param(term::ParametricOnsiteTerm{N}, default = 0) where {N} # parameters(term) only needed for reporting, we omit adding :ω_internal f = (args...; ω_internal = default, kw...) -> term(ω_internal, args...; kw...) pf = ParametricFunction{N-1}(f, parameters(term)) return ParametricOnsiteTerm(pf, selector(term), coefficient(term), is_spatial(term)) end function model_ω_to_param(term::ParametricHoppingTerm{N}, default = 0) where {N} # parameters(term) only needed for reporting, we omit adding :ω_internal f = (args...; ω_internal = default, kw...) -> term(ω_internal, args...; kw...) pf = ParametricFunction{N-1}(f, parameters(term)) return ParametricHoppingTerm(pf, selector(term), coefficient(term), is_spatial(term)) end #endregion ############################################################################################ # interblock and intrablock #region interblock(m::AbstractModel, hams::AbstractHamiltonian...) = interblock(m, blockindices(hams)...) interblock(m::AbstractModel, inds...) = isempty(intersect(inds...)) ? Interblock(hopping(m), inds) : Interblock(m, inds) # if blocks overlap, don't exclude onsite terms intrablock(m::AbstractModel, inds) = Intrablock(m, inds) interblock(m::AbstractModifier, inds) = Interblock(m, inds) intrablock(m::AbstractModifier, inds) = Intrablock(m, inds) function blockindices(hams::NTuple{N,Any}) where {N} offset = 0 inds = ntuple(Val(N)) do i ns = nsites(lattice(hams[i])) rng = offset + 1:offset + ns offset += ns rng end return inds end block(m::Intrablock, b::OrbitalBlockStructure) = flatrange(b, block(m)) block(m::Interblock, b::OrbitalBlockStructure) = flatrange.(Ref(b), block(m)) block(::Union{AbstractModel,AbstractModifier}, b...) = missing #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
22107
############################################################################################ # Observables - common tools #region abstract type IndexableObservable end # any type that can be sliced into (current and ldos) fermi(ω::C, kBT = 0; atol = sqrt(eps(real(C)))) where {C} = iszero(kBT) ? ifelse(abs(ω) < atol, C(0.5), ifelse(real(ω) <= 0, C(1), C(0))) : C(1/(exp(ω/kBT) + 1)) normal_size(h::AbstractHamiltonian) = normal_size(blockstructure(h)) function normal_size(b::OrbitalBlockStructure) n = first(blocksizes(b)) iseven(n) && allequal(blocksizes(b)) || argerror("A Nambu Hamiltonian must have an even and uniform number of orbitals per site, got $(blocksizes(b)).") return n ÷ 2 end trace_tau(g, ::Missing) = tr(g) function trace_tau(g, tau) trace = zero(eltype(g)) for i in axes(g, 2) trace += g[i, i] * tau[i] end return trace end mul_tau!(g, ::Missing) = g mul_tau!(::Missing, g) = g mul_tau!(g, tau::Vector) = (g .*= tau') mul_tau!(tau::Vector, g) = (g .*= tau) tauz_diag(i, normalsize) = ifelse(iseven(fld1(i, normalsize)), -1, 1) taue_diag(i, normalsize) = ifelse(iseven(fld1(i, normalsize)), 0, 1) check_contact_slice(gs) = (rows(gs) isa Integer && cols(gs) isa Integer) || argerror("Please use a Green slice of the form `g[i::Integer, j::Integer]` or `g[i::Integer]`") check_same_contact_slice(gs) = (rows(gs) isa Integer && cols(gs) === rows(gs)) || argerror("Please use a Green slice of the form `g[i::Integer]`") check_different_contact_slice(gs) = (rows(gs) isa Integer && cols(gs) != rows(gs)) || argerror("Please use a Green slice of the form `g[i::Integer, j::Integer] with `i ≠ j`") check_nodiag_axes(gs::GreenSlice) = check_nodiag_axes(rows(gs)), check_nodiag_axes(rows(gs)) check_nodiag_axes(::DiagIndices) = argerror("Diagonal indexing not yet supported for this function") check_nodiag_axes(_) = nothing #endregion ############################################################################################ # Operators #region function current(h::AbstractHamiltonian; charge = -I, direction = 1) current = parametric(h, @onsite!(o -> zero(o)), @hopping!((t, r, dr) -> im*dr[direction]*charge*t)) return Operator(current) end #endregion ############################################################################################ # Integrator - integrates a function f along a complex path ωcomplex(ω::Real), connecting ωi # The path is piecewise linear in the form of a sawtooth with a given ± slope #region struct Integrator{I,T,P,O<:NamedTuple,M,F} integrand::I # call!(integrand, ω::Complex; params...)::Union{Number,Array{Number}} points::P # a tuple of complex points that form the sawtooth integration path result::T # can be missing (for scalar integrand) or a mutable type (nonscalar) opts::O # kwargs for quadgk omegamap::M # function that maps ω to parameters post::F # function to apply to the integrand at the end of integration end #region ## Constructor ## function Integrator(result, f, pts::NTuple{<:Any,Number}; omegamap = Returns((;)), imshift = missing, post = identity, slope = 1, opts...) imshift´ = imshift === missing ? sqrt(eps(promote_type(typeof.(float.(real.(pts)))...))) : float(imshift) pts´ = iszero(slope) ? pts .+ (im * imshift´) : sawtooth(imshift´, slope, pts) opts´ = NamedTuple(opts) return Integrator(f, pts´, result, opts´, omegamap, post) end Integrator(f, pts::NTuple{<:Any,Number}; kw...) = Integrator(missing, f, pts; kw...) sawtooth(is, sl, ωs) = _sawtooth(is, sl, (), ωs...) _sawtooth(is, sl, ::Tuple{}, ω1, ωs...) = _sawtooth(is, sl, (ω1 + im * is,), ωs...) _sawtooth(is, sl, ωs´, ωn, ωs...) = _sawtooth(is, sl, (ωs´..., 0.5 * (real(last(ωs´)) + ωn) + im * (is + sl * 0.5*(ωn - real(last(ωs´)))), ωn + im * is), ωs...) _sawtooth(is, sl, ωs´) = ωs´ #endregion #region ## API ## integrand(I::Integrator) = I.integrand points(I::Integrator) = I.points options(I::Integrator) = I.opts ## call! ## # scalar version function call!(I::Integrator{<:Any,Missing}; params...) fx = x -> call!(I.integrand, x; I.omegamap(x)..., params...) result, err = quadgk(fx, I.points...; I.opts...) result´ = I.post(result) return result´ end # nonscalar version function call!(I::Integrator; params...) fx! = (y, x) -> (y .= call!(I.integrand, x; I.omegamap(x)..., params...)) result, err = quadgk!(fx!, I.result, I.points...; I.opts...) result´ = I.post(result) # note: post-processing is not element-wise & can be in-place return result´ end (I::Integrator)(; params...) = copy(call!(I; params...)) #endregion #endregion ############################################################################################ # ldos: local spectral density # d = ldos(::GreenSolution; kernel = I) -> d[sites...]::Vector # d = ldos(::GreenSlice; kernel = I) -> d(ω; params...)::Vector # Here ldos is given as Tr(ρᵢᵢ * kernel) where ρᵢᵢ is the spectral function at site i # Here is the generic fallback that uses G. Any more specialized methods need to be added # to each GreenSolver #region struct LocalSpectralDensitySolution{T,E,L,G<:GreenSolution{T,E,L},K} <: IndexableObservable gω::G kernel::K # should return a float when applied to gω[CellSite(n,i)] end struct LocalSpectralDensitySlice{T,E,L,G<:GreenSlice{T,E,L},K} gs::G kernel::K # should return a float when applied to gω[CellSite(n,i)] end #region ## Constructors ## ldos(gω::GreenSolution; kernel = I) = LocalSpectralDensitySolution(gω, kernel) function ldos(gs::GreenSlice{T}; kernel = I) where {T} rows(gs) === cols(gs) || argerror("Cannot take ldos of a GreenSlice with rows !== cols") return LocalSpectralDensitySlice(gs, kernel) end #endregion #region ## API ## greenfunction(d::LocalSpectralDensitySlice) = d.g kernel(d::Union{LocalSpectralDensitySolution,LocalSpectralDensitySlice}) = d.kernel ldos_kernel(g, kernel::UniformScaling) = - kernel.λ * imag(tr(g)) / π ldos_kernel(g, kernel) = -imag(tr(g * kernel)) / π Base.getindex(d::LocalSpectralDensitySolution; selectors...) = d[getindex(lattice(d.gω); selectors...)] Base.getindex(d::LocalSpectralDensitySolution, s::SiteSelector) = d[getindex(lattice(d.gω), s)] Base.getindex(d::LocalSpectralDensitySolution{T}, i) where {T} = append_diagonal!(T[], d.gω, i, d.kernel, post = x -> -imag(x)/π) |> maybe_OrbitalSliceArray(sites_to_orbs(i, d.gω)) # see greenfunction.jl (d::LocalSpectralDensitySlice)(ω; params...) = copy(call!(d, ω; params...)) # fallback through LocalSpectralDensitySolution - overload to allow a more efficient path function call!(d::LocalSpectralDensitySlice{T}, ω; params...) where {T} orbslice_or_contact = first(orbinds_or_contactinds(d.gs)) gω = call!(parent(d.gs), ω; params...) l = ldos(gω; kernel = d.kernel) return l[orbslice_or_contact] end #endregion #endregion ############################################################################################ # current: current density Jᵢⱼ(ω) as a function of a charge operator # d = current(::GreenSolution[, dir]; charge) -> d[sites...]::SparseMatrixCSC{SVector{E,T}} # d = current(::GreenSlice[, dir]; charge) -> d(ω; params...)::SparseMatrixCSC{SVector{E,T}} # Computes the zero-temperature equilibrium current density Jᵢⱼ from site j to site i # Jᵢⱼ(ω) = (2/h) rᵢⱼ Re Tr[(Hᵢⱼgʳⱼᵢ - gʳᵢⱼHⱼᵢ)Q] # Here charge = Q, where Q is usually qe*I for normal, and qe*τz/2 for Nambu systems # `dir` projects Jᵢⱼ along a certain direction, or takes the norm if missing # We use a default charge = -I, corresponding to normal currents densities in units of e/h #region struct CurrentDensitySolution{T,E,L,G<:GreenSolution{T,E,L},K,V<:Union{Missing,SVector}} <: IndexableObservable gω::G charge::K # should return a float when traced with gʳᵢⱼHᵢⱼ cache::GreenSolutionCache{T,L,G} # memoizes g[sites] direction::V end struct CurrentDensitySlice{T,E,L,G<:GreenFunction{T,E,L},K,V<:Union{Missing,SVector}} g::G charge::K # should return a float when traced with gʳᵢⱼHᵢⱼ orbslice::OrbitalSliceGrouped{T,E,L} direction::V end #region ## Constructors ## current(gω::GreenSolution; direction = missing, charge = -I) = CurrentDensitySolution(gω, charge, GreenSolutionCache(gω), sanitize_direction(direction, gω)) function current(gs::GreenSlice; direction = missing, charge = -I) rows(gs) === cols(gs) || argerror("Cannot currently take ldos of a GreenSlice with rows !== cols") g = parent(gs) orbslice = orbrows(gs) return CurrentDensitySlice(g, charge, orbslice, sanitize_direction(direction, g)) end sanitize_direction(dir, ::GreenSolution{<:Any,E}) where {E} = _sanitize_direction(dir, Val(E)) sanitize_direction(dir, ::GreenFunction{<:Any,E}) where {E} = _sanitize_direction(dir, Val(E)) _sanitize_direction(::Missing, ::Val) = missing _sanitize_direction(dir::Integer, ::Val{E}) where {E} = unitvector(dir, SVector{E,Int}) _sanitize_direction(dir::SVector{E}, ::Val{E}) where {E} = dir _sanitize_direction(dir::NTuple{E}, ::Val{E}) where {E} = SVector(dir) _sanitize_direction(_, ::Val{E}) where {E} = argerror("Current direction should be an Integer or a NTuple/SVector of embedding dimension $E") #endregion #region ## API ## charge(d::Union{CurrentDensitySolution,CurrentDensitySlice}) = d.charge direction(d::Union{CurrentDensitySolution,CurrentDensitySlice}) = d.direction Base.getindex(d::CurrentDensitySolution; kw...) = d[getindex(lattice(d.gω); kw...)] Base.getindex(d::CurrentDensitySolution, scell::CellSites) = d[lattice(hamiltonian(d.gω))[scell]] Base.getindex(d::CurrentDensitySolution, i::Union{Integer,Colon}) = d[latslice(parent(d.gω), i)] Base.getindex(d::CurrentDensitySolution, ls::LatticeSlice) = current_matrix(d.gω, ls, d) # no call! support here function (d::CurrentDensitySlice)(ω; params...) gω = call!(d.g, ω; params...) ls = d.orbslice cu = current(gω; charge = d.charge) return cu[ls] end function current_matrix(gω, ls, d) h = hamiltonian(parent(gω)) # see slices.jl for unflat_getindex current = unflat_sparse_slice(h, ls, ls, (hij, cij) -> maybe_project(apply_charge_current(hij, cij, d), d.direction)) return current end function apply_charge_current(hij_block::B, (ci, cj), d::CurrentDensitySolution{T,E}) where {T,E,B} ni, i = cell(ci), siteindex(ci) nj, j = cell(cj), siteindex(cj) ni == nj && i == j && return zero(SVector{E,T}) gji = unblock(mask_block(B, d.cache[cj, ci])) gij = unblock(mask_block(B, d.cache[ci, cj])) hij = unblock(hij_block) hji = hij' hgghQ = (hij * gji - gij * hji) * d.charge # safeguard in case (hij * gji - gij * hji) isa Number and d.charge isa UniformScaling Iij = 2 * real(maybe_trace(hgghQ)) lat = lattice(d.gω) ri = site(lat, i, ni) rj = site(lat, j, nj) Jij = (ri - rj) * Iij return Jij end maybe_project(J, ::Missing) = norm(J) maybe_project(J, dir) = dot(dir, J) maybe_trace(m::UniformScaling) = m.λ maybe_trace(m) = tr(m) #endregion #endregion ############################################################################################ # conductance(gs::GreenSlice; nambu = false) -> G(ω; params...)::Real # For gs = g[i::Int, j::Int = i] -> we get zero temperature Gᵢⱼ = dIᵢ/dVⱼ in units of e^2/h # where i, j are contact indices # Gᵢⱼ = e^2/h × Tr{[δᵢⱼi(Gʳ-Gᵃ)Γⁱ-GʳΓⁱGᵃΓʲ]} (nambu = false) # Gᵢⱼ = e^2/h × Tr{[δᵢⱼi(Gʳ-Gᵃ)Γⁱτₑ-GʳΓⁱτzGᵃΓʲτₑ]} (nambu = true) # and where τₑ = [1 0; 0 0] and τz = [1 0; 0 -1] in Nambu space, and ω = eV. #region struct Conductance{T,E,L,C,G<:GreenFunction{T,E,L}} g::G i::Int # contact index for Iᵢ j::Int # contact index for Vⱼ τezdiag::Tuple{C,C} # diagonal of τₑ and τz, or (missing, missing) Γ::Matrix{Complex{T}} # prealloc workspace for selfenergy! (over all contacts) GrΓi::Matrix{Complex{T}} # prealloc workspace GʳⱼᵢΓⁱ GaΓj::Matrix{Complex{T}} # prealloc workspace GᵃᵢⱼΓʲ GΓGΓ::Matrix{Complex{T}} # prealloc workspace GʳⱼᵢΓⁱGᵃᵢⱼΓʲ end #region ## Constructors ## function conductance(gs::GreenSlice{T}; nambu = false) where {T} check_contact_slice(gs) i = rows(gs) j = cols(gs) g = parent(gs) ni = norbitals(contactorbitals(g), i) nj = norbitals(contactorbitals(g), j) Γ = similar_contactΣ(g) if nambu nsize = normal_size(hamiltonian(g)) τezdiag = (taue_diag.(1:nj, nsize), tauz_diag.(1:ni, nsize)) else τezdiag = (missing, missing) end GrΓi = Matrix{Complex{T}}(undef, nj, ni) GaΓj = Matrix{Complex{T}}(undef, ni, nj) GΓGΓ = Matrix{Complex{T}}(undef, nj, nj) return Conductance(g, i, j, τezdiag, Γ, GrΓi, GaΓj, GΓGΓ) end #endregion #region ## API ## currentcontact(G) = G.i biascontact(G) = G.j function (G::Conductance)(ω; params...) τe, τz = G.τezdiag gω = call!(G.g, ω; params...) gʳⱼᵢ = gω[G.j, G.i] gᵃᵢⱼ = gʳⱼᵢ' Γi = selfenergy!(G.Γ, gω, G.i; onlyΓ = true) mul!(G.GrΓi, gʳⱼᵢ, Γi) Γj = G.i == G.j ? Γi : selfenergy!(G.Γ, gω, G.j; onlyΓ = true) mul!(G.GaΓj, gᵃᵢⱼ, Γj) mul_tau!(G.GrΓi, τz) # no-op if τz is missing mul!(G.GΓGΓ, G.GrΓi, G.GaΓj) # the -Tr{GʳΓⁱτzGᵃΓʲτₑ} term cond = - real(trace_tau(G.GΓGΓ, τe)) # simple trace if τe is missing if G.i == G.j # add the Tr(i(Gʳ-Gᵃ)Γⁱτₑ) term gmg = gʳⱼᵢ gmg .-= gᵃᵢⱼ iGmGΓ = mul!(G.GΓGΓ, gmg, Γi, im, 0) cond += real(trace_tau(iGmGΓ, τe)) # simple trace if τe is missing end return cond end #endregion #endregion ############################################################################################ # tramsission(gs::GreenSlice) -> normal Tᵢⱼ = Tr{GʳΓⁱGᵃΓʲ} from contact j to i ≠ j #region struct Transmission{G<:Conductance} conductance::G end #region ## Constructors ## function transmission(gs::GreenSlice) check_different_contact_slice(gs) return Transmission(conductance(gs; nambu = false)) end #endregion #region ## API ## Base.parent(t::Transmission) = t.conductance function (T::Transmission)(ω; params...) G = T.conductance gω = call!(G.g, ω; params...) gʳⱼᵢ = gω[G.j, G.i] gᵃᵢⱼ = gʳⱼᵢ' Γi = selfenergy!(G.Γ, gω, G.i; onlyΓ = true) mul!(G.GrΓi, gʳⱼᵢ, Γi) Γj = G.i == G.j ? Γi : selfenergy!(G.Γ, gω, G.j; onlyΓ = true) mul!(G.GaΓj, gᵃᵢⱼ, Γj) mul!(G.GΓGΓ, G.GrΓi, G.GaΓj) t = real(tr(G.GΓGΓ)) return t end #endregion #endregion ############################################################################################ # densitymatrix: equilibrium (static) ρ::DensityMatrix # ρ = densitymatrix(g::GreenSlice, (ωmin, ωmax); opts...) # ρ(mu, kBT = 0; params...) gives the DensityMatrix that is solved with an integral over (ωmin, ωmax) # ρ(mu, kBT; params...) = -(1/π) Im ∫dω f(ω) g(ω; params...) # ρ = densitymatrix(g::GreenSlice; opts...) uses a GreenSolver-specific algorithm # Keywords opts are passed to QuadGK.quadgk for the integral or the algorithm used #region struct DensityMatrix{S,G<:GreenSlice} solver::S gs::G end # Default solver (integration in complex plane) struct DensityMatrixIntegratorSolver{I} ifunc::I end #region ## Constructors ## (ρ::DensityMatrix)(mu = 0, kBT = 0; params...) = ρ.solver(mu, kBT; params...) |> maybe_OrbitalSliceArray(axes(ρ.gs)) (s::DensityMatrixIntegratorSolver)(mu, kBT; params...) = s.ifunc(mu, kBT; params...) # redirects to specialized method densitymatrix(gs::GreenSlice; kw...) = densitymatrix(solver(parent(gs)), gs::GreenSlice; kw...) # generic fallback densitymatrix(s::AppliedGreenSolver, gs::GreenSlice; kw...) = argerror("Dedicated `densitymatrix` algorithm not implemented for $(nameof(typeof(s))). Use generic one instead.") # default integrator solver densitymatrix(gs::GreenSlice, ωmax::Number; opts...) = densitymatrix(gs, (-ωmax, ωmax); opts...) function densitymatrix(gs::GreenSlice{T}, (ωmin, ωmax)::Tuple; omegamap = Returns((;)), imshift = missing, atol = 1e-7, opts...) where {T} check_nodiag_axes(gs) result = similar_Matrix(gs) opts´ = (; omegamap, imshift, slope = 1, post = gf_to_rho!, atol, opts...) integratorfunc(mu, kBT; params...) = iszero(kBT) ? Integrator(result, GFermi(gs, T(mu), T(kBT)), (ωmin, mu); opts´...)(; params...) : Integrator(result, GFermi(gs, T(mu), T(kBT)), (ωmin, mu, ωmax); opts´...)(; params...) return DensityMatrix(DensityMatrixIntegratorSolver(integratorfunc), gs) end function gf_to_rho!(x) x .= x .- x' x .*= -1/(2π*im) return x end #endregion #region ## API ## struct GFermi{G<:GreenSlice,T} gs::G mu::T kBT::T end function call!(gf::GFermi, ω; params...) gω = call!(gf.gs, ω; params...) f = fermi(ω - gf.mu, gf.kBT) gω .*= f return gω end #endregion ############################################################################################ # josephson # The equilibrium (static) Josephson current, in units of qe/h, *from* lead i is given by # Iᵢ = Re ∫dω J(ω; params...), where J(ω; params...) = (qe/h) × 2f(ω)Tr[(ΣʳᵢGʳ - GʳΣʳᵢ)τz] # J = josephson(g::GreenSlice, ωmax; contact = i, kBT = 0, phases) # J(ω; params...) -> scalar or vector [J(ϕⱼ) for ϕⱼ in phases] if `phases` is an # integer (num phases from 0 to π) or a collection of ϕ's # A phase ϕ can be applied by gauging it away from the lead and into its coupling: # Σʳᵢ(ϕ) = UᵩΣʳᵢUᵩ' and Gʳ(ϕ) = [1+Gʳ(Σʳᵢ-Σʳᵢ(ϕ))]⁻¹Gʳ, where Uᵩ = exp(iϕτz/2). # I = josephson(Integrator(J, (-ωmax, 0, ωmax); post = real, opts...) # Keywords opts are passed to quadgk for the integral #region struct JosephsonDensity{T<:AbstractFloat,P<:Union{Missing,AbstractArray},G<:GreenFunction{T}} g::G kBT::T contactind::Int # contact index tauz::Vector{Int} # precomputed diagonal of tauz phaseshifts::P # missing or collection of phase shifts to apply traces::P # preallocated workspace Σ::Matrix{Complex{T}} # preallocated workspace, full self-energy ΣggΣ::Matrix{Complex{T}} # preallocated workspace Σ´::Matrix{Complex{T}} # preallocated workspace g´::Matrix{Complex{T}} # preallocated workspace den::Matrix{Complex{T}} # preallocated workspace cisτz::Vector{Complex{T}} # preallocated workspace end struct Josephson{S} solver::S end # default solver (integration in complex plane) struct JosephsonIntegratorSolver{I} ifunc::I end #region ## Constructors ## (j::Josephson)(kBT = 0; params...) = j.solver(kBT; params...) (s::JosephsonIntegratorSolver)(kBT; params...) = s.ifunc(kBT; params...) function josephson(gs::GreenSlice{T}, ωmax; omegamap = Returns((;)), phases = missing, imshift = missing, atol = 1e-7, opts...) where {T} check_nodiag_axes(gs) check_same_contact_slice(gs) contact = rows(gs) g = parent(gs) Σfull = similar_contactΣ(g) Σ = similar_contactΣ(g, contact) normalsize = normal_size(hamiltonian(g)) tauz = tauz_diag.(axes(Σ, 1), normalsize) phases´, traces = sanitize_phases_traces(phases, T) jd(kBT) = JosephsonDensity(g, T(kBT), contact, tauz, phases´, traces, Σfull, Σ, similar(Σ), similar(Σ), similar(Σ), similar(tauz, Complex{T})) opts´ = (; omegamap, imshift, slope = 1, post = real, atol, opts...) ifunc(kBT; params...) = iszero(kBT) ? Integrator(traces, jd(kBT), (-ωmax, 0); opts´...)(; params...) : Integrator(traces, jd(kBT), (-ωmax, 0, ωmax); opts´...)(; params...) return Josephson(JosephsonIntegratorSolver(ifunc)) end sanitize_phases_traces(::Missing, ::Type{T}) where {T} = missing, missing sanitize_phases_traces(phases::Integer, ::Type{T}) where {T} = sanitize_phases_traces(range(0, π, length = phases), T) function sanitize_phases_traces(phases, ::Type{T}) where {T} phases´ = Complex{T}.(phases) traces = similar(phases´) return phases´, traces end #endregion #region ## API ## temperature(J::JosephsonDensity) = J.kBT contact(J::JosephsonDensity) = J.contactind phaseshifts(I::Integrator{<:JosephsonDensity}) = phaseshifts(integrand(I)) phaseshifts(J::JosephsonDensity) = real.(J.phaseshifts) numphaseshifts(J::JosephsonDensity) = numphaseshifts(J.phaseshifts) numphaseshifts(::Missing) = 0 numphaseshifts(phaseshifts) = length(phaseshifts) function call!(J::JosephsonDensity, ω; params...) gω = call!(J.g, ω; params...) f = fermi(ω, J.kBT) traces = josephson_traces(J, gω, f) return traces end function josephson_traces(J, gω, f) gr = gω[J.contactind, J.contactind] Σi = selfenergy!(J.Σ, gω, J.contactind) return josephson_traces!(J, gr, Σi, f) end josephson_traces!(J::JosephsonDensity{<:Any,Missing}, gr, Σi, f) = josephson_one_trace!(J, gr, Σi, f) function josephson_traces!(J, gr, Σi, f) for (i, phaseshift) in enumerate(J.phaseshifts) gr´, Σi´ = apply_phaseshift!(J, gr, Σi, phaseshift) J.traces[i] = josephson_one_trace!(J, gr´, Σi´, f) end return J.traces end # 2 f(ω) Tr[(Σi * gr - gr * Σi) * τz] function josephson_one_trace!(J, gr, Σi, f) ΣggΣ = J.ΣggΣ mul!(ΣggΣ, Σi, gr) mul!(ΣggΣ, gr, Σi, -1, 1) trace = 2 * f * trace_tau(ΣggΣ, J.tauz) return trace end # Σi´ = U Σi U' and gr´ = (gr₀⁻¹ - Σi´)⁻¹ = (1+gr*(Σi-Σi´))⁻¹gr function apply_phaseshift!(J, gr, Σi, phaseshift) Σi´ = J.Σ´ U = J.cisτz phasehalf = phaseshift/2 @. U = cis(-phasehalf * J.tauz) @. Σi´ = U * Σi * U' den = J.den one!(den) tmp = J.g´ @. tmp = Σi - Σi´ mul!(den, gr, tmp, 1, 1) # den = 1-gr * (Σi - Σi´) gr´ = ldiv!(J.g´, lu!(den), gr) # gr´ = (1+gr*(Σi-Σi´))⁻¹gr return gr´, Σi´ end #endregion #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
6677
############################################################################################ # Non-numerical sanitizers #region sanitize_Vector_of_Symbols(name::Symbol) = [name] sanitize_Vector_of_Symbols(names) = Symbol[convert(Symbol, name) for name in names] sanitize_orbitals(o::Val) = o sanitize_orbitals(o::Int) = Val(o) sanitize_orbitals(o) = allequal(o) ? sanitize_orbitals(first(o)) : o sanitize_Val(o::Val) = o sanitize_Val(o) = Val(o) #endregion ############################################################################################ # Array sanitizers (padding with zeros if necessary) #region sanitize_Vector_of_Type(::Type{T}, len, x::T´) where {T,T´<:Union{T,Val}} = fill(val_convert(T, x), len) function sanitize_Vector_of_Type(::Type{T}, len, xs) where {T} xs´ = sanitize_Vector_of_Type(T, xs) length(xs´) == len || throw(ArgumentError("Received a collection with $(length(xs´)) elements, should have $len.")) return xs´ end function sanitize_Vector_of_Type(::Type{T}, xs) where {T} xs´ = T[val_convert(T, x) for x in xs] return xs´ end val_convert(T, ::Val{N}) where {N} = convert(T, N) val_convert(T, x) = convert(T, x) sanitize_Vector_of_SVectors(::Type{T}, ::Tuple{}) where {T} = T[] sanitize_Vector_of_SVectors(::Type{T}, vs) where {T} = eltype(vs) <: Number ? [sanitize_SVector(T, vs)] : [sanitize_SVector.(T, vs)...] sanitize_SVector(::Tuple{}) = SVector{0,Float64}() sanitize_SVector(x::Number) = SVector{1}(x) sanitize_SVector(v) = convert(SVector{length(v)}, v) sanitize_SVector(::Type{T}, v::SVector{<:Any,T}) where {T<:Number} = v sanitize_SVector(::Type{T}, v) where {T<:Number} = isempty(v) ? SVector{0,T}() : convert.(T, sanitize_SVector(v)) sanitize_SVector(::Type{SVector{N,T}}, v::SVector{N}) where {N,T} = convert(SVector{N,T}, v) sanitize_SVector(::Type{SVector{N,T}}, v) where {N,T} = SVector{N,T}(ntuple(i -> i > length(v) ? zero(T) : convert(T, v[i]), Val(N))) function sanitize_SMatrix(::Type{S}, x, (rows, cols) = (E, L)) where {T<:Number,E,L,S<:SMatrix{E,L,T}} t = ntuple(Val(E*L)) do l j, i = fldmod1(l, E) i <= max(rows, length(x[j])) && j <= max(cols, length(x)) ? T(x[j][i]) : zero(T) end return SMatrix{E,L,T}(t) end function sanitize_SMatrix(::Type{S}, s::AbstractMatrix, (rows, cols) = (E, L)) where {T<:Number,E,L,S<:SMatrix{E,L,T}} t = ntuple(Val(E*L)) do l j, i = fldmod1(l, E) i <= rows && j <= cols && checkbounds(Bool, s, i, j) ? convert(T, s[i,j]) : zero(T) end return SMatrix{E,L,T}(t) end function sanitize_Matrix(::Type{T}, E, cols::Tuple) where {T} m = zeros(T, E, length(cols)) for (j, col) in enumerate(cols), i in 1:E if i <= length(col) m[i, j] = col[i] end end return m end function sanitize_Matrix(::Type{T}, E, m::AbstractMatrix) where {T} m´ = zeros(T, E, size(m, 2)) axs = intersect.(axes(m), axes(m´)) m´[axs...] .= convert.(T, view(m, axs...)) return m´ end #endregion ############################################################################################ # TEL types # Family of types with well-defined T,E,L #region const TELtypes{T,E,L} = Union{Lattice{T,E,L},LatticeSlice{T,E,L},AbstractHamiltonian{T,E,L}, GreenFunction{T,E,L},GreenSlice{T,E,L},GreenSolution{T,E,L},IJVBuilder{T,E,L},CSCBuilder{T,E,L}} #endregion ############################################################################################ # CellIndices sanitizers #region # an inds::Tuple fails some tests because convert(Tuple, ::UnitRange) doesnt exist, but # convert(SVector, ::UnitRange) does. Used e.g. in compute_or_retrieve_green @ sparselu.jl # We should also demand indices to be unique, since siteindsdict cannot have duplicates sanitize_cellindices(inds::Tuple) = SVector(_check_unique(inds)) sanitize_cellindices(inds) = _check_unique(inds) _check_unique(x::Colon) = x function _check_unique(inds) allunique(inds) || argerror("Cell indices should be unique") return inds end sanitize_cellindices(c::CellIndices{0}, ::Val{L}) where {L} = zerocellinds(c, Val(L)) sanitize_cellindices(c::CellIndices{L}, ::Val{L}) where {L} = c sanitize_cellindices(c::CellIndices{0}, ::Val{0}) = c sanitize_cellindices(c::CellIndices{L}, ::TELtypes{<:Any,<:Any,L}) where {L} = c sanitize_cellindices(c::CellIndices{0}, ::TELtypes{<:Any,<:Any,0}) = c sanitize_cellindices(c::CellIndices{0}, ::TELtypes{<:Any,<:Any,L}) where {L} = zerocellinds(c, Val(L)) sanitize_cellindices(c::CellIndices{L}, ::TELtypes{<:Any,<:Any,L´}) where {L,L´} = argerror("Expected a cell index of dimension $L´, got $L") #endregion ############################################################################################ # block sanitizers # if a is the result of indexing an OrbitalSliceArray with an CellSitePos, ensure it can # be the result of a model term function. Required for e.g. mean-field models. #region sanitize_block(::Type{C}, a) where {C<:Number} = complex(C)(only(a)) sanitize_block(::Type{C}, a) where {C<:SMatrix} = C(a) # here we assume a is already of the correct size and let if fail later otherwise sanitize_block(::Type{C}, a) where {C<:SMatrixView} = a #endregion ############################################################################################ # Supercell sanitizers #region sanitize_supercell(::Val{L}, ::Tuple{}) where {L} = SMatrix{L,0,Int}() sanitize_supercell(::Val{L}, ns::NTuple{L´,NTuple{L,Int}}) where {L,L´} = sanitize_SMatrix(SMatrix{L,L´,Int}, ns) sanitize_supercell(::Val{L}, n::Tuple{Int}) where {L} = SMatrix{L,L,Int}(first(n) * I) sanitize_supercell(::Val{L}, ns::NTuple{L,Int}) where {L} = SMatrix{L,L,Int}(Diagonal(SVector(ns))) sanitize_supercell(::Val{L}, s::Tuple{SMatrix{<:Any,<:Any,Int}}) where {L} = only(s) sanitize_supercell(::Val{L}, v) where {L} = throw(ArgumentError("Improper supercell specification $v for an $L lattice dimensions, see `supercell`")) #endregion ############################################################################################ # Eigen sanitizers #region sanitize_eigen(ε::AbstractVector, Ψs::AbstractVector{<:AbstractVector}) = sanitize_eigen(ε, hcat(Ψs...)) sanitize_eigen(ε, Ψ) = Eigen(sorteigs!(sanitize_eigen(ε), sanitize_eigen(Ψ))...) sanitize_eigen(x::AbstractArray{<:Real}) = complex.(x) sanitize_eigen(x::AbstractArray{<:Complex}) = x function sorteigs!(ϵ::AbstractVector, ψ::AbstractMatrix) p = Vector{Int}(undef, length(ϵ)) p´ = similar(p) sortperm!(p, ϵ, by = real, alg = Base.DEFAULT_UNSTABLE) Base.permute!!(ϵ, copy!(p´, p)) Base.permutecols!!(ψ, copy!(p´, p)) return ϵ, ψ end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
7652
############################################################################################ # selector constructors #region siteselector(s::NamedTuple) = siteselector(; s...) siteselector(; region = missing, sublats = missing, cells = missing) = SiteSelector(region, sublats, cells) siteselector(s::SiteSelector; region = s.region, sublats = s.sublats, cells = s.cells) = SiteSelector(region, sublats, cells) hopselector(h::NamedTuple) = hopselector(; h...) hopselector(; region = missing, sublats = missing, dcells = missing, range = neighbors(1)) = HopSelector(region, sublats, dcells, range) hopselector(s::HopSelector; region = s.region, sublats = s.sublats, dcells = s.dcells, range = s.range) = HopSelector(region, sublats, dcells, range, s.adjoint) neighbors(n::Int) = Neighbors(n) neighbors(n::Int, lat::Lattice) = nrange(n, lat) #endregion ############################################################################################ # Base.in constructors #region function Base.in((s, r)::Tuple{Int,SVector{E,T}}, sel::AppliedSiteSelector{T,E}) where {T,E} return !isnull(sel) && inregion(r, sel) && insublats(s, sel) end function Base.in((s, r, cell)::Tuple{Int,SVector{E,T},SVector{L,Int}}, sel::AppliedSiteSelector{T,E,L}) where {T,E,L} return !isnull(sel) && incells(cell, sel) && inregion(r, sel) && insublats(s, sel) end ## Cannot add this, as it is ambiguous for L == E # function Base.in((i, cell)::Tuple{Int,SVector{L,Int}}, sel::AppliedSiteSelector{T,E,L}) where {T,E,L} # lat = lattice(sel) # r = site(lat, i, cell) # return (i, r, cell) in sel # end ## We therefore also skip this for consistency # function Base.in(((j, i), (nj, ni))::Tuple{Pair,Pair}, sel::AppliedHopSelector) # lat = lattice(sel) # ri, rj = site(lat, i, ni), site(lat, j, nj) # r, dr = rdr(rj => ri) # dcell = ni - nj # return ((j, i), (r, dr), dcell) in sel # end function Base.in(((sj, si), (r, dr), dcell)::Tuple{Pair,Tuple,SVector}, sel::AppliedHopSelector) return !isnull(sel) && !isonsite(dr) && indcells(dcell, sel) && insublats(sj => si, sel) && iswithinrange(dr, sel) && inregion((r, dr), sel) end isonsite((j, i), dn) = ifelse(i == j && iszero(dn), true, false) isonsite(dr) = iszero(dr) #endregion ############################################################################################ # foreach_site, foreach_cell, foreach_hop #region # foreach_cell(f,...) should be called with a boolean function f that returns whether the # cell should be mark as accepted when BoxIterated function foreach_cell(f, sel::AppliedSiteSelector) isnull(sel) && return nothing lat = lattice(sel) cells_list = cells(sel) if isempty(cells_list) # no cells specified iter = BoxIterator(zerocell(lat)) keepgoing = true # will search until we find at least one for cell in iter found = f(cell) if found || keepgoing acceptcell!(iter, cell) found && (keepgoing = false) end end else for cell in cells_list f(cell) end end return nothing end function foreach_cell(f, sel::AppliedHopSelector) isnull(sel) && return nothing lat = lattice(sel) dcells_list = dcells(sel) if isempty(dcells_list) # no dcells specified iter = BoxIterator(zerocell(lat)) for dn in iter found = f(dn) found && acceptcell!(iter, dn) end else for dn in dcells_list f(dn) end end return nothing end function foreach_site(f, sel::AppliedSiteSelector, cell::SVector) isnull(sel) && return nothing lat = lattice(sel) for s in sublats(lat) insublats(s, sel) || continue is = siterange(lat, s) for i in is r = site(lat, i, cell) inregion(r, sel) && f(s, i, r) end end return nothing end function foreach_hop(f, sel::AppliedHopSelector, kdtrees::Vector{<:KDTree}, ni::SVector = zerocell(lattice(sel))) isnull(sel) && return nothing lat = lattice(sel) _, rmax = sel.range # source cell at origin nj = zero(ni) found = false for si in sublats(lat), sj in sublats(lat) insublats(sj => si, sel) || continue js = siterange(lat, sj) for j in js is = inrange_targets(site(lat, j, nj - ni), lat, si, rmax, kdtrees) for i in is isonsite((j, i), ni - nj) && continue r, dr = rdr(site(lat, j, nj) => site(lat, i, ni)) # Make sure we don't stop searching cells until we reach minimum range isbelowrange(dr, sel) && (found = true) if iswithinrange(dr, sel) && inregion((r, dr), sel) found = true f((si, sj), (i, j), (r, dr)) end end end end return found end # Although range can be (rmin, rmax) we return all targets within rmax. # Those below rmin get filtered later function inrange_targets(rsource, lat, si, rmax, kdtrees) if isfinite(rmax) if !isassigned(kdtrees, si) sitepos = sites(lat, si) kdtrees[si] = KDTree(sitepos) end targetlist = inrange(kdtrees[si], rsource, rmax) targetlist .+= offsets(lat)[si] else # need collect for type-stability targetlist = collect(siterange(lat, si)) end return targetlist end ## Unused # function foreach_site(f, sel::AppliedSiteSelector, ls::LatticeSlice) # lat = parent(ls) # islice = 0 # for scell in subcells(ls) # n = cell(scell) # for i in siteindices(scell) # r = site(lat, i, n) # islice += 1 # if (i, r, n) in sel # f(i, r, n, islice) # end # end # end # return nothing # end # function foreach_hop(f, sel::AppliedHopSelector, ls::LatticeSlice, kdtree::KDTree) # lat = lattice(sel) # _, rmax = sel.range # found = false # isfiniterange = isfinite(rmax) # jslice = 0 # for scellj in subcells(ls) # nj = cell(scellj) # for j in siteindices(scellj) # jslice += 1 # rj = site(lat, j, nj) # if isfiniterange # targetlist = inrange(kdtree, rj, rmax) # for islice in targetlist # ni, i = ls[islice] # ri = site(lat, i, ni) # r, dr = rdr(rj => ri) # dcell = ni - nj # if (j => i, (r, dr), dcell) in sel # found = true # f((i, j), (r, dr), (ni, nj), (islice, jslice)) # end # end # else # islice = 0 # for scelli in subcells(ls) # ni = cell(scelli) # dcell = ni - nj # for i in siteindices(scelli) # islice += 1 # isonsite((j, i), dcell) && continue # ri = site(lat, i, ni) # r, dr = rdr(rj => ri) # if (j => i, (r, dr), dcell) in sel # found = true # f((i, j), (r, dr), (ni, nj), (islice, jslice)) # end # end # end # end # end # end # return found # end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
18346
############################################################################################ # show tools #region display_as_tuple(v, prefix = "") = isempty(v) ? "()" : string("(", prefix, join(v, string(", ", prefix)), ifelse(length(v) == 1, ",)", ")")) display_rounded_vectors(vs) = isempty(vs) ? "[]" : display_rounded_vector.(vs) display_rounded_vector(v) = round.(v, digits = 6) pluraltext(m, sing) = ifelse(length(m) == 1, "1 $sing", "$(length(m)) $(sing)s") displayparameter(::Type{<:Function}) = "Function" displayparameter(::Type{T}) where {T} = "$T" displayrange(r::Real) = round(r, digits = 6) displayrange(::Missing) = "any" displayrange(nr::Neighbors) = "Neighbors($(Int(nr)))" displayrange(rs::Tuple) = "($(displayrange(first(rs))), $(displayrange(last(rs))))" #endregion ############################################################################################ # Lattice #region Base.summary(::Sublat{T,E}) where {T,E} = "Sublat{$E,$T} : sublattice of $T-typed sites in $(E)D space" Base.show(io::IO, s::Sublat) = print(io, summary(s), "\n", " Sites : $(nsites(s)) Name : $(displayname(s))") ### Base.summary(::Lattice{T,E,L}) where {T,E,L} = "Lattice{$T,$E,$L} : $(L)D lattice in $(E)D space" function Base.show(io::IO, lat::Lattice) i = get(io, :indent, "") print(io, i, summary(lat), "\n", "$i Bravais vectors : $(display_rounded_vectors(bravais_vectors(lat))) $i Sublattices : $(nsublats(lat)) $i Names : $(displaynames(lat)) $i Sites : $(display_as_tuple(sublatlengths(lat))) --> $(nsites(lat)) total per unit cell") end displaynames(l::Lattice) = display_as_tuple(sublatnames(l), ":") displayname(s::Sublat) = sublatname(s) == Symbol(:_) ? "pending" : string(":", sublatname(s)) #endregion ############################################################################################ # CellSites #region function Base.show(io::IO, c::CellSites) i = get(io, :indent, "") print(io, i, summary(c), "\n") end Base.summary(c::CellSites{L,V}) where {L,V} = "CellSites{$L,$V} : $(display_nsites(c)) in $(display_cell(c))" display_nsites(::CellSites{<:Any,Colon}) = "all sites" display_nsites(c::CellSites) = length(c) == 1 ? "1 site" : "$(length(c)) sites" display_cell(c::CellSites{0}) = "cell zero" display_cell(c::CellSites) = iszero(cell(c)) ? "cell zero" : "cell $(cell(c))" #endregion ############################################################################################ # LatticeSlice #region Base.summary(::SiteSlice{T,E,L}) where {T,E,L} = "SiteSlice{$T,$E,$L} : collection of subcells of sites for a $(L)D lattice in $(E)D space" Base.summary(::OrbitalSliceGrouped{T,E,L}) where {T,E,L} = "OrbitalSliceGrouped{$T,$E,$L} : collection of subcells of orbitals (grouped by sites) for a $(L)D lattice in $(E)D space" function Base.show(io::IO, ls::LatticeSlice) i = get(io, :indent, "") print(io, i, summary(ls), "\n", "$i Cells : $(length(cellsdict(ls))) $i Cell range : $(isempty(ls) ? "empty" : boundingbox(ls)) $i Total sites : $(missing_or_nsites(ls))") end missing_or_nsites(::OrbitalSlice) = "unknown" missing_or_nsites(s) = nsites(s) #endregion ############################################################################################ # Selectors #region function Base.show(io::IO, s::Union{SiteSelector,HopSelector}) i = get(io, :indent, "") ioindent = IOContext(io, :indent => i * " ") print(io, i, summary(s), "\n") print_selector(io, s) end Base.summary(m::SiteSelector) = "SiteSelector: a rule that defines a finite collection of sites in a lattice" Base.summary(m::HopSelector) = "HopSelector: a rule that defines a finite collection of hops between sites in a lattice" function print_selector(io::IO, s::SiteSelector) i = get(io, :indent, "") print(io, "$(i) Region : $(s.region === missing ? "any" : "Function") $(i) Sublattices : $(s.sublats === missing ? "any" : display_maybe_function(s.sublats)) $(i) Cells : $(s.cells === missing ? "any" : display_maybe_function(s.cells))") end function print_selector(io::IO, s::HopSelector) i = get(io, :indent, "") print(io, "$(i) Region : $(s.region === missing ? "any" : "Function") $(i) Sublattice pairs : $(s.sublats === missing ? "any" : display_maybe_function(s.sublats)) $(i) Cell distances : $(s.dcells === missing ? "any" : display_maybe_function(s.dcells)) $(i) Hopping range : $(displayrange(s.range)) $(i) Reverse hops : $(s.adjoint)") end display_maybe_function(::Function) = "Function" display_maybe_function(x) = x #endregion ############################################################################################ # Models and Modifiers #region function Base.show(io::IO, m::TightbindingModel) i = get(io, :indent, "") ioindent = IOContext(io, :indent => i * " ") print(io, i, summary(m)) foreach(t -> print(ioindent, "\n", t), terms(m)) end function Base.show(io::IO, m::ParametricModel) i = get(io, :indent, "") ioindent = IOContext(io, :indent => i * " ") print(io, i, summary(m)) foreach(t -> print(ioindent, "\n", t), terms(m)) foreach(t -> print(ioindent, "\n", t), terms(nonparametric(m))) end function Base.show(io::IO, t::Union{AbstractModelTerm,Modifier}) i = get(io, :indent, "") ioindent = IOContext(io, :indent => i * " ") print(io, i, summary(t), "\n") print_selector(io, t.selector) if !(t isa Modifier) print(io, "\n", "$(i) Coefficient : $(t.coefficient)") end if t isa AbstractParametricTerm || t isa Modifier print(io, "\n", "$(i) Argument type : $(display_argument_type(t))") print(io, "\n", "$(i) Parameters : $(parameters(t))") end end Base.summary(m::TightbindingModel) = "TightbindingModel: model with $(pluraltext(terms(m), "term"))" Base.summary(m::ParametricModel) = "ParametricModel: model with $(pluraltext(allterms(m), "term"))" Base.summary(::OnsiteTerm{F}) where {F} = "OnsiteTerm{$(displayparameter(F))}:" Base.summary(::HoppingTerm{F}) where {F} = "HoppingTerm{$(displayparameter(F))}:" Base.summary(::ParametricOnsiteTerm{N}) where {N} = "ParametricOnsiteTerm{ParametricFunction{$N}}" Base.summary(::ParametricHoppingTerm{N}) where {N} = "ParametricHoppingTerm{ParametricFunction{$N}}" Base.summary(::OnsiteModifier{N}) where {N} = "OnsiteModifier{ParametricFunction{$N}}:" Base.summary(::HoppingModifier{N}) where {N} = "HoppingModifier{ParametricFunction{$N}}:" display_argument_type(t) = is_spatial(t) ? "spatial" : "non-spatial" #endregion ############################################################################################ # AbstractHamiltonian and Operators #region function Base.show(io::IO, h::Union{Hamiltonian,ParametricHamiltonian,Operator,BarebonesOperator}) i = get(io, :indent, "") print(io, i, summary(h), "\n", showstring(h, i)) showextrainfo(io, i, h) end showstring(h::Union{Hamiltonian,ParametricHamiltonian}, i) = "$i Bloch harmonics : $(length(harmonics(h))) $i Harmonic size : $((n -> "$n × $n")(size(h, 1))) $i Orbitals : $(norbitals(h)) $i Element type : $(displaytype(blocktype(h))) $i Onsites : $(nonsites(h)) $i Hoppings : $(nhoppings(h)) $i Coordination : $(round(coordination(h), digits = 5))" showstring(h::BarebonesOperator, i) = "$i Bloch harmonics : $(length(harmonics(h))) $i Harmonic size : $((n -> "$n × $n")(size(h, 1))) $i Element type : $(eltype(h)) $i Nonzero elements : $(nnz(h))" showstring(o::Operator, i) = showstring(hamiltonian(o), i) Base.summary(h::Hamiltonian{T,E,L}) where {T,E,L} = "Hamiltonian{$T,$E,$L}: Hamiltonian on a $(L)D Lattice in $(E)D space" Base.summary(h::ParametricHamiltonian{T,E,L}) where {T,E,L} = "ParametricHamiltonian{$T,$E,$L}: Parametric Hamiltonian on a $(L)D Lattice in $(E)D space" Base.summary(h::Operator{H}) where {T,E,L,H<:AbstractHamiltonian{T,E,L}} = "Operator{$T,$E,$L}: Operator on a $(L)D Lattice in $(E)D space" Base.summary(h::BarebonesOperator{L}) where {L} = "BarebonesOperator{$L}: a simple collection of $(L)D Bloch harmonics" displaytype(::Type{S}) where {N,T,S<:SMatrix{N,N,T}} = "$N × $N blocks ($T)" displaytype(::Type{S}) where {N,T,S<:SMatrixView{N,N,T}} = "At most $N × $N blocks ($T)" displaytype(::Type{T}) where {T} = "scalar ($T)" # fallback showextrainfo(io, i, h) = nothing showextrainfo(io, i, h::ParametricHamiltonian) = print(io, i, "\n", "$i Parameters : $(parameters(h))") showextrainfo(io, i, o::Operator) = showextrainfo(io, i, hamiltonian(o)) #endregion ############################################################################################ # OpenHamiltonian #region function Base.show(io::IO, oh::OpenHamiltonian) i = get(io, :indent, "") print(io, i, summary(oh), "\n", "$i Number of contacts : $(length(selfenergies(oh))) $i Contact solvers : $(solvernames(oh))", "\n") ioindent = IOContext(io, :indent => i * " ") show(ioindent, hamiltonian(oh)) end Base.summary(oh::OpenHamiltonian{T,E,L}) where {T,E,L} = "OpenHamiltonian{$T,$E,$L}: Hamiltonian with a set of open contacts" solvernames(oh::OpenHamiltonian) = nameof.(typeof.(solver.(selfenergies(oh)))) #endregion ############################################################################################ # AbstractEigenSolver #region function Base.show(io::IO, s::AbstractEigenSolver) i = get(io, :indent, "") print(io, i, summary(s)) end Base.summary(s::AbstractEigenSolver) = "AbstractEigenSolver ($(Base.nameof(typeof(s))))" #endregion ############################################################################################ # AppliedEigenSolver #region function Base.show(io::IO, s::AppliedEigenSolver) i = get(io, :indent, "") ioindent = IOContext(io, :indent => i * " ") print(io, i, summary(s), "\n") end Base.summary(::AppliedEigenSolver{T,L}) where {T,L} = "AppliedEigenSolver{$T,$L}: eigensolver over an $L-dimensional parameter manifold of type $T" #endregion ############################################################################################ # Spectrum #region function Base.show(io::IO, s::Spectrum) i = get(io, :indent, "") ioindent = IOContext(io, :indent => i * " ") print(io, i, summary(s)) println(ioindent, "\nEnergies:") show(ioindent, MIME("text/plain"), energies(s)) println(ioindent, "\nStates:") show(ioindent, MIME("text/plain"), states(s)) end Base.summary(::Spectrum{T,B}) where {T,B} = "Spectrum{$T,$B} :" #endregion ############################################################################################ # AbstractMesh #region Base.summary(::Mesh{V}) where {V} = "Mesh{$(nameof(V))}: Mesh with vertices of type $(nameof(V))" Base.summary(::Subband{T,L}) where {T,L} = "Subband{$T,$L}: Subband in a $L-dimensional space (like energy-momentum)" function Base.show(io::IO, m::AbstractMesh) i = get(io, :indent, "") print(io, i, summary(m), "\n", "$i Mesh dim : $(dim(m)) $i Space dim : $(embdim(m)) $i Vertices : $(length(vertices(m))) $i Edges : $(isempty(neighbors(m)) ? 0 : sum(length, neighbors(m)) ÷ 2) $i Simplices : $(length(simplices(m)))") end #endregion ############################################################################################ # Bandstructure #region function Base.show(io::IO, b::Bandstructure) i = get(io, :indent, "") print(io, i, summary(b), "\n", "$i Subbands : $(nsubbands(b)) $i Vertices : $(nvertices(b)) $i Edges : $(nedges(b)) $i Simplices : $(nsimplices(b))") end Base.summary(::Bandstructure{T,E,L}) where {T,E,L} = "Bandstructure{$T,$E,$L}: $(E)D Bandstructure over a $L-dimensional parameter space of type $T" #endregion ############################################################################################ # GreenFunction, GreenSolution and GreenSlice #region function Base.show(io::IO, g::GreenFunction) i = get(io, :indent, "") Σs = selfenergies(contacts(g)) print(io, i, summary(g), "\n", "$i Solver : $(typename(solver(g))) $i Contacts : $(length(Σs)) $i Contact solvers : $(display_as_tuple(typename.(solver.(Σs)))) $i Contact sizes : $(display_as_tuple(nsites.(orbslice.(Σs))))", "\n") ioindent = IOContext(io, :indent => i * " ") show(ioindent, parent(g)) end Base.summary(g::GreenFunction{T,E,L}) where {T,E,L} = "GreenFunction{$T,$E,$L}: Green function of a $(typename(hamiltonian(g))){$T,$E,$L}" function Base.show(io::IO, g::GreenSolution) i = get(io, :indent, "") print(io, i, summary(g)) end Base.summary(g::GreenSolution{T,E,L,S}) where {T,E,L,S} = "GreenSolution{$T,$E,$L}: Green function at arbitrary positions, but at a fixed energy" function Base.show(io::IO, g::GreenSlice) i = get(io, :indent, "") print(io, i, summary(g)) end Base.summary(g::GreenSlice{T,E,L}) where {T,E,L} = "GreenSlice{$T,$E,$L}: Green function at arbitrary energy, but at a fixed lattice positions" #endregion ############################################################################################ # Conductance #region function Base.show(io::IO, G::Conductance) i = get(io, :indent, "") print(io, i, summary(G), "\n", "$i Current contact : $(currentcontact(G)) $i Bias contact : $(biascontact(G))") end Base.summary(::Conductance{T}) where {T} = "Conductance{$T}: Zero-temperature conductance dIᵢ/dVⱼ from contacts i,j, in units of e^2/h" #endregion ############################################################################################ # Transmission #region function Base.show(io::IO, T::Transmission) i = get(io, :indent, "") print(io, i, summary(T), "\n", "$i From contact : $(biascontact(parent(T))) $i To contact : $(currentcontact(parent(T)))") end Base.summary(::Transmission) = "Transmission: total transmission between two different contacts" #endregion ############################################################################################ # Integrator #region function Base.show(io::IO, I::Integrator) i = get(io, :indent, "") print(io, i, summary(I), "\n", "$i Integration path : $(points(I)) $i Integration options : $(display_namedtuple(options(I))) $i Integrand : ") ioindent = IOContext(io, :indent => i * " ") show(ioindent, integrand(I)) end Base.summary(::Integrator) = "Integrator: Complex-plane integrator" display_namedtuple(nt::NamedTuple) = isempty(nt) ? "()" : "$nt" #endregion ############################################################################################ # Josephson (integrand) #region function Base.show(io::IO, J::JosephsonDensity) i = get(io, :indent, "") print(io, summary(J), "\n", "$i kBT : $(temperature(J)) $i Contact : $(contact(J)) $i Number of phase shifts : $(numphaseshifts(J))") end Base.summary(::JosephsonDensity{T}) where {T} = "JosephsonDensity{$T}" #endregion ############################################################################################ # DensityMatrix #region function Base.show(io::IO, d::DensityMatrix) i = get(io, :indent, "") print(io, summary(d)) end Base.summary(::DensityMatrix{S}) where {S} = "DensityMatrix: density matrix on specified sites using solver of type $(nameof(S))" #endregion ############################################################################################ # Josephson #region function Base.show(io::IO, j::Josephson) i = get(io, :indent, "") print(io, summary(j)) end Base.summary(::Josephson{S}) where {S} = "Josephson: equilibrium Josephson current at a specific contact using solver of type $(nameof(S))" #endregion ############################################################################################ # ldos #region function Base.show(io::IO, D::Union{LocalSpectralDensitySolution, LocalSpectralDensitySlice}) i = get(io, :indent, "") print(io, i, summary(D), "\n", "$i kernel : $(kernel(D))") end Base.summary(::LocalSpectralDensitySolution{T}) where {T} = "LocalSpectralDensitySolution{$T} : local density of states at fixed energy and arbitrary location" Base.summary(::LocalSpectralDensitySlice{T}) where {T} = "LocalSpectralDensitySlice{$T} : local density of states at a fixed location and arbitrary energy" #endregion ############################################################################################ # current #region function Base.show(io::IO, J::Union{CurrentDensitySolution, CurrentDensitySlice}) i = get(io, :indent, "") print(io, i, summary(J), "\n", "$i charge : $(charge(J)) $i direction : $(direction(J))") end Base.summary(::CurrentDensitySolution{T}) where {T} = "CurrentDensitySolution{$T} : current density at a fixed energy and arbitrary location" Base.summary(::CurrentDensitySlice{T}) where {T} = "CurrentDensitySlice{$T} : current density at a fixed location and arbitrary energy" #endregion ############################################################################################ # OrbitalSliceMatrix #region # For simplified printing of the array typename function Base.showarg(io::IO, ::OrbitalSliceMatrix{<:Any,M}, toplevel) where {M} toplevel || print(io, "::") print(io, "OrbitalSliceMatrix{$M}") end function Base.showarg(io::IO, ::OrbitalSliceVector{<:Any,M}, toplevel) where {M} toplevel || print(io, "::") print(io, "OrbitalSliceVector{$M}") end #endregion ############################################################################################ # IJVBuilder #region function Base.show(io::IO, b::IJVBuilder) i = get(io, :indent, "") print(io, i, summary(b), "\n", "$i Harmonics : $(length(harmonics(b))) $i IJV tuples : $(display_ijvs(b)) $i Element type : $(displaytype(blocktype(b))) $i Modifiers : $(display_modifiers(b))") end display_modifiers(b::IJVBuilder) = modifiers(b) === missing ? "missing" : length(modifiers(b)) display_ijvs(b::IJVBuilder) = display_as_tuple(length.(collector.(harmonics(b)))) Base.summary(::IJVBuilder{T,E,L}) where {T,E,L} = "IJVBuilder{$T,$E,$L}: AbstractHamiltonian builder based on IJV tuples (row, col, value)" #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
15685
############################################################################################ # slice of Lattice and LatticeSlice - returns a LatticeSlice #region Base.getindex(lat::Lattice; kw...) = lat[siteselector(; kw...)] Base.getindex(lat::Lattice, kw::NamedTuple) = lat[siteselector(; kw...)] Base.getindex(lat::Lattice, ls::LatticeSlice) = ls Base.getindex(lat::Lattice, ss::SiteSelector) = lat[apply(ss, lat)] # Special case for unbounded selector Base.getindex(lat::Lattice, ::SiteSelectorAll) = lat[siteselector(; cells = zerocell(lat))] function Base.getindex(lat::Lattice, as::AppliedSiteSelector) L = latdim(lat) csites = CellSites{L,Vector{Int}}[] if !isnull(as) sinds = Int[] foreach_cell(as) do cell isempty(sinds) || (sinds = Int[]) cs = CellSites(cell, sinds) foreach_site(as, cell) do s, i, r push!(siteindices(cs), i) end if isempty(cs) return false else push!(csites, cs) return true end end end cellsdict = CellSitesDict{L}(cell.(csites), csites) return LatticeSlice(lat, cellsdict) end Base.getindex(l::Lattice, c::AnyCellSites) = LatticeSlice(l, [apply(sanitize_cellindices(c, l), l)]) Base.getindex(ls::LatticeSlice; kw...) = getindex(ls, siteselector(; kw...)) Base.getindex(ls::LatticeSlice, kw::NamedTuple) = getindex(ls, siteselector(; kw...)) Base.getindex(ls::LatticeSlice, ss::SiteSelector, args...) = getindex(ls, apply(ss, ls), args...) # return cell, siteindex of the i-th site of LatticeSlice function Base.getindex(l::LatticeSlice, i::Integer) offset = 0 for scell in cellsdict(l) ninds = length(siteindices(scell)) if ninds + offset < i offset += ninds else return cell(scell), siteindices(scell)[i-offset] end end @boundscheck(boundserror(l, i)) return zerocell(lattice(l)), 0 end function Base.getindex(latslice::SiteSlice, as::AppliedSiteSelector) lat = parent(latslice) L = latdim(lat) cellsdict´ = CellSitesDict{L}() isnull(as) && return SiteSlice(lat, cellsdict´) sinds = Int[] for subcell in cellsdict(latslice) dn = cell(subcell) subcell´ = CellSites(dn, sinds) for i in siteindices(subcell) r = site(lat, i, dn) if (i, r, dn) in as push!(siteindices(subcell´), i) end end if !isempty(subcell´) set!(cellsdict´, cell(subcell´), subcell´) sinds = Int[] # start new site list end end return SiteSlice(lat, cellsdict´) end function Base.getindex(latslice::OrbitalSliceGrouped, as::AppliedSiteSelector) lat = parent(latslice) L = latdim(lat) cellsdict´ = CellOrbitalsGroupedDict{L}() isnull(as) && return OrbitalSliceGrouped(lat, cellsdict´) oinds = Int[] ogroups = Dictionary{Int,UnitRange{Int}}() for subcell in cellsdict(latslice) dn = cell(subcell) subcell´ = CellOrbitalsGrouped(dn, oinds, ogroups) orbs´ = orbindices(subcell´) for (i, orbrng) in pairs(orbgroups(subcell)) r = site(lat, i, dn) if (i, r, dn) in as append!(orbs´, orbrng) set!(ogroups, i, orbrng) end end if !isempty(subcell´) set!(cellsdict´, cell(subcell´), subcell´) # start new orb list oinds = Int[] ogroups = Dictionary{Int,UnitRange{Int}}() end end return OrbitalSliceGrouped(lat, cellsdict´) end # function Base.getindex(latslice::OrbitalSliceGrouped, cs::CellSites) # lat = parent(latslice) # cs´ = apply(cs, lat) # dn = cell(cs´) # cd = cellsdict(latslice) # groups = haskey(cd, dn) ? orbgroups(cd[dn]) : argerror("cell not found in lattice slice") # groups´ = Dictionary{Int,UnitRange{Int}}() # orbs´ = Int[] # for i in siteindices(cs´) # if haskey(groups, i) # orbrange = groups[i] # append!(orbs´, orbrange) # set!(groups´, i, orbrange) # else # argerror("cellsite not found in lattice slice") # end # end # cellsorbs´ = CellOrbitalsGrouped(dn, orbs´, groups´) # cellsdict´ = cellinds_to_dict(cellsorbs´) # return OrbitalSliceGrouped(lat, cellsdict´) # end #endregion ############################################################################################ # unflat_sparse_slice: slice of Hamiltonian h[latslice] - returns a SparseMatrix{B,Int} # This is a more efficient slice builder than mortar, but does not flatten B # Elements::B can be transformed by `post(hij, (ci, cj))` with `h[latslice, latslice, post]` # Here ci and cj are single-site `CellSite` for h # ParametricHamiltonian deliberately not supported, as the output is not updatable #region function unflat_sparse_slice(h::Hamiltonian, lsrows::LS, lscols::LS = lsrows, post = (hij, cij) -> hij) where {LS<:LatticeSlice} # @assert lattice(h) === lattice(ls) # TODO: fails upon plotting a current density (see tutorial) cszero = zerocellsites(h, 1) # like `sites(1)`, but with explicit cell B = typeof(post(zero(blocktype(h)), (cszero, cszero))) nrows, ncols = length(lsrows), length(lscols) builder = CSC{B}(ncols) hars = harmonics(h) for colcs in cellsites(lscols) colcell = cell(colcs) colsite = siteindices(colcs) for har in hars rowcell = colcell + dcell(har) rowsubcell = findsubcell(rowcell, lsrows) rowsubcell === nothing && continue rowoffset = offsets(lsrows, rowcell) rowsubcellinds = siteindices(rowsubcell) # rowsubcellinds are the site indices in original unitcell for subcell = rowcell # rowoffset is the latslice site offset for the rowsubcellinds sites hmat = unflat(matrix(har)) hrows = rowvals(hmat) for ptr in nzrange(hmat, colsite) hrow = hrows[ptr] for (irow, rowsubcellind) in enumerate(rowsubcellinds) if hrow == rowsubcellind rowcs = CellSite(rowcell, hrow) hij, cij = nonzeros(hmat)[ptr], (rowcs, colcs) # hrow is the original unitcell site index for row. # We need the latslice site index lsrow lsrow = rowoffset + irow pushtocolumn!(builder, lsrow, post(hij, cij)) end end end end finalizecolumn!(builder) end return sparse(builder, nrows, ncols) end #endregion ############################################################################################ # combine, combine! and intersect! #region function combine(ls::S, lss::S...) where {S<:LatticeSlice} lat = parent(ls) all(l -> l === lat, parent.(lss)) || argerror("Cannot combine LatticeSlices of different lattices") sc = combine(cellsdict.((ls, lss...))...) return LatticeSlice(lat, sc) end combine(d) = d combine(d1::D, d2::D, ds::D...) where {D<:CellIndicesDict} = mergewith(combine_subcells, d1, d2, ds...) combine_subcells(c::C, cs::C...) where {C<:CellSites} = CellSites(cell(c), union(siteindices(c), siteindices.(cs)...)) combine_subcells(c::C, cs::C...) where {C<:CellOrbitals} = CellOrbitals(cell(c), union(orbindices(c), orbindices.(cs)...)) function combine_subcells(c::C, cs::C...) where {C<:CellOrbitalsGrouped} groups´ = merge(orbgroups(c), orbgroups.(cs)...) indices´ = union(orbindices(c), orbindices.(cs)...) return CellOrbitalsGrouped(cell(c), indices´, groups´) end #endregion ############################################################################################ # grow and growdiff # LatticeSlice generated by hoppings in h and not contained in seed latslice #region function grow(ls::LatticeSlice, h::AbstractHamiltonian) checksamelattice(ls, h) cdict = grow(cellsdict(ls), h) return LatticeSlice(parent(ls), cdict) end function growdiff(ls::LatticeSlice, h::AbstractHamiltonian) checksamelattice(ls, h) cdict = cellsdict(ls) cdict´ = grow(cdict, h) setdiff!(cdict´, cdict) return LatticeSlice(parent(ls), cdict´) end checksamelattice(ls, h) = parent(ls) === lattice(h) || argerror("Tried to grow a LatticeSlice with a Hamiltonian defined on a different Lattice") function grow(css::Union{CellSitesDict{L},CellOrbitalsGroupedDict{L}}, h::AbstractHamiltonian) where {L} css´ = CellSitesDict{L}() for cs in css c = cell(cs) for har in harmonics(h) c´ = c + dcell(har) s = findsubcell(c´, css´) if s === nothing cs´ = CellSites(c´) insert!(css´, c´, cs´) else cs´ = s end mat = unflat(har) for col in siteindices(cs), ptr in nzrange(mat, col) row = rowvals(mat)[ptr] push!(siteindices(cs´), row) end end end for cs in css´ unique!(sort!(siteindices(cs))) end return CellSitesDict{L}(cell.(css´), css´) end function Base.setdiff!(cdict::CellSitesDict, cdict0::Union{CellSitesDict,CellOrbitalsGroupedDict}) for cs in cdict cs0 = findsubcell(cell(cs), cdict0) cs0 === nothing && continue setdiff!(siteindices(cs), siteindices(cs0)) end deleteif!(isempty, cdict) return cdict end function deleteif!(test, d::Dictionary) for (key, val) in pairs(d) test(val) && delete!(d, key) end return d end #endregion ############################################################################################ # convert SiteSlice to a 0D Lattice # build a 0D Lattice using the sites in LatticeSlice #region function lattice0D(ls::LatticeSlice, store = missing) lat = parent(ls) missing_or_empty!(store) sls = [sublat(collect(sublatsites(ls, s, store)); name = sublatname(lat, s)) for s in sublats(lat)] return lattice(sls) end # positions of sites in a given sublattice. Pushes selected slice indices into store function sublatsites(l::LatticeSlice, s::Integer, store = missing) n = 0 gen = ((missing_or_push!(store, n); site(lattice(l), i, cell(subcell))) for subcell in cellsdict(l) for i in siteindices(subcell) if (n += 1; i in siterange(lattice(l), s))) return gen end #endregion ############################################################################################ # reordered_site_orbitals # convert a list of site indices for an OrbitalSliceGrouped or CellOrbitalsGroupedDict # to a list of their of orbital indices #region function reordered_site_orbitals(siteinds, orbs::Union{OrbitalSliceGrouped,CellOrbitalsGroupedDict}) rngs = collect(orbranges(orbs)) # consecutive ranges of orbitals for each site in orbs orbinds = Int[] # will store the reotdered orbital indices for each site for siteind in siteinds append!(orbinds, rngs[siteind]) end return orbinds end #endregion ############################################################################################ # sites_to_orbs: convert sites to orbitals, preserving site groups if possible # sites_to_orbs_nogroups: converts sites to orbitals, without site groups #region #region ## sites_to_orbs ## no-ops sites_to_orbs(s::AnyOrbitalSlice, _) = s sites_to_orbs(c::AnyCellOrbitalsDict, _) = c sites_to_orbs(c::AnyCellOrbitals, _) = c # unused # sites_to_orbs_nogroups(cs::CellOrbitals, _) = cs ## DiagIndices sites_to_orbs(d::DiagIndices, g) = DiagIndices(sites_to_orbs(parent(d), g), kernel(d)) ## convert SiteSlice -> OrbitalSliceGrouped sites_to_orbs(kw::NamedTuple, g) = sites_to_orbs(siteselector(; kw...), g) sites_to_orbs(s::SiteSelector, g) = sites_to_orbs(lattice(g)[s], g) sites_to_orbs(i::Union{Colon,Integer}, g) = orbslice(contacts(g), i) sites_to_orbs(l::SiteSlice, g) = OrbitalSliceGrouped(lattice(l), sites_to_orbs(cellsdict(l), blockstructure(g))) sites_to_orbs(l::SiteSlice, s::OrbitalSliceGrouped) = s[l] ## convert CellSitesDict to CellOrbitalsGroupedDict sites_to_orbs(c::CellSitesDict, g) = sites_to_orbs(c, blockstructure(g)) function sites_to_orbs(cellsdict::CellSitesDict{L}, os::OrbitalBlockStructure) where {L} # inference fails if cellsdict is empty, so we need to specify eltype co = CellOrbitalsGrouped{L,Vector{Int}}[sites_to_orbs(cellsites, os) for cellsites in cellsdict] return cellinds_to_dict(co) end ## convert CellSites -> CellOrbitalsGrouped sites_to_orbs(c::CellSites, g) = sites_to_orbs(sanitize_cellindices(c, g), blockstructure(g)) function sites_to_orbs(cs::CellSites, os::OrbitalBlockStructure) sites = siteindices(cs) groups = _groups(sites, os) # sites, orbranges orbinds = _orbinds(sites, groups, os) return CellOrbitalsGrouped(cell(cs), orbinds, Dictionary(groups...)) end #endregion #region ## sites_to_orbs_nogroups ## convert SiteSlice -> OrbitalSlice sites_to_orbs_nogroups(l::SiteSlice, g) = OrbitalSlice(lattice(l), sites_to_orbs_nogroups(cellsdict(l), blockstructure(g))) ## convert CellSitesDict to CellOrbitalsDict sites_to_orbs_nogroups(c::CellSitesDict, g) = sites_to_orbs_nogroups(c, blockstructure(g)) function sites_to_orbs_nogroups(cellsdict::CellSitesDict{L}, os::OrbitalBlockStructure) where {L} # inference fails if cellsdict is empty, so we need to specify eltype co = CellOrbitals{L,Vector{Int}}[sites_to_orbs_nogroups(cellsites, os) for cellsites in cellsdict] return cellinds_to_dict(co) end ## convert CellSites -> CellOrbitals sites_to_orbs_nogroups(cs::CellSites, g) = sites_to_orbs_nogroups(sanitize_cellindices(cs, g), blockstructure(g)) function sites_to_orbs_nogroups(cs::CellSites, os::OrbitalBlockStructure) sites = siteindices(cs) orbinds = _orbinds(sites, os) return CellOrbitals(cell(cs), orbinds) end ## convert CellOrbitalsGrouped -> CellOrbitals # unused # sites_to_orbs_nogroups(cs::CellOrbitalsGrouped, _) = CellOrbitals(cell(cs), orbindices(cs)) #endregion #region ## CORE FUNCTIONS _groups(i::Integer, os) = [i], [flatrange(os, i)] _groups(::Colon, os) = _groups(siterange(os), os) function _groups(sites, os) siteinds = Int[] orbranges = UnitRange{Int}[] sizehint!(siteinds, length(sites)) sizehint!(orbranges, length(sites)) for site in sites rng = flatrange(os, site) push!(siteinds, site) push!(orbranges, rng) end return siteinds, orbranges end _orbinds(sites::Union{Integer,Colon,AbstractUnitRange}, _, os) = flatrange(os, sites) _orbinds(sites::Union{Integer,Colon,AbstractUnitRange}, os) = flatrange(os, sites) function _orbinds(_, (sites, orbrngs), os) # reuse precomputed groups orbinds = Int[] sizehint!(orbinds, length(sites)) for rng in orbrngs append!(orbinds, rng) end return orbinds end function _orbinds(sites, os) orbinds = Int[] sizehint!(orbinds, length(sites)) for i in sites rng = flatrange(os, i) append!(orbinds, rng) end return orbinds end #endregion #endregion ############################################################################################ # Utilities #region missing_or_empty!(::Missing) = missing missing_or_empty!(v) = empty!(v) missing_or_push!(::Missing, _) = missing missing_or_push!(v, n) = push!(v, n) #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
21446
############################################################################################ # Functionality for various matrix structures in Quantica.jl ############################################################################################ ############################################################################################ ## HybridSparseMatrix #region ############################################################################################ # HybridSparseMatrix - flat/unflat #region function unflat(s::HybridSparseMatrix) check_integrity(s) needs_unflat_sync(s) && unflat_sync!(s) return unflat_unsafe(s) end function flat(s::HybridSparseMatrix) check_integrity(s) needs_flat_sync(s) && flat_sync!(s) return flat_unsafe(s) end # Sync states needs_no_sync!(s::HybridSparseMatrix) = (syncstate(s)[] = 0) needs_flat_sync!(s::HybridSparseMatrix) = (syncstate(s)[] = 1) needs_unflat_sync!(s::HybridSparseMatrix) = (syncstate(s)[] = -1) needs_initialization!(s::HybridSparseMatrix) = (syncstate(s)[] = 2) needs_no_sync(s::HybridSparseMatrix) = (syncstate(s)[] == 0) needs_flat_sync(s::HybridSparseMatrix) = (syncstate(s)[] == 1) needs_unflat_sync(s::HybridSparseMatrix) = (syncstate(s)[] == -1) needs_initialization(s::HybridSparseMatrix) = (syncstate(s)[] == 2) needs_no_sync!(s::HybridSparseMatrix{<:Any,<:Complex}) = (syncstate(s)[] = 0) needs_flat_sync!(s::HybridSparseMatrix{<:Any,<:Complex}) = (syncstate(s)[] = 0) needs_unflat_sync!(s::HybridSparseMatrix{<:Any,<:Complex}) = (syncstate(s)[] = 0) needs_no_sync(s::HybridSparseMatrix{<:Any,<:Complex}) = true needs_flat_sync(s::HybridSparseMatrix{<:Any,<:Complex}) = false needs_unflat_sync(s::HybridSparseMatrix{<:Any,<:Complex}) = false # flat/unflat conversion function flat(b::OrbitalBlockStructure{B}, unflat::SparseMatrixCSC{B´}) where {N,T,B<:MatrixElementNonscalarType{T,N},B´<:MatrixElementNonscalarType{T,N}} nnzguess = nnz(unflat) * N * N builder = CSC{Complex{T}}(flatsize(b), nnzguess) nzs = nonzeros(unflat) rows = rowvals(unflat) cols = 1:unflatsize(b) for col in cols, bcol in 1:blocksize(b, col) for ptr in nzrange(unflat, col) row = rows[ptr] firstrow´ = flatindex(b, row) vals = view(nzs[ptr], 1:blocksize(b, row), bcol) appendtocolumn!(builder, firstrow´, vals) end finalizecolumn!(builder, false) # no need to sort column end n = flatsize(b) return sparse(builder, n, n) end function unflat(b::OrbitalBlockStructure{B}, flat::SparseMatrixCSC{<:Number}) where {N,B<:MatrixElementNonscalarType{<:Any,N}} @boundscheck(checkblocks(b, flat)) nnzguess = nnz(flat) ÷ (N * N) ncols = unflatsize(b) builder = CSC{B}(ncols, nnzguess) rowsflat = rowvals(flat) for ucol in 1:ncols colrng = flatrange(b, ucol) fcol = first(colrng) Ncol = length(colrng) ptrs = nzrange(flat, fcol) ptr = first(ptrs) while ptr in ptrs frow = rowsflat[ptr] urow, Nrow = unflatindex_and_blocksize(b, frow) valview = view(flat, frow:frow+Nrow-1, fcol:fcol+Ncol-1) val = mask_block(B, valview) pushtocolumn!(builder, urow, val) ptr += Nrow end finalizecolumn!(builder, false) # no need to sort column end n = unflatsize(b) return sparse(builder, n, n) end checkblocks(b, flat) = nothing ## TODO: must check that all structural elements come in blocks #endregion ############################################################################################ # HybridSparseMatrix - copying #region function Base.copy!(h::HybridSparseMatrix{T,B}, h´::HybridSparseMatrix{T,B}) where {T,B} copy!(blockstructure(h), blockstructure(h´)) copy!(unflat_unsafe(h), unflat_unsafe(h´)) isaliased(h´) || copy!(flat_unsafe(h), flat_unsafe(h´)) syncstate(h)[] = syncstate(h´)[] return h end function Base.copy(h::HybridSparseMatrix) b = copy(blockstructure(h)) u = copy(unflat_unsafe(h)) f = isaliased(h) ? u : copy(flat_unsafe(h)) s = Ref(syncstate(h)[]) return HybridSparseMatrix(b, u, f, s) end function copy_matrices(h::HybridSparseMatrix) b = blockstructure(h) u = copy(unflat_unsafe(h)) f = isaliased(h) ? u : copy(flat_unsafe(h)) s = Ref(syncstate(h)[]) return HybridSparseMatrix(b, u, f, s) end #endregion ############################################################################################ # HybridSparseMatrix indexing #region Base.getindex(b::HybridSparseMatrix{<:Any,<:SMatrixView}, i::Integer, j::Integer) = view(parent(unflat(b)[i, j]), flatrange(b, i), flatrange(b, j)) Base.getindex(b::HybridSparseMatrix, i::Integer, j::Integer) = unflat(b)[i, j] # only allowed for elements that are already stored function Base.setindex!(b::HybridSparseMatrix{<:Any,B}, val::AbstractVecOrMat, i::Integer, j::Integer) where {B<:SMatrixView} @boundscheck(checkstored(unflat(b), i, j)) val´ = mask_block(B, val, blocksize(blockstructure(b), i, j)) unflat(b)[i, j] = val´ needs_flat_sync!(b) return val´ end function Base.setindex!(b::HybridSparseMatrix, val::AbstractVecOrMat, i::Integer, j::Integer) @boundscheck(checkstored(unflat(b), i, j)) unflat(b)[i, j] = val needs_flat_sync!(b) return val end checkstored(mat, i, j) = i in view(rowvals(mat), nzrange(mat, j)) || throw(ArgumentError("Adding new structural elements is not allowed")) #endregion ############################################################################################ # mask_block # converts input to a specific block type B (with or without size check) #region # in case the first argument is a value, not a type @inline mask_block(::B, val) where {B} = mask_block(B, val) @inline mask_block(::Type{B}, val::UniformScaling, size = (N, N)) where {T,N,B<:MatrixElementNonscalarType{T,N}} = mask_block(B, sanitize_SMatrix(SMatrix{N,N,T}, SMatrix{N,N}(val), size)) @inline mask_block(::Type{B}, val::UniformScaling, size...) where {B<:Number} = convert(B, val.λ) @inline mask_block(::Type{B}, val, size...) where {B<:Number} = convert(B, only(val)) # conversion not needed? @inline function mask_block(B, val, size) @boundscheck(checkmatrixsize(val, size)) # tools.jl return mask_block(B, val) end @inline mask_block(::Type{B}, val) where {N,B<:SMatrix{N,N}} = B(val) @inline mask_block(::Type{B}, val::SMatrix{R,C}) where {R,C,N,T,B<:SMatrixView{N,N,T}} = SMatrixView(SMatrix{N,R}(I) * val * SMatrix{C,N}(I)) @inline function mask_block(::Type{B}, val) where {N,T,B<:SMatrixView{N,N,T}} (nrows, ncols) = size_or_1x1(val) s = ntuple(Val(N*N)) do i n, m = mod1(i, N), fld1(i, N) @inbounds n > nrows || m > ncols ? zero(T) : T(val[n,m]) end return SMatrixView(SMatrix{N,N,T}(s)) end mask_block(t::Type, val) = argerror("Unexpected block size") size_or_1x1(::Number) = (1, 1) size_or_1x1(val) = size(val) #endregion ############################################################################################ # HybridSparseMatrix syncing #region checkinitialized(s) = needs_initialization(s) && internalerror("sync!: Tried to sync uninitialized matrix") # Uniform case function flat_sync!(s::HybridSparseMatrix{<:Any,S}) where {N,S<:SMatrix{N,N}} checkinitialized(s) flat, unflat = flat_unsafe(s), unflat_unsafe(s) cols = axes(unflat, 2) nzflat, nzunflat = nonzeros(flat), nonzeros(unflat) ptr´ = 1 for col in cols, bcol in 1:N, ptr in nzrange(unflat, col) nz = nzunflat[ptr] for brow in 1:N nzflat[ptr´] = nz[brow, bcol] ptr´ += 1 end end needs_no_sync!(s) return s end # Non-uniform case function flat_sync!(s::HybridSparseMatrix{<:Any,S}) where {N,S<:SMatrixView{N,N}} checkinitialized(s) flat, unflat = flat_unsafe(s), unflat_unsafe(s) cols, rows, rowsflat = axes(unflat, 2), rowvals(unflat), rowvals(flat) nzflat, nzunflat = nonzeros(flat), nonzeros(unflat) bs = blockstructure(s) for col in cols colrng = flatrange(bs, col) for (j, colflat) in enumerate(colrng) ptrsflat = nzrange(flat, colflat) ptrflat = first(ptrsflat) for ptr in nzrange(unflat, col) row = rows[ptr] val = nzunflat[ptr] rowrng = flatrange(bs, row) for (i, rowflat) in enumerate(rowrng) rowsflat[ptrflat] == rowflat && ptrflat in ptrsflat || internalerror("flat_sync!: unexpected structural mismatch") nzflat[ptrflat] = val[i,j] ptrflat += 1 end end end end needs_no_sync!(s) return s end # Uniform and non-uniform cases function unflat_sync!(s::HybridSparseMatrix{<:Any,S}) where {S<:Union{SMatrix,SMatrixView}} checkinitialized(s) flat, unflat = flat_unsafe(s), unflat_unsafe(s) cols, rows = axes(unflat, 2), rowvals(unflat) nzunflat = nonzeros(unflat) bs = blockstructure(s) for col in cols colrng = flatrange(bs, col) for ptr in nzrange(unflat, col) row = rows[ptr] rowrng = flatrange(bs, row) val = view(flat, colrng, rowrng) nzunflat[ptr] = S(val) end end needs_no_sync!(s) return s end #endregion #endregion top ############################################################################################ ## BlockSparseMatrix #region ############################################################################################ # MatrixBlock simplify # Revert subarray to parent through a simple reordering of rows and cols # This is possible if rows and cols is a permutation of the parent axes # but we only do a weak check of this (parent size == view size) for performance reasons #region simplify_matrixblock(block::SubArray, rows, cols) = simplify_matrixblock(parent(block), block.indices..., rows, cols) function simplify_matrixblock(mat::AbstractMatrix, viewrows, viewcols, rows, cols) if size(mat) != (length(viewrows), length(viewcols)) internalerror("simplify_matrixblock: received a SubArray that is not a permutation") elseif cols === rows rows´ = cols´ = simplify_indices(viewrows, rows) else rows´ = simplify_indices(viewrows, rows) cols´ = simplify_indices(viewcols, cols) end return MatrixBlock(mat, rows´, cols´) end simplify_indices(viewinds, inds) = invpermute!(convert(Vector{Int}, inds), viewinds) #endregion ############################################################################################ # appendIJ! for MatrixBlocks # Useful to build a BlockSparseMatrix from a set of MatrixBlocks #region function appendIJ!(I, J, b::MatrixBlock{<:Any,<:AbstractSparseMatrixCSC}) for col in axes(blockmat(b), 2), ptr in nzrange(blockmat(b), col) push!(I, blockrows(b)[rowvals(blockmat(b))[ptr]]) push!(J, blockcols(b)[col]) end return I, J end function appendIJ!(I, J, b::MatrixBlock{<:Any,<:Diagonal}) for col in axes(blockmat(b), 2) row = col push!(I, blockrows(b)[row]) push!(J, blockcols(b)[col]) end return I, J end function appendIJ!(I, J, b::MatrixBlock{<:Any,<:StridedArray}) for c in CartesianIndices(blockmat(b)) row, col = Tuple(c) push!(I, blockrows(b)[row]) push!(J, blockcols(b)[col]) end return I, J end #endregion ############################################################################################ # BlockSparseMatrix getblockptrs #region getblockptrs(mblock, mat) = getblockptrs(mblock.block, mblock.rows, mblock.cols, mat) function getblockptrs(block::AbstractSparseMatrixCSC, is, js, mat) checkblockinds(block, is, js) ptrs = Int[] for col in axes(block, 2) colmat = js[col] p = 0 for ptr in nzrange(block, col) p+=1 row = rowvals(block)[ptr] rowmat = is[row] for ptrmat in nzrange(mat, colmat) rowvals(mat)[ptrmat] == rowmat && (push!(ptrs, ptrmat); break) end end end nnz(block) == length(ptrs) || argerror("Sparse matrix does not contain structural block") return ptrs end function getblockptrs(block::StridedMatrix, is, js, mat) checkblockinds(block, is, js) ptrs = Int[] for c in CartesianIndices(block) row, col = Tuple(c) rowmat, colmat = is[row], js[col] for ptrmat in nzrange(mat, colmat) rowvals(mat)[ptrmat] == rowmat && (push!(ptrs, ptrmat); break) end end length(block) == length(ptrs) || argerror("Sparse matrix does not contain structural block") return ptrs end function getblockptrs(block::Diagonal, is, js, mat) checkblockinds(block, is, js) ptrs = Int[] for (col, colmat) in enumerate(js) col > size(block, 1) && break rowmat = is[col] for ptrmat in nzrange(mat, colmat) rowvals(mat)[ptrmat] == rowmat && (push!(ptrs, ptrmat); break) end end min(size(block)...) == length(ptrs) || argerror("Sparse matrix does not contain structural block") return ptrs end #endregion ############################################################################################ # BlockSparseMatrix/BlockMatrix update! #region function update!(m::BlockSparseMatrix) nzs = nonzeros(matrix(m)) fill!(nzs, 0) # Since blocks(m) is an inhomogeneous tuple, we cannot do a type-stable loop sparse_addblocks!(nzs, 1, pointers(m), blocks(m)...) return m end function sparse_addblocks!(nzs, i, ps, mblock, bs...) ptrs = ps[i] bmat = blockmat(mblock) coef = coefficient(mblock) for (x, ptr) in zip(stored(bmat), ptrs) nzs[ptr] += coef * x end return sparse_addblocks!(nzs, i+1, ps, bs...) end sparse_addblocks!(nzs, _, _) = nzs stored(block::AbstractSparseMatrixCSC) = nonzeros(block) stored(block::StridedMatrix) = block stored(block::Diagonal) = block.diag function update!(m::BlockMatrix) mat = matrix(m) fill!(mat, 0) # Since blocks(m) is an inhomogeneous tuple, we cannot do a type-stable loop dense_addblocks!(mat, blocks(m)...) return m end function dense_addblocks!(mat, mblock, bs...) bmat = blockmat(mblock) coef = coefficient(mblock) vmat = view(mat, blockrows(mblock), blockcols(mblock)) vmat .+= coef .* bmat return dense_addblocks!(mat, bs...) end dense_addblocks!(mat) = mat #endregion #endregion top ############################################################################################ ## InverseGreenBlockSparse #region # inverse_green from 0D AbstractHamiltonian + contacts function inverse_green(h::AbstractHamiltonian{T,<:Any,0}, contacts) where {T} hdim = flatsize(h) haxis = 1:hdim ωblock = MatrixBlock((zero(Complex{T}) * I)(hdim), haxis, haxis) hblock = MatrixBlock(call!_output(h), haxis, haxis) mat, unitcinds, unitcindsall = inverse_green_mat((ωblock, -hblock), hdim, contacts) source = zeros(Complex{T}, size(mat, 2), length(unitcindsall)) nonextrng = 1:flatsize(h) return InverseGreenBlockSparse(mat, nonextrng, unitcinds, unitcindsall, source) end # case without contacts function inverse_green_mat(blocks, _, ::Contacts{<:Any,0}) mat = BlockSparseMatrix(blocks...) unitcinds = Vector{Int}[] unitcindsall = Int[] return mat, unitcinds, unitcindsall end function inverse_green_mat(blocks, hdim, contacts) Σs = selfenergies(contacts) extoffset = hdim unitcinds = [orbindices(only(cellsdict(contacts, i))) for i in 1:ncontacts(contacts)] unitcindsall = orbindices(only(cellsdict(contacts))) checkcontactindices(unitcindsall, hdim) solvers = solver.(Σs) Σblocks = selfenergyblocks(extoffset, unitcinds, 1, (), solvers...) g⁻¹blocks = maybe_switch_sign.(Σblocks) blocks´ = (blocks..., g⁻¹blocks...) # we need to flatten extended blocks, that come as NTuple{3}'s mat = BlockSparseMatrix(tupleflatten(blocks´...)...) return mat, unitcinds, unitcindsall end # matrix blocks of g⁻¹ have negative signs for Σreg, positive for Σext = (V', g⁻¹´, V) maybe_switch_sign(Σ::MatrixBlock) = -Σ maybe_switch_sign(Vg⁻¹V::NTuple{3,MatrixBlock}) = Vg⁻¹V checkcontactindices(allcontactinds, hdim) = maximum(allcontactinds) <= hdim || internalerror("InverseGreenBlockSparse: unexpected contact indices beyond Hamiltonian dimension") #endregion ############################################################################################ ## OrbitalSliceArray #region # AbstractArray interface Base.size(a::OrbitalSliceArray) = size(parent(a)) Base.iterate(a::OrbitalSliceArray, i...) = iterate(parent(a), i...) Base.length(a::OrbitalSliceArray) = length(parent(a)) Base.IndexStyle(::Type{T}) where {M,T<:OrbitalSliceArray{<:Any,<:Any,M}} = IndexStyle(M) Base.similar(a::OrbitalSliceArray) = OrbitalSliceArray(similar(parent(a)), orbaxes(a)) Base.similar(a::OrbitalSliceArray, t::Type) = OrbitalSliceArray(similar(parent(a), t), orbaxes(a)) # doesn't make sense to keep orbaxes in similar with different dimensions. Base.similar(a::OrbitalSliceArray, dims::Tuple) = similar(parent(a), dims) Base.copy(a::OrbitalSliceArray) = OrbitalSliceArray(copy(parent(a)), orbaxes(a)) Base.@propagate_inbounds Base.getindex(a::OrbitalSliceArray, i::Int) = getindex(parent(a), i) Base.@propagate_inbounds Base.getindex(a::OrbitalSliceArray, I::Vararg{Int, N}) where {N} = getindex(parent(a), I...) Base.@propagate_inbounds Base.setindex!(a::OrbitalSliceArray, v, i::Int) = setindex!(parent(a), v, i) Base.@propagate_inbounds Base.setindex!(a::OrbitalSliceArray, v, I::Vararg{Int, N}) where {N} = setindex!(parent(a), v, I...) # Additional indexing over sites Base.getindex(a::OrbitalSliceMatrix; sites...) = getindex(a, siteselector(; sites...)) Base.getindex(a::OrbitalSliceMatrix, i::NamedTuple, j::NamedTuple = i) = getindex(a, siteselector(i), siteselector(j)) Base.getindex(a::OrbitalSliceMatrix, i::NamedTuple, j::SiteSelector) = getindex(a, siteselector(i), j) Base.getindex(a::OrbitalSliceMatrix, i::SiteSelector, j::NamedTuple) = getindex(a, i, siteselector(j)) # SiteSelector: return a new OrbitalSliceMatrix function Base.getindex(a::OrbitalSliceMatrix, i::SiteSelector, j::SiteSelector = i) rowslice, colslice = orbaxes(a) rowslice´, colslice´ = rowslice[i], colslice[j] rows = collect(indexcollection(rowslice, rowslice´)) cols = i === j && rowslice === colslice ? rows : indexcollection(colslice, colslice´) m = parent(a)[rows, cols] return OrbitalSliceMatrix(m, (rowslice´, colslice´)) end # CellSites: return an unwrapped Matrix or a view thereof (non-allocating) Base.getindex(a::OrbitalSliceMatrix, i::AnyCellSites, j::AnyCellSites = i) = copy(view(a, i, j)) Base.getindex(a::OrbitalSliceMatrix, i::C, j::C = i) where {B,C<:CellSitePos{<:Any,<:Any,<:Any,B}} = sanitize_block(B, view(a, i, j)) function Base.view(a::OrbitalSliceMatrix, i::AnyCellSites, j::AnyCellSites = i) rowslice, colslice = orbaxes(a) i´, j´ = apply(i, lattice(rowslice)), apply(j, lattice(colslice)) rows = indexcollection(rowslice, i´) cols = j === i && rowslice === colslice ? rows : indexcollection(colslice, j´) return view(parent(a), rows, cols) end ## broadcasting # following the manual: https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-array Broadcast.BroadcastStyle(::Type{<:OrbitalSliceArray}) = Broadcast.ArrayStyle{OrbitalSliceArray}() Base.similar(bc::Broadcast.Broadcasted{Broadcast.ArrayStyle{OrbitalSliceArray}}, ::Type{ElType}) where {ElType} = OrbitalSliceArray(similar(Array{ElType}, axes(bc)), orbaxes(find_osa(bc))) find_osa(bc::Base.Broadcast.Broadcasted) = find_osa(bc.args) find_osa(args::Tuple) = find_osa(find_osa(args[1]), Base.tail(args)) find_osa(x) = x find_osa(::Tuple{}) = nothing find_osa(a::OrbitalSliceArray, rest) = a find_osa(::Any, rest) = find_osa(rest) # taken from https://github.com/JuliaArrays/OffsetArrays.jl/blob/756e839563c88faa4ebe4ff971286747863aaff0/src/OffsetArrays.jl#L469 Base.dataids(A::OrbitalSliceArray) = Base.dataids(parent(A)) Broadcast.broadcast_unalias(dest::OrbitalSliceArray, src::OrbitalSliceArray) = parent(dest) === parent(src) ? src : Broadcast.unalias(dest, src) ## conversion maybe_OrbitalSliceArray(i) = x -> maybe_OrbitalSliceArray(x, i) maybe_OrbitalSliceArray(x::AbstractVector, i) = maybe_OrbitalSliceVector(x, i) maybe_OrbitalSliceArray(x::AbstractMatrix, i) = maybe_OrbitalSliceMatrix(x, i) maybe_OrbitalSliceVector(x, i::DiagIndices{Missing,<:OrbitalSliceGrouped}) = maybe_OrbitalSliceVector(x, parent(i)) maybe_OrbitalSliceVector(x, i::DiagIndices{<:Any,<:OrbitalSliceGrouped}) = maybe_OrbitalSliceVector(x, scalarize(parent(i))) maybe_OrbitalSliceVector(x, i::OrbitalSliceGrouped) = OrbitalSliceVector(x, (i,)) # fallback maybe_OrbitalSliceVector(x, i) = x maybe_OrbitalSliceMatrix(x, i::OrbitalSliceGrouped) = maybe_OrbitalSliceMatrix(x, (i, i)) maybe_OrbitalSliceMatrix(x, (i, j)::Tuple{OrbitalSliceGrouped,OrbitalSliceGrouped}) = OrbitalSliceMatrix(x, (i, j)) # fallback maybe_OrbitalSliceMatrix(x, i) = x #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
13019
supercell(v...; kw...) = x -> supercell(x, v...; kw...) ############################################################################################ # SupercellData (required to build lattice supercell) #region struct SupercellData{T,E,L,L´,LL´} lat::Lattice{T,E,L} sitelist::Vector{SVector{E,T}} # [sitepositions...] masklist::Vector{Tuple{Int,SVector{L,Int},Int}} # [(sublatindex, cell, siteindex)...] bravais´::Bravais{T,E,L´} sm::SMatrix{L,L´,Int,LL´} detsm´::Int proj_invsm´_detsm´::SMatrix{L´,L,Int,LL´} end function supercell_data(lat::Lattice{<:Any,<:Any,L}, vs...; seed = missing, kw...) where {L} smat = sanitize_supercell(Val(L), vs) selector = siteselector(; kw...) applied_selector = apply(selector, lat) # IMPORTANT BEHAVIOR: if lattice dimensions are reduced and there is no bounding region # and no cell list, supercell is infinite. In this case: stop at a single perp unit cell only_one_perp = size(smat, 2) < size(smat, 1) && region(selector) === missing && cells(selector) === missing cellseed = seed === missing ? zero(SVector{L,Int}) : sanitize_SVector(SVector{L,Int}, seed) return supercell_data(lat, smat, cellseed, applied_selector, only_one_perp) end function supercell_data(lat::Lattice{T,E,L}, sm::SMatrix{L,L´,Int}, cellseed::SVector{L,Int}, applied_selector::AppliedSiteSelector{T,E}, only_one_perp::Bool = false) where {T,E,L,L´} sm´ = makefull(sm) detsm´ = round(Int, abs(det(sm´))) iszero(detsm´) && throw(ArgumentError("Supercell is empty. Singular supercell matrix?")) # inverse of full supercell sm´ (times det(sm´) to make it integer) # projected back onto superlattice axes L´ invsm´_detsm´ = round.(Int, inv(sm´) * detsm´) proj_invsm´_detsm´ = SMatrix{L´,L,Bool}(I) * invsm´_detsm´ bravais´ = Bravais{T,E,L´}(bravais_matrix(lat) * sm) masklist = supercell_masklist_full(invsm´_detsm´, detsm´, cellseed, lat) smperp = convert(SMatrix{L,L-L´,Int}, view(sm´, :, L´+1:L)) seedperp = zero(SVector{L-L´,Int}) sitelist = similar(sites(lat), 0) supercell_sitelist!!(sitelist, masklist, smperp, seedperp, lat, applied_selector, only_one_perp) cosort!(masklist, sitelist) # sorted by sublat, then cell, then siteidx return SupercellData(lat, sitelist, masklist, bravais´, sm, detsm´, proj_invsm´_detsm´) end smat_projector(::SupercellData{<:Any,<:Any,L,L´}) where {L,L´} = SMatrix{L´,L,Bool}(I) # Make matrix square by appending (or prepending) independent columns if possible function makefull(m::SMatrix{L,L´}) where {L,L´} Q = qr(Matrix(m), NoPivot()).Q * I for i in 1:L * L´ @inbounds Q[i] = m[i] # overwrite first L´ cols with originals end return SMatrix{L,L}(Q) end # round to integers to preserve eltype makefull(m::SMatrix{<:Any,<:Any,Int}) = round.(Int, makefull(float(m))) # build masklist = [(sublatindex, cell, siteindex)] for all sites # in full supercell defined by makefull(smat) function supercell_masklist_full(smat´⁻¹N::SMatrix{L,L,Int}, N, cellseed::SVector{L,Int}, lat) where {L} supercell_nsites = nsites(lat) * N masklist = Vector{Tuple{Int,SVector{L,Int},Int}}(undef, supercell_nsites) counter = 0 iter = BoxIterator(cellseed) for cell in iter, (i, slat) in sitesublatiter(lat) δn = smat´⁻¹N * cell if all(x -> 0 <= x < N, δn) counter += 1 masklist[counter] = (slat, cell, i) end acceptcell!(iter, cell) counter == supercell_nsites && break end counter == supercell_nsites || internalerror("supercell_masklist_full: failed to find all sites in supercell, only $counter of $supercell_nsites") return masklist end # build sitelist = [sitepositions...] and masklist´ = [(sublat, cell´, siteidx)...] # where cell´ varies along axes smatperp not in smat, filtered by selector function supercell_sitelist!!(sitelist, masklist, smatperp, seedperp, lat, applied_selector, only_one_perp) masklist´ = copy(masklist) empty!(masklist) empty!(sitelist) isnull(applied_selector) && return nothing cs = cells(applied_selector) csbool = zeros(Bool, length(cs)) iter = BoxIterator(seedperp) for n in iter keepgoing = isempty(sitelist) # if none have been found, ensure we don't stop for (s, cell, i) in masklist´ cell´ = cell + smatperp * n r = site(lat, i, cell´) if (i, r, cell´) in applied_selector push!(masklist, (s, cell´, i)) push!(sitelist, r) foundcell!(csbool, cs, cell´) keepgoing = true end end only_one_perp && break # If we haven't found all selector cells, accept supercell n so we keep searching # note that if isempty(csbool) then all(csbool) is true and we stop accepting foundall = all(csbool) keepgoing = keepgoing || !foundall keepgoing && acceptcell!(iter, n) end return nothing end function foundcell!(csbool, cs, cell) isempty(cs) && return true for (i, c) in enumerate(cs) if cell == c csbool[i] = true return true end end return false end #endregion ############################################################################################ # supercell(lattice, ...) #region supercell(lat::Lattice, vs...; kw...) = lattice(supercell_data(lat, vs...; kw...)) function lattice(data::SupercellData) n = sublatnames(data.lat) o = supercell_offsets(data.masklist, nsublats(data.lat)) u = Unitcell(data.sitelist, n, o) lat = Lattice(data.bravais´, u) return lat end function supercell_offsets(masklist, nsublats) ds = zeros(Int, nsublats) @simd for m in masklist ds[first(m)] += 1 end offsets = lengths_to_offsets(ds) return offsets end # function latslice(data::SupercellData) # # data.masklist is [(sublat, cell, siteindex)...] for each site in lat´ # cellindsvec = sort!(Base.tail.(data.masklist)) # subcells = splitruns(last, cellindsvec; by = first, reduce = CellSites) # see tools.jl # ls = LatticeSlice(data.lat, subcells) # return ls # end #endregion ############################################################################################ # supercell(::Hamiltonian, ...) #region function supercell(h::Hamiltonian, v...; mincoordination = 0, kw...) data = supercell_data(lattice(h), v...; kw...) return supercell(h, data; mincoordination) end function supercell(h::Hamiltonian, data::SupercellData; mincoordination = 0) # data.sitelist === sites(lat´), so any change to data will reflect in lat´ too lat´ = lattice(data) B = blocktype(h) bs´ = OrbitalBlockStructure{B}(norbitals(h), sublatlengths(lat´)) builder = CSCBuilder(lat´, bs´) har´ = supercell_harmonics(h, data, builder, mincoordination) return Hamiltonian(lat´, bs´, har´) end function supercell_harmonics(h, data, builder, mincoordination) indexlist, offset = supercell_indexlist(data) if mincoordination > 0 indexlist, offset = remove_low_coordination_sites!(data, indexlist, offset, h, mincoordination) end # Note: masklist = [(sublat, old_cell, old_siteindex)...] for (col´, (_, cellsrc, col)) in enumerate(data.masklist) for har in harmonics(h) celldst = cellsrc + dcell(har) # cell is the position of celldst within its supercell scell cell, scell = wrap_cell_onto_supercell(celldst, data) m = unflat(har) rows = rowvals(m) vals = nonzeros(m) for p in nzrange(m, col) row = rows[p] c = CartesianIndex((row, Tuple(cell)...)) + offset # If any row is out of bounds, all rows are (because cell is out of bounds) checkbounds(Bool, indexlist, c) || break # Note: indexlist[(old_site_index, old_site_cell...) + offset] = new_site_index row´ = indexlist[c] iszero(row´) && continue csc = builder[scell] # if csc is a newly created collector, advance column to current col´ sync_columns!(csc, col´) # val´ = applymodifiers(vals[p], slat, (source_i, target_i), (source_dn, target_dn), modifiers´...) val´ = vals[p] pushtocolumn!(csc, row´, val´) end end finalizecolumn!(builder) end return sparse(builder) end function wrap_cell_onto_supercell(cell, data) # This psmat⁻¹N is the inverse of the full supercell matrix sm´ (i.e. full-rank square), # times N = det(sm´) to make it integer, and projected onto the actual L supercell dims psmat⁻¹N = data.proj_invsm´_detsm´ N = data.detsm´ smat = data.sm # `scell` is the indices of the supercell where `cell` lives scell = fld.(psmat⁻¹N * cell, N) # `cell´` is `cell` shifted back to the zero supercell cell´ = cell - smat * scell return cell´, scell end function supercell_indexlist(data) (cellmin, cellmax), (imin, imax) = mask_bounding_box(data.masklist) indexlist = zeros(Int, 1 + imax - imin, 1 .+ cellmax .- cellmin...) offset = CartesianIndex((1 - imin, 1 .- cellmin...)) for (inew, (_, cellold, iold)) in enumerate(data.masklist) c = CartesianIndex((iold, Tuple(cellold)...)) + offset indexlist[c] = inew end return indexlist, offset end # more general version of boundingbox(cells) function mask_bounding_box(masklist::Vector{Tuple{Int,SVector{L,Int},Int}}) where {L} cellmin = cellmax = ntuple(Returns(0), Val(L)) imin = imax = 0 for (s, cell, i) in masklist tcell = Tuple(cell) cellmin = min.(cellmin, tcell) cellmax = max.(cellmax, tcell) imin = min(imin, i) imax = max(imax, i) end return (cellmin, cellmax), (imin, imax) end function remove_low_coordination_sites!(data, indexlist, offset, h, mincoordination) # remove low-coordination sites in masklist and sitelist until they don't change # when a site is removed, it becomes a zero in indexlist, but the other indices # are not changed. Hence, at the end we must recompute indexlist with the final # masklist and sitelist. Note that lat´ in the calling context is updated through # sitelist too, since sites(lat´) === data.sitelist masklist = data.masklist masklist´ = similar(masklist) sitelist = data.sitelist sitelist´ = similar(sitelist) while true resize!(masklist´, 0) resize!(sitelist´, 0) for (r, (sj, cellj, j)) in zip(sitelist, masklist) coordination = 0 for har in harmonics(h) dn = dcell(har) celli, _ = wrap_cell_onto_supercell(cellj + dn, data) m = matrix(har) rows = rowvals(m) vals = nonzeros(m) for p in nzrange(m, j) i = rows[p] c = CartesianIndex((i, Tuple(celli)...)) + offset checkbounds(Bool, indexlist, c) || break isonsite = i == j && iszero(dn) if !isonsite && !iszero(indexlist[c]) && !iszero(vals[p]) coordination += 1 end end end if coordination >= mincoordination push!(sitelist´, r) push!(masklist´, (sj, cellj, j)) else c = CartesianIndex((j, Tuple(cellj)...)) + offset indexlist[c] = 0 end end length(sitelist´) == length(sitelist) && break sitelist´, sitelist = sitelist, sitelist´ masklist´, masklist = masklist, masklist´ end data.masklist .= masklist´ data.sitelist .= sitelist´ indexlist´, offset´ = supercell_indexlist(data) return indexlist´, offset´ end #endregion ############################################################################################ # supercell(::ParametricHamiltonian, ...) #region function supercell(p::ParametricHamiltonian, v...; mincoordination = 0, kw...) h = parent(p) data = supercell_data(lattice(h), v...; kw...) h´ = supercell(h, data; mincoordination) shifts = supercell_shifts(data) # allows to compute new ptrs to old r, dr ms = parent.(modifiers(p)) # extract unapplied modifiers to reapply them to h´ ams = apply.(ms, Ref(h´), Ref(shifts)) p´ = hamiltonian(h´, ams...) return p´ end # For each site in new lattice, store the corresponding shift = bravais_matrix * cell function supercell_shifts(data::SupercellData) b = bravais_matrix(data.lat) shifts = [b * cell for (_, cell, _) in data.masklist] return shifts end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
8116
############################################################################################ # Misc tools #region rdr((r1, r2)::Pair) = (0.5 * (r1 + r2), r2 - r1) @inline tuplejoin() = () @inline tuplejoin(x) = x @inline tuplejoin(x, y) = (x..., y...) @inline tuplejoin(x, y, z...) = (x..., tuplejoin(y, z...)...) @inline tupleflatten() = () @inline tupleflatten(x::Tuple) = x @inline tupleflatten(x0, xs...) = tupleflatten((x0,), xs...) @inline tupleflatten(x0::Tuple, x1, xs...) = tupleflatten((x0..., x1), xs...) @inline tupleflatten(x0::Tuple, x1::Tuple, xs...) = tupleflatten((x0..., x1...), xs...) tuplefill(x, ::Val{N}) where {N} = ntuple(Returns(x), Val(N)) padtuple(t, x, N) = ntuple(i -> i <= length(t) ? t[i] : x, N) @inline tupletake(x, ::Val{N}) where {N} = ntuple(i -> x[i], Val(N)) @inline function smatrixtake(s::SMatrix, ::Val{N}) where {N} is = SVector{N,Int}(1:N) return s[is, is] end @noinline internalerror(func::String) = throw(ErrorException("Internal error in $func. Please file a bug report at https://github.com/pablosanjose/Quantica.jl/issues")) @noinline argerror(msg) = throw(ArgumentError(msg)) @noinline boundserror(m, i) = throw(BoundsError(m, i)) @noinline checkmatrixsize(::UniformScaling, s) = nothing @noinline checkmatrixsize(val, s) = (size(val, 1), size(val, 2)) == s || throw(ArgumentError("Expected a block or matrix of size $s, got size $((size(val, 1), size(val, 2)))")) @noinline function_not_defined(name) = argerror("Function $name not defined for the requested types") unitvector(i, ::Type{SVector{L,T}}) where {L,T} = SVector{L,T}(ntuple(j -> j == i ? one(T) : zero(T), Val(L))) function padright(pt, ::Val{L}) where {L} T = eltype(pt) L´ = length(pt) return SVector(ntuple(i -> i > L´ ? zero(T) : pt[i], Val(L))) end function boundingbox(positions) isempty(positions) && argerror("Cannot find bounding box of an empty collection") posmin = posmax = first(positions) for pos in positions posmin = min.(posmin, pos) posmax = max.(posmax, pos) end return (posmin, posmax) end copy_ifnotmissing(::Missing) = missing copy_ifnotmissing(d) = copy(d) merge_parameters!(p, m, ms...) = merge_parameters!(append!(p, parameters(m)), ms...) merge_parameters!(p) = unique!(sort!(p)) typename(::T) where {T} = nameof(T) chop(x::T) where {T<:Real} = ifelse(abs2(x) < eps(real(T)), zero(T), x) chop(x::Complex) = chop(real(x)) + im*chop(imag(x)) chop(xs) = chop.(xs) # Flattens matrix of Matrix{<:Number} into a matrix of Number's function mortar(ms::AbstractMatrix{M}) where {C<:Number,M<:AbstractMatrix{C}} isempty(ms) && return convert(Matrix{C}, ms) mrows = size.(ms, 1) mcols = size.(ms, 2) allequal(eachrow(mcols)) && allequal(eachcol(mrows)) || internalerror("mortar: inconsistent rows or columns") roff = lengths_to_offsets(view(mrows, :, 1)) coff = lengths_to_offsets(view(mcols, 1, :)) mat = zeros(C, last(roff), last(coff)) for c in CartesianIndices(ms) src = ms[c] i, j = Tuple(c) Rdst = CartesianIndices((roff[i]+1:roff[i+1], coff[j]+1:coff[j+1])) Rsrc = CartesianIndices(src) copyto!(mat, Rdst, src, Rsrc) end return mat end # faspath for generators or other collections mortar(ms) = length(ms) == 1 ? only(ms) : mortar(collect(ms)) # equivalent to mat = I[:, cols]. Useful for Green function source # no check of mat size vs cols is done function one!(mat::AbstractArray{T}, cols = axes(mat, 2)) where {T} fill!(mat, zero(T)) for (col, row) in enumerate(cols) mat[row, col] = one(T) end return mat end one!(mat::AbstractArray, ::Colon) = one!(mat) lengths_to_offsets(v::NTuple{<:Any,Integer}) = (0, cumsum(v)...) lengths_to_offsets(v) = prepend!(cumsum(v), 0) lengths_to_offsets(f::Function, v) = prepend!(accumulate((i,j) -> i + f(j), v; init = 0), 0) #endregion ############################################################################################ # SparseMatrixCSC tools # all merged_* functions assume matching structure of sparse matrices #region function nnzdiag(b::AbstractSparseMatrixCSC) count = 0 rowptrs = rowvals(b) for col in 1:size(b, 2) for ptr in nzrange(b, col) rowptrs[ptr] == col && (count += 1; break) end end return count end stored_rows(m::AbstractSparseMatrixCSC) = unique!(sort!(copy(rowvals(m)))) function stored_cols(m::AbstractSparseMatrixCSC) cols = Int[] for col in axes(m, 2) isempty(nzrange(m, col)) || push!(cols, col) end return cols end # merge several sparse matrices onto the first using only structural zeros function merge_sparse(mats, ::Type{B} = eltype(first(mats))) where {B} mat0 = first(mats) nrows, ncols = size(mat0) nrows == ncols || throw(ArgumentError("Internal error: matrix not square")) nnzguess = sum(mat -> nnz(mat), mats) collector = CSC{B}(ncols, nnzguess) for col in 1:ncols for (n, mat) in enumerate(mats) vals = nonzeros(mat) rows = rowvals(mat) for p in nzrange(mat, col) val = zero(B) row = rows[p] pushtocolumn!(collector, row, val, false) # skips repeated rows end end finalizecolumn!(collector) end matrix = sparse(collector, ncols, ncols) return matrix end function merged_mul!(C::SparseMatrixCSC{<:Number}, A::HybridSparseMatrix, b::Number, α = 1, β = 0) bs = blockstructure(A) if needs_flat_sync(A) merged_mul!(C, bs, unflat(A), b, α, β) else merged_mul!(C, bs, flat(A), b, α, β) end return C end function merged_mul!(C::SparseMatrixCSC{<:Number}, ::OrbitalBlockStructure, A::SparseMatrixCSC{B}, b::Number, α = 1, β = 0) where {B<:Complex} nzA = nonzeros(A) nzC = nonzeros(C) αb = α * b if length(nzA) == length(nzC) # assume idential structure (C has merged structure) @. nzC = muladd(αb, nzA, β * nzC) else # A has less elements than C for col in axes(A, 2), p in nzrange(A, col) row = rowvals(A)[p] for p´ in nzrange(C, col) row´ = rowvals(C)[p´] if row == row´ nzC[p´] = muladd(αb, nzA[p], β * nzC[p´]) break end end end end return C end function merged_mul!(C::SparseMatrixCSC{<:Number}, bs::OrbitalBlockStructure{B}, A::SparseMatrixCSC{B}, b::Number, α = 1, β = 0) where {B<:MatrixElementNonscalarType} colsA = axes(A, 2) rowsA = rowvals(A) valsA = nonzeros(A) rowsC = rowvals(C) valsC = nonzeros(C) αb = α * b colC = 1 for colA in colsA N = blocksize(bs, colA) for colN in 1:N ptrsA, ptrsC = nzrange(A, colA), nzrange(C, colC) ptrA, ptrC = first(ptrsA), first(ptrsC) while ptrA in ptrsA && ptrC in ptrsC rowA, rowC = rowsA[ptrA], rowsC[ptrC] rngflat = flatrange(bs, rowA) rowAflat, N´ = first(rngflat), length(rngflat) if rowAflat == rowC valA = valsA[ptrA] for rowN in 1:N´ valsC[ptrC] = muladd(αb, valA[rowN, colN], β * valsC[ptrC]) ptrC += 1 end elseif rowAflat > rowC ptrC += N´ else ptrA += 1 end end colC += 1 end end return C end #endregion ############################################################################################ # Dynamic package loader # This is in global Quantica scope to avoid name collisions # We also `import` instead of `using` to avoid collisions between different backends #region function ensureloaded(package::Symbol) if !isdefined(Quantica, package) @warn("Required package $package not loaded. Loading...") eval(:(import $package)) end return nothing end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
2234
############################################################################################ # Currying #region transform(f::Function) = x -> transform(x, f) transform!(f::Function) = x -> transform!(x, f) translate(δr) = x -> translate(x, δr) translate!(δr) = x -> translate!(x, δr) #endregion ############################################################################################ # Lattice transform/translate #region function transform!(l::Lattice, f::Function, keepranges = false) return keepranges ? Lattice(transform!(bravais(l), f), transform!(unitcell(l), f), nranges(l)) : Lattice(transform!(bravais(l), f), transform!(unitcell(l), f)) end function transform!(b::Bravais{<:Any,E}, f::Function) where {E} m = matrix(b) for j in axes(m, 2) v = SVector(ntuple(i -> m[i, j], Val(E))) m[:, j] .= f(v) - f(zero(v)) end return b end transform!(u::Unitcell, f::Function) = (map!(f, sites(u), sites(u)); u) transform(l::Lattice, f::Function) = transform!(copy(l), f) # translate! does not change neighbor ranges, keep whichever have already been computed translate!(lat::Lattice{T,E}, δr::SVector{E,T}) where {T,E} = transform!(lat, r -> r + δr, true) translate!(lat::Lattice{T,E}, δr) where {T,E} = translate!(lat, sanitize_SVector(SVector{E,T}, δr)) translate(l::Lattice, δr) = translate!(copy(l), δr) #endregion ############################################################################################ # Lattice reverse - flip all Bravais vectors #region Base.reverse!(lat::Lattice) = (matrix(bravais(lat)) .*= -1; lat) Base.reverse(lat::Lattice) = reverse!(copy(lat)) Base.reverse!(h::AbstractHamiltonian) = (reverse!(lattice(h)); h) Base.reverse(h::AbstractHamiltonian) = reverse!(copy(h)) #end ############################################################################################ # Hamiltonian transform/translate #region transform(h::AbstractHamiltonian, f::Function) = transform!(copy_lattice(h), f) transform!(h::AbstractHamiltonian, f::Function) = (transform!(lattice(h), f); h) translate(h::AbstractHamiltonian, δr) = translate!(copy_lattice(h), δr) translate!(h::AbstractHamiltonian, δr) = (translate!(lattice(h), δr); h) #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
83702
############################################################################################ # Lattice - see lattice.jl for methods #region struct Sublat{T<:AbstractFloat,E} sites::Vector{SVector{E,T}} name::Symbol end struct Unitcell{T<:AbstractFloat,E} sites::Vector{SVector{E,T}} names::Vector{Symbol} offsets::Vector{Int} # Linear site number offsets for each sublat function Unitcell{T,E}(sites, names, offsets) where {T<:AbstractFloat,E} names´ = uniquenames!(sanitize_Vector_of_Symbols(names)) length(names´) == length(offsets) - 1 || argerror("Incorrect number of sublattice names, got $(length(names´)), expected $(length(offsets) - 1)") return new(sites, names´, offsets) end end struct Bravais{T,E,L} matrix::Matrix{T} function Bravais{T,E,L}(matrix) where {T,E,L} (E, L) == size(matrix) || internalerror("Bravais: unexpected matrix size $((E,L)) != $(size(matrix))") L > E && throw(DimensionMismatch("Number of Bravais vectors ($L) cannot be greater than embedding dimension $E")) return new(matrix) end end struct Lattice{T<:AbstractFloat,E,L} bravais::Bravais{T,E,L} unitcell::Unitcell{T,E} nranges::Vector{Tuple{Int,T}} # [(nth_neighbor, min_nth_neighbor_distance)...] end #region ## Constructors ## Bravais(::Type{T}, E, m) where {T} = Bravais(T, Val(E), m) Bravais(::Type{T}, ::Val{E}, m::Tuple{}) where {T,E} = Bravais{T,E,0}(sanitize_Matrix(T, E, ())) Bravais(::Type{T}, ::Val{E}, m::NTuple{<:Any,Number}) where {T,E} = Bravais{T,E,1}(sanitize_Matrix(T, E, (m,))) Bravais(::Type{T}, ::Val{E}, m::NTuple{L,Any}) where {T,E,L} = Bravais{T,E,L}(sanitize_Matrix(T, E, m)) Bravais(::Type{T}, ::Val{E}, m::SMatrix{<:Any,L}) where {T,E,L} = Bravais{T,E,L}(sanitize_Matrix(T, E, m)) Bravais(::Type{T}, ::Val{E}, m::AbstractMatrix) where {T,E} = Bravais{T,E,size(m,2)}(sanitize_Matrix(T, E, m)) Bravais(::Type{T}, ::Val{E}, m::AbstractVector) where {T,E} = Bravais{T,E,1}(sanitize_Matrix(T, E, hcat(m))) Unitcell(sites::Vector{SVector{E,T}}, names, offsets) where {E,T} = Unitcell{T,E}(sites, names, offsets) function uniquenames!(names::Vector{Symbol}) allnames = Symbol[:_] for (i, name) in enumerate(names) if name in allnames names[i] = uniquename(allnames, name, i) @warn "Renamed repeated sublattice :$name to :$(names[i])" end push!(allnames, names[i]) end return names end function uniquename(allnames, name, i) newname = Symbol(Char(64+i)) # Lexicographic, starting from Char(65) = 'A' newname = newname in allnames ? uniquename(allnames, name, i + 1) : newname return newname end #endregion #region ## API ## bravais(l::Lattice) = l.bravais unitcell(l::Lattice) = l.unitcell nranges(l::Lattice) = l.nranges bravais_vectors(l::Lattice) = bravais_vectors(l.bravais) bravais_vectors(b::Bravais) = eachcol(b.matrix) bravais_matrix(l::Lattice) = bravais_matrix(l.bravais) bravais_matrix(b::Bravais{T,E,L}) where {T,E,L} = convert(SMatrix{E,L,T}, ntuple(i -> b.matrix[i], Val(E*L))) matrix(b::Bravais) = b.matrix sublatnames(l::Lattice) = sublatnames(l.unitcell) sublatnames(u::Unitcell) = u.names sublatname(l::Lattice, s) = sublatname(l.unitcell, s) sublatname(u::Unitcell, s) = u.names[s] sublatname(s::Sublat) = s.name sublatindex(l::Lattice, name::Symbol) = sublatindex(l.unitcell, name) function sublatindex(u::Unitcell, name::Symbol) i = findfirst(==(name), sublatnames(u)) i === nothing && boundserror(u, string(name)) return i end nsublats(l::Lattice) = nsublats(l.unitcell) nsublats(u::Unitcell) = length(u.names) sublats(l::Lattice) = sublats(l.unitcell) sublats(u::Unitcell) = 1:nsublats(u) nsites(s::Sublat) = length(s.sites) nsites(lat::Lattice, sublat...) = nsites(lat.unitcell, sublat...) nsites(u::Unitcell) = length(u.sites) nsites(u::Unitcell, sublat) = sublatlengths(u)[sublat] sites(s::Sublat) = s.sites sites(l::Lattice, sublat...) = sites(l.unitcell, sublat...) sites(u::Unitcell) = u.sites sites(u::Unitcell, sublat) = view(u.sites, siterange(u, sublat)) sites(u::Unitcell, ::Missing) = sites(u) # to work with QuanticaMakieExt sites(l::Lattice, name::Symbol) = sites(unitcell(l), name) sites(u::Unitcell, name::Symbol) = sites(u, sublatindex(u, name)) site(l::Lattice, i) = sites(l)[i] site(l::Lattice, i, dn) = site(l, i) + bravais_matrix(l) * dn siterange(l::Lattice, sublat...) = siterange(l.unitcell, sublat...) siterange(u::Unitcell, sublat::Integer) = (1+u.offsets[sublat]):u.offsets[sublat+1] siterange(u::Unitcell, name::Symbol) = siterange(u, sublatindex(u, name)) siterange(u::Unitcell) = 1:last(u.offsets) sitesublat(lat::Lattice, siteidx) = sitesublat(lat.unitcell.offsets, siteidx) function sitesublat(offsets, siteidx) l = length(offsets) for s in 2:l @inbounds offsets[s] + 1 > siteidx && return s - 1 end return l end sitesublatname(lat, i) = sublatname(lat, sitesublat(lat, i)) sitesublatiter(l::Lattice) = sitesublatiter(l.unitcell) sitesublatiter(u::Unitcell) = ((i, s) for s in sublats(u) for i in siterange(u, s)) offsets(l::Lattice) = offsets(l.unitcell) offsets(u::Unitcell) = u.offsets sublatlengths(lat::Lattice) = sublatlengths(lat.unitcell) sublatlengths(u::Unitcell) = diff(u.offsets) embdim(::Sublat{<:Any,E}) where {E} = E embdim(::Lattice{<:Any,E}) where {E} = E latdim(::Lattice{<:Any,<:Any,L}) where {L} = L numbertype(::Sublat{T}) where {T} = T numbertype(::Lattice{T}) where {T} = T zerocell(::Bravais{<:Any,<:Any,L}) where {L} = zero(SVector{L,Int}) zerocell(::Lattice{<:Any,<:Any,L}) where {L} = zero(SVector{L,Int}) zerocellsites(l::Lattice, i) = sites(zerocell(l), i) Base.length(l::Lattice) = nsites(l) Base.copy(l::Lattice) = deepcopy(l) Base.:(==)(l::Lattice, l´::Lattice) = l.bravais == l´.bravais && l.unitcell == l´.unitcell Base.:(==)(b::Bravais, b´::Bravais) = b.matrix == b´.matrix # we do not demand equal names for unitcells to be equal Base.:(==)(u::Unitcell, u´::Unitcell) = u.sites == u´.sites && u.offsets == u´.offsets #endregion #endregion ############################################################################################ # Selectors - see selectors.jl for methods #region struct SiteSelector{F,S,C} region::F sublats::S cells::C end const SiteSelectorAll = SiteSelector{Missing,Missing,Missing} struct AppliedSiteSelector{T,E,L} lat::Lattice{T,E,L} region::FunctionWrapper{Bool,Tuple{SVector{E,T}}} sublats::Vector{Int} cells::Vector{SVector{L,Int}} isnull::Bool # if isnull, the selector selects nothing, regardless of other fields end struct HopSelector{F,S,D,R} region::F sublats::S dcells::D range::R adjoint::Bool # make apply take the "adjoint" of the selector end struct AppliedHopSelector{T,E,L} lat::Lattice{T,E,L} region::FunctionWrapper{Bool,Tuple{SVector{E,T},SVector{E,T}}} sublats::Vector{Pair{Int,Int}} dcells::Vector{SVector{L,Int}} range::Tuple{T,T} isnull::Bool # if isnull, the selector selects nothing, regardless of other fields end struct Neighbors n::Int end #region ## Constructors ## HopSelector(re, su, dc, ra) = HopSelector(re, su, dc, ra, false) #endregion #region ## API ## Base.Int(n::Neighbors) = n.n region(s::Union{SiteSelector,HopSelector}) = s.region cells(s::SiteSelector) = s.cells lattice(ap::AppliedSiteSelector) = ap.lat lattice(ap::AppliedHopSelector) = ap.lat cells(ap::AppliedSiteSelector) = ap.cells dcells(ap::AppliedHopSelector) = ap.dcells # if isempty(s.dcells) or isempty(s.sublats), none were specified, so we must accept any inregion(r, s::AppliedSiteSelector) = s.region(r) inregion((r, dr), s::AppliedHopSelector) = s.region(r, dr) insublats(n, s::AppliedSiteSelector) = isempty(s.sublats) || n in s.sublats insublats(npair::Pair, s::AppliedHopSelector) = isempty(s.sublats) || npair in s.sublats incells(cell, s::AppliedSiteSelector) = isempty(s.cells) || cell in s.cells indcells(dcell, s::AppliedHopSelector) = isempty(s.dcells) || dcell in s.dcells iswithinrange(dr, s::AppliedHopSelector) = iswithinrange(dr, s.range) iswithinrange(dr, (rmin, rmax)::Tuple{Real,Real}) = ifelse(sign(rmin)*rmin^2 <= dr'dr <= rmax^2, true, false) isbelowrange(dr, s::AppliedHopSelector) = isbelowrange(dr, s.range) isbelowrange(dr, (rmin, rmax)::Tuple{Real,Real}) = ifelse(dr'dr < rmin^2, true, false) isnull(s::AppliedSiteSelector) = s.isnull isnull(s::AppliedHopSelector) = s.isnull Base.adjoint(s::HopSelector) = HopSelector(s.region, s.sublats, s.dcells, s.range, !s.adjoint) Base.NamedTuple(s::SiteSelector) = (; region = s.region, sublats = s.sublats, cells = s.cells) Base.NamedTuple(s::HopSelector) = (; region = s.region, sublats = s.sublats, dcells = s.dcells, range = s.range) #endregion #endregion ############################################################################################ # MatrixElementTypes #region struct SMatrixView{N,M,T,NM} s::SMatrix{N,M,T,NM} SMatrixView{N,M,T,NM}(mat) where {N,M,T,NM} = new(sanitize_SMatrix(SMatrix{N,M,T}, mat)) end const MatrixElementType{T} = Union{ Complex{T}, SMatrix{N,N,Complex{T}} where {N}, SMatrixView{N,N,Complex{T}} where {N}} const MatrixElementUniformType{T} = Union{ Complex{T}, SMatrix{N,N,Complex{T}} where {N}} const MatrixElementNonscalarType{T,N} = Union{ SMatrix{N,N,Complex{T}}, SMatrixView{N,N,Complex{T}}} #region ## Constructors ## SMatrixView(mat::SMatrix{N,M,T,NM}) where {N,M,T,NM} = SMatrixView{N,M,T,NM}(mat) SMatrixView{N,M}(mat::AbstractMatrix{T}) where {N,M,T} = SMatrixView{N,M,T}(mat) SMatrixView{N,M,T}(mat) where {N,M,T} = SMatrixView{N,M,T,N*M}(mat) SMatrixView(::Type{SMatrix{N,M,T,NM}}) where {N,M,T,NM} = SMatrixView{N,M,T,NM} #endregion #region ## API ## unblock(s::SMatrixView) = s.s unblock(s) = s Base.parent(s::SMatrixView) = s.s Base.view(s::SMatrixView, i...) = view(s.s, i...) Base.getindex(s::SMatrixView, i...) = getindex(s.s, i...) Base.zero(::Type{SMatrixView{N,M,T,NM}}) where {N,M,T,NM} = SMatrixView(zero(SMatrix{N,M,T,NM})) Base.zero(::S) where {S<:SMatrixView} = zero(S) Base.adjoint(s::SMatrixView) = SMatrixView(s.s') Base.:+(s::SMatrixView...) = SMatrixView(+(parent.(s)...)) Base.:-(s::SMatrixView) = SMatrixView(-parent.(s)) Base.:*(s::SMatrixView, x::Number) = SMatrixView(parent(s) * x) Base.:*(x::Number, s::SMatrixView) = SMatrixView(x * parent(s)) Base.:(==)(s::SMatrixView, s´::SMatrixView) = parent(s) == parent(s´) #endregion #endregion ############################################################################################ # LatticeSlice - see slices.jl for methods # Encodes subsets of sites (or orbitals) of a lattice in different cells. Produced e.g. by # lat[siteselector]. No ordering is guaranteed, but cells and sites must both be unique #region struct SiteLike end struct SiteLikePos{T,E,B<:MatrixElementType{T}} r::SVector{E,T} blocktype::Type{B} end struct OrbitalLike end struct OrbitalLikeGrouped groups::Dictionary{Int,UnitRange{Int}} # site => range of inds in parent # (non-selected sites are not present) end struct CellIndices{L,I,G<:Union{SiteLike,SiteLikePos,OrbitalLike,OrbitalLikeGrouped}} cell::SVector{L,Int} inds::I # can be anything: Int, Colon, Vector{Int}, etc. type::G # can be SiteLike, OrbitalLike or OrbitalLikeGrouped end const CellSites{L,I} = CellIndices{L,I,SiteLike} const CellSite{L} = CellIndices{L,Int,SiteLike} const CellSitePos{T,E,L,B} = CellIndices{L,Int,SiteLikePos{T,E,B}} # for non-spatial models const AnyCellSite{L} = Union{CellSite{L},CellSitePos{<:Any,<:Any,L}} const AnyCellSites{L} = Union{CellSites{L},CellSitePos{<:Any,<:Any,L}} const CellOrbitals{L,I} = CellIndices{L,I,OrbitalLike} const CellOrbitalsGrouped{L,I} = CellIndices{L,I,OrbitalLikeGrouped} const CellOrbital{L} = CellIndices{L,Int,OrbitalLike} const AnyCellOrbitals{L} = Union{CellOrbital{L},CellOrbitals{L},CellOrbitalsGrouped{L}} const CellIndicesDict{L,C<:CellIndices{L}} = Dictionary{SVector{L,Int},C} const CellSitesDict{L} = Dictionary{SVector{L,Int},CellSites{L,Vector{Int}}} const CellOrbitalsDict{L} = Dictionary{SVector{L,Int},CellOrbitals{L,Vector{Int}}} const CellOrbitalsGroupedDict{L} = Dictionary{SVector{L,Int},CellOrbitalsGrouped{L,Vector{Int}}} const AnyCellOrbitalsDict{L} = Union{CellOrbitalsDict{L},CellOrbitalsGroupedDict{L}} struct LatticeSlice{T,E,L,C<:CellIndices{L}} lat::Lattice{T,E,L} cellsdict::CellIndicesDict{L,C} offsets::Dictionary{SVector{L,Int},Int} # offset from number of indices in each cell siteindsdict::Dictionary{CellSite{L},UnitRange{Int}} # index range in slice per site function LatticeSlice{T,E,L,C}(lat, cellsdict) where {T,E,L,C} all(cs -> allunique(cs.inds), cellsdict) || argerror("CellSlice cells must be unique") offsetsvec = lengths_to_offsets(length, cellsdict) pop!(offsetsvec) # remove last entry, so there is one offset per cellsdict value offsets = Dictionary(cell.(cellsdict), offsetsvec) siteindsdict = siteindexdict(cellsdict) return new(lat, cellsdict, offsets, siteindsdict) end function LatticeSlice{T,E,L,C}(lat, cellsdict, offsets, siteindsdict) where {T,E,L,C} return new(lat, cellsdict, offsets, siteindsdict) end end const SiteSlice{T,E,L} = LatticeSlice{T,E,L,CellSites{L,Vector{Int}}} const OrbitalSlice{T,E,L} = LatticeSlice{T,E,L,CellOrbitals{L,Vector{Int}}} const OrbitalSliceGrouped{T,E,L} = LatticeSlice{T,E,L,CellOrbitalsGrouped{L,Vector{Int}}} const AnyOrbitalSlice = Union{OrbitalSlice,OrbitalSliceGrouped} #region ## Constructors ## # exported constructor for general site inds in a given cell (defaults to zero cell) sites(cell, inds) = CellSites(cell, inds) sites(inds) = CellSites(zero(SVector{0,Int}), inds) CellSite(cell, ind::Int) = CellIndices(sanitize_SVector(Int, cell), ind, SiteLike()) CellSite(c::CellSitePos) = CellSite(c.cell, c.inds) CellSites(cell, inds = Int[]) = CellIndices(sanitize_SVector(Int, cell), sanitize_cellindices(inds), SiteLike()) # no check for unique inds unsafe_cellsites(cell, inds) = CellIndices(cell, inds, SiteLike()) CellOrbitals(cell, inds = Int[]) = CellIndices(sanitize_SVector(Int, cell), sanitize_cellindices(inds), OrbitalLike()) CellOrbital(cell, ind::Int) = CellIndices(sanitize_SVector(Int, cell), ind, OrbitalLike()) CellOrbitalsGrouped(cell, inds, groups::Dictionary) = CellIndices(sanitize_SVector(Int, cell), sanitize_cellindices(inds), OrbitalLikeGrouped(groups)) # B <: MatrixElementType{T} CellSitePos(cell, ind, r, B) = CellIndices(sanitize_SVector(Int, cell), ind, SiteLikePos(r, B)) # LatticeSlice from an AbstractVector of CellIndices LatticeSlice(lat::Lattice, cs::AbstractVector{<:CellIndices}) = LatticeSlice(lat, cellinds_to_dict(cs)) # CellIndices to Dictionary(cell=>cellind) cellinds_to_dict(cs::AbstractVector{C}) where {L,C<:CellIndices{L}} = CellIndicesDict{L,C}(cell.(cs), cs) cellinds_to_dict(cells::AbstractVector{SVector{L,Int}}, cs::AbstractVector{C}) where {L,C<:CellIndices{L}} = CellIndicesDict{L,C}(cells, cs) cellinds_to_dict(cs::CellIndices{L}) where {L} = cellinds_to_dict(SVector(cs)) # don't allow single-CellSites in dictionaries (it polutes the LatticeSlice type diversity) cellinds_to_dict(cs::AbstractVector{C}) where {L,C<:CellSite{L}} = cellinds_to_dict(CellSites{L,Vector{Int}}.(cs)) # make OrbitalSliceGrouped scalar (i.e. groups are siteindex => siteindex:siteindex) scalarize(s::OrbitalSliceGrouped) = OrbitalSliceGrouped(s.lat, scalarize(s.cellsdict)) scalarize(d::CellOrbitalsGroupedDict) = scalarize.(d) scalarize(c::CellOrbitalsGrouped) = CellOrbitalsGrouped(c.cell, collect(keys(c.type.groups)), dictionary(i => i:i for i in keys(c.type.groups))) # outer constructor for LatticeSlice LatticeSlice(lat::Lattice{T,E,L}, cellsdict::CellIndicesDict{L,C}) where {T,E,L,C} = LatticeSlice{T,E,L,C}(lat, cellsdict) SiteSlice(lat::Lattice{T,E,L}, cellsdict::CellIndicesDict{L,C}) where {T,E,L,C<:CellSites} = LatticeSlice{T,E,L,C}(lat, cellsdict) OrbitalSlice(lat::Lattice{T,E,L}, cellsdict::CellIndicesDict{L,C}) where {T,E,L,C<:CellOrbitals} = LatticeSlice{T,E,L,C}(lat, cellsdict) OrbitalSliceGrouped(lat::Lattice{T,E,L}, cellsdict::CellIndicesDict{L,C}) where {T,E,L,C<:CellOrbitalsGrouped} = LatticeSlice{T,E,L,C}(lat, cellsdict) # ranges of inds, where inds are orbital indices for orbgroupeddict, site indices otherwise siteindexdict(cs::CellOrbitalsGroupedDict) = Dictionary(cellsites(cs), orbranges(cs)) # empty siteindexdict when sites are not known siteindexdict(::CellOrbitalsDict{L}) where {L} = Dictionary{CellSite{L}, UnitRange{Int}}() # For CellSitesDict, site indices are used siteindexdict(cs::CellSitesDict) = dictionary(c => i:i for (i, c) in enumerate(cellsites(cs))) unsafe_replace_lattice(l::LatticeSlice{T,E,L,C}, lat::Lattice{T,E´,L}) where {T,E,E´,L,C} = LatticeSlice{T,E´,L,C}(lat, cellsdict(l), offsets(l), siteindexdict(l)) #endregion #region ## API ## lattice(ls::LatticeSlice) = ls.lat siteindices(s::AnyCellSites) = s.inds siteindices(s::CellOrbitalsGrouped) = keys(s.type.groups) orbindices(s::AnyCellOrbitals) = s.inds siteindex(s::AnyCellSite) = s.inds orbindex(s::CellOrbital) = s.inds indexcollection(lold::LatticeSlice, lnew::LatticeSlice) = [j for s in cellsites(lnew) for j in indexcollection(lold, s)] indexcollection(l::LatticeSlice, c::CellSitePos) = siteindexdict(l)[sanitize_cellindices(CellSite(c), l)] indexcollection(l::LatticeSlice, c::CellSite) = siteindexdict(l)[sanitize_cellindices(c, l)] indexcollection(l::LatticeSlice, cs::CellSites) = sanitized_indexcollection(l, sanitize_cellindices(cs, l)) sanitized_indexcollection(l::LatticeSlice, cs::CellSites) = [j for i in siteindices(cs) for j in indexcollection(l, CellSite(cell(cs), i))] siteindexdict(l::LatticeSlice) = l.siteindsdict siteindexdict(l::OrbitalSlice) = missing # in this case, cellsites are not known cellsdict(l::LatticeSlice) = l.cellsdict cellsdict(l::LatticeSlice, cell) = l.cellsdict[cell] offsets(l::LatticeSlice) = l.offsets offsets(l::LatticeSlice, i) = l.offsets[i] ncells(x::LatticeSlice) = ncells(cellsdict(x)) ncells(x::CellIndicesDict) = length(x) ncells(x::CellIndices) = 1 cell(s::CellIndices) = s.cell cells(l::LatticeSlice) = keys(l.cellsdict) # replace cell with zero of requested dimension zerocellinds(c::CellIndices, ::Val{L}) where {L} = CellIndices(zero(SVector{L,Int}), c.inds, c.type) nsites(s::LatticeSlice, cell...) = nsites(cellsdict(s, cell...)) nsites(s::CellIndicesDict) = isempty(s) ? 0 : sum(nsites, s) nsites(c::CellIndices) = length(siteindices(c)) norbitals(s::AnyOrbitalSlice, cell...) = norbitals(cellsdict(s, cell...)) norbitals(s::CellIndicesDict) = isempty(s) ? 0 : sum(norbitals, s) norbitals(c::AnyCellOrbitals) = length(orbindices(c)) findsubcell(cell::SVector, d::CellIndicesDict) = get(d, cell, nothing) findsubcell(cell::SVector, l::LatticeSlice) = findsubcell(cell, cellsdict(l)) boundingbox(l::LatticeSlice) = boundingbox(keys(cellsdict(l))) # interface for non-spatial models (cell already defined for CellIndices) pos(s::CellSitePos) = s.type.r ind(s::CellSitePos) = s.inds # iterators sites(l::LatticeSlice) = (site(l.lat, i, cell(subcell)) for subcell in cellsdict(l) for i in siteindices(subcell)) # single-site (CellSite) iterator cellsites(cs::Union{SiteSlice,OrbitalSliceGrouped}) = cellsites(cs.cellsdict) cellsites(cdict::CellIndicesDict) = (CellSite(cell(cinds), i) for cinds in cdict for i in siteindices(cinds)) # single-orbital (CellOrbital) iterator cellorbs(co::Union{OrbitalSlice,OrbitalSliceGrouped}) = cellorbs(co.cellsdict) cellorbs(codict::Union{CellOrbitalsDict,CellOrbitalsGroupedDict}) = (CellOrbital(cell(corbs), i) for corbs in codict for i in orbindices(corbs)) # orbitals in unit cell for each site orbgroups(s::CellOrbitalsGrouped) = s.type.groups orbgroups(s::CellOrbitalsGrouped, i::Integer) = s.type.groups[i] orbgroups(d::CellOrbitalsGroupedDict) = (orbrng for corbs in d for orbrng in orbgroups(corbs)) orbgroups(cs::OrbitalSliceGrouped) = orbgroups(cellsdict(cs)) # set of consecutive orbital ranges for each site in slice orbranges(cs::OrbitalSliceGrouped) = orbranges(cellsdict(cs)) orbranges(cs::Union{CellOrbitalsGrouped, CellOrbitalsGroupedDict}) = Iterators.accumulate( (rng, rng´) -> maximum(rng)+1:maximum(rng)+length(rng´), orbgroups(cs), init = 0:0) Base.isempty(s::LatticeSlice) = isempty(s.cellsdict) Base.isempty(s::CellIndices) = isempty(s.inds) Base.length(l::LatticeSlice) = nsites(l) Base.length(c::CellIndices) = length(c.inds) Base.parent(ls::LatticeSlice) = ls.lat Base.copy(ls::LatticeSlice) = LatticeSlice(ls.lat, copy(ls.cellsdict)) #endregion #endregion ############################################################################################ # Models - see models.jl for methods #region abstract type AbstractModel end abstract type AbstractModelTerm end # wrapper of a function f(x1, ... xN; kw...) with N arguments and the kwargs in params struct ParametricFunction{N,F} f::F params::Vector{Symbol} end ## Non-parametric ## struct OnsiteTerm{F,S<:SiteSelector,T<:Number} <: AbstractModelTerm f::F selector::S coefficient::T end # specialized for a given lattice *and* hamiltonian - for hamiltonian building struct AppliedOnsiteTerm{T,E,L,B} <: AbstractModelTerm f::FunctionWrapper{B,Tuple{SVector{E,T},Int}} # o(r, sublat_orbitals) selector::AppliedSiteSelector{T,E,L} end struct HoppingTerm{F,S<:HopSelector,T<:Number} <: AbstractModelTerm f::F selector::S coefficient::T end # specialized for a given lattice *and* hamiltonian - for hamiltonian building struct AppliedHoppingTerm{T,E,L,B} <: AbstractModelTerm f::FunctionWrapper{B,Tuple{SVector{E,T},SVector{E,T},Tuple{Int,Int}}} # t(r, dr, (orbs1, orbs2)) selector::AppliedHopSelector{T,E,L} end const AbstractTightbindingTerm = Union{OnsiteTerm, AppliedOnsiteTerm, HoppingTerm, AppliedHoppingTerm} struct TightbindingModel{T<:NTuple{<:Any,AbstractTightbindingTerm}} <: AbstractModel terms::T # Collection of `AbstractTightbindingTerm`s end ## Parametric ## # We fuse applied and non-applied versions, since these only apply the selector, not f struct ParametricOnsiteTerm{N,S<:Union{SiteSelector,AppliedSiteSelector},F<:ParametricFunction{N},T<:Number} <: AbstractModelTerm f::F selector::S coefficient::T spatial::Bool # If true, f is a function of position r. Otherwise it takes a single CellSite end struct ParametricHoppingTerm{N,S<:Union{HopSelector,AppliedHopSelector},F<:ParametricFunction{N},T<:Number} <: AbstractModelTerm f::F selector::S coefficient::T spatial::Bool # If true, f is a function of positions r, dr. Otherwise it takes two CellSite's end const AbstractParametricTerm{N} = Union{ParametricOnsiteTerm{N},ParametricHoppingTerm{N}} const AppliedParametricTerm{N} = Union{ParametricOnsiteTerm{N,<:AppliedSiteSelector}, ParametricHoppingTerm{N,<:AppliedHopSelector}} struct ParametricModel{T<:NTuple{<:Any,AbstractParametricTerm},M<:TightbindingModel} <: AbstractModel npmodel::M # non-parametric model to use as base terms::T # Collection of `AbstractParametricTerm`s end #region ## Constructors ## ParametricFunction{N}(f::F, params = Symbol[]) where {N,F} = ParametricFunction{N,F}(f, params) TightbindingModel(ts::AbstractTightbindingTerm...) = TightbindingModel(ts) ParametricModel(ts::AbstractParametricTerm...) = ParametricModel(TightbindingModel(), ts) ParametricModel(m::TightbindingModel) = ParametricModel(m, ()) ParametricModel(m::ParametricModel) = m #endregion #region ## API ## (f::ParametricFunction)(args...; kw...) = f.f(args...; kw...) nonparametric(m::TightbindingModel) = m nonparametric(m::ParametricModel) = m.npmodel terms(t::AbstractModel) = t.terms allterms(t::TightbindingModel) = t.terms allterms(t::ParametricModel) = (terms(nonparametric(t))..., t.terms...) selector(t::AbstractModelTerm) = t.selector functor(t::AbstractModelTerm) = t.f parameters(t::AbstractParametricTerm) = t.f.params coefficient(t::OnsiteTerm) = t.coefficient coefficient(t::HoppingTerm) = t.coefficient coefficient(t::AbstractParametricTerm) = t.coefficient narguments(t::OnsiteTerm{<:Function}) = 1 narguments(t::HoppingTerm{<:Function}) = 2 narguments(t::OnsiteTerm) = 0 narguments(t::HoppingTerm) = 0 narguments(t::AbstractParametricTerm) = narguments(t.f) narguments(::ParametricFunction{N}) where {N} = N is_spatial(t::AbstractParametricTerm) = t.spatial is_spatial(t) = true ## call API## (term::OnsiteTerm{<:Function})(r) = term.coefficient * term.f(r) (term::OnsiteTerm)(r) = term.coefficient * term.f (term::AppliedOnsiteTerm)(r, orbs) = term.f(r, orbs) (term::HoppingTerm{<:Function})(r, dr) = term.coefficient * term.f(r, dr) (term::HoppingTerm)(r, dr) = term.coefficient * term.f (term::AppliedHoppingTerm)(r, dr, orbs) = term.f(r, dr, orbs) (term::AbstractParametricTerm{0})(args...; kw...) = term.coefficient * term.f.f(; kw...) (term::AbstractParametricTerm{1})(x, args...; kw...) = term.coefficient * term.f.f(x; kw...) (term::AbstractParametricTerm{2})(x, y, args...; kw...) = term.coefficient * term.f.f(x, y; kw...) (term::AbstractParametricTerm{3})(x, y, z, args...; kw...) = term.coefficient * term.f.f(x, y, z; kw...) # We need these for SelfEnergyModelSolver, which uses a ParametricModel. We return a # ParametricOnsiteTerm, not an OnsiteTerm because the latter is tied to a Hamiltonian at its # orbital structure, not only to a site selection function (t::ParametricOnsiteTerm{N})(; kw...) where {N} f = ParametricFunction{N}((args...) -> t.f(args...; kw...)) # no params return ParametricOnsiteTerm(f, t.selector, t.coefficient, t.spatial) end function (t::ParametricHoppingTerm{N})(; kw...) where {N} f = ParametricFunction{N}((args...) -> t.f(args...; kw...)) # no params return ParametricHoppingTerm(f, t.selector, t.coefficient, t.spatial) end ## Model term algebra Base.:*(x::Number, m::TightbindingModel) = TightbindingModel(x .* terms(m)) Base.:*(x::Number, m::ParametricModel) = ParametricModel(x * nonparametric(m), x .* terms(m)) Base.:*(m::AbstractModel, x::Number) = x * m Base.:-(m::AbstractModel) = (-1) * m Base.:+(m::TightbindingModel, m´::TightbindingModel) = TightbindingModel((terms(m)..., terms(m´)...)) Base.:+(m::ParametricModel, m´::ParametricModel) = ParametricModel(nonparametric(m) + nonparametric(m´), (terms(m)..., terms(m´)...)) Base.:+(m::TightbindingModel, m´::ParametricModel) = ParametricModel(m + nonparametric(m´), terms(m´)) Base.:+(m::ParametricModel, m´::TightbindingModel) = m´ + m Base.:-(m::AbstractModel, m´::AbstractModel) = m + (-m´) Base.:*(x::Number, o::OnsiteTerm) = OnsiteTerm(o.f, o.selector, x * o.coefficient) Base.:*(x::Number, t::HoppingTerm) = HoppingTerm(t.f, t.selector, x * t.coefficient) Base.:*(x::Number, o::ParametricOnsiteTerm) = ParametricOnsiteTerm(o.f, o.selector, x * o.coefficient, o.spatial) Base.:*(x::Number, t::ParametricHoppingTerm) = ParametricHoppingTerm(t.f, t.selector, x * t.coefficient, t.spatial) Base.adjoint(m::TightbindingModel) = TightbindingModel(adjoint.(terms(m))...) Base.adjoint(m::ParametricModel) = ParametricModel(adjoint.(terms(m))...) Base.adjoint(t::OnsiteTerm{<:Function}) = OnsiteTerm(r -> t.f(r)', t.selector, t.coefficient') Base.adjoint(t::OnsiteTerm) = OnsiteTerm(t.f', t.selector, t.coefficient') Base.adjoint(t::HoppingTerm{<:Function}) = HoppingTerm((r, dr) -> t.f(r, -dr)', t.selector', t.coefficient') Base.adjoint(t::HoppingTerm) = HoppingTerm(t.f', t.selector', t.coefficient') function Base.adjoint(o::ParametricOnsiteTerm{N}) where {N} f = ParametricFunction{N}((args...; kw...) -> o.f(args...; kw...)', o.f.params) return ParametricOnsiteTerm(f, o.selector, o.coefficient', o.spatial) end function Base.adjoint(t::ParametricHoppingTerm{N}) where {N} f = ParametricFunction{N}((args...; kw...) -> t.f(args...; kw...)', t.f.params) return ParametricHoppingTerm(f, t.selector, t.coefficient', t.spatial) end #endregion #endregion ############################################################################################ # Model Modifiers - see models.jl for methods #region abstract type AbstractModifier end struct OnsiteModifier{N,S<:SiteSelector,F<:ParametricFunction{N}} <: AbstractModifier f::F selector::S spatial::Bool end struct AppliedOnsiteModifier{B,N,R<:SVector,F<:ParametricFunction{N},S<:SiteSelector,P<:CellSitePos} <: AbstractModifier parentselector::S # unapplied selector, needed to grow a ParametricHamiltonian blocktype::Type{B} # These are needed to cast the modification to the sublat block type f::F ptrs::Vector{Tuple{Int,R,P,Int}} # [(ptr, r, si, norbs)...] for each selected site, dn = 0 harmonic spatial::Bool # If true, f is a function of position r. Otherwise it takes a single CellSite end struct HoppingModifier{N,S<:HopSelector,F<:ParametricFunction{N}} <: AbstractModifier f::F selector::S spatial::Bool # If true, f is a function of positions r, dr. Otherwise it takes two CellSite's end struct AppliedHoppingModifier{B,N,R<:SVector,F<:ParametricFunction{N},S<:HopSelector,P<:CellSitePos} <: AbstractModifier parentselector::S # unapplied selector, needed to grow a ParametricHamiltonian blocktype::Type{B} # These are needed to cast the modification to the sublat block type f::F ptrs::Vector{Vector{Tuple{Int,R,R,P,P,Tuple{Int,Int}}}} # [[(ptr, r, dr, si, sj, (norbs, norbs´)), ...], ...] for each selected hop on each harmonic spatial::Bool # If true, f is a function of positions r, dr. Otherwise it takes two CellSite's end const Modifier = Union{OnsiteModifier,HoppingModifier} const AppliedModifier = Union{AppliedOnsiteModifier,AppliedHoppingModifier} #region ## Constructors ## AppliedOnsiteModifier(m::AppliedOnsiteModifier, ptrs) = AppliedOnsiteModifier(m.parentselector, m.blocktype, m.f, ptrs, m.spatial) AppliedHoppingModifier(m::AppliedHoppingModifier, ptrs) = AppliedHoppingModifier(m.parentselector, m.blocktype, m.f, ptrs, m.spatial) #endregion #region ## API ## selector(m::Modifier) = m.selector selector(m::AppliedModifier) = m.parentselector parameters(m::AbstractModifier) = m.f.params parametric_function(m::AbstractModifier) = m.f pointers(m::AppliedModifier) = m.ptrs blocktype(m::AppliedModifier) = m.blocktype is_spatial(m::AbstractModifier) = m.spatial narguments(m::AbstractModifier) = narguments(m.f) @inline (m::AppliedOnsiteModifier{B,1})(o, r, orbs; kw...) where {B} = mask_block(B, m.f.f(o; kw...), (orbs, orbs)) @inline (m::AppliedOnsiteModifier{B,2})(o, r, orbs; kw...) where {B} = mask_block(B, m.f.f(o, r; kw...), (orbs, orbs)) @inline (m::AppliedHoppingModifier{B,1})(t, r, dr, orborb; kw...) where {B} = mask_block(B, m.f.f(t; kw...), orborb) @inline (m::AppliedHoppingModifier{B,3})(t, r, dr, orborb; kw...) where {B} = mask_block(B, m.f.f(t, r, dr; kw...), orborb) Base.similar(m::A) where {A <: AppliedModifier} = A(m.blocktype, m.f, similar(m.ptrs, 0), m.spatial) Base.parent(m::AppliedOnsiteModifier) = OnsiteModifier(m.f, m.parentselector, m.spatial) Base.parent(m::AppliedHoppingModifier) = HoppingModifier(m.f, m.parentselector, m.spatial) #endregion #endregion ############################################################################################ # Intrablock and Interblock - see models.jl # Wrappers to restrict models and modifiers to certain blocks of a Hamiltonian #region struct Interblock{M<:Union{AbstractModel,AbstractModifier},N} parent::M block::NTuple{N,UnitRange{Int}} # May be two or more ranges end struct Intrablock{M<:Union{AbstractModel,AbstractModifier}} parent::M block::UnitRange{Int} end const AnyAbstractModifier = Union{AbstractModifier,Interblock{<:AbstractModifier},Intrablock{<:AbstractModifier}} const AnyModifier = Union{Modifier,Interblock{<:Modifier},Intrablock{<:Modifier}} const BlockModifier = Union{Interblock{<:AbstractModifier},Intrablock{<:AbstractModifier}} Base.parent(m::Union{Interblock,Intrablock}) = m.parent block(m::Union{Interblock,Intrablock}) = m.block #endregion ############################################################################################ # OrbitalBlockStructure # Block structure for Hamiltonians, sorted by sublattices #region struct OrbitalBlockStructure{B} blocksizes::Vector{Int} # number of orbitals per site in each sublattice subsizes::Vector{Int} # number of blocks (sites) in each sublattice function OrbitalBlockStructure{B}(blocksizes, subsizes) where {B} subsizes´ = Quantica.sanitize_Vector_of_Type(Int, subsizes) # This checks also that they are of equal length blocksizes´ = Quantica.sanitize_Vector_of_Type(Int, length(subsizes´), blocksizes) return new(blocksizes´, subsizes´) end end #region ## Constructors ## @inline function OrbitalBlockStructure(T, orbitals, subsizes) orbitals´ = sanitize_orbitals(orbitals) # <:Union{Val,distinct_collection} B = blocktype(T, orbitals´) return OrbitalBlockStructure{B}(orbitals´, subsizes) end # Useful as a minimal constructor when no orbital information is known OrbitalBlockStructure{B}(hsize::Int) where {B} = OrbitalBlockStructure{B}(Val(1), [hsize]) blocktype(::Type{T}, m::Val{1}) where {T} = Complex{T} blocktype(::Type{T}, m::Val{N}) where {T,N} = SMatrix{N,N,Complex{T},N*N} blocktype(T::Type, distinct_norbs) = maybe_SMatrixView(blocktype(T, val_maximum(distinct_norbs))) maybe_SMatrixView(C::Type{<:Complex}) = C maybe_SMatrixView(S::Type{<:SMatrix}) = SMatrixView(S) val_maximum(n::Int) = Val(n) val_maximum(ns) = Val(maximum(argval.(ns))) argval(::Val{N}) where {N} = N argval(n::Int) = n #endregion #region ## API ## blocktype(::OrbitalBlockStructure{B}) where {B} = B blockeltype(::OrbitalBlockStructure{<:MatrixElementType{T}}) where {T} = Complex{T} blocksizes(b::OrbitalBlockStructure) = b.blocksizes subsizes(b::OrbitalBlockStructure) = b.subsizes flatsize(b::OrbitalBlockStructure) = blocksizes(b)' * subsizes(b) flatsize(b::OrbitalBlockStructure{B}, ls::SiteSlice) where {B<:Union{Complex,SMatrix}} = length(ls) * blocksize(b) flatsize(b::OrbitalBlockStructure, ls::SiteSlice) = sum(cs -> flatsize(b, cs), cellsites(ls); init = 0) flatsize(b::OrbitalBlockStructure, cs::AnyCellSite) = blocksize(b, siteindex(cs)) unflatsize(b::OrbitalBlockStructure) = sum(subsizes(b)) blocksize(b::OrbitalBlockStructure, iunflat, junflat) = (blocksize(b, iunflat), blocksize(b, junflat)) blocksize(b::OrbitalBlockStructure{<:SMatrixView}, iunflat) = length(flatrange(b, iunflat)) blocksize(b::OrbitalBlockStructure{B}, iunflat...) where {N,B<:SMatrix{N}} = N blocksize(b::OrbitalBlockStructure{B}, iunflat...) where {B<:Number} = 1 siterange(b::OrbitalBlockStructure) = 1:unflatsize(b) orbrange(b::OrbitalBlockStructure) = 1:flatsize(b) function sublatorbrange(b::OrbitalBlockStructure, sind::Integer) bss = blocksizes(b) sss = subsizes(b) offset = sind == 1 ? 0 : sum(i -> bss[i] * sss[i], 1:sind-1) rng = offset + 1:offset + bss[sind] * sss[sind] return rng end # Basic relation: iflat - 1 == (iunflat - soffset - 1) * b + soffset´ function flatrange(b::OrbitalBlockStructure{<:SMatrixView}, iunflat::Integer) checkinrange(iunflat, b) soffset = 0 soffset´ = 0 @inbounds for (s, b) in zip(b.subsizes, b.blocksizes) if soffset + s >= iunflat offset = muladd(iunflat - soffset - 1, b, soffset´) return offset+1:offset+b end soffset += s soffset´ += b * s end @boundscheck(blockbounds_error()) return 1:0 end flatrange(b::OrbitalBlockStructure{<:SMatrix{N}}, iunflat::Integer) where {N} = (checkinrange(iunflat, b); ((iunflat - 1) * N + 1 : iunflat * N)) flatrange(b::OrbitalBlockStructure{<:Number}, iunflat::Integer) = (checkinrange(iunflat, b); iunflat:iunflat) flatrange(o::OrbitalBlockStructure, ::Colon) = orbrange(o) function flatrange(o::OrbitalBlockStructure, runflat::AbstractUnitRange) imin, imax = first(runflat), last(runflat) checkinrange(imin, o) checkinrange(imax, o) orng = first(flatrange(o, imin)) : last(flatrange(o, imax)) return orng end checkinrange(siteind::Integer, b::OrbitalBlockStructure) = @boundscheck(1 <= siteind <= flatsize(b) || argerror("Requested site $siteind out of range [1, $(flatsize(b))]")) flatindex(b::OrbitalBlockStructure, i) = first(flatrange(b, i)) function unflatindex_and_blocksize(o::OrbitalBlockStructure{<:SMatrixView}, iflat::Integer) soffset = 0 soffset´ = 0 @boundscheck(iflat < 0 && blockbounds_error()) @inbounds for (s, b) in zip(o.subsizes, o.blocksizes) if soffset´ + b * s >= iflat iunflat = (iflat - soffset´ - 1) ÷ b + soffset + 1 return iunflat, b end soffset += s soffset´ += b * s end @boundscheck(blockbounds_error()) end @noinline blockbounds_error() = throw(BoundsError()) unflatindex_and_blocksize(::OrbitalBlockStructure{B}, iflat::Integer) where {N,B<:SMatrix{N}} = (iflat - 1)÷N + 1, N unflatindex_and_blocksize(::OrbitalBlockStructure{<:Number}, iflat::Integer) = (iflat, 1) Base.copy(b::OrbitalBlockStructure{B}) where {B} = OrbitalBlockStructure{B}(copy(blocksizes(b)), copy(subsizes(b))) Base.:(==)(b::OrbitalBlockStructure{B}, b´::OrbitalBlockStructure{B}) where {B} = b.blocksizes == b´.blocksizes && b.subsizes == b´.subsizes #endregion #endregion ############################################################################################ ## Special matrices - see specialmatrices.jl for methods #region ############################################################################################ # HybridSparseMatrix # Internal Matrix type for Bloch harmonics in Hamiltonians # Wraps site-block + flat versions of the same SparseMatrixCSC #region struct HybridSparseMatrix{T,B<:MatrixElementType{T}} <: SparseArrays.AbstractSparseMatrixCSC{B,Int} blockstruct::OrbitalBlockStructure{B} unflat::SparseMatrixCSC{B,Int} flat::SparseMatrixCSC{Complex{T},Int} # 0 = in sync, 1 = flat needs sync, -1 = unflat needs sync, 2 = none initialized sync_state::Base.RefValue{Int} # Number of stored nonzeros in unflat and flat - to guard against tampering ufnnz::Vector{Int} end #region ## Constructors ## HybridSparseMatrix(bs, unflat, flat, sync_state) = HybridSparseMatrix(bs, unflat, flat, sync_state, [nnz(unflat), nnz(flat)]) HybridSparseMatrix(b::OrbitalBlockStructure{Complex{T}}, flat::SparseMatrixCSC{Complex{T},Int}) where {T} = HybridSparseMatrix(b, flat, flat, Ref(0)) # aliasing function HybridSparseMatrix(b::OrbitalBlockStructure{B}, unflat::SparseMatrixCSC{B,Int}) where {T,B<:MatrixElementNonscalarType{T}} m = HybridSparseMatrix(b, unflat, flat(b, unflat), Ref(0)) needs_flat_sync!(m) return m end function HybridSparseMatrix(b::OrbitalBlockStructure{B}, flat::SparseMatrixCSC{Complex{T},Int}) where {T,B<:MatrixElementNonscalarType{T}} m = HybridSparseMatrix(b, unflat(b, flat), flat, Ref(0)) needs_unflat_sync!(m) return m end #endregion #region ## API ## blockstructure(s::HybridSparseMatrix) = s.blockstruct unflat_unsafe(s::HybridSparseMatrix) = s.unflat flat_unsafe(s::HybridSparseMatrix) = s.flat syncstate(s::HybridSparseMatrix) = s.sync_state check_integrity(s::HybridSparseMatrix) = (nnz(s.unflat) == s.ufnnz[1] && nnz(s.flat) == s.ufnnz[2]) || argerror("The AbstractHamiltonian seems to have been modified externally and has become corrupted") update_nnz!(s::HybridSparseMatrix) = (s.ufnnz .= (nnz(s.unflat), nnz(s.flat))) # are flat === unflat? Only for scalar eltype isaliased(::HybridSparseMatrix{<:Any,<:Complex}) = true isaliased(::HybridSparseMatrix) = false Base.size(h::HybridSparseMatrix, i::Integer...) = size(unflat_unsafe(h), i...) flatsize(h::HybridSparseMatrix, args...) = flatsize(blockstructure(h), args...) SparseArrays.getcolptr(s::HybridSparseMatrix) = getcolptr(s.unflat) SparseArrays.rowvals(s::HybridSparseMatrix) = rowvals(s.unflat) SparseArrays.nonzeros(s::HybridSparseMatrix) = nonzeros(s.unflat) #endregion #endregion ############################################################################################ # SparseMatrixView # View of a SparseMatrixCSC that can produce a proper (non-view) SparseMatrixCSC # of size possibly larger than the view (padded with zeros) #region struct SparseMatrixView{C,V<:SubArray} matview::V mat::SparseMatrixCSC{C,Int} ptrs::Vector{Int} # ptrs of parent(matview) that affect mat end #region ## Constructor ## function SparseMatrixView(matview::SubArray{C,<:Any,<:SparseMatrixCSC}, dims = missing) where {C} matparent = parent(matview) viewrows, viewcols = matview.indices rows = rowvals(matparent) ptrs = Int[] for col in viewcols, ptr in nzrange(matparent, col) rows[ptr] in viewrows && push!(ptrs, ptr) end if dims === missing || dims == size(matview) mat = sparse(matview) else nr, nc = dims nrv, ncv = size(matview) nr >= nrv && nc >= ncv || argerror("SparseMatrixView dims cannot be smaller than size(view) = $((nrv, ncv))") # it's important to preserve structural zeros in mat, which sparse(matview) does mat = [sparse(matview) spzeros(C, nrv, nc - ncv); spzeros(C, nr - nrv, ncv) spzeros(C, nr - nrv, nc - ncv)] end return SparseMatrixView(matview, mat, ptrs) end #endregion #region ## API ## matrix(s::SparseMatrixView) = s.mat function update!(s::SparseMatrixView) nzs = nonzeros(s.mat) nzs´ = nonzeros(parent(s.matview)) for (i, ptr) in enumerate(s.ptrs) nzs[i] = nzs´[ptr] end return s end Base.size(s::SparseMatrixView, i...) = size(s.mat, i...) minimal_callsafe_copy(s::SparseMatrixView) = SparseMatrixView(view(copy(parent(s.matview)), s.matview.indices...), copy(s.mat), s.ptrs) minimal_callsafe_copy(s::SparseMatrixView, aliasham) = SparseMatrixView(view(call!_output(aliasham), s.matview.indices...), copy(s.mat), s.ptrs) #endregion #endregion ############################################################################################ # BlockSparseMatrix and BlockMatrix # MatrixBlock : Block within a parent matrix, at a given set of rows and cols # BlockSparseMatrix : SparseMatrixCSC with added blocks that can be updated in place # BlockMatrix : Matrix with added blocks that can be updated in place #region abstract type AbstractBlockMatrix end struct MatrixBlock{C<:Number,A<:AbstractMatrix,UR,UC,D<:Union{Missing,Matrix}} block::A rows::UR # row indices in parent matrix for each row in block cols::UC # col indices in parent matrix for each col in block coefficient::C # coefficient to apply to block denseblock::D # either missing or Matrix(block), to aid in ldiv end struct BlockSparseMatrix{C,N,M<:NTuple{N,MatrixBlock}} <: AbstractBlockMatrix mat::SparseMatrixCSC{C,Int} blocks::M ptrs::NTuple{N,Vector{Int}} # nzvals indices for blocks end struct BlockMatrix{C,N,M<:NTuple{N,MatrixBlock}} <: AbstractBlockMatrix mat::Matrix{C} blocks::M end #region ## Constructors ## function MatrixBlock(block::AbstractMatrix{C}, rows, cols, denseblock = missing) where {C} checkblockinds(block, rows, cols) return MatrixBlock(block, rows, cols, one(C), denseblock) end function MatrixBlock(block::SubArray, rows, cols, denseblock = missing) checkblockinds(block, rows, cols) m = simplify_matrixblock(block, rows, cols) return MatrixBlock(m.block, m.rows, m.cols, m.coefficient, denseblock) end BlockSparseMatrix(mblocks::MatrixBlock...) = BlockSparseMatrix(mblocks) function BlockSparseMatrix(mblocks::NTuple{<:Any,MatrixBlock}, dims = missing) blocks = blockmat.(mblocks) C = promote_type(eltype.(blocks)...) I, J = Int[], Int[] foreach(b -> appendIJ!(I, J, b), mblocks) mat = dims === missing ? sparse(I, J, zero(C)) : sparse(I, J, zero(C), dims...) ptrs = getblockptrs.(mblocks, Ref(mat)) return BlockSparseMatrix(mat, mblocks, ptrs) end function BlockMatrix(mblocks::MatrixBlock...) nrows = maxrows(mblocks) ncols = maxcols(mblocks) C = promote_type(eltype.(blocks)...) mat = zeros(C, nrows, ncols) return BlockMatrix(mat, blocks) end #endregion #region ## API ## blockmat(m::MatrixBlock) = m.block blockrows(m::MatrixBlock) = m.rows blockcols(m::MatrixBlock) = m.cols coefficient(m::MatrixBlock) = m.coefficient denseblockmat(m::MatrixBlock) = m.denseblock pointers(m::BlockSparseMatrix) = m.ptrs blocks(m::AbstractBlockMatrix) = m.blocks matrix(b::AbstractBlockMatrix) = b.mat maxrows(mblocks::NTuple{<:Any,MatrixBlock}) = maximum(b -> maximum(b.rows), mblocks; init = 0) maxcols(mblocks::NTuple{<:Any,MatrixBlock}) = maximum(b -> maximum(b.cols), mblocks; init = 0) Base.size(b::AbstractBlockMatrix, i...) = size(b.mat, i...) Base.size(b::MatrixBlock, i...) = size(blockmat(b), i...) Base.eltype(b::MatrixBlock) = eltype(blockmat(b)) Base.eltype(m::AbstractBlockMatrix) = eltype(matrix(m)) Base.:-(b::MatrixBlock) = MatrixBlock(blockmat(b), blockrows(b), blockcols(b), -coefficient(b), denseblockmat(b)) @noinline function checkblockinds(block, rows, cols) length.((rows, cols)) == size(block) && allunique(rows) && (cols === rows || allunique(cols)) || internalerror("MatrixBlock: mismatched size") return nothing end isspzeros(b::MatrixBlock) = isspzeros(b.block) isspzeros(b::SubArray) = isspzeros(parent(b)) isspzeros(b::SparseMatrixCSC) = iszero(nnz(b)) isspzeros(b::Tuple) = all(isspzeros, b) isspzeros(b) = false minimal_callsafe_copy(s::BlockSparseMatrix) = BlockSparseMatrix(copy(s.mat), minimal_callsafe_copy.(s.blocks), s.ptrs) minimal_callsafe_copy(s::BlockMatrix) = BlockMatrix(copy(s.mat), minimal_callsafe_copy.(s.blocks)) minimal_callsafe_copy(m::MatrixBlock) = MatrixBlock(m.block, m.rows, m.cols, m.coefficient, copy_ifnotmissing(m.denseblock)) #endregion #endregion ############################################################################################ # InverseGreenBlockSparse # BlockSparseMatrix representing G⁻¹ on a unitcell (+ possibly extended sites) # with self-energies as blocks. It knows which indices correspond to which contacts #region struct InverseGreenBlockSparse{C} mat::BlockSparseMatrix{C} nonextrng::UnitRange{Int} # range of indices for non-extended sites unitcinds::Vector{Vector{Int}} # orbital indices in parent unitcell of each contact unitcindsall::Vector{Int} # merged, uniqued and sorted unitcinds source::Matrix{C} # preallocation for ldiv! solve end #region ## API ## matrix(s::InverseGreenBlockSparse) = matrix(s.mat) orbrange(s::InverseGreenBlockSparse) = s.nonextrng extrange(s::InverseGreenBlockSparse) = last(s.nonextrng + 1):size(mat, 1) Base.size(s::InverseGreenBlockSparse, I::Integer...) = size(matrix(s), I...) Base.axes(s::InverseGreenBlockSparse, I::Integer...) = axes(matrix(s), I...) # updates only ω block and applies all blocks to BlockSparseMatrix function update!(s::InverseGreenBlockSparse, ω) bsm = s.mat Imat = blockmat(first(blocks(bsm))) Imat.diag .= ω # Imat should be <: Diagonal return update!(bsm) end #endregion #endregion #endregion top ############################################################################################ # Harmonic - see hamiltonian.jl for methods #region struct Harmonic{T,L,B} dn::SVector{L,Int} h::HybridSparseMatrix{T,B} end #region ## API ## dcell(h::Harmonic) = h.dn matrix(h::Harmonic) = h.h flat(h::Harmonic) = flat(h.h) unflat(h::Harmonic) = unflat(h.h) flat_unsafe(h::Harmonic) = flat_unsafe(h.h) unflat_unsafe(h::Harmonic) = unflat_unsafe(h.h) Base.size(h::Harmonic, i...) = size(matrix(h), i...) Base.isless(h::Harmonic, h´::Harmonic) = sum(abs2, dcell(h)) < sum(abs2, dcell(h´)) Base.zero(h::Harmonic{<:Any,<:Any,B}) where {B} = Harmonic(zero(dcell(h)), zero(matrix(h))) Base.copy(h::Harmonic) = Harmonic(dcell(h), copy(matrix(h))) Base.:(==)(h::Harmonic, h´::Harmonic) = h.dn == h´.dn && unflat(h.h) == unflat(h´.h) Base.iszero(h::Harmonic) = iszero(flat(h)) #endregion #endregion ############################################################################################ # UnflatInds, HybridInds - getindex(::AbstractHamiltonian), see hamiltonian.jl for methods #region struct UnflatInds{T} inds::T end struct HybridInds{T} inds::T end unflat(i) = UnflatInds(i) unflat(i, is...) = UnflatInds((i, is...)) unflat() = UnflatInds(()) hybrid(i) = HybridInds(i) hybrid(i, is...) = HybridInds((i, is...)) hybrid() = HybridInds(()) Base.parent(u::UnflatInds) = u.inds Base.parent(u::HybridInds) = u.inds #endregion ############################################################################################ # Hamiltonian - see hamiltonian.jl for methods #region abstract type AbstractHamiltonian{T,E,L,B} end const AbstractHamiltonian0D{T,E,B} = AbstractHamiltonian{T,E,0,B} const AbstractHamiltonian1D{T,E,B} = AbstractHamiltonian{T,E,1,B} struct Hamiltonian{T,E,L,B} <: AbstractHamiltonian{T,E,L,B} lattice::Lattice{T,E,L} blockstruct::OrbitalBlockStructure{B} harmonics::Vector{Harmonic{T,L,B}} bloch::HybridSparseMatrix{T,B} # Enforce sorted-dns-starting-from-zero invariant onto harmonics function Hamiltonian{T,E,L,B}(lattice, blockstruct, harmonics, bloch) where {T,E,L,B} n = nsites(lattice) all(har -> size(matrix(har)) == (n, n), harmonics) || throw(DimensionMismatch("Harmonic $(size.(matrix.(harmonics), 1)) sizes don't match number of sites $n")) sort!(harmonics) (isempty(harmonics) || !iszero(dcell(first(harmonics)))) && pushfirst!(harmonics, Harmonic(zero(SVector{L,Int}), HybridSparseMatrix(blockstruct, spzeros(B, n, n)))) return new(lattice, blockstruct, harmonics, bloch) end end #region ## API ## ## AbstractHamiltonian latdim(h::AbstractHamiltonian) = latdim(lattice(h)) bravais_matrix(h::AbstractHamiltonian) = bravais_matrix(lattice(h)) norbitals(h::AbstractHamiltonian) = blocksizes(blockstructure(h)) blockeltype(::AbstractHamiltonian) = blockeltype(blockstructure(h)) blocktype(h::AbstractHamiltonian) = blocktype(blockstructure(h)) nsites(h::AbstractHamiltonian) = nsites(lattice(h)) flatsize(h::AbstractHamiltonian, args...) = flatsize(blockstructure(h), args...) flatrange(h::AbstractHamiltonian, iunflat) = flatrange(blockstructure(h), iunflat) flatrange(h::AbstractHamiltonian, name::Symbol) = sublatorbrange(blockstructure(h), sublatindex(lattice(h), name)) zerocell(h::AbstractHamiltonian) = zerocell(lattice(h)) zerocellsites(h::AbstractHamiltonian, i) = zerocellsites(lattice(h), i) # OpenHamiltonian is not <: AbstractHamiltonian ncontacts(h::AbstractHamiltonian) = 0 function harmonic_index(h::AbstractHamiltonian, dn) for (i, har) in enumerate(harmonics(h)) dcell(har) == dn && return har, i end boundserror(harmonics(h), dn) return first(harmonics(h)), 1 # unreachable end # Unless params are given, it returns the Hamiltonian with defaults parameters default_hamiltonian(h::AbstractHamiltonian; params...) = h(; params...) # type-stable computation of common blocktype (for e.g. combine) blocktype(h::AbstractHamiltonian, hs::AbstractHamiltonian...) = blocktype(promote_type(typeof.((h, hs...))...)) blocktype(::Type{<:AbstractHamiltonian{<:Any,<:Any,<:Any,B}}) where {B} = B # lat must be the result of combining the lattices of h, hs... function blockstructure(lat::Lattice{T}, h::AbstractHamiltonian{T}, hs::AbstractHamiltonian{T}...) where {T} B = blocktype(h, hs...) orbitals = sanitize_orbitals(vcat(norbitals.((h, hs...))...)) subsizes = sublatlengths(lat) return OrbitalBlockStructure{B}(orbitals, subsizes) end ## Hamiltonian Hamiltonian(l::Lattice{T,E,L}, b::OrbitalBlockStructure{B}, h::Vector{Harmonic{T,L,B}}, bl) where {T,E,L,B} = Hamiltonian{T,E,L,B}(l, b, h, bl) function Hamiltonian(l, b::OrbitalBlockStructure{B}, h) where {B} n = nsites(l) bloch = HybridSparseMatrix(b, spzeros(B, n, n)) needs_initialization!(bloch) return Hamiltonian(l, b, h, bloch) end hamiltonian(h::Hamiltonian) = h blockstructure(h::Hamiltonian) = h.blockstruct lattice(h::Hamiltonian) = h.lattice harmonics(h::Hamiltonian) = h.harmonics bloch(h::Hamiltonian) = h.bloch minimal_callsafe_copy(h::Hamiltonian) = Hamiltonian( lattice(h), blockstructure(h), copy.(harmonics(h)), copy_matrices(bloch(h))) function flat_sync!(h::Hamiltonian) for har in harmonics(h) harmat = matrix(har) needs_flat_sync(harmat) && flat_sync!(harmat) end return h end Base.size(h::Hamiltonian, i...) = size(bloch(h), i...) Base.axes(h::Hamiltonian, i...) = axes(bloch(h), i...) Base.iszero(h::Hamiltonian) = all(iszero, harmonics(h)) Base.copy(h::Hamiltonian) = Hamiltonian( copy(lattice(h)), copy(blockstructure(h)), copy.(harmonics(h)), copy(bloch(h))) copy_lattice(h::Hamiltonian) = Hamiltonian( copy(lattice(h)), blockstructure(h), harmonics(h), bloch(h)) function LinearAlgebra.ishermitian(h::Hamiltonian) for hh in h.harmonics isassigned(h, -hh.dn) || return false flat(hh.h) ≈ h[-hh.dn]' || return false end return true end function Base.:(==)(h::Hamiltonian, h´::Hamiltonian) hs = sort(h.harmonics, by = har -> har.dn) hs´ = sort(h.harmonics, by = har -> har.dn) equalharmonics = length(hs) == length(hs´) && all(splat(==), zip(hs, hs´)) return h.lattice == h´.lattice && h.blockstruct == h´.blockstruct && equalharmonics end #endregion #endregion ############################################################################################ # ParametricHamiltonian - see hamiltonian.jl for methods #region struct ParametricHamiltonian{T,E,L,B,M<:NTuple{<:Any,AppliedModifier}} <: AbstractHamiltonian{T,E,L,B} hparent::Hamiltonian{T,E,L,B} h::Hamiltonian{T,E,L,B} # To be modified upon application of parameters modifiers::M # Tuple of AppliedModifier's. Cannot FunctionWrapper them # because they involve kwargs allptrs::Vector{Vector{Int}} # allptrs are all modified ptrs in each harmonic (needed for reset!) allparams::Vector{Symbol} end #region ## API ## # Note: this gives the *modified* hamiltonian, not parent hamiltonian(h::ParametricHamiltonian) = h.h bloch(h::ParametricHamiltonian) = h.h.bloch parameters(h::ParametricHamiltonian) = h.allparams modifiers(h::ParametricHamiltonian) = h.modifiers modifiers(h::Hamiltonian) = () pointers(h::ParametricHamiltonian) = h.allptrs # refers to hparent [not h.h, which is only used as the return of call!(ph, ω; ...)] harmonics(h::ParametricHamiltonian) = harmonics(h.hparent) blockstructure(h::ParametricHamiltonian) = blockstructure(parent(h)) blocktype(h::ParametricHamiltonian) = blocktype(parent(h)) lattice(h::ParametricHamiltonian) = lattice(hamiltonian(h)) minimal_callsafe_copy(p::ParametricHamiltonian) = ParametricHamiltonian( p.hparent, minimal_callsafe_copy(p.h), p.modifiers, p.allptrs, p.allparams) Base.parent(h::ParametricHamiltonian) = h.hparent Base.size(h::ParametricHamiltonian, i...) = size(parent(h), i...) Base.copy(p::ParametricHamiltonian) = ParametricHamiltonian( copy(p.hparent), copy(p.h), p.modifiers, copy.(p.allptrs), copy(p.allparams)) LinearAlgebra.ishermitian(h::ParametricHamiltonian) = argerror("`ishermitian(::ParametricHamiltonian)` not supported, as the result can depend on the values of parameters.") copy_lattice(p::ParametricHamiltonian) = ParametricHamiltonian( copy_lattice(p.hparent), p.h, p.modifiers, p.allptrs, p.allparams) #endregion #endregion ############################################################################################ # Mesh - see mesh.jl for methods #region abstract type AbstractMesh{V,S} end struct Mesh{V,S} <: AbstractMesh{V,S} # S-1 is the manifold dimension verts::Vector{V} neighs::Vector{Vector{Int}} # all neighbors neighs[i][j] of vertex i simps::Vector{NTuple{S,Int}} # list of simplices, each a group of S neighboring # vertex indices end #region ## Constructors ## function Mesh{S}(verts, neighs) where {S} simps = build_cliques(neighs, Val(S)) return Mesh(verts, neighs, simps) end #endregion #region ## API ## dim(::AbstractMesh{<:Any,S}) where {S} = S - 1 coordinates(s::AbstractMesh) = (coordinates(v) for v in vertices(s)) coordinates(s::AbstractMesh, i::Int) = coordinates(vertices(s, i)) nvertices(m::Mesh) = length(m.verts) vertices(m::Mesh) = m.verts vertices(m::Mesh, i) = m.verts[i] neighbors(m::Mesh) = m.neighs neighbors(m::Mesh, i::Int) = m.neighs[i] neighbors_forward(m::Mesh, i::Int) = Iterators.filter(>(i), m.neighs[i]) neighbors_forward(v::Vector, i::Int) = Iterators.filter(>(i), v[i]) simplices(m::Mesh) = m.simps simplices(m::Mesh, i::Int) = m.simps[i] Base.copy(m::Mesh) = Mesh(copy(m.verts), copy.(m.neighs), copy(m.simps)) #endregion #endregion ############################################################################################ # Spectrum and Bandstructure - see solvers/eigensolvers.jl for solver backends <: AbstractEigenSolver # - see bands.jl for methods # AppliedEigenSolver - wraps a solver vs ϕs, with a mapping and transform, into a FunctionWrapper #region abstract type AbstractEigenSolver end const EigenComplex{T} = Eigen{Complex{T},Complex{T},Matrix{Complex{T}},Vector{Complex{T}}} const MatrixView{C} = SubArray{C,2,Matrix{C},Tuple{Base.Slice{Base.OneTo{Int}}, UnitRange{Int}}, true} struct Spectrum{T<:AbstractFloat,B} eigen::EigenComplex{T} blockstruct::OrbitalBlockStructure{B} end struct AppliedEigenSolver{T<:AbstractFloat,L} solver::FunctionWrapper{EigenComplex{T},Tuple{SVector{L,T}}} end struct BandVertex{T<:AbstractFloat,E} coordinates::SVector{E,Complex{T}} # SVector(momentum..., energy) states::MatrixView{Complex{T}} end # Subband: an AbstractMesh with manifold_dimension (S-1) = embedding_dimension (E) - 1 # and with interval search trees to allow slicing # CAUTION: "embedding" dimension E here refers to the Mesh object (unrelated to Lattice's E) # unlike a Subband, a general Mesh can have S≠E, like a 1D curve (S=2) in 3D (E=3) space. struct Subband{T,E} <: AbstractMesh{BandVertex{T,E},E} # we restrict S == E mesh::Mesh{BandVertex{T,E},E} trees::NTuple{E,IntervalTree{T,IntervalValue{T,Int}}} # for interval searches projstates::Dict{Tuple{Int,Int},Matrix{Complex{T}}} # (simpind, vind) => projected_states end struct Bandstructure{T,E,L,B} # E = L+1 subbands::Vector{Subband{T,E}} solvers::Vector{AppliedEigenSolver{T,L}} # one per Julia thread blockstruct::OrbitalBlockStructure{B} end #region ## Constructors ## Spectrum(eigen::Eigen, h::AbstractHamiltonian) = Spectrum(eigen, blockstructure(h)) Spectrum(eigen::Eigen, h, ::Missing) = Spectrum(eigen, h) function Spectrum(ss::Vector{Subband{<:Any,1}}, os::OrbitalBlockStructure) ϵs = [energy(only(vertices(s))) for s in ss] ψs = stack(hcat, (states(only(vertices(s))) for s in ss)) eigen = Eigen(ϵs, ψs) return Spectrum(eigen, os) end BandVertex(ke::SVector{N}, s::MatrixView{Complex{T}}) where {N,T} = BandVertex(SVector{N,Complex{T}}(ke), s) BandVertex(ke, s::Matrix) = BandVertex(ke, view(s, :, 1:size(s, 2))) BandVertex(k, e, s::Matrix) = BandVertex(k, e, view(s, :, 1:size(s, 2))) BandVertex(k, e, s::SubArray) = BandVertex(vcat(k, e), s) Subband(verts::Vector{<:BandVertex{<:Any,E}}, neighs::Vector) where {E} = Subband(Mesh{E}(verts, neighs)) function Subband(mesh::Mesh) verts, simps = vertices(mesh), simplices(mesh) orient_simplices!(simps, verts) # see mesh.jl trees = subband_trees(verts, simps) return Subband(mesh, trees) end function Subband(mesh::Mesh{<:BandVertex{T}}, trees) where {T} projs = Dict{Tuple{Int,Int},Matrix{Complex{T}}}() return Subband(mesh, trees, projs) end function subband_trees(verts::Vector{BandVertex{T,E}}, simps) where {T,E} trees = ntuple(Val(E)) do i list = [IntervalValue(shrinkright(extrema(j->coordinates(verts[j])[i], s))..., n) for (n, s) in enumerate(simps)] sort!(list) return IntervalTree{T,IntervalValue{T,Int}}(list) end return trees end # Interval is closed, we want semiclosed on the left -> exclude the upper limit shrinkright((x, y)) = (x, prevfloat(y)) #endregion #region ## API ## (s::AppliedEigenSolver{T,0})() where {T} = s.solver(SVector{0,T}()) (s::AppliedEigenSolver{T,L})(φs::SVector{L}) where {T,L} = s.solver(sanitize_SVector(SVector{L,T}, φs)) (s::AppliedEigenSolver{T,L})(φs::NTuple{L,Any}) where {T,L} = s.solver(sanitize_SVector(SVector{L,T}, φs)) (s::AppliedEigenSolver{T,L})(φs...) where {T,L} = throw(ArgumentError("AppliedEigenSolver call requires $L parameters/Bloch phases, received $φs")) energies(s::Spectrum) = s.eigen.values states(s::Spectrum) = s.eigen.vectors blockstructure(s::Spectrum) = s.blockstruct blockstructure(b::Bandstructure) = b.blockstruct solvers(b::Bandstructure) = b.solvers subbands(b::Bandstructure) = b.subbands subbands(b::Bandstructure, i...) = getindex(b.subbands, i...) nsubbands(b::Bandstructure) = nsubbands(subbands(b)) nsubbands(b::Vector{<:Subband}) = length(b) nvertices(b::Bandstructure) = nvertices(subbands(b)) nvertices(b::Vector{<:Subband}) = sum(s->length(vertices(s)), b; init = 0) nedges(b::Bandstructure) = nedges(subbands(b)) nedges(b::Vector{<:Subband}) = sum(s -> sum(length, neighbors(s)), b; init = 0) ÷ 2 nsimplices(b::Bandstructure) = nsimplices(subbands(b)) nsimplices(b::Vector{<:Subband}) = sum(s->length(simplices(s)), b) # vertex coordinates can be complex, interally, but always appear real through the API coordinates(s::SVector) = real(s) coordinates(v::BandVertex) = real(v.coordinates) energy(v::BandVertex) = last(v.coordinates) base_coordinates(v::BandVertex) = SVector(Base.front(Tuple(coordinates(v)))) states(v::BandVertex) = v.states degeneracy(v::BandVertex) = size(v.states, 2) parentrows(v::BandVertex) = first(parentindices(v.states)) parentcols(v::BandVertex) = last(parentindices(v.states)) vertices(s::Subband, i...) = vertices(s.mesh, i...) neighbors(s::Subband, i...) = neighbors(s.mesh, i...) neighbors_forward(s::Subband, i) = neighbors_forward(s.mesh, i) simplices(s::Subband, i...) = simplices(s.mesh, i...) energy(s::Subband, vind::Int) = energy(vertices(s, vind)) energies(s::Subband, vinds::NTuple{D´,Int}) where {D´} = SVector{D´}(energy.(Ref(s), vinds)) base_coordinates(s::Subband, vind::Int) = base_coordinates(vertices(s, vind)) base_coordinates(s::Subband, vinds::NTuple{D,Int}) where {D} = reduce(hcat, base_coordinates.(Ref(s), vinds)) trees(s::Subband) = s.trees trees(s::Subband, i::Int) = s.trees[i] projected_states(s::Subband) = s.projstates # last argument: saxes = ((dim₁, x₁), (dim₂, x₂)...) function foreach_simplex(f, s::Subband, ((dim, k), xs...)) for interval in intersect(trees(s, dim), (k, k)) interval_in_slice!(interval, s, xs...) || continue sind = value(interval) f(sind) end return nothing end interval_in_slice!(interval, s, (dim, k), xs...) = interval in intersect(trees(s, dim), (k, k)) && interval_in_slice!(interval, s, xs...) interval_in_slice!(interval, s) = true mesh(s::Subband) = s.mesh mesh(m::Mesh) = m meshes(b::Bandstructure) = (mesh(s) for s in subbands(b)) meshes(s::Subband) = (mesh(s),) meshes(s::Mesh) = (s,) meshes(xs) = (mesh(x) for x in xs) embdim(::AbstractMesh{<:SVector{E}}) where {E} = E embdim(::AbstractMesh{<:BandVertex{<:Any,E}}) where {E} = E meshdim(::AbstractMesh{<:Any,S}) where {S} = S dims(m::AbstractMesh) = (embdim(m), meshdim(m)) Base.size(s::Spectrum, i...) = size(s.eigen.vectors, i...) Base.isempty(s::Subband) = isempty(simplices(s)) Base.length(b::Bandstructure) = length(b.subbands) #endregion #endregion ############################################################################################ # SelfEnergySolvers - see solvers/selfenergy.jl for self-energy solvers #region abstract type AbstractSelfEnergySolver end abstract type RegularSelfEnergySolver <: AbstractSelfEnergySolver end abstract type ExtendedSelfEnergySolver <: AbstractSelfEnergySolver end #endregion ############################################################################################ # Green solvers - see solvers/greensolvers.jl #region # Generic system-independent directives for solvers, e.g. GS.Schur() abstract type AbstractGreenSolver end # Application to a given OpenHamiltonian, but still independent from (ω; params...) # It should support call!(::AppliedGreenSolver, ω; params...) -> GreenSolution abstract type AppliedGreenSolver end # Solver with fixed ω and params that can compute G[subcell, subcell´] or G[cell, cell´] # It should also be able to return contact G with G[] abstract type GreenSlicer{C<:Complex} end # C is the eltype of the slice #endregion ############################################################################################ # SelfEnergy - see solvers/selfenergy.jl # Wraps an AbstractSelfEnergySolver and a SiteSlice # -It produces Σs(ω)::AbstractMatrix defined over a SiteSlice # -If solver::ExtendedSelfEnergySolver -> 3 AbstractMatrix blocks over latslice+extended # AbstractSelfEnergySolvers can be associated with methods of attach(h, sargs...; kw...) # To associate such a method we add a SelfEnergy constructor that will be used by attach # - SelfEnergy(h::AbstractHamiltonian, sargs...; kw...) -> SelfEnergy #region struct SelfEnergy{T,E,L,S<:AbstractSelfEnergySolver} solver::S # returns AbstractMatrix block(s) over latslice orbslice::OrbitalSliceGrouped{T,E,L} # sites on each unitcell with a selfenergy function SelfEnergy{T,E,L,S}(solver, orbslice) where {T,E,L,S<:AbstractSelfEnergySolver} isempty(orbslice) && argerror("Cannot create a self-energy over an empty LatticeSlice") return new(solver, orbslice) end end #region ## Constructors ## SelfEnergy(solver::S, orbslice::OrbitalSliceGrouped{T,E,L}) where {T,E,L,S<:AbstractSelfEnergySolver} = SelfEnergy{T,E,L,S}(solver, orbslice) #endregion #region ## API ## orbslice(Σ::SelfEnergy) = Σ.orbslice solver(Σ::SelfEnergy) = Σ.solver has_selfenergy(s::SelfEnergy) = has_selfenergy(solver(s)) has_selfenergy(s::AbstractSelfEnergySolver) = true # see nothing.jl for override for the case of SelfEnergyEmptySolver call!(Σ::SelfEnergy, ω; params...) = call!(Σ.solver, ω; params...) call!_output(Σ::SelfEnergy) = call!_output(solver(Σ)) (Σ::SelfEnergy)(; params...) = SelfEnergy(Σ.solver(; params...), Σ.orbslice) minimal_callsafe_copy(Σ::SelfEnergy) = SelfEnergy(minimal_callsafe_copy(Σ.solver), Σ.orbslice) #endregion #endregion ############################################################################################ # OpenHamiltonian # A collector of selfenergies `attach`ed to an AbstractHamiltonian #region struct OpenHamiltonian{T,E,L,H<:AbstractHamiltonian{T,E,L},S<:NTuple{<:Any,SelfEnergy}} h::H selfenergies::S end #region ## Constructors ## OpenHamiltonian(h::AbstractHamiltonian) = OpenHamiltonian(h, ()) #endregion #region ## API ## selfenergies(oh::OpenHamiltonian) = oh.selfenergies hamiltonian(oh::OpenHamiltonian) = oh.h default_hamiltonian(oh::OpenHamiltonian) = default_hamiltonian(oh.h) lattice(oh::OpenHamiltonian) = lattice(oh.h) zerocell(h::OpenHamiltonian) = zerocell(parent(h)) ncontacts(h::OpenHamiltonian) = length(selfenergies(h)) attach(Σ::SelfEnergy) = oh -> attach(oh, Σ) attach(args...; kw...) = oh -> attach(oh, args...; kw...) attach(oh::OpenHamiltonian, args...; kw...) = attach(oh, SelfEnergy(oh.h, args...; kw...)) attach(oh::OpenHamiltonian, Σ::SelfEnergy) = OpenHamiltonian(oh.h, (oh.selfenergies..., Σ)) attach(h::AbstractHamiltonian, args...; kw...) = attach(h, SelfEnergy(h, args...; kw...)) attach(h::AbstractHamiltonian, Σ::SelfEnergy) = OpenHamiltonian(h, (Σ,)) # fallback for SelfEnergy constructor SelfEnergy(h::AbstractHamiltonian, args...; kw...) = argerror("Unknown attach/SelfEnergy systax") minimal_callsafe_copy(oh::OpenHamiltonian) = OpenHamiltonian(minimal_callsafe_copy(oh.h), minimal_callsafe_copy.(oh.selfenergies)) Base.size(oh::OpenHamiltonian, i...) = size(oh.h, i...) Base.parent(oh::OpenHamiltonian) = oh.h boundingbox(oh::OpenHamiltonian) = boundingbox(tupleflatten(boundingbox.(orbslice.(selfenergies(oh)))...)) #endregion #endregion ############################################################################################ # Contacts - see greenfunction.jl # Collection of selfenergies supplemented with a ContactOrbitals # ContactOrbitals includes orbslice = flat merged Σlatslices + block info # Supports call!(c, ω; params...) -> (Σs::MatrixBlock...) over orbslice #region struct ContactOrbitals{L} orbsdict::CellOrbitalsGroupedDict{L} # non-extended orbital indices for merged contact corbsdict::Vector{CellOrbitalsGroupedDict{L}} # same for each contact (alias of Σ's) contactinds::Vector{Vector{Int}} # orbital indices in orbdict for each contact offsets::Vector{Int} # orbsdict offset from number of orbs per cell end struct Contacts{L,N,S<:NTuple{N,SelfEnergy},O<:OrbitalSliceGrouped} selfenergies::S # one per contact, produce flat AbstractMatrices orbitals::ContactOrbitals{L} # needed to extract site/subcell/contact blocks orbslice::O end const EmptyContacts{L} = Contacts{L,0,Tuple{}} #region ## Constructors ## ContactOrbitals{L}() where {L} = ContactOrbitals(CellOrbitalsGroupedDict{L}(), CellOrbitalsGroupedDict{L}[], Vector{Int}[], Int[]) function Contacts(oh::OpenHamiltonian) Σs = selfenergies(oh) Σorbslices = orbslice.(Σs) h = hamiltonian(oh) orbitals = ContactOrbitals(h, Σorbslices...) # see greenfunction.jl for constructor oslice = OrbitalSliceGrouped(lattice(oh), cellsdict(orbitals)) return Contacts(Σs, orbitals, oslice) end #endregion #region ## API ## cellsdict(c::ContactOrbitals) = c.orbsdict cellsdict(c::ContactOrbitals, i::Integer) = c.corbsdict[i] contactinds(c::ContactOrbitals) = c.contactinds contactinds(c::ContactOrbitals, i) = c.contactinds[i] ncontacts(c::Contacts) = ncontacts(c.orbitals) ncontacts(c::ContactOrbitals) = length(c.corbsdict) offsets(c::Contacts) = offsets(c.orbitals) offsets(c::ContactOrbitals) = c.offsets selfenergies(c::Contacts) = c.selfenergies selfenergies(c::Contacts, i::Integer) = (check_contact_index(i, c); c.selfenergies[i]) has_selfenergy(c::Contacts) = any(has_selfenergy, selfenergies(c)) # c::Union{Contacts,ContactOrbitals} here check_contact_index(i, c) = 1 <= i <= ncontacts(c) || argerror("Cannot get contact $i, there are $(ncontacts(c)) contacts") # for checks in contact construction check_contact_slice(s::LatticeSlice) = isempty(s) && argerror("No contact sites found in selection") contactorbitals(c::Contacts) = c.orbitals function contact_orbslice(h; sites...) contactslice = getindex(lattice(h); sites...) check_contact_slice(contactslice) # in case it is empty lsparent = sites_to_orbs(contactslice, h) return lsparent end orbslice(c::Contacts) = c.orbslice orbslice(c::Contacts, ::Colon) = c.orbslice orbslice(c::Contacts, i::Integer) = orbslice(selfenergies(c, i)) cellsdict(c::Contacts, i...) = cellsdict(c.orbitals, i...) contactinds(c::Contacts, i...) = contactinds(c.orbitals, i...) norbitals(c::ContactOrbitals) = norbitals(c.orbsdict) norbitals(c::ContactOrbitals, i) = norbitals(c.corbsdict[i]) orbgroups(c::ContactOrbitals) = orbgroups(c.orbsdict) orbgroups(c::ContactOrbitals, i) = orbgroups(c.corbsdict[i]) orbranges(c::ContactOrbitals) = orbranges(c.orbsdict) orbranges(c::ContactOrbitals, i) = orbranges(c.corbsdict[i]) boundingbox(c::Contacts) = boundingbox(orbslice(c)) Base.isempty(c::Contacts) = isempty(selfenergies(c)) # Base.length(c::Contacts) = length(selfenergies(c)) # unused minimal_callsafe_copy(c::Contacts) = Contacts(minimal_callsafe_copy.(c.selfenergies), c.orbitals, c.orbslice) #endregion #endregion ############################################################################################ # Green - see greenfunction.jl and solvers/green # General strategy: # -Contacts: Σs::Tuple(Selfenergy...) + contactBS -> call! produces MatrixBlocks for Σs # -SelfEnergy: latslice + solver -> call! produces flat matrices (one or three) # -GreenFunction: ham + c::Contacts + an AppliedGreenSolver = apply(GS.AbsSolver, ham, c) # -call!(::GreenFunction, ω; params...) -> call! ham + Contacts, returns GreenSolution # -AppliedGreenSolver: usually wraps the SelfEnergy flat matrices. call! -> GreenSlicer # -GreenSolution: ham, slicer, Σblocks, contactBS # -GreenSlicer: implements getindex to build g(ω)[rows, cols] #region struct GreenFunction{T,E,L,S<:AppliedGreenSolver,H<:AbstractHamiltonian{T,E,L},C<:Contacts} parent::H solver::S contacts::C end # Obtained with gω = call!(g::GreenFunction, ω; params...) or g(ω; params...) # Allows gω[i, j] for i,j integer Σs indices ("contacts") # Allows gω[cell, cell´] using T-matrix, with cell::Union{SVector,CellSites} # Allows also view(gω, ...) struct GreenSolution{T,E,L,S<:GreenSlicer,G<:GreenFunction{T,E,L},Σs} parent::G slicer::S # gives G(ω; p...)[i,j] for i,j::AppliedGreenIndex contactΣs::Σs # Tuple of selfenergies Σ(ω)::MatrixBlock or NTuple{3,MatrixBlock}, one per contact contactorbs::ContactOrbitals{L} end struct DiagIndices{K,V} # represents Green indices to return only diagonal elements inds::V kernel::K end struct GreenIndices{I,R} inds::I orbinds::R # orbinds = sites_to_orbs(inds) end # Obtained with gs = g[; siteselection...] # Alows call!(gs, ω; params...) or gs(ω; params...) # required to do e.g. h |> attach(g´[sites´], couplingmodel; sites...) struct GreenSlice{T,E,L,G<:GreenFunction{T,E,L},R<:GreenIndices,C<:GreenIndices} parent::G rows::R cols::C end #region ## Constuctors ## function GreenSlice(parent, rows, cols) if rows isa DiagIndices || cols isa DiagIndices rows === cols || argerror("Diagonal indices should be identical for rows and columns") end rows´ = greenindices(rows, parent) cols´ = cols === rows ? rows´ : greenindices(cols, parent) return GreenSlice(parent, rows´, cols´) end # see sites_to_orbs in slices.jl greenindices(inds, g) = GreenIndices(inds, sites_to_orbs(inds, g)) greenindices(g::GreenSlice) = g.rows, g.cols #endregion #region ## API ## diagonal(inds; kernel = missing) = DiagIndices(inds, kernel) # exported diagonal(; kernel = missing, kw...) = DiagIndices(siteselector(; kw...), kernel) # exported Base.parent(i::DiagIndices) = i.inds kernel(i::DiagIndices) = i.kernel # returns the Hamiltonian field hamiltonian(g::Union{GreenFunction,GreenSolution,GreenSlice}) = hamiltonian(g.parent) # Like the above, but it may not be === the field (it can be a copy with parameters applied) # needed for qplot(g(; params...)) default_hamiltonian(g::GreenFunction) = default_hamiltonian(parent(g)) # default params lattice(g::Union{GreenFunction,GreenSolution,GreenSlice}) = lattice(g.parent) latslice(g::GreenFunction, i) = orbslice(g.contacts, i) # function latslice(g::GreenFunction, ls::LatticeSlice) # lattice(g) === lattice(ls) || internalerror("latslice: parent lattice mismatch") # return ls # end # latslice(g::GreenFunction, is::SiteSelector) = lattice(g)[is] # latslice(g::GreenFunction; kw...) = latslice(g, siteselector(; kw...)) zerocell(g::Union{GreenFunction,GreenSolution,GreenSlice}) = zerocell(lattice(g)) solver(g::GreenFunction) = g.solver contacts(g::GreenFunction) = g.contacts contacts(g::Union{GreenSolution,GreenSlice}) = contacts(parent(g)) ncontacts(g::GreenFunction) = ncontacts(g.contacts) ncontacts(g::Union{GreenSolution,GreenSlice}) = ncontacts(parent(g)) slicer(g::GreenSolution) = g.slicer selfenergies(g::GreenFunction) = selfenergies(contacts(g)) selfenergies(g::GreenSolution) = g.contactΣs has_selfenergy(g::Union{GreenFunction,GreenSlice,GreenSolution}) = has_selfenergy(contacts(g)) contactorbitals(g::GreenFunction) = contactorbitals(g.contacts) contactorbitals(g::GreenSolution) = g.contactorbs contactorbitals(g::GreenSlice) = contactorbitals(parent(g)) blockstructure(g::GreenFunction) = blockstructure(hamiltonian(g)) blockstructure(g::GreenSolution) = blockstructure(hamiltonian(g)) blockstructure(g::GreenSlice) = blockstructure(parent(g)) norbitals(g::GreenFunction) = norbitals(g.parent) norbitals(g::GreenSlice) = norbitals(g.parent.parent) contactinds(g::GreenFunction, i...) = contactinds(contacts(g), i...) contactinds(g::Union{GreenSolution,GreenSlice}, i...) = contactinds(contactorbitals(g), i...) greenfunction(g::GreenSlice) = g.parent rows(g::GreenSlice) = g.rows.inds cols(g::GreenSlice) = g.cols.inds orbrows(g::GreenSlice) = g.rows.orbinds orbcols(g::GreenSlice) = g.cols.orbinds Base.axes(g::GreenSlice) = (orbrows(g), orbcols(g)) # ifelse(rows && cols are contacts, (rows, cols), (orbrows, orbcols)) # I.e: if rows, cols are contact indices retrieve them instead of orbslices. orbinds_or_contactinds(g) = orbinds_or_contactinds(rows(g), cols(g), orbrows(g), orbcols(g)) orbinds_or_contactinds(r::Union{Colon,Integer}, c::Union{Colon,Integer}, _, _) = (r, c) orbinds_or_contactinds(_, _, or, oc) = (or, oc) Base.parent(g::GreenFunction) = g.parent Base.parent(g::GreenSolution) = g.parent Base.parent(g::GreenSlice) = g.parent Base.size(g::GreenFunction, i...) = size(g.parent, i...) Base.size(g::GreenSolution, i...) = size(g.parent, i...) flatsize(g::GreenFunction, i...) = flatsize(g.parent, i...) flatsize(g::GreenSolution, i...) = flatsize(g.parent, i...) function similar_Matrix(gs::GreenSlice{T}) where {T} m = norbitals(orbrows(gs)) n = norbitals(orbcols(gs)) return Matrix{Complex{T}}(undef, m, n) end boundaries(g::GreenFunction) = boundaries(solver(g)) # fallback (for solvers without boundaries, or for OpenHamiltonian) boundaries(_) = () boundingbox(g::GreenFunction) = isempty(contacts(g)) ? (zerocell(lattice(g)), zerocell(lattice(g))) : boundingbox(contacts(g)) copy_lattice(g::GreenFunction) = GreenFunction(copy_lattice(g.parent), g.solver, g.contacts) copy_lattice(g::GreenSolution) = GreenSolution( copy_lattice(g.parent), g.slicer, g.contactΣs, g.contactbs) copy_lattice(g::GreenSlice) = GreenSlice( copy_lattice(g.parent), g.rows, g.cols) function minimal_callsafe_copy(g::GreenFunction) parent´ = minimal_callsafe_copy(g.parent) contacts´ = minimal_callsafe_copy(g.contacts) solver´ = minimal_callsafe_copy(g.solver, parent´, contacts´) return GreenFunction(parent´, solver´, contacts´) end function minimal_callsafe_copy(g::GreenSolution) parentg´ = minimal_callsafe_copy(g.parent) parentham = hamiltonian(parentg´) parentcontacts = contacts(parentg´) slicer´ = minimal_callsafe_copy(g.slicer, parentham, parentcontacts) g´ = GreenSolution(parentg´, slicer´, g.contactΣs, g.contactorbs) return g´ end minimal_callsafe_copy(g::GreenSlice) = GreenSlice(minimal_callsafe_copy(g.parent), g.rows, g.cols) Base.:(==)(g::GreenFunction, g´::GreenFunction) = function_not_defined("==") Base.:(==)(g::GreenSolution, g´::GreenSolution) = function_not_defined("==") Base.:(==)(g::GreenSlice, g´::GreenSlice) = function_not_defined("==") #endregion #endregion ############################################################################################ # Operator - Hamiltonian-like operator representing observables other than a Hamiltonian # It works as a wrapper of an AbstractHamiltonian, see observables.jl for constructors # VectorOperator - like the above for a collection of AbstractHamiltonians # BarebonesOperator - same thing but with arbitrary element type and no support for call! #region struct Operator{H<:AbstractHamiltonian} h::H end struct BarebonesHarmonic{L,B} dn::SVector{L,Int} mat::SparseMatrixCSC{B,Int} end struct BarebonesOperator{L,B} harmonics::Dictionary{SVector{L,Int},BarebonesHarmonic{L,B}} end #region ## Constructors ## BarebonesOperator(harmonics::Vector) = BarebonesOperator(index(dcell, BarebonesHarmonic.(harmonics))) BarebonesHarmonic(har) = BarebonesHarmonic(dcell(har), sparse(har)) #endregion #region ## API ## hamiltonian(o::Operator) = o.h harmonics(o::BarebonesOperator) = o.harmonics matrix(h::BarebonesHarmonic) = h.mat dcell(h::BarebonesHarmonic) = h.dn (o::Operator)(φ...; kw...) = o.h(φ...; kw...) call!(o::Operator, φ...; kw...) = call!(o.h, φ...; kw...) Base.getindex(o::Operator, i...) = getindex(o.h, i...) Base.eltype(::BarebonesOperator{<:Any,B}) where {B} = B Base.size(o::BarebonesOperator, is...) = size(matrix(first(harmonics(o))), is...) Base.getindex(o::BarebonesOperator{L}, dn) where {L} = getindex(o, sanitize_SVector(SVector{L,Int}, dn)) Base.getindex(o::BarebonesOperator{L}, dn::SVector{L,Int}) where {L} = matrix(harmonics(o)[dn]) # Unlike o[dn][i, j], o[si::AnyCellSites, sj::AnyCellSites] returns a zero if !haskey(dn) function Base.getindex(o::BarebonesOperator{L}, i::AnyCellSites, j::AnyCellSites = i) where {L} i´, j´ = sanitize_cellindices(i, Val(L)), sanitize_cellindices(j, Val(L)) dn = cell(j´) - cell(i´) si, sj = siteindices(i´), siteindices(j´) if haskey(harmonics(o), dn) x = o[dn][si, sj] else checkbounds(Bool, matrix(first(harmonics(o))), si, sj) x = zero(eltype(o)) end return x end SparseArrays.nnz(h::BarebonesOperator) = sum(har -> nnz(matrix(har)), harmonics(h)) #endregion ############################################################################################ # OrbitalSliceArray: array type over orbital slice - see specialmatrices.jl # orbaxes is a tuple of OrbitalSlice's or Missing's, one per dimension # if missing, the dimension does not span orbitals but something else #region struct OrbitalSliceArray{C,N,M<:AbstractArray{C,N},A<:NTuple{N,Union{OrbitalSliceGrouped,Missing}}} <: AbstractArray{C,N} parent::M orbaxes::A end const OrbitalSliceVector{C,V,A} = OrbitalSliceArray{C,1,V,A} const OrbitalSliceMatrix{C,M,A} = OrbitalSliceArray{C,2,M,A} OrbitalSliceVector(v::AbstractVector, axes) = OrbitalSliceArray(v, axes) OrbitalSliceMatrix(m::AbstractMatrix, axes) = OrbitalSliceArray(m, axes) orbaxes(a::OrbitalSliceArray) = a.orbaxes Base.parent(a::OrbitalSliceArray) = a.parent #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
2253
""" ExternalPresets.wannier90(filename::String; kw...) Import a Wannier90 tight-binding file in the form of a `w::EP.WannierBuilder` object. It can be used to obtain a `Hamiltonian` with `hamiltonian(w)`, and the matrix of the position operator with `sites(w)`. ExternalPresets.wannier90(filename, model::AbstractModel; kw...) Modify the `WannierBuilder` after import by adding `model` to it. push!(w::EP.WannierBuilder, modifier::AbstractModifier) w |> modifier Applies a `modifier` to `w`. ## Keywords - htol: skip matrix elements of the Hamiltonian smaller than this (in absolute value). Default: `1e-8` - rtol: skip non-diagonal matrix elements of the position operator smaller than this (in absolute value). Default: `1e-8` - dim: dimensionality of the embedding space for the Wannier orbitals, dropping trailing dimensions beyond `dim` if smaller than 3. Default: `3` - latdim: dimensionality of the lattice, dropping trailing dimensions beyond `latdim` if smaller than 3. Should be `latdim <= dim`. Default: `dim` - type: override the real number type of the imported system. Default: `Float64` # Examples ``` julia> w = EP.wannier90("wannier_tb.dat", @onsite((; o) -> o); htol = 1e-4, rtol = 1e-4, dim = 2, type = Float32) WannierBuilder{Float32,2,2} : 2-dimensional Hamiltonian builder from Wannier90 input, with positions of type Float32 in 2D-dimensional space cells : 151 elements : 6724 modifiers : 1 julia> h = hamiltonian(w) ParametricHamiltonian{Float32,2,2}: Parametric Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 151 Harmonic size : 10 × 10 Orbitals : [1] Element type : scalar (ComplexF32) Onsites : 10 Hoppings : 6704 Coordination : 670.4 Parameters : [:o] julia> r = position(w) BarebonesOperator{2}: a simple collection of 2D Bloch harmonics Bloch harmonics : 151 Harmonic size : 10 × 10 Element type : SVector{2, ComplexF32} Nonzero elements : 7408 julia> r[sites(SA[0,0], 3), sites(SA[1,0],2)] 2-element SVector{2, ComplexF32} with indices SOneTo(2): -0.0016230071f0 - 0.00012927242f0im 0.008038711f0 + 0.004102786f0im ``` # See also `hamiltonian`, `position` """ ExternalPresets.wannier90
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
6808
############################################################################################ # ExternalPresets #region module ExternalPresets using Quantica ############################################################################################ # WannierBuilder #region using Quantica: IJVBuilder, IJVHarmonic, IJV, AbstractHamiltonianBuilder, AbstractModel, BarebonesOperator, Modifier, push_ijvharmonics!, postype, tupleflatten, dcell, ncells, collector, builder, modifiers, harmonics, sanitize_Val, add! struct WannierBuilder{T,E,L} <: AbstractHamiltonianBuilder{T,L,L,Complex{T}} hbuilder::IJVBuilder{T,E,L,Complex{T},Vector{Any}} rharmonics::Vector{IJVHarmonic{L,SVector{E,Complex{T}}}} end struct Wannier90Data{T,E,L} brvecs::NTuple{L,SVector{E,T}} norbs::Int ncells::Int h::Vector{IJVHarmonic{L,Complex{T}}} # must be dn-sorted, with (0,0,0) first r::Vector{IJVHarmonic{L,SVector{E,Complex{T}}}} # must be dn-sorted, with (0,0,0) first end #region ## Constructors ## function WannierBuilder(file::AbstractString; kw...) data = load_wannier90(file; kw...) lat = lattice(data) hbuilder = builder(lat; orbitals = Val(1)) # one orbital per site push_ijvharmonics!(hbuilder, data.h) rharmonics = data.r return WannierBuilder(hbuilder, rharmonics) end function WannierBuilder(file, model::AbstractModel; kw...) b = WannierBuilder(file; kw...) add!(b.hbuilder, model) return b end (m::Quantica.Modifier)(b::WannierBuilder) = (push!(b, m); b) #endregion #region ## API ## wannier90(args...; kw...) = WannierBuilder(args...; kw...) # API (extendable) Quantica.hamiltonian(b::WannierBuilder) = hamiltonian(b.hbuilder) Quantica.position(b::WannierBuilder) = BarebonesOperator(b.rharmonics) Quantica.ncells(b::WannierBuilder) = ncells(b.hbuilder) Quantica.modifiers(b::WannierBuilder) = modifiers(b.hbuilder) Quantica.harmonics(b::WannierBuilder) = harmonics(b.hbuilder) Quantica.lattice(b::WannierBuilder) = lattice(b.hbuilder) Quantica.blockstructure(b::WannierBuilder) = blockstructure(b.hbuilder) Base.push!(b::WannierBuilder, m::Modifier) = push!(b.hbuilder, m) Base.pop!(b::WannierBuilder) = pop!(b.hbuilder) hbuilder(b::WannierBuilder) = b.hbuilder nelements(b::WannierBuilder) = sum(length, harmonics(b)) #endregion #region ## Wannier90Data ## load_wannier90(filename; type = Float64, dim = Val(3), latdim = dim, kw...) = load_wannier90(filename, sanitize_Val(latdim), postype(dim, type); kw...) function load_wannier90(filename, ::Val{L}, ::Type{SVector{E,T}}; htol = 1e-8, rtol = 1e-8) where {L,E,T} L > 3 && argerror("dim = $L should be dim <= 3") data = open(filename, "r") do f # skip header readline(f) # read three Bravais 3D-vectors, keep L Bravais LD-vectors brvecs3 = ntuple(_ -> SVector{3,T}(readline_realtypes(f, SVector{3,T})), Val(3)) brvecs = ntuple(i -> brvecs3[i][SVector{E,Int}(1:E)], Val(L)) # read number of orbitals norbs = readline_realtypes(f, Int) # read number of cells ncells = readline_realtypes(f, Int) # skip symmetry degeneracies while !eof(f) isempty(readline(f)) && break end # read Hamiltonian h = load_harmonics(f, Val(L), Complex{T}, norbs, ncells, htol) # read positions r = load_harmonics(f, Val(L), SVector{E,Complex{T}}, norbs, ncells, rtol) return Wannier90Data(brvecs, norbs, ncells, h, r) end return data end function load_harmonics(f, ::Val{L}, ::Type{B}, norbs, ncells, atol) where {L,B} ncell = 0 hars = IJVHarmonic{L,B}[] ijv = IJV{B}(norbs^2) while !eof(f) ncell += 1 dn3D = SVector{3,Int}(readline_realtypes(f, SVector{3,Int})) dn = dn3D[SVector{L,Int}(1:L)] # if skip, read but not write harmonic (since it is along a non-projected axes) skip = L < 3 && !iszero(dn3D[SVector{3-L,Int}(L+1:3)]) for j in 1:norbs, i in 1:norbs skip && (readline(f); continue) i´, j´, reims... = readline_realtypes(f, Int, Int, B) i´ == i && j´ == j || argerror("load_wannier90: unexpected entry in file at element $((dn, i, j))") v = build_complex(reims, B) push_if_nonzero!(ijv, (i, j, v), dn, atol) end if !skip && !isempty(ijv) push!(hars, IJVHarmonic(dn, ijv)) ijv = IJV{B}(norbs^2) # allocate new IJV end isempty(readline(f)) || argerror("load_wannier90: unexpected line after harmonic $dn") ncell == ncells && break end sort!(hars, by = ijv -> abs.(dcell(ijv))) iszero(dcell(first(hars))) || pushfirst!(hars, IJVHarmonic(zero(SVector{L,Int}), IJV{B}())) return hars end readline_realtypes(f, type::Type{<:Real}) = parse(type, readline(f)) readline_realtypes(f, types::Type...) = readline_realtypes(f, tupleflatten(realtype.(types)...)...) function readline_realtypes(f, realtypes::Vararg{Type{<:Real},N}) where {N} tokens = split(readline(f)) # realtypes could be less than originally read tokens if we have reduced dimensionality reals = ntuple(i -> parse(realtypes[i], tokens[i]), Val(N)) return reals end realtype(t::Type{<:Real}) = t realtype(::Type{Complex{T}}) where {T} = (T, T) realtype(::Type{SVector{N,T}}) where {N,T<:Real} = ntuple(Returns(T), Val(N)) realtype(::Type{SVector{N,Complex{T}}}) where {N,T<:Real} = (t -> (t..., t...))(realtype(SVector{N,T})) build_complex((r, i), ::Type{B}) where {B<:Complex} = Complex(r, i) build_complex(ri, ::Type{B}) where {C<:Complex,N,B<:SVector{N,C}} = SVector{N,C}(ntuple(i -> C(ri[2i-1], ri[2i]), Val(N))) push_if_nonzero!(ijv::IJV{<:Number}, (i, j, v), dn, htol) = abs(v) > htol && push!(ijv, (i, j, v)) push_if_nonzero!(ijv::IJV{<:SVector}, (i, j, v), dn, rtol) = (i == j && iszero(dn) || any(>(rtol), abs.(v))) && push!(ijv, (i, j, v)) function Quantica.lattice(data::Wannier90Data{T,E}) where {T,E} bravais = hcat(data.brvecs...) rs = SVector{E,T}[] ijv = collector(first(data.r)) for (i, j, r) in zip(ijv.i, ijv.j, ijv.v) i == j && push!(rs, real(r)) end return lattice(sublat(rs); bravais) end #endregion #region ## show ## function Base.show(io::IO, b::WannierBuilder) i = get(io, :indent, "") print(io, i, summary(b), "\n", "$i cells : $(ncells(b)) $i elements : $(nelements(b)) $i modifiers : $(length(modifiers(b)))") end Base.summary(::WannierBuilder{T,E,L}) where {T,E,L} = "WannierBuilder{$T,$E,$L} : $(L)D Hamiltonian builder from Wannier90 input with positions of type $T in $(E)D space" #endregion #endregion end # module const EP = ExternalPresets #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
2746
############################################################################################ # HamiltonianPresets #region module HamiltonianPresets using Quantica, LinearAlgebra function graphene(; a0 = 0.246, range = neighbors(1), t0 = 2.7, β = 3, dim = 2, type = Float64, names = (:A, :B), kw...) lat = LatticePresets.honeycomb(; a0, dim, type, names) h = hamiltonian(lat, hopping((r, dr) -> t0 * exp(-β*(sqrt(3) * norm(dr)/a0 - 1)) * I, range = range); kw...) return h end function twisted_bilayer_graphene(; twistindex = 1, twistindices = (twistindex, 1), a0 = 0.246, interlayerdistance = 1.36a0, rangeintralayer = neighbors(1), rangeinterlayer = 4a0/sqrt(3), hopintra = 2.70 * I, hopinter = 0.48, modelintra = hopping(hopintra, range = rangeintralayer), type = Float64, names = (:Ab, :Bb, :At, :Bt), kw...) (m, r) = twistindices θ = acos((3m^2 + 3m*r +r^2/2)/(3m^2 + 3m*r + r^2)) sAbot = sublat((0.0, -0.5a0/sqrt(3.0), - interlayerdistance / 2); name = :Ab) sBbot = sublat((0.0, 0.5a0/sqrt(3.0), - interlayerdistance / 2); name = :Bb) sAtop = sublat((0.0, -0.5a0/sqrt(3.0), interlayerdistance / 2); name = :At) sBtop = sublat((0.0, 0.5a0/sqrt(3.0), interlayerdistance / 2); name = :Bt) brbot = a0 * SA[ cos(pi/3) sin(pi/3) 0; -cos(pi/3) sin(pi/3) 0]' brtop = a0 * SA[ cos(pi/3) sin(pi/3) 0; -cos(pi/3) sin(pi/3) 0]' # Supercell matrices sc. # The one here is a [1 0; -1 1] rotation of the one in Phys. Rev. B 86, 155449 (2012) if gcd(r, 3) == 1 scbot = SA[m -(m+r); (m+r) 2m+r] * SA[1 0; -1 1] sctop = SA[m+r -m; m 2m+r] * SA[1 0; -1 1] else scbot = SA[m+r÷3 -r÷3; r÷3 m+2r÷3] * SA[1 0; -1 1] sctop = SA[m+2r÷3 r÷3; -r÷3 m+r÷3] * SA[1 0; -1 1] end latbot = lattice(sAbot, sBbot; bravais = brbot, dim = Val(3), type, names = (names[1], names[2])) lattop = lattice(sAtop, sBtop; bravais = brtop, dim = Val(3), type, names = (names[3], names[4])) htop = hamiltonian(lattop, modelintra; kw...) |> supercell(sctop) hbot = hamiltonian(latbot, modelintra; kw...) |> supercell(scbot) let R = SA[cos(θ/2) -sin(θ/2) 0; sin(θ/2) cos(θ/2) 0; 0 0 1] Quantica.transform!(htop, r -> R * r) end let R = SA[cos(θ/2) sin(θ/2) 0; -sin(θ/2) cos(θ/2) 0; 0 0 1] Quantica.transform!(hbot, r -> R * r) end modelinter = hopping((r,dr) -> ( I * hopintra * exp(-3*(norm(dr)/a0 - 1)) * dot(dr, SVector(1,1,0))^2/sum(abs2, dr) - I * hopinter * exp(-3*(norm(dr)/a0 - interlayerdistance/a0)) * dr[3]^2/sum(abs2, dr)), range = rangeinterlayer) return combine(hbot, htop; coupling = modelinter) end end # module const HP = HamiltonianPresets #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
1274
############################################################################################ # LatticePresets #region module LatticePresets using Quantica linear(; a0 = 1, kw...) = lattice(sublat((0.,)); bravais = a0 .* (1,), kw...) square(; a0 = 1, kw...) = lattice(sublat((0., 0.)); bravais = a0 * SA[1. 0.; 0. 1.]', kw...) triangular(; a0 = 1, kw...) = lattice(sublat((0., 0.)); bravais = a0 * SA[cos(pi/3) sin(pi/3); -cos(pi/3) sin(pi/3)]', kw...) honeycomb(; a0 = 1, kw...) = lattice(sublat((0.0, -0.5*a0/sqrt(3.0)), name = :A), sublat((0.0, 0.5*a0/sqrt(3.0)), name = :B); bravais = a0 * SA[cos(pi/3) sin(pi/3); -cos(pi/3) sin(pi/3)]', kw...) cubic(; a0 = 1, kw...) = lattice(sublat((0., 0., 0.)); bravais = a0 * SA[1. 0. 0.; 0. 1. 0.; 0. 0. 1.]', kw...) fcc(; a0 = 1, kw...) = lattice(sublat((0., 0., 0.)); bravais = (a0/sqrt(2.)) * SA[-1. -1. 0.; 1. -1. 0.; 0. 1. -1.]', kw...) bcc(; a0 = 1, kw...) = lattice(sublat((0., 0., 0.)); bravais = a0 * SA[1. 0. 0.; 0. 1. 0.; 0.5 0.5 0.5]', kw...) hcp(; a0 = 1, kw...) = lattice(sublat((0., 0., 0.), (a0*0.5, a0*0.5/sqrt(3.), a0*0.5)); bravais = a0 * SA[1. 0. 0.; -0.5 0.5*sqrt(3.) 0.; 0. 0. 1.]', kw...) end # module const LP = LatticePresets #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
2796
############################################################################################ # RegionPresets #region module RegionPresets using StaticArrays using Quantica: sanitize_SVector struct Region{E,F} <: Function f::F end Region{E}(f::F) where {E,F<:Function} = Region{E,F}(f) (region::Region{E})(r::SVector{E}) where {E} = region.f(r) (region::Region{E})(r) where {E} = region.f(sanitize_SVector(SVector{E,Float64}, r)) (region::Region{E})(r::Number...) where {E} = region(r) Base.:&(r1::Region{E}, r2::Region{E}) where {E} = Region{E}(r -> r1.f(r) && r2.f(r)) Base.:|(r1::Region{E}, r2::Region{E}) where {E} = Region{E}(r -> r1.f(r) || r2.f(r)) Base.xor(r1::Region{E}, r2::Region{E}) where {E} = Region{E}(r -> xor(r1.f(r), r2.f(r))) Base.:!(r1::Region{E}) where {E} = Region{E}(r -> !r1.f(r)) extended_eps(T = Float64) = sqrt(eps(T)) segment(side = 10.0, c...) = Region{1}(_region_segment(side, c...)) circle(radius = 10.0, c...) = Region{2}(_region_ellipse((radius, radius), c...)) ellipse(radii = (10.0, 15.0), c...) = Region{2}(_region_ellipse(radii, c...)) square(side = 10.0, c...) = Region{2}(_region_rectangle((side, side), c...)) rectangle(sides = (10.0, 15.0), c...) = Region{2}(_region_rectangle(sides, c...)) sphere(radius = 10.0, c...) = Region{3}(_region_ellipsoid((radius, radius, radius), c...)) spheroid(radii = (10.0, 15.0, 20.0), c...) = Region{3}(_region_ellipsoid(radii, c...)) cube(side = 10.0, c...) = Region{3}(_region_cuboid((side, side, side), c...)) cuboid(sides = (10.0, 15.0, 20.0), c...) = Region{3}(_region_cuboid(sides, c...)) function _region_segment(l, c = 0) return r -> abs(2*(r[1]-c)) <= l * (1 + extended_eps()) end function _region_ellipse((rx, ry), (cx, cy) = (0, 0)) return r -> ((r[1]-cx)/rx)^2 + ((r[2]-cy)/ry)^2 <= 1 + extended_eps(Float64) end function _region_rectangle((lx, ly), (cx, cy) = (0, 0)) return r -> abs(2*(r[1]-cx)) <= lx * (1 + extended_eps()) && abs(2*(r[2]-cy)) <= ly * (1 + extended_eps()) end function _region_ellipsoid((rx, ry, rz), (cx, cy, cz) = (0, 0, 0)) return r -> ((r[1]-cx)/rx)^2 + ((r[2]-cy)/ry)^2 + ((r[3]-cz)/rz)^2 <= 1 + eps() end function _region_cuboid((lx, ly, lz), (cx, cy, cz) = (0, 0, 0)) return r -> abs(2*(r[1]-cx)) <= lx * (1 + extended_eps()) && abs(2*(r[2]-cy)) <= ly * (1 + extended_eps()) && abs(2*(r[3]-cy)) <= lz * (1 + extended_eps()) end #endregion ############################################################################################ # show #region Base.summary(::Region{E}) where {E} = "Region{$E} : boolean region function in $E-dimensional space" Base.show(io::IO, ::MIME"text/plain", r::Region) = print(io, summary(r)) #end end # module const RP = RegionPresets #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
3520
############################################################################################ # EigenSolvers module # An AbstractEigenSolver is defined by a set of kwargs for the eigensolver and a set of # methods AbstractMatrix -> Eigen associated to that AbstractEigenSolver #region module EigenSolvers using FunctionWrappers: FunctionWrapper using SparseArrays: SparseMatrixCSC, AbstractSparseMatrix using Quantica: Eigen, I, lu, ldiv! using Quantica: Quantica, AbstractEigenSolver, ensureloaded, SVector, SMatrix, sanitize_eigen, call!_output #endregion ############################################################################################ # AbstractEigensolvers #region ## Fallbacks (s::AbstractEigenSolver)(mat) = throw(ArgumentError("The eigensolver backend $(typeof(s)) is not defined to work on $(typeof(mat))")) # an alias of h's call! output makes apply call! conversion a no-op, see apply.jl input_matrix(::AbstractEigenSolver, h) = call!_output(h) is_thread_safe(::AbstractEigenSolver) = true #### LinearAlgebra ##### struct LinearAlgebra{K} <: AbstractEigenSolver kwargs::K end function LinearAlgebra(; kw...) return LinearAlgebra(kw) end function (solver::LinearAlgebra)(mat::AbstractMatrix{<:Number}) ε, Ψ = Quantica.LinearAlgebra.eigen(mat; solver.kwargs...) return sanitize_eigen(ε, Ψ) end # LinearAlgebra.eigen doesn't like sparse Matrices as input, must convert input_matrix(::LinearAlgebra, h) = Matrix(call!_output(h)) #### Arpack ##### struct Arpack{K} <: AbstractEigenSolver kwargs::K end function Arpack(; kw...) ensureloaded(:Arpack) return Arpack(kw) end function (solver::Arpack)(mat::AbstractMatrix{<:Number}) ε, Ψ, _ = Quantica.Arpack.eigs(mat; solver.kwargs...) return sanitize_eigen(ε, Ψ) end # See https://github.com/JuliaLinearAlgebra/Arpack.jl/issues/86 is_thread_safe(::Arpack) = false #### KrylovKit ##### struct KrylovKit{P<:Tuple,K<:NamedTuple} <: AbstractEigenSolver params::P kwargs::K end function KrylovKit(params...; kw...) ensureloaded(:KrylovKit) return KrylovKit(params, NamedTuple(kw)) end function (solver::KrylovKit)(mat) ε, Ψ, _ = Quantica.KrylovKit.eigsolve(mat, solver.params...; solver.kwargs...) return sanitize_eigen(ε, Ψ) end #### ArnoldiMethod ##### struct ArnoldiMethod{K} <: AbstractEigenSolver kwargs::K end function ArnoldiMethod(; kw...) ensureloaded(:ArnoldiMethod) return ArnoldiMethod(kw) end function (solver::ArnoldiMethod)(mat) pschur, _ = Quantica.ArnoldiMethod.partialschur(mat; solver.kwargs...) ε, Ψ = Quantica.ArnoldiMethod.partialeigen(pschur) return sanitize_eigen(ε, Ψ) end #### ShiftInvert #### struct ShiftInvert{T,E<:AbstractEigenSolver} <: AbstractEigenSolver eigensolver::E origin::T function ShiftInvert{T,E}(eigensolver, origin) where {T,E<:AbstractEigenSolver} ensureloaded(:LinearMaps) return new(eigensolver, origin) end end ShiftInvert(eigensolver::E, origin::T) where {E,T} = ShiftInvert{T,E}(eigensolver, origin) function (solver::ShiftInvert)(mat::AbstractSparseMatrix{T}) where {T<:Number} mat´ = mat - I * solver.origin F = lu(mat´) lmap = Quantica.LinearMaps.LinearMap{T}((x, y) -> ldiv!(x, F, y), size(mat)...; ismutating = true, ishermitian = false) eigen = solver.eigensolver(lmap) @. eigen.values = 1 / (eigen.values) + solver.origin return eigen end #endregion end # module const ES = EigenSolvers #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
4433
############################################################################################ # Green solvers # All new solver::AbstractGreenSolver must live in the GreenSolvers module, and must implement # - apply(solver, h::AbstractHamiltonian, c::Contacts) -> AppliedGreenSolver # All new s::AppliedGreenSolver must implement (with Σblock a [possibly nested] tuple of MatrixBlock's) # - s(ω, Σblocks, ::ContactOrbitals) -> GreenSlicer # - minimal_callsafe_copy(s, parentham, parentcontacts) # injects aliases from parent # - optional: needs_omega_shift(s) (has a `true` default fallback) # A gs::GreenSlicer's allows to compute G[gi, gi´]::AbstractMatrix for indices gi # To do this, it must implement contact slicing (unless it relies on TMatrixSlicer) # - view(gs, ::Int, ::Int) -> g(ω; kw...) between specific contacts (has error fallback) # - view(gs, ::Colon, ::Colon) -> g(ω; kw...) between all contacts (has error fallback) # - Both of the above are of type `SubArray` # It must also implement generic slicing, and minimal copying # - gs[i::CellOrbitals, j::CellOrbitals] -> must return a `Matrix` for type stability # - minimal_callsafe_copy(gs, parentham, parentcontacts) # The user-facing indexing API accepts: # - i::Integer -> Sites of Contact number i # - sites(cell::Tuple, sind::Int)::Subcell -> Single site in a cell # - sites(cell::Tuple, sindcollection)::Subcell -> Site collection in a cell # - sites(cell::Tuple, slat::Symbol)::Subcell -> Whole sublattice in a cell # - sites(cell::Tuple, :) ~ cell::Union{NTuple,SVector} -> All sites in a cell # - sel::SiteSelector ~ NamedTuple -> forms a LatticeSlice # Optional: to properly plot boundaries, an ::AbstractGreenSolver may also implement # - boundaries(s::AbstractGreenSolver) -> collection of (dir => cell)::Pair{Int,Int} # Aliasing: Green solvers may only alias fields from the parent Hamiltonian and Contacts ############################################################################################ module GreenSolvers using Quantica: Quantica, AbstractGreenSolver, ensureloaded, I struct SparseLU <:AbstractGreenSolver end struct Schur{T<:AbstractFloat} <: AbstractGreenSolver shift::T # Tunable parameter in algorithm, see Ω in scattering.pdf boundary::T # Cell index for boundary (float to allow boundary at Inf) end Schur(; shift = 1.0, boundary = Inf) = Schur(shift, float(boundary)) struct KPM{B<:Union{Missing,NTuple{2}},A} <: AbstractGreenSolver order::Int bandrange::B kernel::A padfactor::Float64 # for automatically computed bandrange end function KPM(; order = 100, bandrange = missing, padfactor = 1.01, kernel = I) bandrange === missing && ensureloaded(:Arpack) return KPM(order, bandrange, kernel, padfactor) end # Used in kpm.jl function bandrange_arpack(h::AbstractMatrix{T}) where {T} R = real(T) ϵL, _ = Quantica.Arpack.eigs(h, nev=1, tol=1e-4, which = :LR); ϵR, _ = Quantica.Arpack.eigs(h, nev=1, tol=1e-4, which = :SR); ϵmax = R(real(ϵL[1])) ϵmin = R(real(ϵR[1])) return (ϵmin, ϵmax) end ## Alternative bandrange, requires ensureloaded(:ArnoldiMethod) in KPM constructor # function bandrange_arnoldi(h::AbstractMatrix{T}) where {T} # # ensureloaded(:ArnoldiMethod) # R = real(T) # decompl, _ = Quantica.ArnoldiMethod.partialschur(h, nev=1, tol=1e-4, which = Main.ArnoldiMethod.LR()); # decomps, _ = Quantica.ArnoldiMethod.partialschur(h, nev=1, tol=1e-4, which = Main.ArnoldiMethod.SR()); # ϵmax = R(real(decompl.eigenvalues[1])) # ϵmin = R(real(decomps.eigenvalues[1])) # return (ϵmin, ϵmax) # end struct Spectrum{K} <:AbstractGreenSolver spectrumkw::K end Spectrum(; spectrumkw...) = Spectrum(NamedTuple(spectrumkw)) struct Bands{B<:Union{Missing,Pair},A,K} <: AbstractGreenSolver bandsargs::A # sorted to make slices easier bandskw::K boundary::B end Bands(bandargs...; boundary = missing, bandskw...) = Bands(sort.(bandargs), NamedTuple(bandskw), boundary) Bands(bandargs::Quantica.Mesh; kw...) = argerror("Positional arguments of GS.Bands should be collections of Bloch phases or parameters") end # module const GS = GreenSolvers include("green/sparselu.jl") include("green/spectrum.jl") include("green/schur.jl") include("green/kpm.jl") include("green/bands.jl")
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
2133
############################################################################################ # SelfEnergy solvers # All s::AbstractSelfEnergySolver must support the call! API # - call!(s::RegularSelfEnergySolver, ω; params...) -> Σreg::AbstractMatrix # - call!(s::ExtendedSelfEnergySolver, ω; params...) -> (Vᵣₑ, gₑₑ⁻¹, Vₑᵣ) AbsMats # With the extended case, the equivalent Σreg reads Σreg = VᵣₑgₑₑVₑᵣ # - call!_output(s::AbstractSelfEnergySolver) -> object returned by call!(s, ω; kw...) # - minimal_callsafe_copy(s::AbstractSelfEnergySolver) # no aliasing # These AbstractMatrices are flat, defined on the LatticeSlice in parent SelfEnergy # Note: `params` are only needed in cases where s adds new parameters that must be # applied (e.g. SelfEnergyModelSolver). Otherwise one must assume that any parent # ParametricHamiltonian to GreenFunction has already been call!-ed before calling s. # Optional: AbstractSelfEnergySolver's can also implement `selfenergy_plottables` # - selfenergy_plottables(s::AbstractSelfEnergySolver, parent_latslice) # -> collection of tuples to be passed to plotlattice!(axis, tup...) for visualization # Aliasing: AbstractSelfEnergySolver's are not allowed to alias anything from outside ############################################################################################ ############################################################################################ # SelfEnergy constructors # For each attach(h, sargs...; kw...) syntax we need, we must implement: # - SelfEnergy(h::AbstractHamiltonian, sargs...; kw...) -> SelfEnergy # SelfEnergy wraps the corresponding SelfEnergySolver, be it Regular or Extended ############################################################################################ selfenergy_plottables(s::SelfEnergy) = selfenergy_plottables(s.solver, orbslice(s)) # fallback selfenergy_plottables(s::AbstractSelfEnergySolver, parent_latslice) = (parent_latslice,) include("selfenergy/nothing.jl") include("selfenergy/model.jl") include("selfenergy/schur.jl") include("selfenergy/generic.jl")
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
30825
############################################################################################ # Series # A generalization of dual numbers to arbitrary powers of differential ε, also negative # When inverting (dividing), negative powers may be produced if leading terms are zero # Higher terms can be lost throughout operations. # Series{N}(f(x), f'(x)/1!, f''(x)/2!,..., f⁽ᴺ⁾(x)/N!) = Series[f(x + ε), {ε, 0, N-1}] # If we need derivatives respect to x/α instead of x, we do rescale(::Series, α) #region struct Series{N,T} x::SVector{N,T} # term coefficients pow::Int # power of first term end Series(x::Tuple, pow = 0) = Series(SVector(x), pow) Series(x...) = Series(SVector(x), 0) Series{N}(x...) where {N} = Series{N}(SVector(x)) Series{N}(t::Tuple) where {N} = Series{N}(SVector(t)) Series{N}(d::Series) where {N} = Series{N}(d.x) Series{N}(x::SVector{<:Any,T}, pow = 0) where {N,T} = Series(SVector(padtuple(x, zero(T), Val(N))), pow) function rescale(d::Series{N}, α::Number) where {N} αp = cumprod((α ^ d.pow, ntuple(Returns(α), Val(N-1))...)) d´ = Series(Tuple(d.x) .* αp, d.pow) return d´ end chop(d::Series) = Series(chop(d.x), d.pow) function trim(d::Series{N}) where {N} nz = leading_zeros(d) iszero(nz) && return d pow = d.pow + nz t = ntuple(i -> d[i + pow - 1], Val(N)) return Series(t, pow) end trim(x) = x function leading_zeros(d::Series{N}) where {N} @inbounds for i in 0:N-1 iszero(d[d.pow + i]) || return i end return 0 end function trim_and_map(func, d::Series{N}, d´::Series{N}) where {N} f, f´ = trim(d), trim(d´) pow = min(f.pow, f´.pow) t = ntuple(i -> func(f[pow + i - 1], f´[pow + i - 1]), Val(N)) return Series(t, pow) end scalar(d::Series) = d[0] scalar(d) = d Base.first(d::Series) = first(d.x) function Base.getindex(d::Series{N,T}, i::Integer) where {N,T} i´ = i - d.pow + 1 checkbounds(Bool, d.x, i´) ? (@inbounds d.x[i´]) : zero(T) end Base.eltype(::Series{<:Any,T}) where {T} = T Base.one(::Type{<:Series{N,T}}) where {N,T} = Series{N}(one(T)) Base.one(d::S) where {S<:Series} = one(S) Base.zero(::Type{<:Series{N,T}}) where {N,T} = Series(zero(SVector{N,T}), 0) Base.zero(d::S) where {S<:Series} = zero(S) Base.iszero(d::Series) = iszero(d.x) Base.transpose(d::Series) = d # act as a scalar Base.:-(d::Series) = Series(-d.x, d.pow) Base.:+(d::Series, d´::Series) = trim_and_map(+, d, d´) Base.:-(d::Series, d´::Series) = trim_and_map(-, d, d´) Base.:+(d::Number, d´::Series{N}) where {N} = Series{N}(d) + d´ Base.:-(d::Number, d´::Series{N}) where {N} = Series{N}(d) - d´ Base.:*(d::Number, d´::Series) = Series(d * d´.x, d´.pow) Base.:*(d´::Series, d::Number) = Series(d * d´.x, d´.pow) Base.:/(d::Series{N}, d´::Series{N}) where {N} = d * inv(d´) Base.:/(d::Series, d´::Number) = Series(d.x / d´, d.pow) Base.:^(d::Series, n::Integer) = Base.power_by_squaring(d, n) # necessary for the case n = 0 and n = 1 in power_by_squaring Base.copy(d::Series) = d function Base.:*(d::Series{N}, d´::Series{N}) where {N} x, x´ = promote(d.x, d´.x) dp = Series(x, d.pow) dp´ = Series(x´, d´.pow) return dp * dp´ end function Base.:*(d::Series{N,T}, d´::Series{N,T}) where {N,T} iszero(d´) && return d´ f, f´ = trim(d), trim(d´) pow = f.pow + f´.pow s = product_matrix(f.x) * f´.x return Series(s, pow) end function Base.inv(d::Series) d´ = trim(d) # remove leading zeros iszero(d´) && argerror("Divide by zero") pow = d´.pow # impose d * inv(d) = 1. This is equivalent to Ud * inv(d).x = 1.x, where # Ud = hcat(d.x, shift(d.x, 1), ...) s = inv(product_matrix(d´.x))[:, 1] # faster than \ invd = Series(Tuple(s), -pow) return invd end # Ud = [x1 0 0 0; x2 x1 0 0; x3 x2 x1 0; x4 x3 x2 x1] # product of two series d*d´ is Ud * d´.x function product_matrix(s::SVector{N}) where {N} t = ntuple(Val(N)) do i shiftpad(s, i - 1) end return hcat(t...) end # shift SVector to the right by i, padding on the left with zeros shiftpad(s::SVector{N,T}, i) where {N,T} = SVector(ntuple(j -> j - i > 0 ? s[j - i] : zero(T), Val(N))) #endregion ############################################################################################ # BandSimplex: encodes energy and momenta of vertices, and derived quantitities #region struct Expansions{D,T,DD} cis::Tuple{Complex{T},Vararg{Complex{T},D}} J0::NTuple{D,Complex{T}} Jmat::SMatrix{D,D,Complex{T},DD} log::NTuple{D,T} end struct BandSimplex{D,T,S1<:SVector{<:Any,<:Real},S2<:SMatrix{<:Any,D,<:Real},S3<:SMatrix{<:Any,<:Any,<:Real},R<:Ref{<:Expansions}} # D = manifold dimension ei::S1 # eᵢ::SVector{D´,T} = energy of vertex i kij::S2 # kᵢ[j]::SMatrix{D´,D,T,DD´} = coordinate j of momentum for vertex i eij::S3 # ϵᵢʲ::SMatrix{D´,D´,T,D´D´} = e_j - e_i dualphi::S1 # dual::SVector{D´,T}, first hyperdual coefficient VD::T # D!V = |det(kᵢʲ - kᵢ⁰)| refex::R # Ref to Series expansions for necessary functions end # Precomputes the Series expansion coefficients for cis, J(z->0) and J(z) function Expansions(::Val{D}, ::Type{T}) where {D,T} # here order = D C = complex(T) # series coefs of cis(t) around t = 0 cis = ntuple(n -> C(im)^(n-1)/(factorial(n-1)), Val(D+1)) # series coefs of Ci(t) - im * Si(t) around t = 0, starting at order 1 J0 = ntuple(n -> C(-im)^n/(n*factorial(n)), Val(D)) # series coefs of Ci(t) - im * Si(t) around t = t_0 is cis(t0) * Jmat * SA[1/t, 1/t², ...] Jmat = ntuple(Val(D*D)) do ij j, i = fldmod1(ij, D) j > i ? zero(C) : ifelse(isodd(i), 1, -1) * C(im)^(i-j) / (i*factorial(i-j)) end |> SMatrix{D,D,C} # series coefs of ln(x) around x = Δ is ln(Δ) + log .* SA[1/Δ, 1/Δ², ...] log = ntuple(n -> -T(-1)^n/n, Val(D)) return Expansions(cis, J0, Jmat, log) end #region ## Constructors ## BandSimplex(ei, kij, refex...) = BandSimplex(real(ei), real(kij), refex...) BandSimplex(sb::Subband, simpinds, refex...) = # for simpinds = (v1::Int, v2::Int,...) BandSimplex(energies(sb, simpinds), transpose(base_coordinates(sb, simpinds)), refex...) function BandSimplex(ei::SVector{D´,T}, kij::SMatrix{D´,D,T}, refex = Ref(Expansions(Val(D), T))) where {D´,D,T} D == D´ - 1 || argerror("The dimension $D of Bloch phases in simplex should be one less than the number of vertices $(D´)") ei, eij = snap_and_diff(ei) k0 = kij[1, :] U = kij[SVector{D}(2:D´),:]' .- k0 # edges as columns VD = T(abs(det(U)) / (2π)^D) dualphi = generate_dual_phi(eij) return BandSimplex(ei, kij, eij, dualphi, VD, refex) end # make similar ei[i] exactly the same, and compute the pairwise difference function snap_and_diff(es) mes = MVector(es) for j in eachindex(es), i in j+1:lastindex(es) ei, ej = es[i], es[j] if ei ≈ ej mes[i] = mes[j] end end ess = SVector(mes) return ess, chop(ess' .- ess) end # e_j such that e^j_k are all nonzero generate_dual_e(::Type{SVector{D´,T}}) where {D´,T} = SVector(ntuple(i -> T(i^2), Val(D´))) # dϕ such that M = tʲ₁tʲ₂tʲ₃...(tʲ₁-tʲ₂)(tʲ₁-tʲ₃)...(tʲ₂-tʲ₃)... is maximal # This is a (pseudo-)vandermonde determinant, and tʲₖ = dϕʲₖ/eʲₖ # The empirical solution turns out to be tʲₙ ≈ normalize((-1)ⁿsqrt((1+n^2)/2)) (n != j, e.g. j = 0) function generate_dual_phi(eij::SMatrix{D´,D´,T}) where {D´,T} t⁰ₙ = SVector(ntuple(n -> T((-1)^n*sqrt(0.5*(1 + n^2))), Val(D´-1))) t⁰ₙ = SVector(zero(T), normalize(t⁰ₙ)...) dϕₙ = multiply_if_nonzero.(t⁰ₙ, eij[:, 1]) return dϕₙ end #endregion #region ## API ## g_integrals(s::BandSimplex, ω, dn, val...) = isreal(ω) ? _g_integrals(s, real(ω), dn, val...) : # this may be faster _g_integrals(s, ω, dn, val...) function _g_integrals(s::BandSimplex, ω, dn, val...) g₀, gi = iszero(dn) ? g_integrals_local(s, ω, val...) : g_integrals_nonlocal(s, ω, dn, val...) return NaN_to_Inf(g₀), NaN_to_Inf.(gi) end # Since complex(1) * (Inf+Inf*im) is NaN, we convert the result to Inf in this case NaN_to_Inf(x::T) where {T} = ifelse(isnan(x), T(Inf), x) #endregion #endregion ############################################################################################ # g_integrals_local: zero-dn g₀(ω) and gⱼ(ω) with normal or hyperdual numbers for φ #region function g_integrals_local(s::BandSimplex{<:Any,<:Any,SVector{D´,T}}, ω, ::Val{N} = Val(0)) where {D´,T,N} eⱼ = s.ei eₖʲ = s.eij g₀, gⱼ = begin if N > 0 || is_degenerate(eₖʲ) eⱼ´ = generate_dual_e(SVector{D´,T}) order = ifelse(N > 0, N, D´) eⱼseries = Series{order}.(eⱼ, eⱼ´) g_integrals_local_e(s, ω, eⱼseries) else g_integrals_local_e(s, ω, eⱼ) end end return g₀, gⱼ end # whether any eₖ == eⱼ for j != k function is_degenerate(eₖʲ::SMatrix{D´}) where {D´} for j in 2:D´, k in 1:j-1 iszero(eₖʲ[k,j]) && return true end return false end function g_integrals_local_e(s::BandSimplex{D,T}, ω::Number, eⱼ) where {D,T} Δⱼ = ω .- eⱼ eₖʲ = map(chop, transpose(eⱼ) .- eⱼ) # broadcast too hard for inference qⱼ = q_vector(eₖʲ) # SVector{D´,T} lΔⱼ = logim.(Δⱼ, s.refex) Eᴰⱼ = (-1)^D .* Δⱼ.^(D-1) .* lΔⱼ ./ factorial(D-1) Eᴰ⁺¹ⱼ = (-1)^(D+1) .* Δⱼ.^D .* lΔⱼ ./ factorial(D) if iszero(eₖʲ) # special case, full energy degeneracy Δ0 = chop(first(Δⱼ)) if iszero(Δ0) g₀ = zero(complex(T)) gⱼ = SVector(ntuple(Returns(g₀), Val(D))) else g₀ = complex(scalar(inv(Δ0)))/factorial(D) gⱼ = SVector(ntuple(Returns(g₀/(D+1)), Val(D))) end else g₀ = scalar(sum(qⱼ .* Eᴰⱼ)) gⱼ = ntuple(Val(D)) do j j´ = j + 1 D´ = D + 1 x = (Eᴰⱼ[j´] - (-Δⱼ[j´])^(D-1)/factorial(D)) * qⱼ[j´] for k in 1:D´ if k != j´ x -= (qⱼ[j´] * Eᴰ⁺¹ⱼ[j´] + qⱼ[k] * Eᴰ⁺¹ⱼ[k]) / eₖʲ[k, j´] end end return scalar(x) end |> SVector end return g₀, gⱼ end function q_vector(eₖʲ::SMatrix{D´,D´,S}) where {D´,S} qⱼ = ntuple(Val(D´)) do j x = one(S) for k in 1:D´ j != k && (x *= eₖʲ[k, j]) end return inv(x) end return qⱼ end # imaginary log with branchcut in the lower plane logim(x::Complex) = iszero(imag(x)) ? logim(real(x)) : log(-im * x) logim(x::T) where {T<:Real} = log(abs(x)) - im * T(0.5π) * sign(x) logim(x, ex) = logim(x) # required for local degenerate case (expansion of logim(Δ::Series, ex)) function logim(s::Series{N}, ex) where {N} s₀ = scalar(s) l₀ = logim(s₀) log_coeff = tupletake(ex.log, Val(N-1)) invzΔ = cumprod(ntuple(Returns(1/s₀), Val(N-1))) lⱼ = log_coeff .* invzΔ l = Series(l₀, lⱼ...) return rescale(l, s[1]) end #endregion ############################################################################################ # g_integrals_nonlocal: finite-dn g₀(ω) and gⱼ(ω) with normal or hyperdual numbers for φ #region function g_integrals_nonlocal(s::BandSimplex{D,T}, ω, dn, ::Val{N} = Val(0)) where {D,T,N} ϕⱼ = s.kij * dn ϕₖʲ = chop.(transpose(ϕⱼ) .- ϕⱼ) eₖʲ = s.eij g₀, gⱼ = begin if N > 0 || is_degenerate(ϕₖʲ, eₖʲ) order = ifelse(N > 0, N, D+1) ## This dynamical estimate of the order is not type-stable. Not worth it # order = N == 0 ? simplex_degeneracy(ϕₖʲ, eₖʲ) + 1 : N # if order > 1 ϕⱼ´ = s.dualphi ϕⱼseries = Series{order}.(ϕⱼ, ϕⱼ´) g_integrals_nonlocal_ϕ(s, ω, ϕⱼseries) else g_integrals_nonlocal_ϕ(s, ω, ϕⱼ) end end return g₀, gⱼ end # If any ϕₖʲ = 0, or if any tₖʲ and tₗʲ are equal function is_degenerate(ϕₖʲ::SMatrix{D´}, eₖʲ) where {D´} for j in 2:D´, k in 1:j-1 # iszero(ϕₖʲ[k,j]) && iszero(eₖʲ[k,j]) && return true # fails for g₁ iszero(ϕₖʲ[k,j]) && return true if !iszero(eₖʲ[k,j]) for l in 1:D´ if l != k && l != j ϕₖʲ[k,j]*eₖʲ[l,j] ≈ eₖʲ[k,j]*ϕₖʲ[l,j] && return true end end end end return false end function g_integrals_nonlocal_ϕ(s::BandSimplex{D,T}, ω::Number, ϕⱼ) where {D,T} eⱼ = s.ei eₖʲ = s.eij Δⱼ = ω .- eⱼ ϕₖʲ = map(chop, transpose(ϕⱼ) .- ϕⱼ) # broadcast too hard for inference tₖʲ = divide_if_nonzero.(ϕₖʲ, eₖʲ) eϕⱼ = cis_scalar.(ϕⱼ, s.refex) αₖʲγⱼ = αγ_matrix(ϕₖʲ, tₖʲ, eₖʲ) # αₖʲγⱼ :: SMatrix{D´,D´} if iszero(eₖʲ) # special case, full energy degeneracy Δ0 = chop(first(Δⱼ)) if iszero(Δ0) g₀ = zero(complex(T)) gⱼ = ntuple(Returns(g₀), Val(D)) else Δ0⁻¹ = inv(Δ0) γⱼ = αₖʲγⱼ[1,:] # if eₖʲ == 0, then αₖʲ == 1 λⱼ = γⱼ .* eϕⱼ λₖʲ = divide_if_nonzero.(transpose(λⱼ), ϕₖʲ) q = (-im)^D * Δ0⁻¹ g₀ = q * sum(scalar.(λⱼ)) gⱼ = ntuple(Val(D)) do j q * scalar(λⱼ[j+1] + im * sum(λₖʲ[:,j+1] - transpose(λₖʲ)[:,j+1])) end end else αₖʲγⱼeϕⱼ = αₖʲγⱼ .* transpose(eϕⱼ) # αₖʲγⱼeϕⱼ :: SMatrix{D´,D´} Jₖʲ = J_scalar.(tₖʲ, eₖʲ, transpose(Δⱼ), s.refex) # Jₖʲ :: SMatrix{D´,D´} αₖʲγⱼeϕⱼJₖʲ = αₖʲγⱼeϕⱼ .* Jₖʲ Λⱼ = sum(αₖʲγⱼeϕⱼJₖʲ, dims = 1) Λₖʲ = Λ_matrix(eₖʲ, ϕₖʲ, Λⱼ, Δⱼ, tₖʲ, αₖʲγⱼeϕⱼ, Jₖʲ) q´ = (-im)^(D+1) g₀ = q´ * sum(scalar.(Λⱼ)) gⱼ = ntuple(Val(D)) do j q´ * scalar(Λⱼ[j+1] + im * sum(Λₖʲ[:,j+1] - transpose(Λₖʲ)[:,j+1])) end end return Complex{T}(g₀), SVector{D,Complex{T}}(gⱼ) end # Series of cis(ϕ) function cis_scalar(s::Series{N}, ex) where {N} @assert iszero(s.pow) cis_series = Series(tupletake(ex.cis, Val(N))) c = cis(s[0]) * cis_series # Go from ds differential to dϕ return rescale(c, s[1]) end cis_scalar(s, ex) = cis(s) divide_if_nonzero(a, b) = iszero(b) ? a : a/b multiply_if_nonzero(a, b) = iszero(b) ? a : a*b function αγ_matrix(ϕedges::S, tedges::S, eedges::SMatrix{D´,D´}) where {D´,S<:SMatrix{D´,D´}} js = ks = SVector{D´}(1:D´) kjs = tuple.(ks, js') α⁻¹ = α⁻¹_scalar.(kjs, Ref(tedges), Ref(eedges)) γ⁻¹ = γ⁻¹_scalar.(js', Ref(ϕedges), Ref(eedges)) γα = inv.(α⁻¹ .* γ⁻¹) return γα end function α⁻¹_scalar((k, j), tedges::SMatrix{D´,D´,S}, eedges) where {D´,S} x = one(S) j != k && !iszero(eedges[k, j]) || return x @inbounds for l in 1:D´ if l != j && !iszero(eedges[l, j]) x *= eedges[l, j] if l != k # ekj != 0, already constrained above x *= chop(tedges[l, j] - tedges[k, j]) end end end return x end function γ⁻¹_scalar(j, ϕedges::SMatrix{D´,D´,S}, eedges) where {D´,S} x = one(S) @inbounds for l in 1:D´ if l != j && iszero(eedges[l, j]) x *= ϕedges[l, j] end end return x end function Λ_matrix(eₖʲ::SMatrix{D´}, ϕₖʲ, Λⱼ, Δⱼ, tₖʲ, αₖʲγⱼeϕⱼ, Jₖʲ) where {D´} js = ks = SVector{D´}(1:D´) ## Inference currently struggles with this # kjs = tuple.(ks, js') # Λₖʲ = Λ_scalar.(kjs, ϕₖʲ, transpose(Λⱼ), transpose(Δⱼ), Ref(eₖʲ), Ref(tₖʲ), Ref(αₖʲγⱼeϕⱼ), Ref(Jₖʲ)) kjs = Tuple(tuple.(ks, js')) Λₖʲtup = ntuple(Val(D´*D´)) do i (k,j) = kjs[i] Λ_scalar((k,j), ϕₖʲ[k,j], Λⱼ[j], Δⱼ[j], eₖʲ, tₖʲ, αₖʲγⱼeϕⱼ, Jₖʲ) end Λₖʲ = SMatrix{D´,D´}(Λₖʲtup) return Λₖʲ end function Λ_scalar((k, j), ϕₖʲ, Λⱼ, Δⱼ, emat::SMatrix{D´,D´,T}, tmat, αγeϕmat, Jmat) where {D´,T} Λₖʲ = zero(typeof(Λⱼ)) j == k && return Λₖʲ eₖʲ = emat[k,j] if iszero(eₖʲ) Λₖʲ = Λⱼ / ϕₖʲ else tₖʲ = tmat[k,j] Jₖʲ = Jmat[k,j] @inbounds for l in 1:D´ if !iszero(emat[l,j]) tₗʲ = tmat[l,j] Jₗʲ = Jmat[l,j] if tₗʲ == tₖʲ Λₖʲ -= (αγeϕmat[l, j] / eₖʲ) * (inv(tₗʲ) + im * Δⱼ * Jₗʲ) else Λₖʲ -= (αγeϕmat[l, j] / eₖʲ) * chop(Jₗʲ - Jₖʲ) * inv(chop(tₗʲ - tₖʲ)) end end end end return Λₖʲ end function J_scalar(t::T, e, Δ, ex) where {T<:Real} iszero(e) && return zero(complex(T)) tΔ = t * Δ J = iszero(tΔ) ? logim(Δ) : cis(tΔ) * J_integral(tΔ, t, Δ) return Complex{T}(J) end function J_scalar(t::Series{N,T}, e, Δ, ex) where {N,T<:Real} iszero(e) && return zero(Series{N,Complex{T}}) N´ = N - 1 C = Complex{T} iszero(Δ) && return Series{N}(C(Inf)) t₀ = t[0] tΔ = t₀ * Δ if iszero(tΔ) J₀ = logim(Δ) Jᵢ = tupletake(ex.J0, Val(N´)) # ntuple(n -> C(-im)^n/(n*factorial(n)), Val(N´)) J = Series{N}(J₀, Jᵢ...) cis_coefs = tupletake(ex.cis, Val(N)) E = Series(cis_coefs) # cis(tΔ) == 1 EJ = E * J else cistΔ = cis(tΔ) J₀ = J_integral(tΔ, t₀, Δ) if N > 1 invzΔ = cumprod(ntuple(Returns(1/tΔ), Val(N-1))) Jmat = smatrixtake(ex.Jmat, Val(N´)) Jᵢ = Tuple(inv(cistΔ) * (Jmat * SVector(invzΔ))) J = Series(J₀, Jᵢ...) else J = Series(J₀) end cis_coefs = tupletake(ex.cis, Val(N)) Eᵢ = cistΔ .* cis_coefs E = Series(Eᵢ) EJ = E * J end return rescale(EJ, t[1] * Δ) end function J_integral(tΔ, t::T, Δ) where {T} J = iszero(imag(tΔ)) ? cosint(abs(tΔ)) - im*sinint(real(tΔ)) - im*T(0.5π)*sign(Δ) : -gamma(0, im*tΔ) - im*T(0.5π)*(sign(real(Δ))+sign(real(tΔ))) return Complex{T}(J) end #endregion ############################################################################################ # AppliedBandsGreenSolver <: AppliedGreenSolver #region struct SubbandSimplices{BS<:BandSimplex} simps::Vector{BS} # collection of k_∥-ordered simplices simpslices::Vector{UnitRange{Int}} # ranges of simplices with "equal" k_∥ to boundary end struct BoundaryOrbs{L} boundary::Pair{Int,Int} # dir => pos orbsright::OrbitalSlice{L} # 1D boundary orbslice coupled to right half-"plane" orbsleft::OrbitalSlice{L} # 1D boundary orbslice coupled to left half-"plane" end struct AppliedBandsGreenSolver{B<:Union{Missing,BoundaryOrbs},SB<:Subband,SS<:SubbandSimplices} <: AppliedGreenSolver subband::SB # single (non-split) subband subbandsimps::SS # BandSimplices in subband boundaryorbs::B # missing or BoundaryOrbs end #region ## Constructors ## boundaryorbs(::Missing, h::AbstractHamiltonian) = missing function boundaryorbs((dir, pos), h::AbstractHamiltonian) L = latdim(h) rcell = (pos+1) * unitvector(dir, SVector{L,Int}) lcell = (pos-1) * unitvector(dir, SVector{L,Int}) orbsright = coupled_orbslice(<=(pos), h, rcell, dir) orbsleft = coupled_orbslice(>=(pos), h, lcell, dir) return BoundaryOrbs(dir => pos, orbsright, orbsleft) end function coupled_orbslice(condition, h, seedcell, dir) lat = lattice(h) ls = grow(lat[CellSites(seedcell, :)], h) (cells, inds) = group_projected_cell_indices(condition, dir, cellsdict(ls)) cdict = cellinds_to_dict(cells, unsafe_cellsites.(cells, inds)) # no uniqueness check here sslice = SiteSlice(lat, cdict) # here we get an (unnecessary) uniqueness check oslice = sites_to_orbs_nogroups(sslice, h) return oslice end projected_cell(cell::SVector{L,Int}, dir) where {L} = cell[dir] * unitvector(dir, SVector{L,Int}) # A merged version of: # [(projected_cell(cell(c), dir), inds(c)) for c in cellsdict(ls) if condition(cell(c)[dir])] function group_projected_cell_indices(condition, dir, d::CellSitesDict{L}) where {L} keys´ = SVector{L,Int}[] indvals´ = Vector{Int}[] if !isempty(d) # get [cell => sites(cell, inds)...] ps = collect(pairs(d)) # get [projcell => sites(cell, inds)...] map!(kv -> projected_cell(first(kv), dir) => last(kv), ps, ps) # remove those pcells that do not satisfy condition filter!(kv -> condition(first(kv)[dir]), ps) # sort by projcell sort!(ps, by = first) # Do an append!-merge of equal projcells key´ = first(first(ps)) indval´ = Int[] for (key, val) in ps if key != key´ push!(keys´, key´) push!(indvals´, unique!(sort!(indval´))) key´ = key indval´ = copy(siteindices(val)) else append!(indval´, siteindices(val)) end end push!(keys´, key´) push!(indvals´, unique!(sort!(indval´))) end return keys´, indvals´ end #endregion #region ## API ## # Parent hamiltonian needs to be non-parametric, so no need to alias minimal_callsafe_copy(s::AppliedBandsGreenSolver, parentham, parentcontacts) = s needs_omega_shift(s::AppliedBandsGreenSolver) = false bands(g::GreenFunction{<:Any,<:Any,<:Any,<:AppliedBandsGreenSolver}) = g.solver.subband boundaries(s::AppliedBandsGreenSolver{Missing}) = () boundaries(s::AppliedBandsGreenSolver) = (s.boundaryorbs.boundary,) #endregion #region ## apply ## function apply(s::GS.Bands, h::AbstractHamiltonian{T,<:Any,L}, cs::Contacts) where {T,L} L == 0 && argerror("Cannot use GreenSolvers.Bands with 0D AbstractHamiltonians") ticks = s.bandsargs kw = s.bandskw b = bands(h, ticks...; kw..., projectors = true, split = false) sb = only(subbands(b)) ex = Expansions(Val(L), T) subbandsimps = subband_simplices!(sb, ex, s) boundary = boundaryorbs(s.boundary, h) return AppliedBandsGreenSolver(sb, subbandsimps, boundary) end # reorders simplices(sb) (simp indices) to match simps::Vector{<:BandSimplex} function subband_simplices!(sb::Subband, ex::Expansions, s::GS.Bands) refex = Ref(ex) simpinds = simplices(sb) simps = [BandSimplex(sb, simp, refex) for simp in simpinds] simpslices = simplex_slices!(simps, simpinds, s) return SubbandSimplices(simps, simpslices) end # order simplices by their k∥ and compute ranges in each kranges bin function simplex_slices!(simps::Vector{<:BandSimplex{D}}, simpinds, s::GS.Bands) where {D} boundary = s.boundary ticks = applied_ticks(s.bandsargs, Val(D)) if boundary !== missing dir = first(boundary) checkdirection(dir, simps) if D > 1 p = sortperm(simps, by = simp -> parallel_base_coordinate(simp, dir)) permute!(simps, p) permute!(simpinds, p) # Discrete values for L-1 dimensional k∥ mesh kticks = ntuple(i -> ifelse(i < dir, ticks[i], ticks[i+1]), Val(D-1)) simpslices = collect(Runs(simps, (s1, s2) -> in_same_interval((s1, s2), kticks, dir))) else simpslices = [UnitRange(eachindex(simps))] end return simpslices end return UnitRange{Int}[] end # in case s.bandargs is empty (relying on defauld_band_ticks) applied_ticks(bandsargs::Tuple{}, val) = default_band_ticks(val) applied_ticks(bandsargs, val) = bandsargs checkdirection(dir, ::Vector{<:BandSimplex{D}}) where {D} = 1 <= dir <= D || argerror("Boundary direction $dir should be 1 <= dir <= $D") function parallel_base_coordinate(s::BandSimplex{D}, dir) where {D} kmean = mean(s.kij, dims = 1) notdir = SVector(ntuple(i -> ifelse(i < dir, i, i+1), Val(D-1))) kpar = kmean[notdir] return kpar end # assumes kticks are sorted, see GS.Bands constructor function in_same_interval((s1, s2), kticks, dir) kvec1 = parallel_base_coordinate(s1, dir) kvec2 = parallel_base_coordinate(s2, dir) for (k1, k2, ks) in zip(kvec1, kvec2, kticks) for i in firstindex(ks):lastindex(ks)-1 in1 = ks[i] < k1 < ks[i+1] in2 = ks[i] < k2 < ks[i+1] xor(in1, in2) && return false in1 && in2 && break end end return true end #endregion #region ## call ## function (s::AppliedBandsGreenSolver)(ω, Σblocks, corbitals) g0slicer = BandsGreenSlicer(complex(ω), s) gslicer = maybe_TMatrixSlicer(g0slicer, Σblocks, corbitals) return gslicer end #endregion #endregion ############################################################################################ # BandsGreenSlicer <: GreenSlicer #region struct BandsGreenSlicer{C,B,S<:AppliedBandsGreenSolver{B}} <: GreenSlicer{C} ω::C solver::S end #region ## API ## Base.getindex(s::BandsGreenSlicer{<:Any,Missing}, i::CellOrbitals, j::CellOrbitals) = inf_band_slice(s, i, j) Base.getindex(s::BandsGreenSlicer, i::CellOrbitals, j::CellOrbitals) = semi_band_slice(s, i, j) function inf_band_slice(s::BandsGreenSlicer{C}, i::CellOrbitals, j::CellOrbitals) where {C} solver = s.solver gmat = zeros(C, norbitals(i), norbitals(j)) inf_band_slice!(gmat, s.ω, (i, j), solver.subband, solver.subbandsimps) return gmat end function inf_band_slice!(gmat, ω, (i, j)::Tuple{CellOrbitals,CellOrbitals}, subband::Subband, subbandsimps::SubbandSimplices, simpinds = eachindex(simplices(subband))) dist = cell(i) - cell(j) orbs = orbindices(i), orbindices(j) return inf_band_slice!(gmat, ω, dist, orbs, subband, subbandsimps, simpinds) end # main driver function inf_band_slice!(gmat, ω, dist, orbs, subband, subbandsimps, simpinds) ψPdict = projected_states(subband) for simpind in simpinds bandsimplex = subbandsimps.simps[simpind] g₀, gⱼs = g_integrals(bandsimplex, ω, dist) isinf(g₀) && continue v₀, vⱼs... = simplices(subband)[simpind] ψ = states(vertices(subband, v₀)) pind = (simpind, v₀) muladd_ψPψ⁺!(gmat, bandsimplex.VD * (g₀ - sum(gⱼs)), ψ, ψPdict, pind, orbs) for (j, gⱼ) in enumerate(gⱼs) vⱼ = vⱼs[j] ψ = states(vertices(subband, vⱼ)) pind = (simpind, vⱼ) muladd_ψPψ⁺!(gmat, bandsimplex.VD * gⱼ, ψ, ψPdict, pind, orbs) end end return gmat end function inf_band_slice!(gmat, ω, (si, sj)::Tuple, args...) # si, sj can be orbslice or cellorbs if ncells(si) == ncells(sj) == 1 # boundary slice is one-cell-wide, no need for views i, j = get_single_cellorbs(si), get_single_cellorbs(sj) inf_band_slice!(gmat, ω, (i, j), args...) else offsetj = 0 for j in get_multiple_cellorbs(sj) offseti = 0 nj = norbitals(j) for i in get_multiple_cellorbs(si) ni = norbitals(i) gv = view(gmat, offseti+1:offseti+ni, offsetj+1:offsetj+nj) inf_band_slice!(gv, ω, (i, j), args...) offseti += ni end offsetj += nj end end return gmat end get_single_cellorbs(c::CellOrbitals) = c get_single_cellorbs(c::OrbitalSlice) = only(cellsdict(c)) get_multiple_cellorbs(c::CellOrbitals) = (c,) get_multiple_cellorbs(c::LatticeSlice) = cellsdict(c) # Gᵢⱼ(k∥) = G⁰ᵢⱼ(k∥) - G⁰ᵢᵦ(k∥)G⁰ᵦᵦ(k∥)⁻¹G⁰ᵦⱼ(k∥), where β are removed sites at boundary function semi_band_slice(s::BandsGreenSlicer{C}, i::CellOrbitals{L}, j::CellOrbitals{L}) where {C,L} borbs = s.solver.boundaryorbs ni, nj = length(orbindices(i)), length(orbindices(j)) gij = zeros(C, ni, nj) (dir, pos) = borbs.boundary xi, xj = cell(i)[dir] - pos, cell(j)[dir] - pos if sign(xi) == sign(xj) != 0 subband, subbandsimps = s.solver.subband, s.solver.subbandsimps b = ifelse(xi > 0, borbs.orbsright, borbs.orbsleft) # 1D boundary orbital slice n0 = norbitals(b) g0j = zeros(C, n0, nj) gi0 = zeros(C, ni, n0) g00 = zeros(C, n0, n0) for simpinds in subbandsimps.simpslices fill!(g00, zero(C)) fill!(g0j, zero(C)) fill!(gi0, zero(C)) inf_band_slice!(gij, s.ω, (i, j), subband, subbandsimps, simpinds) inf_band_slice!(g00, s.ω, (b, b), subband, subbandsimps, simpinds) inf_band_slice!(g0j, s.ω, (b, j), subband, subbandsimps, simpinds) inf_band_slice!(gi0, s.ω, (i, b), subband, subbandsimps, simpinds) gg = ldiv!(lu!(g00), g0j) mul!(gij, gi0, gg, -1, 1) end end return gij end # does g += α * ψPψ´ = α * ψP * (ψP)´, where ψP = ψPdict[pind] is the vertex projection onto # the simplex subspace. If pind = (simpind, vind) is not in ψPdict::Dict, no P is necessary function muladd_ψPψ⁺!(gmat, α, ψ, ψPdict, pind, orbs) if haskey(ψPdict, pind) muladd_ψPψ⁺!(gmat, α, ψPdict[pind], orbs) else muladd_ψPψ⁺!(gmat, α, ψ, orbs) end return gmat end function muladd_ψPψ⁺!(gmat, α, ψ, (rows, cols)::Tuple) if size(ψ, 1) == length(rows) == length(cols) mul!(gmat, ψ, ψ', α, 1) else ψrows = view_or_copy(ψ, rows, :) ψcols = view_or_copy(ψ, cols, :) mul!(gmat, ψrows, ψcols', α, 1) end return gmat end view_or_copy(ψ, rows::Union{Colon,AbstractRange}, cols::Union{Colon,AbstractRange}) = view(ψ, rows, cols) view_or_copy(ψ, rows, cols) = ψ[rows, cols] minimal_callsafe_copy(s::BandsGreenSlicer, parentham, parentcontacts) = s # it is read-only #endregion ############################################################################################ # diagonal_slice # optimized block diagonal of g[::CellOrbitals] for BandsGreenSlicer without boundary # otherwise we need to do it the normal way #region function diagonal_slice(gω::GreenSolution{T,<:Any,<:Any,G}, o::CellOrbitals) where {T,G<:BandsGreenSlicer{<:Any,Missing}} s = slicer(gω) # BandsGreenSlicer norbs = flatsize(gω) rngs = orbranges(o) dist = zero(cell(o)) C = complex(T) gmat = Matrix{C}(undef, norbs, norbs) for rng in rngs gmat[rng, rng] .= zero(C) end subband, subbandsimps = s.solver.subband, s.solver.subbandsimps simpinds = eachindex(simplices(subband)) # to main driver with orbs = rngs inf_band_slice!(gmat, s.ω, dist, rngs, subband, subbandsimps, simpinds) return gmat end function muladd_ψPψ⁺!(gmat, α, ψ, rngs::Vector{<:UnitRange}) for rng in rngs if length(rng) == 1 i = only(rng) gmat[i, i] += α * abs2(ψ[i]) else gv = view(gmat, rng, rng) ψv = view(ψ, rng, :) mul!(gv, ψv, ψv', α, 1) end end return gmat end #endregion #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
8918
############################################################################################ # KPMBuilder # computes μⁱʲₙ = ⟨ψⱼ|kernel T_n(h)|ψᵢ⟩ #region struct KPMBuilder{O,M,T,K,H} h::H kernel::O ket::K ket1::K ket2::K bandCH::T # (center, halfwidth) mulist::M end function KPMBuilder(h, kernel, ket, bandCH, order) mulist = empty_mulist(ket, order) ket1, ket2 = similar(ket), similar(ket) return KPMBuilder(h, kernel, ket, ket1, ket2, bandCH, mulist) end empty_mulist(::Vector{C}, order) where {C<:Complex} = zeros(C, order + 1) empty_mulist(ket::Matrix{C}, order) where {C<:Complex} = [zeros(C, size(ket, 2), size(ket, 2)) for _ in 1:(order + 1)] function momentaKPM(h, ket, (center, halfwidth); order = 10, kernel = I) pmeter = Progress(order; desc = "Computing moments: ") builder = KPMBuilder(h, kernel, ket, (center, halfwidth), order) mulist = addmomentaKPM!(builder, pmeter) jackson!(mulist) return mulist end # Single step algorithm (non-identity Kernel) function addmomentaKPM!(b::KPMBuilder{<:AbstractMatrix}, pmeter) seed_singlestep_KPM!(b) mulist, h, bandCH, kmat, kmat0, kmat1 = b.mulist, b.h, b.bandCH, b.ket, b.ket1, b.ket2 order = length(mulist) - 1 for n in 3:(order+1) ProgressMeter.next!(pmeter; showvalues = ()) iterateKPM!(kmat0, h', kmat1, bandCH) mulat!(mulist, n, kmat0', kmat, 1, 1) # μ[n] += kmat0'*kmat1 kmat0, kmat1 = kmat1, kmat0 end return mulist end # Double step algorithm (identity Kernel) function addmomentaKPM!(b::KPMBuilder{<:UniformScaling}, pmeter) μ0, μ1 = seed_doublestep_KPM!(b) mulist, h, bandCH, A, kmat0, kmat1 = b.mulist, b.h, b.bandCH, b.kernel, b.ket1, b.ket2 order = length(mulist) - 1 for n in 3:2:(order+1) ProgressMeter.next!(pmeter; showvalues = ()) ProgressMeter.next!(pmeter; showvalues = ()) # twice because of 2-step iterateKPM!(kmat0, h', kmat1, bandCH) mulat!(mulist, n, kmat1', kmat1, 2, 1) minusat!(mulist, n, μ0) # μ[n] += 2*kmat1'*kmat1 - μ0 n + 1 > order + 1 && break mulat!(mulist, n + 1, kmat1', kmat0, 2, 1) minusat!(mulist, n + 1, μ1) # μ[n+1] += 2*kmat1'*kmat0 - μ1 kmat0, kmat1 = kmat1, kmat0 end A.λ ≈ 1 || (mulist .*= A.λ) return mulist end function seed_singlestep_KPM!(b::KPMBuilder) mul!(b.ket1, b.kernel', b.ket) mulscaled!(b.ket2, b.h', b.ket1, b.bandCH) mulat!(b.mulist, 1, b.ket1', b.ket, 1, 1) mulat!(b.mulist, 2, b.ket2', b.ket, 1, 1) return nothing end function seed_doublestep_KPM!(b::KPMBuilder{<:UniformScaling,Vector{T}}) where {T<:Matrix} copy!(b.ket1, b.ket) mulscaled!(b.ket2, b.h', b.ket1, b.bandCH) μ0, μ1 = copy(b.mulist[1]), copy(b.mulist[2]) mulat!(b.mulist, 1, b.ket1', b.ket1, 1, 1) mulat!(b.mulist, 2, b.ket2', b.ket1, 1, 1) μ0 .= b.mulist[1] .- μ0 μ1 .= b.mulist[2] .- μ1 return μ0, μ1 end function seed_doublestep_KPM!(b::KPMBuilder{<:UniformScaling,Vector{T}}) where {T<:Number} copy!(b.ket1, b.ket) mulscaled!(b.ket2, b.h', b.ket1, b.bandCH) b.mulist[1] += μ0 = b.ket1' * b.ket1 b.mulist[2] += μ1 = b.ket2' * b.ket1 return μ0, μ1 end # y = rescaled(h) * x function mulscaled!(y, h´, x, (center, halfwidth)) mul!(y, h´, x) invhalfwidth = 1/halfwidth @. y = (y - center * x) * invhalfwidth return y end # kmat0 = 2 * rescaled(h) * kmat1 - kmat1 function iterateKPM!(kmat0, h, kmat1, (center, halfwidth)) α = 2/halfwidth β = 2center/halfwidth mul!(kmat0, h, kmat1, α, -1) @. kmat0 = kmat0 - β * kmat1 return kmat0 end mulat!(C::Vector{<:Matrix}, n, A, B, α, β) = mul!(C[n], A, B, α, β) mulat!(C::Vector{<:Number}, n, A, B, α, β) = (C[n] = α * A * B + β * C[n]) minusat!(A::Vector{<:Matrix}, n, x) = (A[n] .-= x) minusat!(A::Vector{<:Number}, n, x) = (A[n] -= x) function jackson!(μ::AbstractVector) order = length(μ) - 1 @inbounds for n in eachindex(μ) μ[n] *= ((order - n + 1) * cos(π * n / (order + 1)) + sin(π * n / (order + 1)) * cot(π / (order + 1))) / (order + 1) end return μ end #endregion ############################################################################################ # AppliedKPMGreenSolver #region struct AppliedKPMGreenSolver{T<:AbstractFloat,M<:Union{Complex{T},AbstractMatrix{Complex{T}}}} <: AppliedGreenSolver momenta::Vector{M} bandCH::Tuple{T,T} end #region ## API ## moments(s::AppliedKPMGreenSolver) = s.moments # Parent ham needs to be non-parametric, so no need to alias minimal_callsafe_copy(s::AppliedKPMGreenSolver, parentham, parentcontacts) = s needs_omega_shift(s::AppliedKPMGreenSolver) = false #endregion #region ## apply ## function apply(s::GS.KPM, h::Hamiltonian{T,<:Any,0}, cs::Contacts) where {T} isempty(cs) && argerror("The KPM solver requires at least one contact to be added that defiens where the Green function will be computed. A dummy contact can be created with `attach(nothing; sites...)`.") hmat = h(()) bandCH = T.(band_ceter_halfwidth(hmat, s.bandrange, s.padfactor)) ket = contact_basis(h, cs) momenta = momentaKPM(hmat, ket, bandCH; order = s.order, kernel = s.kernel) return AppliedKPMGreenSolver(momenta, bandCH) end apply(::GS.KPM, h::AbstractHamiltonian, cs::Contacts) = argerror("Can only use KPM with bounded non-parametric Hamiltonians") band_ceter_halfwidth(_, (emin, emax), padfactor) = 0.5 * (emin + emax), 0.5 * (emax - emin) function band_ceter_halfwidth(h, ::Missing, padfactor) @warn "Computing spectrum bounds... Consider using the `bandrange` option for faster performance." # (ϵmin, ϵmax) = GS.bandrange_arnoldi(h) (emin, emax) = GS.bandrange_arpack(h) @warn "Computed real bandrange = ($emin, $emax)" bandCH = 0.5 * (emin + emax), 0.5 * (emax - emin) * padfactor return bandCH end function contact_basis(h::AbstractHamiltonian{T}, contacts) where {T} n = flatsize(h) # Orbital indices in merged contacts, all belonging to a single unit cell mergedorbinds = orbindices(only(cellsdict(contacts))) basis = zeros(Complex{T}, n, length(mergedorbinds)) one!(basis, mergedorbinds) return basis end #endregion #region ## call ## function (s::AppliedKPMGreenSolver{T})(ω, Σblocks, corbitals) where {T} g0contacts = KPMgreen(s.momenta, ω, s.bandCH) # We rely on TMatrixSlicer to incorporate contact self-energie, and to slice contacts gslicer = TMatrixSlicer(g0contacts, Σblocks, corbitals) return gslicer end #endregion #endregion ############################################################################################ # KPM Green # h = rescaled(H) = (H - ω0)/Δ, where (ω0, Δ) = bandsCH = (center, halfwidth) # G_H(ω) = 1/(ω-H) = 1/(ω - Δ*h - ω0*I) = Δ⁻¹/((ω - ω0)/Δ - h) = Δ⁻¹ G_h((ω-ω0)/Δ) #region function KPMgreen(momenta::Vector{<:Matrix}, ω, (ω0, Δ) = (0, 1)) Δ⁻¹ = 1/Δ ω´ = (ω - ω0) * Δ⁻¹ g0 = zero(first(momenta)) for (i, μi) in enumerate(momenta) g0n = Δ⁻¹ * KPMgreen_coefficient(i - 1, ω´) g0 .+= g0n .* μi end return g0 end function KPMgreen_coefficient(n, ω) σ = ifelse(imag(ω) < 0, -1, 1) ωc = complex(ω) g0n = -2 * im * σ * cis(-n * σ * acos(ωc)) / (ifelse(iszero(n), 2, 1) * sqrt(1 - ωc^2)) return g0n end #endregion ############################################################################################ # densitymatrix # specialized DensityMatrix method for GS.KPM #region struct DensityMatrixKPMSolver{T,M} momenta::Vector{M} bandCH::Tuple{T,T} end ## Constructor function densitymatrix(s::AppliedKPMGreenSolver, gs::GreenSlice{T}) where {T} check_nodiag_axes(gs) has_selfenergy(gs) && argerror("The KPM densitymatrix solver currently support only `nothing` contacts") momenta = slice_momenta(s.momenta, gs) solver = DensityMatrixKPMSolver(momenta, s.bandCH) return DensityMatrix(solver, gs) end function slice_momenta(momenta, gs) r = _maybe_contactinds(gs, rows(gs)) c = _maybe_contactinds(gs, cols(gs)) momenta´ = [view(m, r, c) for m in momenta] return momenta´ end _maybe_contactinds(gs, ::Colon) = Colon() _maybe_contactinds(gs, i::Integer) = contactinds(gs, i) _maybe_contactinds(gs, _) = throw(argerror("KPM doesn't support generic indexing")) ## call function (d::DensityMatrixKPMSolver)(mu, kBT; params...) ω0, Δ = d.bandCH kBT´ = kBT / Δ mu´ = (mu - ω0) / Δ if kBT´ ≈ 0 ϕ = acos(mu´) ρ = copy(first(d.momenta)) * (1-ϕ/π) for n in 1:length(d.momenta)-1 @. ρ += d.momenta[n+1] * 2 * (sin(π*n)-sin(n*ϕ))/(π*n) end else throw(argerror("KPM densitymatrix currently doesn't support finite temperatures")) end return ρ end #endregion #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
23071
############################################################################################ # SchurFactorsSolver - see scattering.pdf notes for derivations # Auxiliary functions for AppliedSchurGreenSolverSolver # Computes dense factors PR*R*Z21, Z11 and R'*PR'. The retarded self-energy on the open # unitcell surface of a semi-infinite rightward lead reads Σᵣ = PR R Z21 Z11⁻¹ R' PR' # Computes also the leftward PL*L*Z11´, Z21´, L'*PL', with Σₗ = PL L Z11´ Z21´⁻¹ L' PL' #region struct SchurWorkspace{C} GL::Matrix{ComplexF64} GR::Matrix{ComplexF64} LG::Matrix{C} RG::Matrix{C} A::Matrix{C} B::Matrix{C} Z11::Matrix{C} Z21::Matrix{C} Z11´::Matrix{C} Z21´::Matrix{C} LD::Matrix{C} DL::Matrix{C} RD::Matrix{C} DR::Matrix{C} end struct SchurFactorsSolver{T,B} shift::T # called Ω in the scattering.pdf notes hm::HybridSparseMatrix{T,B} # aliases parent hamiltonian h0::HybridSparseMatrix{T,B} # aliases parent hamiltonian hp::HybridSparseMatrix{T,B} # aliases parent hamiltonian l_leq_r::Bool # whether l <= r (left and right surface dims) iG::SparseMatrixCSC{Complex{T},Int} # to store iG = ω - h0 - Σₐᵤₓ ptrs::Tuple{Vector{Int},Vector{Int},Vector{Int}} # iG ptrs for h0 nzvals, diagonal and Σₐᵤₓ surface linds::Vector{Int} # orbital indices on left surface rinds::Vector{Int} # orbital indices on right surface sinds::Vector{Int} # orbital indices on the smallest surface (left for l<=r, right for l>r) L::Matrix{ComplexF64} # l<=r ? PL : PL*H' === hp PR (n × min(l,r)) R::Matrix{ComplexF64} # l<=r ? PR*H === hm PL : PR (n × min(l,r)) R´L´::Matrix{ComplexF64} # [R'; -L']. L and R must be dense for iG \ (L,R) tmp::SchurWorkspace{Complex{T}} # L, R, R´L´ need 64bit end #region ## Constructors ## SchurFactorsSolver(::AbstractHamiltonian, _) = argerror("The Schur solver requires 1D Hamiltonians with 0 and ±1 as only Bloch Harmonics.") function SchurFactorsSolver(h::Hamiltonian{T,<:Any,1}, shift = one(Complex{T})) where {T} hm, h0, hp = nearest_cell_harmonics(h) fhm, fh0, fhp = flat(hm), flat(h0), flat(hp) # h*'s may be updated after flat but only fh* structure matters linds, rinds, L, R, sinds, l_leq_r = left_right_projectors(fhm, fhp) R´L´ = [R'; -L'] iG, (p, pd) = store_diagonal_ptrs(fh0) ptrs = (p, pd, pd[sinds]) workspace = SchurWorkspace{Complex{T}}(size(L), length(linds), length(rinds)) return SchurFactorsSolver(T(shift), hm, h0, hp, l_leq_r, iG, ptrs, linds, rinds, sinds, L, R, R´L´, workspace) end function SchurWorkspace{C}((n, d), l, r) where {C} GL = Matrix{ComplexF64}(undef, n, d) GR = Matrix{ComplexF64}(undef, n, d) LG = Matrix{C}(undef, d, n) RG = Matrix{C}(undef, d, n) A = Matrix{C}(undef, 2d, 2d) B = Matrix{C}(undef, 2d, 2d) Z11 = Matrix{C}(undef, d, d) Z21 = Matrix{C}(undef, d, d) Z11´ = Matrix{C}(undef, d, d) Z21´ = Matrix{C}(undef, d, d) LD = Matrix{C}(undef, l, d) DL = Matrix{C}(undef, d, l) RD = Matrix{C}(undef, r, d) DR = Matrix{C}(undef, d, r) return SchurWorkspace(GL, GR, LG, RG, A, B, Z11, Z21, Z11´, Z21´, LD, DL, RD, DR) end function nearest_cell_harmonics(h) is_nearest = length(harmonics(h)) == 3 && all(harmonics(h)) do hh dn = dcell(hh) dn == SA[0] || dn == SA[1] || dn == SA[-1] end is_nearest || argerror("Too many or too few harmonics. Perhaps try `supercell` to ensure strictly nearest-cell harmonics.") hm, h0, hp = h[hybrid(-1)], h[hybrid(0)], h[hybrid(1)] flat(hm) == flat(hp)' || argerror("The Hamiltonian should have h[1] == h[-1]' to use the Schur solver") return hm, h0, hp end # hp = L*R' = PL H' PR'. We assume hm = hp' function left_right_projectors(hm::SparseMatrixCSC, hp::SparseMatrixCSC) linds = stored_cols(hm) rinds = stored_cols(hp) # dense projectors o = one(ComplexF64) * I allrows = 1:size(hp,1) l_leq_r = length(linds) <= length(rinds) PR = o[allrows, rinds] PL = o[allrows, linds] if l_leq_r sinds = linds R = Matrix{ComplexF64}(hm[:, linds]) # R = PR H = hm PL L = PL else sinds = rinds R = PR L = Matrix{ComplexF64}(hp[:, rinds]) # L = PL H' = hp PR end return linds, rinds, L, R, sinds, l_leq_r end # Build a new sparse matrix mat´ with same structure as mat plus the diagonal # Return also: # (1) pointers pmat´ to mat´ for each nonzero in mat # (2) diagonal ptrs pdiag´ in mat´ function store_diagonal_ptrs(mat::SparseMatrixCSC{T}) where {T} mat´ = store_diagonal(mat) pmat´, pdiag´ = Int[], Int[] rows, rows´ = rowvals(mat), rowvals(mat´) for col in axes(mat´, 2) ptrs = nzrange(mat, col) ptrs´ = nzrange(mat´, col) p, p´ = first(ptrs), first(ptrs´) while p´ in ptrs´ row´ = rows´[p´] row´ == col && push!(pdiag´, p´) if p in ptrs && row´ == rows[p] push!(pmat´, p´) p += 1 end p´ += 1 end end return mat´, (pmat´, pdiag´) end # ensure diagonal is stored *without* dropping any structural zeros function store_diagonal(mat::SparseMatrixCSC{T}) where {T} m, n = size(mat) d = min(m, n) I, J, V = findnz(mat) append!(I, 1:d) append!(J, 1:d) append!(V, Iterators.repeated(zero(T), d)) return sparse(I, J, V, m, n) end #endregion #region ## API ## ## Call API ## call!_output(s::SchurFactorsSolver) = (s.tmp.RD, s.tmp.Z11, s.tmp.DR), (s.tmp.LD, s.tmp.Z21´, s.tmp.DL) function call!(s::SchurFactorsSolver, ω) R, Z11, Z21, L, Z11´, Z21´ = s.R, s.tmp.Z11, s.tmp.Z21, s.L, s.tmp.Z11´, s.tmp.Z21´ update_LR!(s) # We must update L, R in case a parametric parent has been call!-ed update_iG!(s, ω) # also iG = ω - h0 + iΩP'P A, B = pencilAB!(s) sch = schur!(A, B) whichmodes = Vector{Bool}(undef, length(sch.α)) r = size(A, 1) ÷ 2 # Retarded modes retarded_modes!(whichmodes, sch) checkmodes(whichmodes) ordschur!(sch, whichmodes) copy!(Z11, view(sch.Z, 1:r, 1:sum(whichmodes))) copy!(Z21, view(sch.Z, r+1:2r, 1:sum(whichmodes))) # Advanced modes advanced_modes!(whichmodes, sch) checkmodes(whichmodes) ordschur!(sch, whichmodes) copy!(Z11´, view(sch.Z, 1:r, 1:sum(whichmodes))) copy!(Z21´, view(sch.Z, r+1:2r, 1:sum(whichmodes))) RZ21, LZ11´, LD, DL, RD, DR = s.tmp.GR, s.tmp.GL, s.tmp.LD, s.tmp.DL, s.tmp.RD, s.tmp.DR linds, rinds = s.linds, s.rinds # compute rightward blocks: PR*R*Z21, Z11 and R'*PR' mul!(RZ21, R, Z21) PR_R_Z21 = copy!(RD, view(RZ21, rinds, :)) R´_PR = copy!(DR, view(R', :, rinds)) # compute leftward blocks: PL*L*Z11´, Z21´, L'*PL' mul!(LZ11´, L, Z11´) PL_L_Z11´ = copy!(LD, view(LZ11´, linds, :)) L´_PL = copy!(DL, view(L', :, linds)) return (PR_R_Z21, Z11, R´_PR), (PL_L_Z11´, Z21´, L´_PL) end # need this barrier for type-stability (sch.α and sch.β are finicky) function retarded_modes!(whichmodes, sch) whichmodes .= abs.(sch.α) .< abs.(sch.β) return whichmodes end function advanced_modes!(whichmodes, sch) whichmodes .= abs.(sch.β) .< abs.(sch.α) return whichmodes end checkmodes(whichmodes) = sum(whichmodes) == length(whichmodes) ÷ 2 || argerror("Cannot differentiate retarded from advanced modes. Consider increasing imag(ω) or check that your Hamiltonian is Hermitian") # this does not include a parentcontacts because there are none # (SchurFactorsSolver is not an AppliedGreenSolver, so it may have different API) function minimal_callsafe_copy(s::SchurFactorsSolver, parentham) hm´, h0´, hp´ = nearest_cell_harmonics(parentham) s´ = SchurFactorsSolver(s.shift, hm´, h0´, hp´, s.l_leq_r, copy(s.iG), s.ptrs, s.linds, s.rinds, s.sinds, copy(s.L), copy(s.R), copy(s.R´L´), minimal_callsafe_copy(s.tmp)) return s´ end minimal_callsafe_copy(s::SchurWorkspace) = SchurWorkspace(copy.((s.GL, s.GR, s.LG, s.RG, s.A, s.B, s.Z11, s.Z21, s.Z11´, s.Z21´, s.LD, s.DL, s.RD, s.DR))...) ## Pencil A - λB ## # Compute G*R and G*L where G = inv(ω - h0 - Σₐᵤₓ) for Σₐᵤₓ = -iΩL'L or -iΩR'R # From this compute the deflated A - λB, whose eigenstates are the deflated eigenmodes # Pencil A - λB : # A = [R'GL (1-δ)iΩR'GL; -L'GL 1-(1-δ)iΩL´GL] and B = [1-δiΩR'GR -R'GR; δiΩL'GR L'GR] # where δ = l <= r ? 1 : 0 # A = [Γₗ (1-δ)iΩΓₗ] + [0 0; 0 1] and B = [-Γᵣ -δiΩΓᵣ] + [1 0; 0 0] # Γₗ = [R'; -L']GL and Γᵣ = [R'; -L']GR function pencilAB!(s::SchurFactorsSolver{T}) where {T} o, z = one(Complex{T}), zero(Complex{T}) iGlu = lu(s.iG) Ω = s.shift d = size(s.L, 2) GL = ldiv!(s.tmp.GL, iGlu, s.L) GR = ldiv!(s.tmp.GR, iGlu, s.R) A, B, R´L´ = s.tmp.A, s.tmp.B, s.R´L´ fill!(A, z) fill!(B, z) mul!(view(A, :, 1:d), R´L´, GL) mul!(view(B, :, d+1:2d), R´L´, GR, -1, 0) if s.l_leq_r view(A, :, d+1:2d) .= view(A, :, 1:d) .* (im*Ω) else view(B, :, 1:d) .= view(B, :, d+1:2d) .* (im*Ω) end for i in 1:d A[d+i, d+i] += o B[i, i] += o end return A, B end # updates L and R from the current hm and hp function update_LR!(s) d = size(s.L, 2) if s.l_leq_r # slicing is faster than a view of sparse copy!(s.R, flat(s.hm)[:, s.sinds]) view(s.R´L´, 1:d, :) .= s.R' else # slicing is faster than a view of sparse copy!(s.L, flat(s.hp)[:, s.sinds]) view(s.R´L´, d+1:2d, :) .= .- s.L' end return s end # updates iG = ω - h0 - Σₐᵤₓ from the present h0 function update_iG!(s::SchurFactorsSolver{T}, ω) where {T} Ω = s.shift nzs, nzsh0 = nonzeros(s.iG), nonzeros(flat(s.h0)) ps, pds, pss = s.ptrs fill!(nzs, zero(Complex{T})) for (p, p´) in enumerate(ps) nzs[p´] = -nzsh0[p] end for pd in pds nzs[pd] += ω end for ps in pss nzs[ps] += im*Ω end return s end #endregion #endregion ############################################################################################ # AppliedSchurGreenSolver #region # Mutable: we delay initialization of some fields until they are first needed (which may be never) mutable struct AppliedSchurGreenSolver{T,B,O,O∞,G,G∞} <: AppliedGreenSolver fsolver::SchurFactorsSolver{T,B} boundary::T ohL::O # OpenHamiltonian for unitcell with ΣL (aliases parent h) ohR::O # OpenHamiltonian for unitcell with ΣR (aliases parent h) oh∞::O∞ # OpenHamiltonian for unitcell with ΣL + ΣR (aliases parent h) gL::G # Lazy field: GreenFunction for ohL gR::G # Lazy field: GreenFunction for ohR g∞::G∞ # Lazy field: GreenFunction for oh∞ function AppliedSchurGreenSolver{T,B,O,O∞,G,G∞}(fsolver, boundary, ohL, ohR, oh∞) where {T,B,O,O∞,G,G∞} s = new() s.fsolver = fsolver s.boundary = boundary s.ohL = ohL s.ohR = ohR s.oh∞ = oh∞ return s end end AppliedSchurGreenSolver{G,G∞}(fsolver::SchurFactorsSolver{T,B}, boundary, ohL::O, ohR::O, oh∞::O∞) where {T,B,O,O∞,G,G∞} = AppliedSchurGreenSolver{T,B,O,O∞,G,G∞}(fsolver, boundary, ohL, ohR, oh∞) #region ## API ## schurfactorsolver(s::AppliedSchurGreenSolver) = s.fsolver boundaries(s::AppliedSchurGreenSolver) = (1 => s.boundary,) #endregion #region ## getproperty ## function Base.getproperty(s::AppliedSchurGreenSolver, f::Symbol) if !isdefined(s, f) if f == :gL s.gL = greenfunction(s.ohL, GS.SparseLU()) # oh's harmonics alias parent h[()], elseif f == :gR # but not used until called with ω s.gR = greenfunction(s.ohR, GS.SparseLU()) elseif f == :g∞ s.g∞ = greenfunction(s.oh∞, GS.SparseLU()) else argerror("Unknown field $f for AppliedSchurGreenSolver") end end return getfield(s, f) end #endregion #region ## apply ## function apply(s::GS.Schur, h::AbstractHamiltonian1D{T}, contacts::Contacts) where {T} h´ = hamiltonian(h) fsolver = SchurFactorsSolver(h´, s.shift) boundary = T(round(only(s.boundary))) ohL, ohR, oh∞, G, G∞ = schur_openhams_types(fsolver, h, boundary) solver = AppliedSchurGreenSolver{G,G∞}(fsolver, boundary, ohL, ohR, oh∞) return solver end function schur_openhams_types(fsolver, h, boundary) h0 = unitcell_hamiltonian(h) # h0 is non-parametric, but will alias h.h first harmonic rsites = stored_cols(hamiltonian(h)[unflat(1)]) lsites = stored_cols(hamiltonian(h)[unflat(-1)]) orbslice_l = sites_to_orbs(lattice(h0)[sites(lsites)], h) orbslice_r = sites_to_orbs(lattice(h0)[sites(rsites)], h) ΣR_solver = SelfEnergySchurSolver(fsolver, h, :R, boundary) ΣL_solver = SelfEnergySchurSolver(fsolver, h, :L, boundary) ΣL = SelfEnergy(ΣL_solver, orbslice_l) ΣR = SelfEnergy(ΣR_solver, orbslice_r) # ohL, ohR, oh∞ have no parameters, but will be updated by call!(h; params...) ohL = attach(h0, ΣL) ohR = attach(h0, ΣR) oh∞ = ohR |> attach(ΣL) G, G∞ = green_type(h0, ΣL), green_type(h0, ΣL, ΣR) return ohL, ohR, oh∞, G, G∞ end apply(::GS.Schur, h::AbstractHamiltonian, cs::Contacts) = argerror("Can only use GreenSolvers.Schur with 1D AbstractHamiltonians") const GFUnit{T,E,H,N,S} = GreenFunction{T,E,0,AppliedSparseLUGreenSolver{Complex{T}},H,Contacts{0,N,S,OrbitalSliceGrouped{T,E,0}}} green_type(::H,::S) where {T,E,H<:AbstractHamiltonian{T,E},S} = GFUnit{T,E,H,1,Tuple{S}} green_type(::H,::S1,::S2) where {T,E,H<:AbstractHamiltonian{T,E},S1,S2} = GFUnit{T,E,H,2,Tuple{S1,S2}} #endregion #region ## call API ## function minimal_callsafe_copy(s::AppliedSchurGreenSolver, parentham, _) fsolver´ = minimal_callsafe_copy(s.fsolver, parentham) ohL´, ohR´, oh∞´, G, G∞ = schur_openhams_types(fsolver´, parentham, s.boundary) s´ = AppliedSchurGreenSolver{G,G∞}(fsolver´, s.boundary, ohL´, ohR´, oh∞´) # we don't copy the lazy fields gL, gR, g∞, even if already materialized, since they # must be linked to ohL´, ohR´, oh∞´, not the old ones. return s´ end function (s::AppliedSchurGreenSolver)(ω, Σblocks, corbitals) # call! fsolver once for all the g's call!(s.fsolver, ω) g0slicer = SchurGreenSlicer(ω, s) gslicer = maybe_TMatrixSlicer(g0slicer, Σblocks, corbitals) return gslicer end #endregion #endregion ############################################################################################ # SchurGreenSlicer # Slicer for a 1D lead using the LR Schur factors, with or without a single boundary # For n >= 1: # hⁿ ≡ h₊ⁿ = (LR')ⁿ # h⁻ⁿ ≡ h₋ⁿ = (RL')ⁿ # Infinite lattice: # G∞ₙₙ = G∞₀₀ = (ω*I - h0 - ΣR - ΣL)⁻¹ # G∞ₙₘ = (G₁₁h₊)ⁿ⁻ᵐ G∞₀₀ = G₁₁L (R'G₁₁L)ⁿ⁻ᵐ⁻¹ R'G∞₀₀ for n-m >= 1 # G∞ₙₘ = (G₋₁₋₁h₋)ᵐ⁻ⁿ G∞₀₀ = G₋₁₋₁R(L'G₋₁₋₁R)ᵐ⁻ⁿ⁻¹L'G∞₀₀ for n-m <= -1 # Semiinifinite lattice: # Gₙₘ = (Ghⁿ⁻ᵐ - GhⁿGh⁻ᵐ)G∞₀₀ = G∞ₙₘ - GhⁿG∞₀ₘ # Gₙₘ = G∞ₙₘ - G₁₁L(R'G₁₁L)ⁿ⁻¹ R'G∞₀ₘ for m,n >= 1 # Gₙₘ = G∞ₙₘ - G₋₁₋₁R(L'G₋₁₋₁R)¹⁻ⁿL'G∞₀ₘ for m,n <= -1 #region # We delay initialization of most fields until they are first needed (which may be never) mutable struct SchurGreenSlicer{C,A<:AppliedSchurGreenSolver} <: GreenSlicer{C} ω::C solver::A boundary::C L::Matrix{C} R::Matrix{C} G₋₁₋₁::SparseLUGreenSlicer{C} # These are independent of parent hamiltonian G₁₁::SparseLUGreenSlicer{C} # as they only rely on call!_output(fsolver) G∞₀₀::SparseLUGreenSlicer{C} # which is updated after call!(solver.fsolver, ω) L´G∞₀₀::Matrix{C} R´G∞₀₀::Matrix{C} G₁₁L::Matrix{C} G₋₁₋₁R::Matrix{C} R´G₁₁L::Matrix{C} L´G₋₁₋₁R::Matrix{C} function SchurGreenSlicer{C,A}(ω, solver) where {C,A} s = new() s.ω = ω s.solver = solver s.boundary = solver.boundary s.L = solver.fsolver.L s.R = solver.fsolver.R return s end end SchurGreenSlicer(ω, solver::A) where {T,A<:AppliedSchurGreenSolver{T}} = SchurGreenSlicer{Complex{T},A}(ω, solver) #region ## getproperty ## function Base.getproperty(s::SchurGreenSlicer, f::Symbol) if !isdefined(s, f) solver = s.solver d = size(s.L, 2) # Issue #268: the result of the following call!'s depends on the current value of h0 # which aliases the parent h. This is only a problem if `s` was obtained through # `gs = call!(g, ω; params...)`. In that case, doing call!(g, ω; params´...) before # gs[sites...] will be call!-ing e.g. solver.g∞ with the wrong h0 (the one from # params´...). However, if `gs = g(ω; params...)` a copy was made, so it is safe. if f == :G₋₁₋₁ s.G₋₁₋₁ = slicer(call!(solver.gL, s.ω; skipsolve_internal = true)) elseif f == :G₁₁ s.G₁₁ = slicer(call!(solver.gR, s.ω; skipsolve_internal = true)) elseif f == :G∞₀₀ s.G∞₀₀ = slicer(call!(solver.g∞, s.ω; skipsolve_internal = true)) elseif f == :L´G∞₀₀ tmp = solver.fsolver.tmp.LG s.L´G∞₀₀ = extended_rdiv!(tmp, s.L, s.G∞₀₀) elseif f == :R´G∞₀₀ tmp = solver.fsolver.tmp.RG s.R´G∞₀₀ = extended_rdiv!(tmp, s.R, s.G∞₀₀) elseif f == :G₁₁L tmp = solver.fsolver.tmp.GL s.G₁₁L = extended_ldiv!(tmp, s.G₁₁, s.L) elseif f == :G₋₁₋₁R tmp = solver.fsolver.tmp.GR s.G₋₁₋₁R = extended_ldiv!(tmp, s.G₋₁₋₁, s.R) elseif f == :R´G₁₁L tmp = similar(s.R, d, d) s.R´G₁₁L = mul!(tmp, s.R', s.G₁₁L) elseif f == :L´G₋₁₋₁R tmp = similar(s.L, d, d) s.L´G₋₁₋₁R = mul!(tmp, s.L', s.G₋₁₋₁R) else argerror("Unknown field $f for SchurGreenSlicer") end end return getfield(s, f) end # note that g.sourceC is taller than L, R, due to extended sites, but of >= witdth # size(L, 2) = size(R, 2) = min(l, r) = d (deflated surface) function extended_ldiv!(gL::Matrix{C}, g::SparseLUGreenSlicer, L) where {C} Lext = view(g.source64, :, axes(L, 2)) fill!(Lext, zero(C)) copyto!(Lext, CartesianIndices(L), L, CartesianIndices(L)) copy!(gL, view(ldiv!(g.fact, Lext), axes(L)...)) return gL end function extended_rdiv!(L´g::Matrix{C}, L, g::SparseLUGreenSlicer) where {C} Lext = view(g.source64, :, axes(L, 2)) fill!(Lext, zero(C)) copyto!(Lext, CartesianIndices(L), L, CartesianIndices(L)) copy!(L´g, view(ldiv!(g.fact', Lext), axes(L)...)') return L´g end #endregion #region ## API ## function Base.getindex(s::SchurGreenSlicer, i::CellOrbitals, j::CellOrbitals) G = isinf(s.boundary) ? inf_schur_slice(s, i, j) : semi_schur_slice(s, i, j) # for type-stability with SVector indices return maybe_SMatrix(G, orbindices(i), orbindices(j)) end function inf_schur_slice(s::SchurGreenSlicer, i::CellOrbitals, j::CellOrbitals) rows, cols = orbindices(i), orbindices(j) dist = only(cell(i) - cell(j)) if dist == 0 g = s.G∞₀₀ i´, j´ = CellOrbitals((), rows), CellOrbitals((), cols) return g[i´, j´] elseif dist >= 1 # G∞ₙₘ = G₁₁L (R'G₁₁L)ⁿ⁻ᵐ⁻¹ R'G∞₀₀ R´G∞₀₀ = view(s.R´G∞₀₀, :, cols) R´G₁₁L = s.R´G₁₁L G₁₁L = view(s.G₁₁L, rows, :) G = G₁₁L * (R´G₁₁L^(dist - 1)) * R´G∞₀₀ return G else # dist <= -1 # G∞ₙₘ = G₋₁₋₁R (L'G₋₁₋₁R)ᵐ⁻ⁿ⁻¹ L'G∞₀₀ L´G∞₀₀ = view(s.L´G∞₀₀, :, cols) L´G₋₁₋₁R = s.L´G₋₁₋₁R G₋₁₋₁R = view(s.G₋₁₋₁R, rows, :) G = G₋₁₋₁R * (L´G₋₁₋₁R^(- dist - 1)) * L´G∞₀₀ return G end end function semi_schur_slice(s::SchurGreenSlicer{C}, i, j) where {C} n = only(cell(i)) - Int(s.boundary) m = only(cell(j)) - Int(s.boundary) rows, cols = orbindices(i), orbindices(j) if n * m <= 0 # This includes inter-boundary # need to add view with specific index types for type stability return zeros(C, norbitals(i), norbitals(j)) elseif n == m == 1 g = s.G₁₁ i´, j´ = CellOrbitals((), rows), CellOrbitals((), cols) return g[i´, j´] elseif n == m == -1 g = s.G₋₁₋₁ i´, j´ = CellOrbitals((), rows), CellOrbitals((), cols) return g[i´, j´] elseif m >= 1 # also n >= 1 # Gₙₘ = G∞ₙₘ - G₁₁L(R'G₁₁L)ⁿ⁻¹ R'G∞₀ₘ i´ = CellOrbitals(n, rows) j´ = CellOrbitals(m, cols) G∞ₙₘ = inf_schur_slice(s, i´, j´) i´ = CellOrbitals(0, :) R´G∞₀ₘ = s.R' * inf_schur_slice(s, i´, j´) R´G₁₁L = s.R´G₁₁L G₁₁L = view(s.G₁₁L, rows, :) Gₙₘ = n == 1 ? mul!(G∞ₙₘ, G₁₁L, R´G∞₀ₘ, -1, 1) : mul!(G∞ₙₘ, G₁₁L, (R´G₁₁L^(n-1)) * R´G∞₀ₘ, -1, 1) return Gₙₘ else # m, n <= -1 # Gₙₘ = G∞ₙₘ - G₋₁₋₁R(L'G₋₁₋₁R)⁻ⁿ⁻¹L'G∞₀ₘ i´ = CellOrbitals(n, rows) j´ = CellOrbitals(m, cols) G∞ₙₘ = inf_schur_slice(s, i´, j´) i´ = CellOrbitals(0, :) L´G∞₀ₘ = s.L' * inf_schur_slice(s, i´, j´) L´G₋₁₋₁R = s.L´G₋₁₋₁R G₋₁₋₁R = view(s.G₋₁₋₁R, rows, :) Gₙₘ = n == -1 ? mul!(G∞ₙₘ, G₋₁₋₁R, L´G∞₀ₘ, -1, 1) : mul!(G∞ₙₘ, G₋₁₋₁R, (L´G₋₁₋₁R^(-n-1)) * L´G∞₀ₘ, -1, 1) return Gₙₘ end end maybe_SMatrix(G::Matrix, rows::SVector{L}, cols::SVector{L´}) where {L,L´} = SMatrix{L,L´}(G) maybe_SMatrix(G, rows, cols) = G # TODO: Perhaps too conservative function minimal_callsafe_copy(s::SchurGreenSlicer, parentham, parentcontacts) s´ = SchurGreenSlicer(s.ω, minimal_callsafe_copy(s.solver, parentham, parentcontacts)) isdefined(s, :G₋₁₋₁) && (s´.G₋₁₋₁ = minimal_callsafe_copy(s.G₋₁₋₁, parentham, parentcontacts)) isdefined(s, :G₁₁) && (s´.G₁₁ = minimal_callsafe_copy(s.G₁₁, parentham, parentcontacts)) isdefined(s, :G∞₀₀) && (s´.G∞₀₀ = minimal_callsafe_copy(s.G∞₀₀, parentham, parentcontacts)) isdefined(s, :L´G∞₀₀) && (s´.L´G∞₀₀ = copy(s.L´G∞₀₀)) isdefined(s, :R´G∞₀₀) && (s´.R´G∞₀₀ = copy(s.R´G∞₀₀)) isdefined(s, :G₁₁L) && (s´.G₁₁L = copy(s.G₁₁L)) isdefined(s, :G₋₁₋₁R) && (s´.G₋₁₋₁R = copy(s.G₋₁₋₁R)) isdefined(s, :R´G₁₁L) && (s´.R´G₁₁L = copy(s.R´G₁₁L)) isdefined(s, :L´G₋₁₋₁R) && (s´.L´G₋₁₋₁R = copy(s.L´G₋₁₋₁R)) return s´ end #endregion #endregion #endregion top
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
6636
############################################################################################ # SparseLU - for 0D AbstractHamiltonians # It doesn't use T-matrix for contacts. Instead it incorporates them into the LU factor- # ization, possibly using inverse-free self-energies (using extended sites). #region # invgreen aliases contacts (they are not implemented through a TMatrixSlicer) struct AppliedSparseLUGreenSolver{C} <: AppliedGreenSolver invgreen::InverseGreenBlockSparse{C} # aliases parent contacts end mutable struct SparseLUGreenSlicer{C} <:GreenSlicer{C} fact::SparseArrays.UMFPACK.UmfpackLU{ComplexF64,Int} # of full system plus extended orbs nonextrng::UnitRange{Int} # range of non-extended orbital indices unitcinds::Vector{Vector{Int}} # non-extended fact indices per contact unitcindsall::Vector{Int} # merged and uniqued unitcinds source64::Matrix{ComplexF64} # preallocation for ldiv! source @ contacts sourceC::Matrix{C} # alias of source64 or C conversion unitg::Matrix{C} # lazy storage of a full ldiv! solve of all (nonextrng) sites function SparseLUGreenSlicer{C}(fact, nonextrng, unitcinds, unitcindsall, source64) where {C} s = new() s.fact = fact # Note that there is no SparseArrays.UMFPACK.UmfpackLU{ComplexF32} s.nonextrng = nonextrng s.unitcinds = unitcinds s.unitcindsall = unitcindsall s.source64 = source64 s.sourceC = convert(Matrix{C}, source64) # note that unitg is not allocated here. It is allocated on first use. return s end end #region ## API ## inverse_green(s::AppliedSparseLUGreenSolver) = s.invgreen unitcellinds_contacts(s::SparseLUGreenSlicer) = s.unitcinds unitcellinds_contacts(s::SparseLUGreenSlicer, i::Integer) = 1 <= i <= length(s.unitcinds) ? s.unitcinds[i] : argerror("Cannot access contact $i, there are $(length(s.unitcinds)) contacts") unitcellinds_contacts_merged(s::SparseLUGreenSlicer) = s.unitcindsall function minimal_callsafe_copy(s::AppliedSparseLUGreenSolver, parentham, parentcontacts) invgreen´ = inverse_green(parentham, parentcontacts) return AppliedSparseLUGreenSolver(invgreen´) end #endregion #region ## apply ## function apply(::GS.SparseLU, h::AbstractHamiltonian0D, cs::Contacts) invgreen = inverse_green(h, cs) return AppliedSparseLUGreenSolver(invgreen) end apply(::GS.SparseLU, h::AbstractHamiltonian, cs::Contacts) = argerror("Can only use GreenSolvers.SparseLU with 0D AbstractHamiltonians") #endregion #region ## call ## # Σblocks and contactorbitals are not used here, because they are already inside invgreen function (s::AppliedSparseLUGreenSolver{C})(ω, Σblocks, contactorbitals) where {C} invgreen = s.invgreen nonextrng = orbrange(invgreen) unitcinds = invgreen.unitcinds unitcindsall = invgreen.unitcindsall source64 = convert(Matrix{ComplexF64}, s.invgreen.source) # the H0 and Σs inside invgreen have already been updated by the parent call!(g, ω; ...) update!(invgreen, ω) igmat = matrix(invgreen) fact = try lu(igmat) catch argerror("Encountered a singular G⁻¹(ω) at ω = $ω, cannot factorize") end so = SparseLUGreenSlicer{C}(fact, nonextrng, unitcinds, unitcindsall, source64) return so end #endregion #endregion ############################################################################################ # SparseLUGreenSlicer indexing #region function Base.view(s::SparseLUGreenSlicer, i::Integer, j::Integer) dstinds = unitcellinds_contacts(s, i) srcinds = unitcellinds_contacts(s, j) source64 = view(s.source64, :, 1:length(srcinds)) sourceC = view(s.sourceC, :, 1:length(srcinds)) return compute_or_retrieve_green(s, dstinds, srcinds, source64, sourceC) end Base.view(s::SparseLUGreenSlicer, ::Colon, ::Colon) = compute_or_retrieve_green(s, s.unitcindsall, s.unitcindsall, s.source64, s.sourceC) function Base.view(s::SparseLUGreenSlicer{C}, i::CellOrbitals, j::CellOrbitals) where {C} # we only preallocate if we actually need to call ldiv! below (empty unitg cache) must_call_ldiv! = !isdefined(s, :unitg) # need similar because s.source64 has only ncols = number of orbitals in contacts source64 = must_call_ldiv! ? similar_source64(s, j) : s.source64 # this will alias if C == ComplexF64 sourceC = must_call_ldiv! ? convert(Matrix{C}, source64) : s.sourceC v = compute_or_retrieve_green(s, orbindices(i), orbindices(j), source64, sourceC) return v end # Implements cache for full ldiv! solve (unitg) # source64 and sourceC are of size (total_orbs_including_extended, length(srcinds)) function compute_or_retrieve_green(s::SparseLUGreenSlicer{C}, dstinds, srcinds, source64, sourceC) where {C} if isdefined(s, :unitg) # we have already computed the full-cell slice g = view(s.unitg, dstinds, srcinds) else # we haven't, so we must do some work still fact = s.fact allinds = 1:size(fact, 1) # axes not defined on SparseArrays.UMFPACK.UmfpackLU one!(source64, srcinds) gext = ldiv!(fact, source64) sourceC === gext || copy!(sourceC, gext) # required when C != ComplexF64 # allinds may include extended orbs -> exclude them from the view dstinds´ = ifelse(dstinds === allinds, s.nonextrng, dstinds) srcinds´ = convert(typeof(srcinds), 1:length(srcinds)) g = view(sourceC, dstinds´, srcinds´) if srcinds == allinds s.unitg = copy(view(gext, s.nonextrng, s.nonextrng)) # exclude extended orbs end end return g end similar_source64(s::SparseLUGreenSlicer, ::CellOrbitals{<:Any,Colon}) = similar(s.source64, size(s.source64, 1), maximum(s.nonextrng)) similar_source64(s::SparseLUGreenSlicer, j::CellOrbitals) = similar(s.source64, size(s.source64, 1), norbitals(j)) # getindex must return a Matrix Base.getindex(s::SparseLUGreenSlicer, i::CellOrbitals, j::CellOrbitals) = copy(view(s, i, j)) # the lazy unitg field only aliases source64 or a copy of it. It is not necessary to # maintain the alias, as this is just a prealloc for a full-cell slice. We don't even need # to copy it, since once it is computed, it is never modified, only read function minimal_callsafe_copy(s::SparseLUGreenSlicer{C}, parentham, parentcontacts) where {C} s´ = SparseLUGreenSlicer{C}(s.fact, s.nonextrng, s.unitcinds, s.unitcindsall, copy(s.source64)) isdefined(s, :unitg) && (s´.unitg = s.unitg) return s´ end #endregion #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
3149
############################################################################################ # Spectrum - for 0D AbstractHamiltonians #region struct AppliedSpectrumGreenSolver{B,S<:Spectrum{<:Any,B}} <: AppliedGreenSolver spectrum::S end struct SpectrumGreenSlicer{C,B,S<:AppliedSpectrumGreenSolver{B}} <: GreenSlicer{C} ω::C solver::S end #region ## Constructor ## #end #region ## API ## spectrum(s::AppliedSpectrumGreenSolver) = s.spectrum # Parent ham needs to be non-parametric, so no need to alias minimal_callsafe_copy(s::AppliedSpectrumGreenSolver, parentham, parentcontacts) = AppliedSpectrumGreenSolver(s.spectrum) minimal_callsafe_copy(s::SpectrumGreenSlicer, parentham, parentcontacts) = SpectrumGreenSlicer(s.ω, s.solver) #endregion #region ## apply ## apply(s::GS.Spectrum, h::Hamiltonian{<:Any,<:Any,0}, ::Contacts) = AppliedSpectrumGreenSolver(spectrum(h; s.spectrumkw...)) apply(s::GS.Spectrum, h::ParametricHamiltonian, ::Contacts) = argerror("Cannot use GS.Spectrum with ParametricHamiltonian. Apply parameters with h(;params...) first.") apply(::GS.Spectrum, h::AbstractHamiltonian, ::Contacts) = argerror("Can only use Spectrum with bounded Hamiltonians") #endregion #region ## call ## function (s::AppliedSpectrumGreenSolver)(ω, Σblocks, corbitals) g0slicer = SpectrumGreenSlicer(complex(ω), s) gslicer = maybe_TMatrixSlicer(g0slicer, Σblocks, corbitals) return gslicer end #endregion #endregion ############################################################################################ # SpectrumGreenSlicer indexing # We don't implement view over contacts because that is taken care of by TMatrixSlicer #region function Base.getindex(s::SpectrumGreenSlicer{C}, i::CellOrbitals{0}, j::CellOrbitals{0}) where {C} oi, oj = orbindices(i), orbindices(j) es, psis = spectrum(s.solver) vi, vj = view(psis, oi, :), view(psis, oj, :) vj´ = vj' ./ (s.ω .- es) return vi * vj´ end #endregion ############################################################################################ # densitymatrix # specialized DensityMatrix method for GS.Spectrum #region struct DensityMatrixSpectrumSolver{T,R,C} es::Vector{Complex{T}} psirows::R psicols::C end ## Constructor function densitymatrix(s::AppliedSpectrumGreenSolver, gs::GreenSlice) # SpectrumGreenSlicer is 0D, so there is a single cellorbs in dict. # If rows/cols are contacts, we need their orbrows/orbcols (unlike for gs(ω; params...)) check_nodiag_axes(gs) i, j = only(cellsdict(orbrows(gs))), only(cellsdict(orbcols(gs))) oi, oj = orbindices(i), orbindices(j) es, psis = spectrum(s) solver = DensityMatrixSpectrumSolver(es, _maybe_view(psis, oi), _maybe_view(psis, oj)) return DensityMatrix(solver, gs) end ## API ## call function (d::DensityMatrixSpectrumSolver)(mu, kBT; params...) vi = d.psirows vj´ = d.psicols' .* fermi.(d.es .- mu, kBT) return vi * vj´ end # if the orbindices cover all the unit cell, use matrices instead of _maybe_view(m, oi) = length(oi) == size(m, 1) ? m : view(m, oi, :) #endregion #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
3476
############################################################################################ # SelfEnergy(h, gs::GreenSlice, model::AbstractModel; sites...) # A RegularSelfEnergy -> Σ(ω) = V' gs(ω) V, where V = model coupling from sites to slice #region struct SelfEnergyGenericSolver{C,G<:GreenSlice,S,S´,H<:AbstractHamiltonian} <: RegularSelfEnergySolver hcoupling::H V´::S´ # parent <- bath block view of call!_output(hcoupling) gslice::G # bath GreenSlice, allows gslice(ω) V::S # bath <- parent block view of call!_output(hcoupling) V´g::Matrix{C} # prealloc matrix Σ::Matrix{C} # prealloc matrix end #region ## Constructors ## # nparent is the number of sites in gs, to know how to split hcoupling into (parent, bath) blocks function SelfEnergyGenericSolver(gslice::GreenSlice, hcoupling::AbstractHamiltonian, nparent::Integer) lastflatparent = last(flatrange(hcoupling, nparent)) parentinds, bathinds = 1:lastflatparent, lastflatparent+1:flatsize(hcoupling) hmatrix = call!_output(hcoupling) V = SparseMatrixView(view(hmatrix, bathinds, parentinds)) V´ = SparseMatrixView(view(hmatrix, parentinds, bathinds)) return SelfEnergyGenericSolver(gslice, hcoupling, V´, V) end function SelfEnergyGenericSolver(gslice::GreenSlice{T}, hcoupling::AbstractHamiltonian, V´::SparseMatrixView, V::SparseMatrixView) where {T} V´g = Matrix{Complex{T}}(undef, size(V´, 1), size(V, 1)) Σ = Matrix{Complex{T}}(undef, size(V´, 1), size(V, 2)) return SelfEnergyGenericSolver(hcoupling, V´, gslice, V, V´g, Σ) end #endregion #region ## API ## function SelfEnergy(hparent::AbstractHamiltonian, gslice::GreenSlice, model::AbstractModel; transform = missing, sites...) rows(gslice) === cols(gslice) || argerror("To attach a Greenfunction with `attach(h, g[cols, rows], coupling; ...)`, we must have `cols == rows`") lsbath = orbrows(gslice) lat0bath = lattice0D(lsbath) transform === missing || transform!(lat0bath, transform) lsparent = contact_orbslice(hparent; sites...) lat0parent = lattice0D(lsparent) lat0 = combine(lat0parent, lat0bath) nparent, ntotal = nsites(lat0parent), nsites(lat0) # apply model to lat0 to get hcoupling interblockmodel = interblock(model, 1:nparent, nparent+1:ntotal) hcoupling = hamiltonian(lat0, interblockmodel; orbitals = vcat(norbitals(hparent), norbitals(gslice))) solver´ = SelfEnergyGenericSolver(gslice, hcoupling, nparent) return SelfEnergy(solver´, lsparent) end function call!(s::SelfEnergyGenericSolver, ω; params...) gω = call!(s.gslice, ω; params...) call!(s.hcoupling; params...) V = matrix(update!(s.V)) V´ = matrix(update!(s.V´)) mul!(s.V´g, V´, gω) Σω = mul!(s.Σ, s.V´g, V) return Σω end call!_output(s::SelfEnergyGenericSolver) = s.Σ function minimal_callsafe_copy(s::SelfEnergyGenericSolver) hcoupling´ = minimal_callsafe_copy(s.hcoupling) s´ = SelfEnergyGenericSolver( hcoupling´, minimal_callsafe_copy(s.V´, hcoupling´), minimal_callsafe_copy(s.gslice), minimal_callsafe_copy(s.V, hcoupling´), copy(s.V´g), copy(s.Σ)) return s´ end function selfenergy_plottables(s::SelfEnergyGenericSolver, ls::LatticeSlice) p1 = s.hcoupling p2 = ls return (p1, p2) end #endregion #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
2157
############################################################################################ # SelfEnergy(h, model::AbstractModel; sites...) # A SelfEnergy solver that implements an AbstractModel on a selection of sites #region struct SelfEnergyModelSolver{T,E,P<:ParametricHamiltonian{T,E,0}} <: RegularSelfEnergySolver ph::P # pham over lat0D lattice == parent latslice # pham has an extra parameter :ω_internal for the frequency parentinds::Vector{Int} # stores the orb index in parent latslice for each ph orbital end #region ## Constructor ## function SelfEnergyModelSolver(h::AbstractHamiltonian, model::AbstractModel, orbslice::OrbitalSliceGrouped) modelω = model_ω_to_param(model) # see models.jl - transforms ω into a ω_internal param siteinds = Int[] # this converts orbslice to a 0D Lattice lat0 # and fills siteinds::Vector{Int} with the site index for each lat0 site (i.e. for sites ordered by sublattices) lat0 = lattice0D(orbslice, siteinds) # this is a 0D ParametricHamiltonian to build the Σ(ω) as a view over flat(ph(; ...)) ph = hamiltonian(lat0, modelω; orbitals = norbitals(h)) # WARNING: type-unstable orbs # translation from orbitals in lat0 to orbslice indices # i.e. orbital index on orbslice for each orbital in lat0 (this is just a reordering!) parentinds = reordered_site_orbitals(siteinds, orbslice) return SelfEnergyModelSolver(ph, parentinds) end #endregion #region ## API ## function SelfEnergy(h::AbstractHamiltonian, model::AbstractModel; kw...) orbslice = contact_orbslice(h; kw...) solver = SelfEnergyModelSolver(h, model, orbslice) return SelfEnergy(solver, orbslice) end function call!(s::SelfEnergyModelSolver, ω; params...) m = call!(s.ph, (); ω_internal = ω, params...) rows = cols = s.parentinds return view(m, rows, cols) end call!_output(s::SelfEnergyModelSolver) = view(call!_output(s.ph), s.parentinds, s.parentinds) minimal_callsafe_copy(s::SelfEnergyModelSolver) = SelfEnergyModelSolver(minimal_callsafe_copy(s.ph), s.parentinds) #endregion #endregion top
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
792
############################################################################################ # Selfenergy(h, nothing; siteselection...) # Empty self energy at selectors #region struct SelfEnergyEmptySolver{C} <: RegularSelfEnergySolver emptymat::SparseMatrixCSC{C,Int} end function SelfEnergy(h::AbstractHamiltonian{T}, ::Nothing; kw...) where {T} orbslice = contact_orbslice(h; kw...) norbs = norbitals(orbslice) emptyΣ = spzeros(Complex{T}, norbs, norbs) solver = SelfEnergyEmptySolver(emptyΣ) return SelfEnergy(solver, orbslice) end call!(s::SelfEnergyEmptySolver, ω; params...) = s.emptymat call!_output(s::SelfEnergyEmptySolver) = s.emptymat has_selfenergy(::SelfEnergyEmptySolver) = false minimal_callsafe_copy(s::SelfEnergyEmptySolver) = s #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
13465
const GreenFunctionSchurEmptyLead{T,E} = GreenFunction{T,E,1,<:AppliedSchurGreenSolver,<:Any,<:EmptyContacts} const GreenFunctionSchurLead{T,E} = GreenFunction{T,E,1,<:AppliedSchurGreenSolver,<:Any,<:Any} ############################################################################################ # SelfEnergy(h, glead::GreenFunctionSchurEmptyLead; kw...) # Extended self energy solver for deflated ΣL or ΣR Schur factors of lead unitcell #region struct SelfEnergySchurSolver{T,B,V<:Union{Missing,Vector{Int}},H<:AbstractHamiltonian} <: ExtendedSelfEnergySolver fsolver::SchurFactorsSolver{T,B} hlead::H isleftside::Bool boundary::T leadtoparent::V # orbital index in parent for each orbital in open lead surface # so that Σlead[leadtoparent, leadtoparent] == Σparent end #region ## Constructors ## SelfEnergySchurSolver(fsolver::SchurFactorsSolver, hlead, side::Symbol, boundary, parentinds = missing) = SelfEnergySchurSolver(fsolver, hlead, isleftside(side), boundary, parentinds) function isleftside(side) if side == :L return true elseif side == :R return false else argerror("Unexpeced side = $side in SelfEnergySchurSolver. Only :L and :R are allowed.") end end #endregion #region ## API ## # This syntax checks that the selected sites of hparent match the L/R surface of the # semi-infinite lead (possibly by first transforming the lead lattice with `transform`) # and if so, builds the extended Self Energy directly, using the same intercell coupling of # the lead, but using the correct site order of hparent function SelfEnergy(hparent::AbstractHamiltonian, glead::GreenFunctionSchurEmptyLead; reverse = false, transform = missing, kw...) lsparent = contact_orbslice(hparent; kw...) schursolver = solver(glead) fsolver = schurfactorsolver(schursolver) boundary = schursolver.boundary isfinite(boundary) || argerror("The form attach(h, glead; sites...) assumes a semi-infinite lead, but got `boundary = Inf`") # we obtain latslice of open surface in gL/gR gunit = reverse ? schursolver.gL : schursolver.gR blocksizes(blockstructure(gunit)) == blocksizes(blockstructure(hparent)) || argerror("The orbital/sublattice structure of parent and lead Hamiltonians do not match. Maybe you meant to use `attach(h, g1D, coupling; sites...)`?") # This is a SelfEnergy for a lead unit cell with a SelfEnergySchurSolver Σlead = only(selfenergies(contacts(gunit))) lslead = orbslice(Σlead) # find lead site index in lslead for each site in lsparent leadsites, displacement = lead_siteind_foreach_parent_siteind(lsparent, lslead, transform) # convert lead site indices to lead orbital indices using lead's ContactOrbitals leadorbs = reordered_site_orbitals(leadsites, cellsdict(contactorbitals(gunit))) # translate glead unitcell by displacement, so it overlaps sel sites (modulo transform) hlead = copy_lattice(parent(glead)) # don't copy, since you would break === link to fsolver transform === missing || Quantica.transform!(hlead, transform) translate!(hlead, displacement) reverse && Base.reverse!(hlead) # only flips bravais vectors in place solver´ = SelfEnergySchurSolver(fsolver, hlead, reverse, boundary, leadorbs) return SelfEnergy(solver´, lsparent) end # find ordering of lslead sites that match lsparent sites, modulo a displacement function lead_siteind_foreach_parent_siteind(lsparent, lslead, transform) np, nl = nsites(lsparent), nsites(lslead) np == nl || argerror("The contact surface has $np sites, which doesn't match the $nl sites in the lead surface") sp = collect(sites(lsparent)) sl = collect(sites(lslead)) transform === missing || (sl .= transform.(sl)) displacement = mean(sp) - mean(sl) sl .+= Ref(displacement) tree = KDTree(sl) indslead, dists = nn(tree, sp) iszero(chop(maximum(dists))) && allunique(indslead) || argerror("The contact and lead surface sites have the same number of sites but do not match (modulo a displacement). Perhaps an error in the `attach` site selection? Otherwise consider using the `transform` keyword to specify an attachment transformation.") return indslead, displacement end # This solver produces two solutions (L/R) for the price of one. We can opt out of calling # it if we know it has already been called, so the solution is already in its call!_output function call!(s::SelfEnergySchurSolver, ω; skipsolve_internal = false, params...) fsolver = s.fsolver Rfactors, Lfactors = if skipsolve_internal call!_output(fsolver) else # first apply params to the lead Hamiltonian call!(s.hlead; params...) call!(fsolver, ω) end factors = maybe_match_parent(ifelse(s.isleftside, Lfactors, Rfactors), s.leadtoparent) return factors end call!_output(s::SelfEnergySchurSolver) = call!(s, missing; skipsolve_internal = true) maybe_match_parent((V, ig, V´), leadtoparent) = (view(V, leadtoparent, :), ig, view(V´, :, leadtoparent)) maybe_match_parent(factors, ::Missing) = factors function minimal_callsafe_copy(s::SelfEnergySchurSolver) hlead´ = minimal_callsafe_copy(s.hlead) fsolver´ = minimal_callsafe_copy(s.fsolver, hlead´) s´ = SelfEnergySchurSolver(fsolver´, hlead´, s.isleftside, s.boundary, s.leadtoparent) return s´ end function selfenergy_plottables(s::SelfEnergySchurSolver, ls::LatticeSlice) p1 = ftuple(s.hlead; selector = siteselector(cells = SA[1])) p2 = (ls, ) return p1, p2 end #endregion #endregion ############################################################################################ # SelfEnergy(h, glead, model::AbstractModel; kw...) # Depending on whether glead has zero contacts or not, it yields an Extended or Generic # self-energy. Model gives arbitrary couplings to parent Hamiltonian. # For the Extended self energy, is uses g⁻¹ = h0 + ExtendedSchurΣ (adds extended sites) # V and V´ are SparseMatrixView because they span only the coupled parent <-> unitcell # sites, but for Extended they need to be padded with zeros over the extended sites #region mutable struct SelfEnergyCouplingSchurSolver{C,G,H,S<:SparseMatrixView,S´<:SparseMatrixView} <: ExtendedSelfEnergySolver gunit::G hcoupling::H V´::S´ # aliases a view of hcoupling g⁻¹::InverseGreenBlockSparse{C} # aliases the one in solver(gunit)::AppliedSparseLUGreenSolver V::S # aliases a view of hcoupling end #region ## Constructors ## # This is similar to SelfEnergyGenericSolver in generic.jl, but <: ExtendedSelfEnergySolver # It relies on gunit having a AppliedSparseLUGreenSolver, so a sparse g⁻¹ can be extracted function SelfEnergyCouplingSchurSolver(gunit::GreenFunction{T}, hcoupling::AbstractHamiltonian{T}, nparent) where {T} hmatrix = call!_output(hcoupling) invgreen = inverse_green(solver(gunit)) # the solver is AppliedSparseLUGreenSolver lastflatparent = last(flatrange(hcoupling, nparent)) size(hmatrix, 1) == lastflatparent + length(orbrange(invgreen)) || internalerror("SelfEnergyCouplingSchurSolver builder: $(size(hmatrix, 1)) != $lastflatparent + $(length(orbrange(invgreen)))") parentrng, leadrng = 1:lastflatparent, lastflatparent+1:size(hmatrix, 1) sizeV = size(invgreen, 1), lastflatparent V = SparseMatrixView(view(hmatrix, leadrng, parentrng), sizeV) V´ = SparseMatrixView(view(hmatrix, parentrng, leadrng), reverse(sizeV)) return SelfEnergyCouplingSchurSolver(gunit, hcoupling, V´, invgreen, V) end #endregion #region ## API ## # With this syntax we attach the surface unit cell of the lead (left or right) to hparent # through the model coupling. The lead is transformed with `transform` to align it to # hparent. Then we apply the model to the 0D lattice of hparent's selected surface plus the # lead unit cell, and then build an extended self energy function SelfEnergy(hparent::AbstractHamiltonian, glead::GreenFunctionSchurLead, model::AbstractModel; reverse = false, transform = missing, kw...) schursolver = solver(glead) gunit = copy_lattice(reverse ? schursolver.gL : schursolver.gR) lat0lead = lattice(gunit) # lat0lead is the zero cell of parent(glead) hlead = copy_lattice(parent(glead)) # move hlead and lat0lead to the left or right of boundary (if boundary is finite) boundary = schursolver.boundary xunit = isfinite(boundary) ? boundary + ifelse(reverse, -1, 1) : zero(boundary) if !iszero(xunit) bm = bravais_matrix(hlead) translate!(hlead, bm * SA[xunit]) translate!(lat0lead, bm * SA[xunit]) end # apply transform if transform !== missing transform!(lat0lead, transform) transform!(hlead, transform) end # combine gunit and parent sites into lat0 lsparent = contact_orbslice(hparent; kw...) isempty(lsparent) && argerror("No sites selected in the parent lattice") lat0parent = lattice0D(lsparent) lat0 = combine(lat0parent, lat0lead) nparent, ntotal = nsites(lat0parent), nsites(lat0) # apply model to lat0 to get hcoupling interblockmodel = interblock(model, 1:nparent, nparent+1:ntotal) hcoupling = hamiltonian(lat0, interblockmodel; orbitals = vcat(norbitals(hparent), norbitals(hlead))) gslice = glead[cells = SA[xunit]] Σs = selfenergies(contacts(glead)) solver´ = extended_or_regular_solver(Σs, gslice, gunit, hcoupling, nparent) reverse && Base.reverse!(hlead) return SelfEnergy(solver´, lsparent) end # No contacts -> Extended solver extended_or_regular_solver(::Tuple{}, gslice, gunit, hcoupling, nparent) = SelfEnergyCouplingSchurSolver(gunit, hcoupling, nparent) # With contacts -> Regular Generic solver - see generic.jl extended_or_regular_solver(::Tuple, gslice, gunit, hcoupling, nparent) = SelfEnergyGenericSolver(gslice, hcoupling, nparent) function call!(s::SelfEnergyCouplingSchurSolver, ω; params...) call!(s.hcoupling; params...) call!(s.gunit, ω; params...) update!(s.V) update!(s.V´) return matrix(s.V´), matrix(s.g⁻¹), matrix(s.V) end call!_output(s::SelfEnergyCouplingSchurSolver) = matrix(s.V´), matrix(s.g⁻¹), matrix(s.V) function minimal_callsafe_copy(s::SelfEnergyCouplingSchurSolver) hcoupling´ = minimal_callsafe_copy(s.hcoupling) gunit´ = minimal_callsafe_copy(s.gunit) s´ = SelfEnergyCouplingSchurSolver(gunit´, hcoupling´, minimal_callsafe_copy(s.V´, hcoupling´), inverse_green(solver(gunit´)), # alias of the invgreen from the solver minimal_callsafe_copy(s.V, hcoupling´)) return s´ end function selfenergy_plottables(s::SelfEnergyCouplingSchurSolver, ls::LatticeSlice) p1 = ftuple(s.hcoupling; hide = :sites) p2 = hamiltonian(s.gunit) p3 = ls return (p1, p2, p3) end #endregion #endregion ############################################################################################ # SelfEnergy(h, glead::GreenFunctionSchurLead; kw...) # Regular (Generic) self energy, since Extended is not possible for lead with contacts # Otherwise equivalent to SelfEnergy(h, glead::GreenFunctionSchurEmptyLead; kw...) #region function SelfEnergy(hparent::AbstractHamiltonian, glead::GreenFunctionSchurLead; reverse = false, transform = missing, sites...) blocksizes(blockstructure(glead)) == blocksizes(blockstructure(hparent)) || argerror("The orbital/sublattice structure of parent and lead Hamiltonians do not match") # find boundary ± 1 schursolver = solver(glead) boundary = schursolver.boundary isfinite(boundary) || argerror("The form attach(h, glead; sites...) assumes a semi-infinite lead, but got `boundary = Inf`") xunit = boundary + ifelse(reverse, -1, 1) gslice = glead[cells = SA[xunit]] # lattice slices for parent and lead unit cell lsparent = contact_orbslice(hparent; sites...) # The above is currently broken when unitcell surface does not match full unit cell. Perhaps use some version of this: # Compute lslead as lead unicell surface: # gL and gR are unitcell GreenFunctions with ΣL and ΣR, but same ordering as gslice gunit = reverse ? schursolver.gL : schursolver.gR Σlead = only(selfenergies(contacts(gunit))) lslead = orbslice(Σlead) # find lead site index in lslead for each site in lsparent leadsites, displacement = lead_siteind_foreach_parent_siteind(lsparent, lslead, transform) displacement += bravais_matrix(hamiltonian(glead)) * SA[xunit] # convert lead site indices to lead orbital indices using lead's ContactOrbitals leadorbs = reordered_site_orbitals(leadsites, cellsdict(contactorbitals(glead))) # build V and V´ as a leadorbs reordering of inter-cell harmonics of hlead hlead = copy_lattice(hamiltonian(glead)) # careful, not parent, which could be a ParametricHamiltonian h₊₁, h₋₁ = hlead[SA[1]], hlead[SA[-1]] V = SparseMatrixView(view(h₊₁, :, leadorbs)) V´ = SparseMatrixView(view(h₋₁, leadorbs, :)) transform === missing || Quantica.transform!(hlead, transform) translate!(hlead, displacement) reverse && Base.reverse!(hlead) solver´ = SelfEnergyGenericSolver(gslice, hlead, V´, V) return SelfEnergy(solver´, lsparent) end #endregion
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
280
using Test using Quantica @testset "Quantica.jl" begin include("test_lattice.jl") include("test_hamiltonian.jl") include("test_bandstructure.jl") include("test_greenfunction.jl") include("test_show.jl") Sys.WORD_SIZE == 64 && include("test_plots.jl") end
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
6512
using Quantica: nsubbands, nvertices, nedges, nsimplices using Random @testset "basic bandstructures" begin h = LatticePresets.honeycomb() |> hamiltonian(hopping(-1)) b = bands(h, subdiv(-pi, pi, 13), subdiv(-pi, pi, 13), showprogress = false) @test nsubbands(b) == 1 h = LatticePresets.honeycomb() |> hamiltonian(hopping(-1)) |> supercell(2) b = bands(h, 0.99 * subdiv(-pi, pi, 13), 0.99 * subdiv(-pi, pi, 13), showprogress = false) @test nsubbands(b) == 3 h = LatticePresets.honeycomb() |> hamiltonian(onsite(0.5, sublats = :A) + onsite(-0.5, sublats = :B) + hopping(-1, range = 1/√3)) b = h |> bands(subdiv(-pi, pi, 13), subdiv(-pi, pi, 15), showprogress = false) @test nsubbands(b) == 2 h = LatticePresets.cubic() |> hamiltonian(hopping((r,dr)-> im*dr'SA[1,1.5,2])) |> supercell(2) b = bands(h, subdiv(-pi, pi, 5), subdiv(-pi, pi, 7), subdiv(-pi, pi, 5), showprogress = false) @test nsubbands(b) == 1 b = bands(h, subdiv(0, 1, 4), mapping = (:Γ, :X), showprogress = false) @test nsubbands(b) == 1 b = bands(h, subdiv(0, 4, 13), mapping = (:Γ, :X, (0, π), :Z, :Γ), showprogress = false) @test nsubbands(b) == 1 @test nvertices(b) == 32 b = bands(h, subdiv(1:5, (4,5,6,7)), mapping = [1,2,3,5,4] => (:Γ, :X, (0, π), :Z, :Γ), showprogress = false) @test nsubbands(b) == 1 @test nvertices(b) == 42 b = bands(h, subdiv((1,3,4), 5), mapping = (1,4,3) => (:Γ, :X, :Z), showprogress = false) @test nsubbands(b) == 1 @test nvertices(b) == 23 # complex spectra h = LatticePresets.honeycomb() |> hamiltonian(onsite(im) + hopping(-1)) |> supercell(2) b = bands(h, subdiv(-pi, pi, 13), subdiv(-pi,pi, 13), showprogress = false) @test nsubbands(b) == 1 # spectrum sorting h = LatticePresets.honeycomb() |> hamiltonian(hopping(-1)) |> supercell(10) b = bands(h, subdiv(0, 1, 7); solver = ES.Arpack(sigma = 0.1im, nev = 12), mapping = (:K, :K´), showprogress = false) @test nsubbands(b) == 1 # defect insertion and patching h = LatticePresets.honeycomb() |> hamiltonian(hopping(-1)) b = bands(h, subdiv(0, 2pi, 8), subdiv(0, 2pi, 8); showprogress = false, defects = ((2pi/3, 4pi/3), (4pi/3, 2pi/3)), patches = 10) @test nvertices(b) == 140 end @testset "functional bandstructures" begin hc = LatticePresets.honeycomb() |> hamiltonian(hopping(-1, sublats = :A=>:B) |> plusadjoint) |> supercell(3) hf1((x,)) = Matrix(Quantica.call!(hc, (x, -x))) m = subdiv(0, 1, 4) b = bands(hf1, m, showprogress = false, mapping = x -> 2π * x) @test nsubbands(b) == 1 @test nsimplices(b) == 36 # teting thread safety - we should fall back to a single thread for hf2::Function hf2((x,)) = Quantica.call!(hc, (x, -x)) m = subdiv(0,2π,40) Random.seed!(1) # to have ArnoldiMethod be deterministic b = bands(hf2, m, showprogress = false, solver = ES.ArnoldiMethod(nev = 18)) @test nsubbands(b) <= 2 # there is a random, platform-dependent component to this hp2 = LatticePresets.honeycomb() |> hamiltonian(hopping(-1), @hopping!((t; s) -> s*t)) hf3((s, x)) = Matrix(Quantica.call!(hp2, (x, x); s)) m = subdiv(0, pi, 13) b = bands(hf3, m, m, showprogress = false) @test nsubbands(b) == 1 @test nsimplices(b) == 288 * 2 b = bands(hf3, m, m, showprogress = false, transform = ω -> ω^2) # degeneracies doubled @test nsubbands(b) == 1 @test nsimplices(b) == 288 end @testset "parametric bandstructures" begin ph = LatticePresets.linear() |> hamiltonian(onsite(0I) + hopping(-I), orbitals = Val(2)) |> supercell(2) |> hamiltonian(@onsite!((o; k) -> o + k*I), @hopping!((t; k = 2, p = [1,2])-> t - k*I .+ p'p)) mesh2D = subdiv(0, 1, 15), subdiv(0, 2π, 15) b = bands(ph, mesh2D..., mapping = (x, k) -> ftuple(x; k = k), showprogress = false) @test nsubbands(b) == 4 b = bands(ph, mesh2D..., mapping = (k, φ) -> ftuple(1; k = k, p = SA[1, φ]), showprogress = false) @test nsubbands(b) == 1 ph = LatticePresets.linear() |> hamiltonian(onsite(0I) + hopping(-I), orbitals = Val(2)) |> supercell(2) |> supercell |> hamiltonian(@onsite!((o; k) -> o + k*I), @hopping!((t; k = 2, p = [1,2])-> t - k*I .+ p'p)) b = bands(ph, mesh2D..., mapping = (k, φ) -> ftuple(; k = k, p = SA[1, φ]), showprogress = false) @test nsubbands(b) == 1 # multithreading loop does not throw error b = bands(ph, mesh2D..., mapping = (k, φ) -> ftuple(; k, p = SA[1, φ]), showprogress = false) @test nsubbands(b) == 1 end @testset "spectrum" begin h = LatticePresets.honeycomb() |> hamiltonian(onsite(2I) + hopping(I, range = 1), orbitals = (Val(2), Val(1))) |> supercell(2) |> supercell for solver in (ES.LinearAlgebra(), ES.Arpack(), ES.KrylovKit(), ES.ArnoldiMethod(), ES.ShiftInvert(ES.ArnoldiMethod(), 0.4)) sp = spectrum(h; solver) e1, s1 = sp e2, s2 = first(sp), last(sp) e3, s3 = energies(sp), states(sp) @test e1 === e2 === e3 @test s1 === s2 === s3 @test Tuple(sp) === (e1, s1) for sp´ in (sp[[3,5]], sp[1:2], sp[[2,3], around = 0]) @test length(sp´[1]) == 2 @test size(sp´[2]) == (Quantica.flatsize(h), 2) end @test sp[around = 0] isa Tuple @test sp[2, around = 0] isa Tuple @test sp[[2,3,4], around = 0] == sp[2:4, around = 0] @test sp[[2,3,4], around = 0] !== sp[2:4, around = 0] @test sp[[2,4,3], around = -Inf][2] == hcat(sp[2][2], sp[4][2], sp[3][2]) end end @testset "bandstructures/spectrum slices" begin h = LatticePresets.honeycomb() |> hamiltonian(hopping(-1, range = 1/√3)) |> supercell(4) b = bands(h, subdiv(0, 2pi, 13), subdiv(0, 2pi, 15), showprogress = false) @test b[(:, pi)] isa Vector{Quantica.Subband{Float64,2}} @test length(b[(pi,)]) == length(b[(pi, :)]) == length(b[(pi, :, :)]) == 1 @test b[1] isa Quantica.Subband @test b[[1,end]] isa Vector{<:Quantica.Subband} m = Quantica.slice(b, (:,1)) @test only(m) isa Quantica.Mesh m = Quantica.slice(b[1], (:,1)) @test m isa Quantica.Mesh s = spectrum(b, (pi, pi)) s´ = spectrum(torus(h, (pi, pi))) s´´ = spectrum(h, (pi, pi)) ϵs, ψs = ES.LinearAlgebra()(Matrix(h((pi, pi)))) @test s isa Quantica.Spectrum @test Tuple(s) == Tuple(s´) == Tuple(s´´) == (ϵs, ψs) @test s[1:10, around = 0] == s´[1:10, around = 0] == s´´[1:10, around = 0] end
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
21369
using Quantica: GreenFunction, GreenSlice, GreenSolution, zerocell, CellOrbitals, ncontacts, solver function testgreen(h, s; kw...) ω = 0.2 g = greenfunction(h, s) @test g isa GreenFunction gω = g(ω; kw...) @test gω isa GreenSolution @test g(0) isa GreenSolution # promote Int to AbstractFloat to add eps L = Quantica.latdim(lattice(h)) z = zero(SVector{L,Int}) o = Quantica.unitvector(1, SVector{L,Int}) conts = ntuple(identity, ncontacts(h)) locs = (sites(z, :), sites(z, 2), sites(1:2), sites(o, (1,2)), CellOrbitals(o, 1), CellOrbitals(z, 1:2), CellOrbitals(z, SA[2,1]), conts...) for loc in locs, loc´ in locs gs = g[loc, loc´] @test gs isa GreenSlice gsω = gs(ω; kw...) gωs = gω[loc, loc´] @test gsω == gωs loc === loc´ && @test all(x->imag(x)<=0, diag(gωs)) end return nothing end @testset "basic greenfunctions" begin h0 = LP.honeycomb() |> hamiltonian(hopping(SA[0 1; 1 0]), orbitals = 2) |> supercell(region = RP.circle(10)) s0 = GS.SparseLU() s0´ = GS.Spectrum() h1 = LP.square() |> hamiltonian(@onsite((; o = 1) -> o*I) + hopping(SA[0 1; 1 0]), orbitals = 2) |> supercell((1,0), region = r -> abs(r[2]) < 2) s1 = GS.Schur() s1´ = GS.Schur(boundary = -1) for (h, s) in zip((h0, h0, h1, h1), (s0, s0´, s1, s1´)) testgreen(h, s; o = 2) end # This ensures that flat_sync! is called with multiorbitals when call!-ing ph upon calling g g = LP.square() |> hamiltonian(@onsite(()->I), orbitals = 2) |> supercell |> greenfunction @test g[](0.0 + 0im) ≈ SA[-1 0; 0 -1] g = LP.linear() |> hopping(0) + @onsite((;ω=0) -> ω)|> greenfunction; @test only(g[sites(SA[1],1)](1.0; ω = 0)) ≈ 1.0 atol = 0.000001 @test only(g[sites(SA[1],1)](1.0; ω = -1)) ≈ 0.5 atol = 0.000001 end @testset "greenfunction with contacts" begin g = LP.linear() |> hamiltonian(hopping(I), orbitals = 2) |> attach(@onsite(ω->im*I), cells = 1) |> attach(@onsite(ω->im*I), cells = 4) |> greenfunction @test size(g[(; cells = 2), (; cells = 3)](0.2)) == (2,2) h0 = LP.square() |> hamiltonian(hopping(SA[0 1; 1 0]), orbitals = 2) |> supercell(region = RP.circle(10)) s0 = GS.SparseLU() s0´ = GS.Spectrum() h1 = LP.square() |> hamiltonian(@onsite((; o = 1) -> o*I) + hopping(SA[0 1; 1 0]), orbitals = 2) |> supercell((1,0), region = r -> abs(r[2]) < 2) s1 = GS.Schur() s1´ = GS.Schur(boundary = -1) sites´ = (; region = r -> abs(r[2]) < 2 && r[1] == 0) # non-hermitian Σ model mod = @onsite((ω, r; o = 1) -> (o - im*ω)*I) + @onsite((ω, s; o = 1, b = 2) --> o*b*pos(s)[1]*I) + plusadjoint(@onsite((ω; p=1)-> p*I) + @hopping((ω, r, dr; t = 1) -> im*dr[1]*t*I; range = 1)) g0, g0´, g1´ = greenfunction(h0, s0), greenfunction(h0, s0´), greenfunction(h1, s1´) for (h, s) in zip((h0, h0, h1, h1), (s0, s0´, s1, s1´)) oh = h |> attach(nothing; sites´...) testgreen(oh, s) oh = h |> attach(mod; sites´...) testgreen(oh, s) for glead in (g0, g0´, g1´) oh = h |> attach(glead[sites´], hopping(I; range = (1,2)); sites´...) testgreen(oh, s) L´ = Quantica.latdim(lattice(parent(glead))) iszero(L´) && continue oh = h |> attach(glead; sites´...) testgreen(oh, s) oh = h |> attach(glead, hopping(I; range = (1,2)); sites´...) testgreen(oh, s) end end # SparseLU and Spectrum are equivalent @test g0[(; region = RP.circle(2)), (; region = RP.circle(3))](0.2) ≈ g0´[(; region = RP.circle(2)), (; region = RP.circle(3))](0.2) # contacts that don't include all sublattices h = lattice(sublat(0, name = :L), sublat(1, name = :R)) |> hamiltonian @test h |> attach(onsite(ω->1), sublats = :L) |> greenfunction isa GreenFunction # multiple contacts h0 = LP.square(type = Float32) |> hopping(1) hc = h0 |> supercell(region = RP.rectangle((2, 2))) glead = h0 |> supercell((1,0), region = r -> -1 <= r[2] <= 1) |> attach(nothing; cells = SA[1]) |> greenfunction(GS.Schur(boundary = 0)); g = hc |> attach(glead, region = r -> r[1] == 1) |> attach(glead, region = r -> r[1] == -1, reverse = true) |> attach(onsite(ω->1), region = r -> r == SA[0,0]) |> greenfunction @test Quantica.ncontacts(g) == 3 # 1D leads with contacts glead = LP.honeycomb() |> hopping(1) |> supercell((1,-1), region = r -> 0<=r[2]<=5) |> attach(nothing, cells = SA[5]) |> greenfunction(GS.Schur(boundary = 0)); g = LP.honeycomb() |> hopping(1) |> supercell(region = r -> -6<=r[1]<=6 && 0<=r[2]<=5) |> attach(glead, region = r -> r[1] > 5.1) |> greenfunction @test g isa GreenFunction # attach(gslice, model; transform) Rot = r -> SA[0 -1; 1 0] * r glead = LP.square(a0 = 1, dim = 2) |> onsite(4) - hopping(1) |> supercell((1,0), region = r -> -1 <= r[2] <= 1) |> greenfunction(GS.Schur(boundary = 0)); central = LP.honeycomb() |> onsite(4) - hopping(1) |> supercell(region = RP.rectangle((3,3))) |> transform(Rot) g = central |> attach(glead[cells = 1], -hopping(1), region = r -> r[1] > 1.3 && -1.1 <= r[2] <= 1.1, transform = r -> r + SA[1.2,0]) |> greenfunction @test g isa GreenFunction @test_throws ArgumentError central |> attach(glead[cells = 1], -hopping(1), region = r -> r[1] > 2.3 && -1.1 <= r[2] <= 1.1, transform = r -> r + SA[1.2,0]) # cheap views g = LP.linear() |> hopping(1) |> attach(@onsite((ω; p = 1) -> p), cells = 1) |> attach(@onsite((ω; p = 1) -> p), cells = 3) |> greenfunction gs = g(0.2) @test view(gs, 1, 2) isa SubArray @test (@allocations view(gs, 1, 2)) <= 2 # should be 1, but in some platforms/versions it could be 2 end @testset "GreenFunction partial evaluation" begin g = LP.linear() |> hamiltonian(@hopping((; q = 1) -> q*I), orbitals = 2) |> attach(@onsite((ω; p = 0) ->p*SA[0 1; 1 0]), cells = 1) |> greenfunction g´ = g(p = 2) h´, h = hamiltonian(g´), hamiltonian(g) @test h´ !== h @test h´ == h(p = 2) @test g(0.2, p = 2)[] == g´(0.2)[] @test g(0.2, p = 1)[] != g´(0.2, p = 1)[] # p = 1 is ignored by g´, fixed to p = 2 @test solver(g) !== solver(parent(solver(g´))) # no aliasing gs = g[] gs´ = gs(p = 2) @test gs´ isa GreenSlice @test gs´(0.3) == gs(0.3, p = 2) @test gs´(0.3, p = 1) != gs(0.3, p = 1) end @testset "GreenSolvers applicability" begin h = HP.graphene() @test_throws ArgumentError greenfunction(h, GS.Schur()) @test_throws ArgumentError greenfunction(h, GS.KPM()) @test_throws ArgumentError greenfunction(h, GS.SparseLU()) @test_throws ArgumentError greenfunction(h, GS.Spectrum()) h = supercell(h) @test_throws ArgumentError greenfunction(h, GS.Schur()) @test_throws ArgumentError greenfunction(h, GS.Bands()) h = LP.honeycomb() |> @onsite((; o = 1) -> o*I) |> supercell @test_throws ArgumentError greenfunction(h, GS.Spectrum()) @test greenfunction(h(), GS.Spectrum()) isa GreenFunction end @testset "greenfunction KPM" begin g = HP.graphene(a0 = 1, t0 = 1, orbitals = (2,1)) |> supercell(region = RP.circle(20)) |> attach(nothing, region = RP.circle(1)) |> greenfunction(GS.KPM(order = 300, bandrange = (-3.1, 3.1))) ρs = ldos(g[1], kernel = missing) for ω in -3:0.1:3 @test all(>=(0), ρs(ω)) end ω = -0.1 gωs = g[1](ω) ρflat = -imag.(diag(gωs))/pi @test all(>(0), ρflat) ρs = ldos(g[1], kernel = missing) ρ = ρs(ω) @test sum(ρ) ≈ sum(ρflat) @test (length(ρflat), length(ρ)) == (9, 9) ω = -0.1 gωs = g[1](ω) ρflat = -imag.(diag(gωs))/pi @test all(>(0), ρflat) ρs = ldos(g[1], kernel = I) ρ = ρs(ω) @test ρ isa OrbitalSliceVector @test sum(ρ) ≈ sum(ρflat) @test (length(ρflat), length(ρ)) == (9, 6) g = HP.graphene(a0 = 1, t0 = 1, orbitals = (2,1)) |> supercell(region = RP.circle(20)) |> attach(nothing, region = RP.circle(1)) |> greenfunction(GS.KPM(order = 500)) gωs = g[1](ω) ρflat´ = -imag.(diag(gωs))/pi ρ´ = ldos(g[1])(ω) @test all(<(0.01), abs.(ρ .- ρ´)) @test all(<(0.01), abs.(ρflat .- ρflat´)) @test_throws ArgumentError g[sites((), 3:4)](ω) @test g[:](ω) == g[1](ω) == g(ω)[1] == g(ω)[:] g´ = HP.graphene(a0 = 1, t0 = 1, orbitals = (2,1)) |> supercell(region = RP.circle(20)) |> attach(g[1], hopping((r, dr) -> I, range = 1), region = RP.circle(1)) |> attach(nothing, region = RP.circle(1, (2,2))) |> greenfunction(GS.KPM(order = 500)) ρs = ldos(g´[1]) for ω in -3:0.1:3 @test all(>=(0), ρs(ω)) end h = HP.graphene(a0 = 1) |> supercell(region = RP.circle(20)) hmat = h[()] g = h |> attach(nothing, region = RP.circle(1)) |> greenfunction(GS.KPM(order = 500, kernel = hmat)) ρs = ldos(g[1]) for ω in subdiv(-3, 3, 20) @test all(x -> sign(x) == sign(ω), ρs(ω)) end end @testset "greenfunction bands" begin h = HP.graphene(a0 = 1, t0 = 1, orbitals = (2,1)) ga = h |> attach(nothing, cells = 1) |> greenfunction() gb = h |> attach(nothing, cells = 1) |> greenfunction(GS.Bands(boundary = 2 => -3)) for g in (ga, gb) @test Quantica.solver(g) isa Quantica.AppliedBandsGreenSolver @test bands(g) isa Quantica.Subband g1 = g[1](0.2) @test size(g1) == (3,3) @test abs(g1[2,2] - 1/0.2) < 0.02 @test all(x -> Quantica.chop(imag(x)) ≈ 0, g1[2,:]) @test all(x -> Quantica.chop(imag(x)) ≈ 0, g1[:,2]) g2 = g[sites((0,0),:), sites((1,1),2)](0.2) @test size(g2) == (3,1) end ha = LP.honeycomb() |> hopping(1) |> supercell((1,-1), region = r -> abs(r[2])<2) hb = LP.honeycomb() |> hopping(1, range = 1) |> supercell((1,-1), region = r -> abs(r[2])<2) hc = LP.honeycomb() |> hamiltonian(hopping(I, range = 1), orbitals = (2,1)) |> supercell((3,-3), region = r -> abs(r[2])<2) hd = LP.square() |> hopping(1) |> supercell((1,0), region = r -> abs(r[2])<2) for h in (ha, hb, hc, hd) gc = h |> attach(nothing, cells = 3) |> greenfunction(GS.Bands(subdiv(-π, π, 89))) gd = h |> attach(nothing, cells = 3) |> greenfunction(GS.Schur()) @test maximum(abs.(gc[cells = 1](0.5) - gd[cells = 1](0.5))) < 0.08 @test all(>=(0), ldos(gc[1])(0.2)) @test all(>=(0), ldos(gc[region = RP.circle(2)])(0.2)) gc = h |> attach(nothing, cells = 3) |> greenfunction(GS.Bands(subdiv(-π, π, 89), boundary = 1 => 0)) gd = h |> attach(nothing, cells = 3) |> greenfunction(GS.Schur(boundary = 0)) @test maximum(abs.(gc[cells = 1](0.5) - gd[cells = 1](0.5))) < 0.08 @test all(>=(0), ldos(gc[1])(0.2)) @test all(>=(0), ldos(gc[region = RP.circle(2)])(0.2)) end # Issue #252 g = LP.honeycomb() |> hopping(1, range = 3) |> supercell((1,-1), (1,1)) |> attach(nothing, region = RP.circle(1, SA[2,3])) |> attach(nothing, region = RP.circle(1, SA[3,-3])) |> greenfunction(GS.Bands(subdiv(-π, π, 13), subdiv(-π, π, 13), boundary = 2=>-3)) @test g isa GreenFunction @test iszero(g[cells = SA[1,-3]](0.2)) # Issue #257 h = LP.square() |> hopping(-1) ϕs = subdiv(0, 0.6π, 2) b = bands(h, ϕs, ϕs, showprogress = false) g = h |> attach(@onsite(ω->-im), cells = SA[20,0]) |> greenfunction(GS.Bands(ϕs, ϕs)) @test g(-1)[sites(SA[1,-1], 1), sites(1)] isa AbstractMatrix end @testset "greenfunction 32bit" begin # GS.Bands # skip for older versions due to https://github.com/JuliaLang/julia/issues/53054 # which makes solve not deterministic when adding sufficiently many band simplices if VERSION >= v"1.11.0-DEV.632" h = HP.graphene(type = Float32) s = GS.Bands() testgreen(h, s) end h = HP.graphene(type = Float32, a0 = 1) |> supercell(10) |> supercell s = GS.SparseLU() testgreen(h, s) # GS.Schur h = HP.graphene(type = Float32, a0 = 1) |> supercell((1,-1), region = r -> 0<=r[2]<=3) s = GS.Schur() testgreen(h, s) s = GS.Schur(boundary = -1) testgreen(h, s) # GS.KPM g = HP.graphene(a0 = 1, t0 = 1, orbitals = (2,1), type = Float32) |> supercell(region = RP.circle(20)) |> attach(nothing, region = RP.circle(1)) |> greenfunction(GS.KPM(order = 300, bandrange = (-3.1, 3.1))) ρs = ldos(g[1], kernel = missing) for ω in -3:0.1:3 @test all(>=(0), ρs(ω)) end end @testset "diagonal slicing" begin g = HP.graphene(a0 = 1, t0 = 1, orbitals = (2,1)) |> supercell((2,-2), region = r -> 0<=r[2]<=5) |> attach(nothing, cells = 2, region = r -> 0<=r[2]<=2) |> attach(nothing, cells = 3) |> greenfunction(GS.Schur(boundary = -2)) ω = 0.6 @test g[diagonal(2)](ω) isa OrbitalSliceVector @test g[diagonal(2)](ω) == g(ω)[diagonal(2)] @test size(g[diagonal(1)](ω)) == (12,) @test size(g[diagonal(1, kernel = I)](ω)) == (8,) @test length(g[diagonal(:)](ω)) == length(g[diagonal(1)](ω)) + length(g[diagonal(2)](ω)) == 48 @test length(g[diagonal(:, kernel = I)](ω)) == length(g[diagonal(1, kernel = I)](ω)) + length(g[diagonal(2, kernel = I)](ω)) == 32 @test length(g[diagonal(cells = 2:3)](ω)) == 72 @test length(g[diagonal(cells = 2:3, kernel = I)](ω)) == 48 @test ldos(g[1])(ω) ≈ -imag.(g[diagonal(1; kernel = I)](ω)) ./ π end @testset "OrbitalSliceArray slicing" begin g = LP.linear() |> hopping(1) + onsite(1) |> supercell(4) |> greenfunction gmat = g[cells = SA[2]](0.2) @test gmat isa Quantica.OrbitalSliceMatrix @test size(gmat) == (4, 4) gmat´ = gmat[cells = SA[1]] @test gmat´ isa Quantica.OrbitalSliceMatrix @test isempty(gmat´) gmat = g[(; cells = SA[2]), sites(SA[1], 1:2)](0.2) @test gmat isa Matrix @test size(gmat) == (4, 2) gmat = g[(; cells = SA[1]), (; region = r -> 3<=r[1]<=5)](0.2) @test gmat isa Quantica.OrbitalSliceMatrix @test size(gmat) == (4, 3) gmat´ = gmat[(; cells = SA[1]), (; cells = SA[0])] @test gmat´ isa Quantica.OrbitalSliceMatrix @test size(gmat´) == (4, 1) gmat´ = gmat[(; cells = SA[1])] @test gmat´ isa Quantica.OrbitalSliceMatrix @test size(gmat´) == (4, 2) @test_throws Quantica.Dictionaries.IndexError gmat[sites(SA[1],:)] # `:` means all sites in cell gmat´ = gmat[sites(SA[1], 1:2)] @test gmat´ isa Matrix @test size(gmat´) == (2, 2) c = sites(SA[1], 1) view(gmat, c) @test (@allocations view(gmat, c)) <= 2 end function testcond(g0; nambu = false) G1 = conductance(g0[1]; nambu) G2 = conductance(g0[2]; nambu) G12 = conductance(g0[1,2]; nambu) T12 = transmission(g0[1,2]) @test_throws ArgumentError transmission(g0[1]) @test_throws ArgumentError transmission(g0[1, 1]) for ω in -3:0.1:3 ωc = ω + im*1e-10 @test ifelse(nambu, 6.000001, 3.00000001) >= G1(ωc) >= 0 @test G1(ωc) ≈ G1(-ωc) ≈ G2(ωc) ≈ G2(-ωc) @test T12(ωc) ≈ T12(-ωc) nambu || @test G1(ωc) ≈ T12(ωc) atol = 0.000001 @test G12(ωc) ≈ G12(-ωc) atol = 0.000001 nambu || @test G1(ωc) ≈ -G12(ωc) atol = 0.000001 end end function testjosephson(g0) J1 = josephson(g0[1], 4; phases = subdiv(0, pi, 10)) J2 = josephson(g0[2], 4; phases = subdiv(0, pi, 10)) @test all(>=(0), Quantica.chop.(J1())) @test all(((j1, j2) -> ≈(j1, j2, atol = 0.000001)).(J1(), J2())) end @testset "greenfunction observables" begin # single-orbital vs two-orbital g1 = LP.square() |> supercell((1,0), region = r->-2<r[2]<2) |> hamiltonian(@hopping((r, dr; B = 0.1) -> I * cis(B * dr' * SA[r[2],-r[1]])), orbitals = 1) |> greenfunction(GS.Schur(boundary = 0)); g2 = LP.square() |> supercell((1,0), region = r->-2<r[2]<2) |> hamiltonian(@hopping((r, dr; B = 0.1) -> I * cis(B * dr' * SA[r[2],-r[1]])), orbitals = 2) |> greenfunction(GS.Schur(boundary = 0)); J1 = current(g1[cells = SA[1]]) J2 = current(g2[cells = SA[1]]) @test size(J1(0.2)) == size(J2(0.2)) == (3, 3) @test 2*J1(0.2; B = 0.1) ≈ J2(0.2; B = 0.1) ρ = densitymatrix(g1[cells = SA[1]], 5) @test all(≈(0.5), diag(ρ(0, 0; B=0.3))) # half filling ρ = densitymatrix(g1[cells = SA[1]], 7) @test all(<(0.96), real(diag(ρ(4, 1; B=0.1)))) # thermal depletion h = LP.honeycomb() |> hopping(1) |> supercell(region = RP.circle(10)) reg = (; region = RP.circle(0.5)) gLU = h |> greenfunction(GS.SparseLU()); gSpectrum = h |> greenfunction(GS.Spectrum()); gKPM = h |> attach(nothing; reg...) |> greenfunction(GS.KPM(order = 100000, bandrange = (-3,3))); ρ1, ρ2, ρ3 = densitymatrix(gLU[reg], (-3,3)), densitymatrix(gSpectrum[reg]), densitymatrix(gKPM[1]) @test ρ1() ≈ ρ2() atol = 0.00001 @test ρ2() ≈ ρ3() atol = 0.00001 gLU´ = h |> attach(nothing; reg...) |> greenfunction(GS.SparseLU()); ρ1´ = densitymatrix(gLU´[1], (-3, 3)) @test ρ1() ≈ ρ1´() gSpectrum´ = h |> attach(nothing; reg...) |> greenfunction(GS.Spectrum()); ρ2´ = densitymatrix(gSpectrum´[1]) @test ρ2() ≈ ρ2´() ρ = densitymatrix(g2[(; cells = SA[0]), (; cells = SA[1])], 5) ρ0 = ρ(0, 0; B=0.3) @test ρ0 isa OrbitalSliceMatrix @test iszero(ρ0) # rows are on boundary @test ρ0[sites(1), sites(SA[1], 1)] isa Matrix @test size(view(ρ0, sites(1), sites(SA[1], 1))) == (2, 2) # Diagonal slicing not yet supported @test_broken densitymatrix(g1[diagonal(cells = SA[1])], 5) @test_broken densitymatrix(gSpectrum[diagonal(cells = SA[])]) @test_broken densitymatrix(gKPM[diagonal(1)]) glead = LP.square() |> hamiltonian(hopping(1)) |> supercell((0,1), region = r -> -1 <= r[1] <= 1) |> attach(nothing; cells = SA[10]) |> greenfunction(GS.Schur(boundary = 0)); contact1 = r -> r[1] ≈ 5 && -1 <= r[2] <= 1 contact2 = r -> r[2] ≈ 5 && -1 <= r[1] <= 1 g0 = LP.square() |> hamiltonian(hopping(1)) |> supercell(region = RP.square(10)) |> attach(glead, reverse = true; region = contact2) |> attach(glead; transform = r->SA[0 1; 1 0] * r, region = contact1) |> greenfunction; testcond(g0) glead = LP.square() |> hamiltonian(hopping(1)) |> supercell((1,0), region = r -> -1 <= r[2] <= 1) |> greenfunction(GS.Schur(boundary = 0)); contact1 = r -> r[1] ≈ 5 && -1 <= r[2] <= 1 contact2 = r -> r[1] ≈ -5 && -1 <= r[2] <= 1 g0 = LP.square() |> hamiltonian(hopping(1)) |> supercell(region = RP.square(10)) |> attach(glead, reverse = true; region = contact2) |> attach(glead; region = contact1) |> greenfunction; testcond(g0) glead = LP.square() |> hamiltonian(hopping(I) + onsite(SA[0 1; 1 0]), orbitals = 2) |> supercell((1,0), region = r -> -1 <= r[2] <= 1) |> greenfunction(GS.Schur(boundary = 0)); g0 = LP.square() |> hamiltonian(hopping(I), orbitals = 2) |> supercell(region = RP.square(10)) |> attach(glead, reverse = true; region = contact2) |> attach(glead; region = contact1) |> greenfunction; testcond(g0; nambu = true) testjosephson(g0) # test fermi at zero temperature g = LP.linear() |> hopping(1) |> supercell(3) |> supercell |> greenfunction(GS.Spectrum()) @test ρ = diag(densitymatrix(g[])()) ≈ [0.5, 0.5, 0.5] end @testset "mean-field models" begin h1 = LP.honeycomb() |> supercell(2) |> supercell |> hamiltonian(onsite(0I) + hopping(I), orbitals = 1) h2 = LP.honeycomb() |> supercell(2) |> supercell |> hamiltonian(onsite(0I) + hopping(I), orbitals = 2) h3 = LP.honeycomb() |> supercell(2) |> supercell |> hamiltonian(onsite(0I) + hopping(I), orbitals = (1,2)) for h0 in (h1, h2, h3) ρ0 = densitymatrix(greenfunction(h0, GS.Spectrum())[cells = SA[]])(); h = h0 |> @onsite!((o, s; ρ = ρ0, t) --> o + t*ρ[s]) @test diag(h(t = 2)[()]) ≈ 2*diag(ρ0) atol = 0.0000001 h = h0 |> @hopping!((t, si, sj; ρ = ρ0, α = 2) --> α*ρ[si, sj]) @test h() isa Quantica.Hamiltonian diff = (h()[()] - 2ρ0) .* h()[()] @test iszero(diff) end end @testset "aliasing" begin # Issue #267 g = LP.linear() |> hamiltonian(@hopping((; q = 1) -> q*I), orbitals = 2) |> greenfunction g´ = Quantica.minimal_callsafe_copy(g) @test g(0.2; q = 2)[cells = 1] == g´(0.2; q = 2)[cells = 1] @test g´.solver.fsolver.h0 === g´.parent.h.harmonics[1].h # The Schur slicer has uninitialized fields whose eventual value depends on the parent hamiltonian # at call time, not creation time. This can produce bugs if Quantica.call!(g, ω; params...) is used. # The exported g(ω; params...) syntax decouples the slicer's parent Hamiltonian, so it is safe. g = LP.linear() |> hamiltonian(@onsite((; q = 1) -> q) + @hopping((; q = 1) -> q)) |> greenfunction m = g(0.4, q = 0.1)[cells = 0] gs = Quantica.call!(g, 0.4, q = 0.1) @test gs[cells = 0] == m gs = Quantica.call!(g, 0.4, q = 0.1) parent(g)(q = 2) @test_broken gs[cells = 0] == m # Ensure that g.solver.invgreen alias of parent contacts is not broken by minimal_callsafe_copy glead = LP.linear() |> @onsite((; o = 1) -> o) - hopping(1) |> greenfunction(GS.Schur(boundary = 0)); g = LP.linear() |> -hopping(1) |> supercell |> attach(glead) |> greenfunction; g´ = Quantica.minimal_callsafe_copy(g); @test g´(0, o = 0)[] == g(0, o = 0)[] @test g´(0, o = 1)[] == g(0, o = 1)[] end
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
24232
using Quantica: Hamiltonian, ParametricHamiltonian, BarebonesOperator, OrbitalSliceMatrix, SparseMatrixCSC, sites, nsites, nonsites, nhoppings, coordination, flat, hybrid, transform!, nnz, nonzeros @testset "basic hamiltonians" begin presets = (LatticePresets.linear, LatticePresets.square, LatticePresets.triangular, LatticePresets.honeycomb, LatticePresets.cubic, LatticePresets.fcc, LatticePresets.bcc, LatticePresets.hcp) types = (Float16, Float32, Float64) ts = (1, 2.0I, @SMatrix[1 2; 3 4], 1.0f0*I) orbs = (1, Val(1), Val(2), 2) for preset in presets, type in types, lat in (preset(; type), supercell(preset(; type))) E, L = Quantica.embdim(lat), Quantica.latdim(lat) dn0 = ntuple(_ -> 1, Val(L)) for (t, o) in zip(ts, orbs) @test hamiltonian(lat, onsite(t) + hopping(t; range = 1), orbitals = o) isa Hamiltonian @test hamiltonian(lat, onsite(t) - hopping(t; dcells = dn0), orbitals = o) isa Hamiltonian end end h = LatticePresets.honeycomb() |> hopping(1, range = 1/√3) @test h[SA[0,0]] === h[()] === flat(h.harmonics[1].h) # Inf range h = LatticePresets.square() |> supercell(region = RegionPresets.rectangle((5,6))) |> hamiltonian(hopping(1, range = Inf)) @test Quantica.nhoppings(h) == 1190 h = LatticePresets.square() |> hamiltonian(hopping(1, dcells = (10,0), range = Inf)) |> transform(r -> SA[0 1; 2 0] * r) @test Quantica.nhoppings(h) == 1 @test isassigned(h, (10,0)) @test bravais_matrix(h) == SA[0 1; 2 0] h = LatticePresets.honeycomb() |> hamiltonian(onsite(1.0, sublats = :A) + hopping(I, range = 2/√3), orbitals = (Val(1), Val(2))) @test Quantica.nonsites(h) == 1 @test Quantica.nhoppings(h) == 24 @test ishermitian(h) h = LatticePresets.square() |> supercell(3) |> hamiltonian(hopping(1, range = 3) |> plusadjoint) @test Quantica.nhoppings(h) == 252 @test ishermitian(h) h = LatticePresets.honeycomb() |> hamiltonian(hopping(1, range = (1, 1))) @test Quantica.nhoppings(h) == 12 h = LatticePresets.honeycomb() |> hamiltonian(hopping(1, range = (1, 2), sublats = :A => :B)) @test Quantica.nhoppings(h) == 9 @test !ishermitian(h) h = LatticePresets.honeycomb() |> hamiltonian(hopping(1, range = (1, 2), sublats = :A => :B) |> plusadjoint) @test Quantica.nhoppings(h) == 18 @test ishermitian(h) h = LatticePresets.honeycomb() |> hamiltonian(hopping(1, range = (1, 2/√3))) @test Quantica.nhoppings(h) == 18 h = LatticePresets.honeycomb() |> hamiltonian(hopping(1, range = (2, 1))) @test Quantica.Quantica.nhoppings(h) == 0 h = LatticePresets.honeycomb() |> hamiltonian(hopping(1, range = (30, 30))) @test Quantica.Quantica.nhoppings(h) == 12 h = LatticePresets.honeycomb() |> hamiltonian(hopping(1, range = (10, 10.1))) @test Quantica.Quantica.nhoppings(h) == 48 @test Hamiltonian{3}(h) isa Hamiltonian{<:Any,3} @test convert(Hamiltonian{3}, h) isa Hamiltonian{<:Any,3} end @testset "hamiltonian orbitals" begin lat = LP.honeycomb() hop = hopping(SA[1 0], sublats = :A => :B) h = hamiltonian(lat, plusadjoint(hopping(hop)) + onsite(1, sublats = 2), orbitals = (2, Val(1))) h´ = hamiltonian(lat, hop + hop' + onsite(1, sublats = 2), orbitals = (2, Val(1))) @test h isa Hamiltonian @test h == h´ @test_throws ArgumentError hamiltonian(lat, hopping(SA[1 0]), orbitals = (2, Val(1))) h = hamiltonian(lat, hopping(I) + onsite(SA[1 0; 0 1], sublats = :A), orbitals = (2, Val(1))) @test h isa Hamiltonian end @testset "hamiltonian sublats" begin lat = LP.honeycomb() h = hamiltonian(lat, hopping(1, sublats = (:A,:B) .=> (:A, :B))) @test iszero(h((1,2))) h = hamiltonian(lat, hopping(1, sublats = :A => :B)) @test h((0,0)) == SA[0 0; 3 0] h = hamiltonian(lat, hopping(1, sublats = :A => :B) |> plusadjoint) @test h((0,0)) == SA[0 3; 3 0] h = hamiltonian(lat, hopping(1, sublats = (:A,:B) .=> (:B, :A), range = neighbors(2))) @test h((0,0)) == SA[0 3; 3 0] h = hamiltonian(lat, hopping(1, sublats = (:A,:B) => (:A, :B), range = neighbors(2))) @test h((0,0)) == SA[6 3; 3 6] h = hamiltonian(lat, hopping(1, sublats = (:A => :B, :A => :A), range = neighbors(2))) @test h((0,0)) == SA[6 0; 3 0] h = hamiltonian(lat, hopping(1, sublats = (:A => :B, (:A, :B) .=> (:A, :B)), range = neighbors(2))) @test h((0,0)) == SA[6 0; 3 6] end @testset "hamiltonian presets" begin h = HP.graphene(; a0 = 1, dim = 3, range = neighbors(2), t0 = 2.7, β = 3, orbitals = 2, names = (:a, :b), type = Float32) @test h isa Hamiltonian{Float32,3,2} h = HP.twisted_bilayer_graphene(; twistindex = 0, rangeinterlayer = 2, interlayerdistance = 1, a0 = 1, hopintra = 2.7 * I, orbitals = 2, names = (:A, :B, :A´, :B´)) @test h isa Hamiltonian{Float64,3,2} end @testset "siteselectors/hopselectors" begin lat = LatticePresets.linear() @test supercell(lat, region = RP.segment(10)) isa Quantica.Lattice lat = LatticePresets.bcc() for r in (RP.sphere(3), RP.cube(3), RP.spheroid((3,4,5), (3,3,3)), RP.cuboid((3,4,5), (2,3,4))) @test supercell(lat, region = r) isa Quantica.Lattice end lat = LatticePresets.honeycomb() for r in (RP.circle(10), missing), s in (:A, 1, (:A, :B), [1, :B], missing), c in (SA[0,1], (0,1)), cs in (c, (c, 2 .* c), [c, 2 .* c], missing) @test supercell(lat, region = r, sublats = s, cells = cs) isa Quantica.Lattice end r1 = RP.ellipse((10,15)) r2 = (r, dr) -> norm(r) + norm(dr) < 2 for region in (r1, missing), sublats in (:A, 1, (:A, :B), missing), c in (SA[0,1], (0,1)), dcells in (c, (c, 2 .* c), missing), range in (1, neighbors(2), (1, 2.0), (1, neighbors(3))), sublats´ in (:A, 1, (:A, :B)), regionhop in (r2, missing) sublatshop = ifelse(sublats === missing, missing, sublats´ .=> sublats) @test Quantica.apply(siteselector(; region, sublats), lat) isa Quantica.AppliedSiteSelector @test Quantica.apply(hopselector(; range, dcells, region = regionhop, sublats = sublatshop), lat) isa Quantica.AppliedHopSelector sublatshop = ifelse(sublats === missing, missing, sublats´ => sublats) @test Quantica.apply(hopselector(; range, dcells, region = regionhop, sublats = sublatshop), lat) isa Quantica.AppliedHopSelector end end @testset "models" begin mo = (onsite(1), onsite(r-> r[1]), @onsite((; o) -> o), @onsite((r; o=2) -> r[1]*o), @onsite((s; o, p) --> pos(s)[1]*o)) mh = (hopping(1), hopping((r, dr)-> im*dr[1]), @hopping((; t) -> t), @hopping((r, dr; t) -> r[1]*t), @hopping((si, sj) --> im*ind(si)), @hopping((si, sj; t, p = 2) --> pos(sj)[1]*t)) argso, argsh = (0, 1, 0, 1, 1), (0, 2, 0, 2, 2, 2) for (o, no) in zip(mo, argso) @test Quantica.narguments(only(Quantica.terms(o))) == no end for (h, nh) in zip(mh, argsh) @test Quantica.narguments(only(Quantica.terms(h))) == nh end for o in mo, h in mh @test length(Quantica.allterms(-o - 2*h)) == 2 @test Quantica.ParametricModel(o+h) isa Quantica.ParametricModel m = onsite(o + h; cells = 1) ts = Quantica.allterms(m) @test length(ts) == 1 && all(t->Quantica.selector(t).cells == 1, ts) m = hopping(2*(o' + h'); dcells = 1) ts = Quantica.allterms(m) @test length(ts) == 1 && all(t->Quantica.selector(t).dcells == 1, ts) end end @testset "hamiltonian supercell" begin h = LatticePresets.honeycomb() |> hamiltonian(hopping(1)) |> supercell((1,-1), region = r -> abs(r[2])<2) @test nhoppings(h) == 22 h = LatticePresets.square() |> hamiltonian(hopping(1)) |> supercell(3) |> supercell((1,0)) @test nsites(h) == 9 h = LatticePresets.square() |> hamiltonian(hopping(1, range = √2)) |> supercell(5) |> supercell((1,0)) @test nhoppings(h) == 170 @test nsites(h) == 25 # dim-preserving supercell reshaping should always preserve coordination lat = lattice(sublat((0.0, -0.1), (0,0), (0,1/√3), (0.0,1.6/√3)), bravais = SA[cos(pi/3) sin(pi/3); -cos(pi/3) sin(pi/3)]') h = lat |> hamiltonian(hopping(1, range = 1/√3)) c = coordination(h) iter = CartesianIndices((-3:3, -3:3)) for Ic´ in iter, Ic in iter sc = SMatrix{2,2,Int}(Tuple(Ic)..., Tuple(Ic´)...) iszero(det(sc)) && continue h´ = supercell(h, sc) h´´ = supercell(h´, 2) @test coordination(h´´) ≈ coordination(h´) ≈ c h´ = supercell(h´, Tuple(Ic)) h´´ = supercell(h´, 2) @test coordination(h´´) ≈ coordination(h´) end h = LP.honeycomb() |> hamiltonian(hopping(1)) |> supercell(2) |> supercell(mincoordination = 2) @test nsites(h) == 6 h = LP.cubic() |> hamiltonian(hopping(1)) |> supercell(4) |> supercell(mincoordination = 4) @test nsites(h) == 0 h = LP.honeycomb() |> hamiltonian(hopping(1)) |> supercell(region = RP.circle(5) & !RP.circle(2)) |> supercell(mincoordination = 2) @test nsites(h) == 144 h = LP.honeycomb() |> hamiltonian(hopping(1)) |> supercell(10, region = !RP.circle(2, (0,8))) h´ = h |> supercell(1, mincoordination = 2) @test nsites(h´) == nsites(h) - 1 h = LP.square() |> hamiltonian(hopping(0)) |> supercell(4, mincoordination = 2) @test nsites(h) == 0 # check dn=0 invariant h = LP.linear() |> hamiltonian(hopping(1)) |> supercell((1,)) @test length(h.harmonics) == 3 && iszero(first(h.harmonics).dn) # seeds p1 = SA[100,0] p2 = SA[0,20] lat = LatticePresets.honeycomb() model = hopping(1, range = 1/√3) + onsite(2) h1 = lat |> hamiltonian(model) |> supercell(region = r -> norm(r-p1)<3, seed = p1) h2 = lat |> hamiltonian(model) |> supercell(region = r -> norm(r-p2)<3, seed = p2) h = combine(h1, h2) h3 = lat |> hamiltonian(model) |> supercell(region = r -> norm(r-p1)<3 || norm(r-p2)<3, seed = p2) @test Quantica.nsites(h) == 130 @test Quantica.nsites(h3) == 64 end @testset "hamiltonian torus" begin for o in (1, (2,3)) h = LatticePresets.honeycomb() |> hamiltonian(hopping((r, dr) -> 1/norm(dr) * I, range = 10), orbitals = o) @test_throws ArgumentError torus(h, (1,2,3)) @test_throws ArgumentError torus(h, 1) wh = h |> torus((1,2)) @test wh(()) ≈ h(SA[1,2]) wh = torus(h, (1,:)) @test wh(SA[2]) ≈ h(SA[1,2]) h = LatticePresets.honeycomb() |> hamiltonian(hopping((r, dr) -> 1/norm(dr) * I, range = 10)) |> supercell(3) wh = torus(h, (1,2)) @test wh(()) ≈ h(SA[1,2]) wh = torus(h, (1,:)) @test wh(SA[2]) ≈ h(SA[1,2]) wh = torus(h, (:,:)) @test wh == h @test wh !== h h = LP.linear() |> supercell(2) |> hopping(1) |> @hopping!((t, r, dr) -> t*(r[1]-1/2)) @test_warn "unexpected results for position-dependent modifiers" torus(h, (0.2,)) end end @testset "hamiltonian HybridSparseMatrix" begin for o in (1, 2, (2, 2), (2,3)) h = HP.graphene(orbitals = o) |> supercell(2) @test h[()] === h[(0,0)] s = h[hybrid((1,0))] @test !Quantica.needs_unflat_sync(s) if o == 1 @test eltype(h[hybrid()]) === ComplexF64 @test !Quantica.needs_flat_sync(s) @test Quantica.isaliased(s) @test h[()] === h[unflat()] elseif o == (2,2) || o == 2 @test eltype(h[unflat()]) <: Quantica.SMatrix @test Quantica.needs_flat_sync(s) @test !Quantica.isaliased(s) h[()] @test Quantica.needs_flat_sync(s) else @test eltype(h[unflat()]) <: Quantica.SMatrixView @test Quantica.needs_flat_sync(s) @test !Quantica.isaliased(s) h[()] @test Quantica.needs_flat_sync(s) end @test_throws BoundsError h[(1,1)] bs = Quantica.blockstructure(h) hflat, hunflat = h[()], h[unflat()] @test Quantica.flat(Quantica.HybridSparseMatrix(bs, hflat)) == hflat @test unflat(Quantica.HybridSparseMatrix(bs, hunflat)) == hunflat @test Quantica.flat(Quantica.HybridSparseMatrix(bs, hunflat)) == hflat @test unflat(Quantica.HybridSparseMatrix(bs, hflat)) == hunflat # Tampering protection h[(1,0)][1,1] = 1 @test_throws ArgumentError h[(1,0)] @test h[unflat(0,0)] isa Quantica.SparseMatrixCSC @test_throws ArgumentError h((0,0)) end end @testset "hamiltonian call" begin for o in (1, (2,3)) h = HP.graphene(orbitals = o) |> supercell(2) @test h() == h @test h() !== h @test h(; param = 1) == h @test_throws ArgumentError h(()) @test_throws ArgumentError h(1,2) @test h((1,2)) == h(SA[1,2]) @test Quantica.call!(h, (1,2)) === Quantica.call!(h, SA[2,3]) === Quantica.call!_output(h) h = supercell(h) @test h(()) == h(SA[]) == h[()] @test Quantica.call!(h, ()) === Quantica.call!(h, SA[]) === h[()] === Quantica.call!_output(h) end h = hamiltonian(LP.linear(), hopping(1)) @test h(π) == h((π,)) == h([π]) == [-2;;] end @testset "parametric hamiltonian" begin lat = LP.honeycomb() |> supercell(2) h = hamiltonian(lat, @onsite((; o) -> o)) h0 = h((0,0); o = 2) @test h0 == 2I @test Quantica.nnz(h0) == 8 @test_throws UndefKeywordError h((0,0)) h = hamiltonian(lat, @onsite((r; o = 0) -> o*r[1])) @test h((0,0); o = 2) ≈ Quantica.Diagonal([0, -1, 1, 0, 0, -1, 1, 0]) @test h(; o = 1)[()] !== h(; o = 2)[()] @test Quantica.call!(h; o = 1)[()] === Quantica.call!(h; o = 2)[()] h´ = hamiltonian(h, @onsite!((o´, r; o = 0) -> o´ - o*r[1])) @test iszero(h´((0,0), o = 3)) @test Quantica.nnz(h´((0,0), o = 3)) == 8 h = hamiltonian(lat, onsite(1) + @hopping((r, dr; t) -> t * cis(dr[2])), @hopping!((t´, r, dr; takeabs = false) -> ifelse(takeabs, abs(t´), t´))) @test ishermitian(h(t = 1)) h0 = h(t = 1)((0,0)) @test !all(x -> x isa Real, h0) h0 = h(t = 1, takeabs = true)((0,0)) @test all(==(1), Quantica.nonzeros(h0)) h = LatticePresets.linear() |> hopping(1) |> @onsite!((o; k) -> o + k*I) # No onsites, no need to specify k @test h() isa Hamiltonian # Issue #35 for orb in (Val(1), Val(2)) h = LatticePresets.triangular() |> hamiltonian(hopping(I) + onsite(I), orbitals = orb) |> supercell(10) h´ = hamiltonian(h, @onsite!((o, r; b) -> o+b*I), @hopping!((t, r, dr; a = 2) -> t+r[1]*I), @onsite!((o, r; b) -> o-b*I), @hopping!((t, r, dr; a = 2) -> t-r[1]*I)) @test isapprox(h´(a=1, b=2)((1, 2)), h((1, 2))) end # Issue #37 for orb in (Val(1), Val(2)) h = LatticePresets.triangular() |> hamiltonian(hopping(I) + onsite(I), orbitals = orb) |> supercell(10) h´ = hamiltonian(h, @onsite!(o -> o*cis(1))) @test h´()[()][1,1] ≈ h[()][1,1]*cis(1) end # Issue #54. Parametric Haldane model, unbounded modifiers sK(dr::SVector) = sK(atan(dr[2],dr[1])) sK(ϕ) = 2*mod(round(Int, 6*ϕ/(2π)), 2) - 1 h = LatticePresets.honeycomb() |> hamiltonian(hopping(1, range = 1), @hopping!((t, r, dr; λ, k = SA[0,0]) -> λ*im*sK(dr+k); sublats = :A=>:A), # These should have range = Inf @hopping!((t, r, dr; λ, k = SA[0,0]) -> -λ*im*sK(dr+k); sublats = :B=>:B)) # These should have range = Inf @test h((π/2, -π/2), λ=1) ≈ [4 1; 1 -4] # Non-numeric parameters @test h((π/2, -π/2); λ = 1, k = SA[1,0]) ≈ [-4 1; 1 4] # # Issue #61, type stability. TODO: must review this test # h = LatticePresets.honeycomb() |> hamiltonian(onsite(0)) # @inferred hamiltonian(h, @onsite!((o;μ) -> o- μ)) # @test_broken @inferred hamiltonian(h, @onsite!(o->2o), @hopping!((t)->2t), @onsite!((o, r)->o+r[1])) # @test_broken @inferred hamiltonian(h, @onsite!((o, r)->o*r[1]), @hopping!((t; p)->p*t), @onsite!((o; μ)->o-μ)) h = LatticePresets.honeycomb() |> hamiltonian(hopping(2I), orbitals = (Val(2), Val(1)), @hopping!((t; α, β = 0) -> α * t .+ β)) b = h((0, 0); α = 2) @test b == [0 0 12; 0 0 0; 12 0 0] @test ParametricHamiltonian{3}(h) isa ParametricHamiltonian{<:Any,3} # Old bug in apply h = LP.honeycomb() |> supercell(2) |> onsite(1) |> @onsite!(o -> 0; sublats = :A) @test tr(h((0,0))) == 4 # torus and supercell commutativity with modifier application h = LP.linear() |> hopping(1) |> supercell(3) |> @onsite!((o,r; E = 1)-> E*r[1]) |> @hopping!((t, r,dr; A = SA[1])->t*cis(dot(A,dr[1]))) @test supercell(h(), 4)((1,)) ≈ supercell(h, 4)((1,)) @test torus(h, (2,))(()) ≈ torus(h(), (2,))(()) ≈ h((2,)) h = LP.linear() |> supercell(3) |> @hopping((r,dr; ϕ = 1) -> cis(ϕ * dr[1])) @test supercell(h(), 4)((1,)) ≈ supercell(h, 4)((1,)) @test torus(h(), (2,))(()) ≈ h((2,)) h0 = LP.square() |> hopping(1) |> supercell(3) |> @hopping!((t, r, dr; A = SA[1,2]) -> t*cis(A'dr)) h = torus(h0, (0.2,:)) @test h0((0.2, 0.3)) ≈ h((0.3,)) # non-spatial models h = LP.linear() |> @hopping((i,j) --> ind(i) + ind(j)) + @onsite((i; k = 1) --> pos(i)[k]) @test ishermitian(h()) # null selectors h0 = LP.square() |> onsite(0) + hopping(0) |> supercell(3) |> @onsite!((t, r) -> 1; sublats = Symbol[]) @test iszero(h0()) h0 = LP.square() |> hopping(0) |> supercell(3) |> @hopping!((t, r, dr) -> 1; dcells = SVector{2,Int}[]) @test iszero(h0()) # Issue #118 sublats = :A; h0 = LP.honeycomb() |> @hopping(r->0, sublats, range = 2) + @onsite((r; p = 3) ->3p; sublats) + @onsite((r; q = 3) ->3q, sublats, region = RP.circle(2)) |> @hopping!((t, r, dr; p = 1) -> p+r[2], dcells = SVector{2,Int}[]) |> @onsite!((o, r; q = 1) -> o + q, sublats, region = RP.circle(3)) @test h0 isa ParametricHamiltonian @test Quantica.parameters(h0) == [:p, :q] end @testset "ExternalPresets.wannier90" begin # wannier import w = EP.wannier90("wannier_test_tb.dat", htol = 1e-4, rtol = 1e-4, dim = 2, type = Float32); h = hamiltonian(w) @test h isa Hamiltonian{Float32,2,2,ComplexF32} R = position(w) @test R isa BarebonesOperator{2,SVector{2,ComplexF32}} @test R[sites(1)] isa SVector{2,ComplexF32} @test_throws Quantica.Dictionaries.IndexError R[SA[1000,0]] @test iszero(R[sites(1), sites(SA[1000,0],1)]) # Wannier90 coupling to dipole moments w = EP.wannier90("wannier_test2_tb.dat", onsite(2); dim = 2, htol = 1e-4, rtol = 1e-4) |> @onsite!((o; k = 1) -> o * k) h = hamiltonian(w) R = position(w) hE = h |> @onsite!((o, i; E = SA[0,0]) --> o + E'*R[i,i]) |> @hopping!((t, i, j; E = SA[0,0]) --> t + E'*R[i,j]) @test hE() isa Hamiltonian{Float64,2,2} end @testset "hamiltonian nrange" begin lat = LatticePresets.honeycomb(a0 = 2) @test Quantica.nrange(1, lat) ≈ 2/√3 @test Quantica.nrange(2, lat) ≈ 2 @test Quantica.nrange(3, lat) ≈ 4/√3 @test hamiltonian(lat, hopping(1)) |> nhoppings == 6 @test hamiltonian(lat, hopping(1, range = neighbors(2))) |> nhoppings == 18 @test hamiltonian(lat, hopping(1, range = neighbors(3))) |> nhoppings == 24 @test hamiltonian(lat, hopping(1, range = (neighbors(2), neighbors(3)))) |> nhoppings == 18 @test hamiltonian(lat, hopping(1, range = (neighbors(20), neighbors(20)))) |> nhoppings == 18 @test hamiltonian(lat, hopping(1, range = (neighbors(20), neighbors(21)))) |> nhoppings == 30 end @testset "hamiltonians transform" begin h = LP.honeycomb(dim = 3) |> hamiltonian(hopping(1)) h1 = copy(h) h2 = transform!(h1, r -> SA[1 2 0; 2 3 0; 0 0 1] * r + SA[0,0,1]) h3 = h1 |> transform!(r -> SA[1 2 0; 2 3 0; 0 0 1] * r + SA[0,0,1]) @test h1 === h2 === h3 @test all(r->r[3] == 2.0, sites(lattice(h3))) @test h((1,2)) == h3((1,2)) h = LP.square() |> @hopping((; t=1) -> t) |> supercell((2,0), (0, 1)) h´ = h |> transform(r -> SA[r[2], r[1]]) @test sites(lattice(h´)) == sites(h´.h.lattice) != sites(lattice(parent(h´))) @test sites(lattice(h´)) == [SA[0,0], SA[0,1]] h´´ = reverse(h´) @test bravais_matrix(lattice(h´´)) == - bravais_matrix(lattice(h´)) @test reverse!(h´´) === h´´ @test bravais_matrix(lattice(h´´)) == bravais_matrix(lattice(h´)) end @testset "hamiltonians combine" begin h1 = LP.square(dim = Val(3)) |> hamiltonian(hopping(1)) h2 = transform(h1, r -> r + SA[0,0,1]) h = combine(h1, h2; coupling = hopping((r,dr) -> exp(-norm(dr)), range = √2)) @test Quantica.coordination(h) == 9 h0 = LP.honeycomb(dim = Val(3), names = (:A, :B)) |> hamiltonian(hopping(1)) ht = LP.honeycomb(dim = Val(3), names = (:At, :Bt)) |> hamiltonian(hopping(1)) |> transform!(r -> r + SA[0,1/√3,1]) hb = LP.honeycomb(dim = Val(3), names = (:Ab, :Bb)) |> hamiltonian(hopping(1)) |> transform!(r -> r + SA[0,1/√3,-1]) h = combine(hb, h0, ht; coupling = hopping((r,dr) -> exp(-norm(dr)), range = 2, sublats = ((:A,:B) => (:At, :Bt), (:A,:B) => (:Ab, :Bb))) |> plusadjoint) @test iszero(h((0,0))[1:2, 5:6]) h = combine(hb, h0, ht; coupling = hopping((r,dr) -> exp(-norm(dr)), range = 2)) @test !iszero(h((0,0))[1:2, 5:6]) # Parametric combine h1 = LP.linear(dim = 2) |> hopping(1) h2 = LP.linear(dim = 2) |> hamiltonian(@hopping((; p = 1) -> p*I), orbitals = 2) coupling = @hopping((; p = 1) -> im*p*SA[1 0], range = 3, sublats = :B => :A) |> plusadjoint @test_throws ArgumentError combine(h1, h2) @test_throws ArgumentError combine(h1, h2(); coupling) @test combine(h1, h2()) isa Hamiltonian h2 = LP.linear(dim = 2, names = :B) |> hamiltonian(@hopping((; p = 1) -> p*I), orbitals = 2) @test combine(h1, h2) isa ParametricHamiltonian{Float64,2,1,Quantica.SMatrixView{2,2,ComplexF64,4}} h = combine(h1, h2; coupling) @test h isa ParametricHamiltonian{Float64,2,1,Quantica.SMatrixView{2,2,ComplexF64,4}} # plustadjoint broken for ParametricModels @test_broken h((p = 10)) end @testset "current operator" begin h = LP.honeycomb() |> hamiltonian(@onsite((; μ = 0) -> (2-μ)*I) - hopping(SA[0 1; 1 0]), orbitals = 2) |> supercell(2) co = current(h, direction = 2) c = co(SA[0,0]) @test c ≈ c' @test iszero(diag(c)) @test all(x -> real(x) ≈ 0, c) cp = co[unflat(SA[1,0])] cm = co[unflat(SA[-1,0])] @test nnz(cp) == nnz(cm) == 2 @test cp ≈ cm' @test all(x -> x[1] ≈ x[2]', zip(nonzeros(cp), nonzeros(cm))) @test all(x -> iszero(real(x)), nonzeros(cp)) end @testset "hamiltonian builder" begin b = LP.linear() |> Quantica.builder(orbitals = 2) @test b isa Quantica.IJVBuilder @test hamiltonian(b) isa Hamiltonian Quantica.add!(b, hopping(2I)) Quantica.add!(b, @onsite((; w = 0) -> w*I)) Quantica.add!(b, SA[0 1; 1 0], sites(1)) @test length(Quantica.modifiers(b)) == 1 h = hamiltonian(b) @test h(w=3)[()] == 3*I + SA[0 1; 1 0] push!(b, @onsite!((o; w = 0) -> o*w)) @test length(Quantica.modifiers(b)) == 2 h = hamiltonian(b) @test h(w=3)[()] == 9*I + + SA[0 3; 3 0] b = LP.honeycomb() |> Quantica.builder(orbitals = (1,2)) Quantica.add!(b, SA[0 1; 1 0], sites(2)) Quantica.add!(b, 2, sites(1)) h = hamiltonian(b) @test h[()] == SA[2 0 0; 0 0 1; 0 1 0] b = LP.honeycomb() |> Quantica.builder(orbitals = (1,2)) Quantica.add!(b, 2I, sites(1:2)) h = hamiltonian(b) @test h[()] == 2I b = LP.honeycomb() |> Quantica.builder Quantica.add!(b, 2, sites(1:2), sites(1:2)) h = hamiltonian(b) @test all(isequal(2), h[()]) end @testset "hamiltonian indexing" begin h = LP.honeycomb() |> hamiltonian(hopping(I), orbitals = (2, 1)) |> @hopping!((t; p = 1) -> p*t) m = h[sites(1), sites(2)] @test m isa SparseMatrixCSC @test m == SA[1; 0;;] @test iszero(h[sites(1), sites(SA[2,3], 2)]) m = h[cells = 1] @test m isa OrbitalSliceMatrix @test m == SA[0 0 1; 0 0 0; 1 0 0] m = h[sites(2), (; cells = 1)] @test m isa SparseMatrixCSC @test m == SA[1 0 0] m = view(h, sites(2), sites(1)) @test m isa SubArray @test m == SA[1 0] end
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
9075
using Quantica: Sublat, Lattice, transform!, translate!, nsites @testset "Internal API" begin s = sublat((0,0,0)) @test Quantica.embdim(s) == 3 @test Quantica.numbertype(s) <: AbstractFloat lat = LP.honeycomb() @test length(Quantica.bravais_vectors(lat)) == 2 @test_throws BoundsError sites(lat, :C) @test length(sites(lat, 1)) == 1 @test length(lat) == 2 nt = (; region = r -> r[1] == 1, sublats = :C) s = siteselector(; nt...) @test NamedTuple(s) === (; nt..., cells = missing) h = hopselector(; nt...) @test NamedTuple(h).sublats == :C h = HP.graphene(orbitals = 2) @test Quantica.flatrange(h, :B) === 3:4 end @testset "lattice sublats" begin sitelist = [(3,3), (3,3.), [3,3.], SA[3, 3], SA[3, 3f0], SA[3f0, 3.0]] for site2 in sitelist, site1 in sitelist T = float(promote_type(typeof.(site1)..., typeof.(site2)...)) @test sublat(site1, site2) isa Sublat{T,2} @test sublat([site1, site2]) isa Sublat{T,2} @test lattice(sublat(site1), sublat(site2)) isa Lattice end @test sublat((3,)) isa Sublat{Float64,1} @test sublat(()) isa Sublat{Float64,0} @test sublat(SVector{3,Float64}[]) isa Sublat{Float64,3} end @testset "lattice construction" begin s = sublat((1, 2)) s´ = sublat([0,0f0]) for t in (Float32, Float64), e in 1:4, l = 1:4 br = SMatrix{e,l,Float64}(I) if l > e @test_throws DimensionMismatch lattice(s; bravais = br, type = t, dim = Val(e)) @test_throws DimensionMismatch lattice(s; bravais = br, type = t, dim = e) else @test lattice(s; bravais = br, type = t, dim = Val(e)) isa Lattice{t,e,l} @test lattice([s, s´]; bravais = Matrix(br), type = t, dim = e) isa Lattice{t,e,l} end if l > 2 @test_throws DimensionMismatch lattice(s; bravais = br, type = t) else @test lattice(s; bravais = br, type = t) isa Lattice{t,2,l} end end lat = lattice(sublat((0,0,0)); names = :A) # scalar `names` @test lat isa Lattice{Float64,3,0} lat = lattice(sublat((0,0,0f0)), sublat((1,1,1f0)); bravais = SMatrix{3,3}(I)) lat2 = lattice(lat, bravais = ()) @test lat2 isa Lattice{Float32,3,0} @test sites(lat) === sites(lat2) # site aliasing lat2 = lattice(lat, bravais = (), names = (:A,:B)) @test lat2 isa Lattice{Float32,3,0} @test sites(lat) === sites(lat2) # site aliasing @test_throws ArgumentError lattice(lat, names = (:A,:B,:C)) # too many `names` lat2 = lattice(lat, type = Float64) @test lat2 isa Lattice{Float64,3,3} @test sites(lat) !== sites(lat2) # no site aliasing lat2 = lattice(lat, dim = Val(2), bravais = SA[1 2; 3 4]) @test lat2 isa Lattice{Float32,2,2} # dimension cropping @test bravais_matrix(lat2) == SA[1 2; 3 4] # dim/type promotion @test lattice(sublat(Float16(0), name = :A), sublat(SA[1,2f0], name = :B)) isa Lattice{Float32,2} end @testset "lattice presets" begin a0s = (1, 2) presets = (LatticePresets.linear, LatticePresets.square, LatticePresets.triangular, LatticePresets.honeycomb, LatticePresets.cubic, LatticePresets.fcc, LatticePresets.bcc, LatticePresets.hcp) for a0 in a0s, t in (Float32, Float64), preset in presets @test preset(; a0 = a0, type = t) isa Lattice{t} end @test LatticePresets.cubic(bravais = (1,0)) isa Lattice{Float64,3,1} @test LatticePresets.cubic(bravais = ((1,0), (0,1)), dim = Val(2)) isa Lattice{Float64,2,2} end # @testset "siteindices/sitepositions" begin # lat = LatticePresets.honeycomb() |> unitcell(region = RegionPresets.circle(10)) # @test sum(sitepositions(lat, sublats = :A)) ≈ -sum(sitepositions(lat, sublats = :B)) # @test length(collect(siteindices(lat, sublats = :A))) == nsites(lat) ÷ 2 # lat = LatticePresets.honeycomb() |> unitcell(2) # @test collect(siteindices(lat)) == 1:8 # @test collect(siteindices(lat; indices = 10)) == Int[] # @test collect(siteindices(lat; indices = 5:10)) == 5:8 # @test collect(siteindices(lat; indices = 5:10)) == 5:8 # @test collect(siteindices(lat; indices = 5:10)) == 5:8 # @test collect(siteindices(lat; indices = (1, 5:10))) == [1, 5 ,6, 7, 8] # @test collect(siteindices(lat; indices = (1, 10))) == [1] # end @testset "lattice combine" begin lat0 = transform!(LatticePresets.honeycomb(), r -> SA[r[2], -r[1]]) |> supercell((1,1), (-1,1)) br = bravais_matrix(lat0) cell_1 = lat0 |> supercell(region = r -> -1.01/√3 <= r[1] <= 4/√3 && 0 <= r[2] <= 3.5) cell_2 = translate(transform(cell_1, r -> r + br * SA[2.2, -1]), SA[1,2]) cell_p = lattice(sublat(br * SA[1.6,0.73], br * SA[1.6,1.27])) cells = combine(cell_1, cell_2, cell_p) @test length.(sites.(Ref(cells), 1:5)) == [14, 14, 14, 14, 2] @test_throws ArgumentError combine(LatticePresets.honeycomb(), LatticePresets.square()) @test_throws ArgumentError combine(LatticePresets.honeycomb(), LatticePresets.linear()) lat1 = transform(LatticePresets.honeycomb(), r -> SA[r[2], -r[1]]) |> supercell((-1,1), (1,1)) lat2 = combine(lat0, lat1) @test lat2 isa typeof(lat0) @test allunique(Quantica.sublatnames(lat2)) lat1 = transform(LatticePresets.honeycomb(), r -> SA[r[2], -r[1]]) |> supercell((-3,3), (1,1)) @test_throws ArgumentError combine(lat0, lat1) end @testset "lattice nrange" begin lat = LP.honeycomb(a0 = 1) @test Quantica.nrange(1, lat) ≈ 1/√3 @test Quantica.nrange(2, lat) ≈ 1 @test Quantica.nrange(3, lat) ≈ 2/√3 lat = LP.cubic(a0 = 1) |> supercell(10) @test Quantica.nrange(1, lat) ≈ 1 @test Quantica.nrange(2, lat) ≈ √2 @test Quantica.nrange(3, lat) ≈ √3 end @testset "lattice supercell" begin presets = (LatticePresets.linear, LatticePresets.square, LatticePresets.triangular, LatticePresets.honeycomb, LatticePresets.cubic, LatticePresets.fcc, LatticePresets.bcc, LatticePresets.hcp) for preset in presets lat = preset() E, L = Quantica.embdim(lat), Quantica.latdim(lat) for l in 1:L # some ramdon but deterministic svecs svecs = ntuple(i -> ntuple(j -> i*round(Int, cos(2j)) + j*round(Int, sin(2i)) , Val(E)), L-l) @test supercell(lat, svecs...) isa Lattice{Float64,E,L-l} @test supercell(lat, l) isa Lattice{Float64,E,L} end end @test supercell(LatticePresets.honeycomb(), region = RegionPresets.circle(10, (10,0))) isa Lattice{Float64,2,0} @test supercell(LatticePresets.honeycomb(), (2,1), region = RegionPresets.circle(10)) isa Lattice{Float64,2,1} @test supercell(LatticePresets.bcc(), (2,1,0), region = RegionPresets.circle(10)) isa Lattice{Float64,3,1} @test supercell(LatticePresets.cubic(), (2,1,0), region = RegionPresets.sphere(10, (10,2,1))) isa Lattice{Float64,3,1} end @testset "lattice boolean regions" begin lat = supercell(LP.square(), region = xor(RP.square(10), RP.square(20)), seed = SA[20,0]) @test length(sites(lat)) == 320 lat = supercell(LP.honeycomb(), region = xor(RP.circle(20), RP.square(10))) lat´ = supercell(LP.honeycomb(), region = RP.circle(20) & !RP.square(10)) @test sites(lat) == sites(lat´) lat = supercell(LP.honeycomb(), region = RP.circle(5, (5,0)) | RP.circle(5, (15,0)) | RP.circle(5, (25,0))) lat´ = supercell(LP.honeycomb(), region = RP.circle(5, (5,0))) @test length(sites(lat)) == 3 * length(sites(lat´)) end @testset "lattice slices" begin lat = LP.honeycomb() |> supercell(2) ls = lat[sites(1:2)] @test length(ls) == 2 ls = lat[sites(:)] @test length(ls) == 8 ls = lat[sites(SA[1,2], :)] @test length(ls) == 8 ls1 = lat[sublats = :B, region = RP.ellipse((10, 20), (0, 1/√3))] ls2 = lat[sublats = :A, region = RP.ellipse((10, 20))] ls3 = lat[region = RP.ellipse((10, 20))] @test length(ls1) == length(ls2) @test ls2[2] isa Tuple{SVector{2, Int}, Int} ls = ls1[sublats = :B] @test isempty(ls) ls = ls3[sublats = :B, region = RP.ellipse((1, 2))] @test !isempty(ls) ls´ = ls3[(; sublats = :B, region = RP.ellipse((1, 2)))] @test nsites(ls) == nsites(ls´) ls = lat[cells = n -> 5 < norm(n) < 10] @test !isempty(Quantica.cells(ls)) && all(n -> 5 < norm(n) < 10, Quantica.cells(ls)) ls = lat[region = r -> 5 < norm(r) < 10] @test !isempty(Quantica.cells(ls)) && all(r -> 5 < norm(r) < 10, Quantica.sites(ls)) ls = lat[sites(SA[1,0], 1:3)] @test ls isa Quantica.SiteSlice @test nsites(ls) == 3 ls = lat[sites(SA[1,0], 2)] @test ls isa Quantica.SiteSlice @test nsites(ls) == 1 # test the difference between a null selector and an unspecified one ls = lat[cells = SVector{2,Int}[]] @test isempty(ls) ls = lat[cells = missing] @test !isempty(ls) ls = lat[region = RP.circle(4)] ls´ = ls[cells = n -> !isreal(n[1])] @test isempty(ls´) end
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
3934
@test_throws ArgumentError qplot(LP.linear()) # no backend loaded using CairoMakie @testset "plot lattice" begin # Makie issue #3009 workaround lat = LP.linear() |> supercell(10) |> supercell @test display(qplot(lat)) isa CairoMakie.Screen{CairoMakie.IMAGE} end @testset "plot hamiltonian" begin h = LP.bcc() |> hamiltonian(hopping(1)) |> supercell(3) |> supercell((1,0,0)) g = greenfunction(h) @test qplot(h, sitecolor = :blue, siteradius = 0.3, inspector = true) isa Figure @test qplot(h, sitecolor = :yellow, siteopacity = (i, r) -> r[1], inspector = true, flat = false) isa Figure h = LP.honeycomb() |> hamiltonian(hopping(1)) |> supercell(3) |> supercell g = h |> attach(nothing) |> greenfunction @test qplot(h, hopcolor = :blue, hopradius = ldos(g(0.2)), inspector = true) isa Figure @test qplot(h, hopcolor = (:blue, RGBAf(1,0,0)), sitecolor = [:orange, :white], inspector = true) isa Figure @test qplot(h, hopcolor = :yellow, hopopacity = current(g(0.2)), inspector = true, flat = false) isa Figure @test qplot(g, hopcolor = :yellow, hopopacity = (ij, (r, dr)) -> r[1], inspector = true, flat = false) isa Figure @test scatter(h, :A) isa Makie.FigureAxisPlot @test scatter(g, 1) isa Makie.FigureAxisPlot @test scatter(lattice(g)) isa Makie.FigureAxisPlot @test lines(h, :A) isa Makie.FigureAxisPlot @test lines(g) isa Makie.FigureAxisPlot @test_throws BoundsError lines(lattice(h), 3) h = LP.linear() |> hamiltonian(@hopping(()->I), orbitals = 2) @test qplot(h) isa Figure g = LP.linear() |> hamiltonian(hopping(I), orbitals = 2) |> attach(@onsite(ω->im*I), cells = 1) |> attach(@onsite(ω->im*I), cells = 4) |> greenfunction @test qplot(g, selector = siteselector(; cells = -10:10)) isa Figure # matrix shader gx1 = abs2.(g(0.01)[siteselector(cells = 1:10), 1]) @test qplot(g, selector = siteselector(cells = 1:10), sitecolor = gx1) isa Figure # vector shader gx1´ = vec(sum(gx1, dims = 2)) @test qplot(g, selector = siteselector(cells = 1:10), sitecolor = gx1´) isa Figure # green with leads glead = LP.honeycomb() |> hopping(1, range = 1) |> supercell((1,-1), region = r -> 0<=r[2]<=5) |> attach(nothing, cells = SA[5]) |> greenfunction(GS.Schur(boundary = 0)); g = LP.honeycomb() |> hopping(1) |> supercell(region = r -> -6<=r[1]<=6 && 0<=r[2]<=5) |> attach(glead, region = r -> r[1] > 4.9) |> greenfunction; @test qplot(g, shellopacity = 0.3) isa Figure hlead = LP.square() |> supercell((1,0), region = r -> 0 <= r[2] < 2) |> hopping(1) glead = LP.square() |> onsite(4) - hopping(1) |> supercell((1, 0), region = r -> abs(r[2]) <= 5/2) |> attach(nothing, cells = SA[2]) |> greenfunction(GS.Schur(boundary = -2)) @test qplot(glead, siteradius = 0.25, children = (; sitecolor = :blue)) isa Figure g = LP.honeycomb() |> hopping(1, range = 1) |> attach(nothing, region = RP.circle(1, SA[2,3])) |> attach(nothing, region = RP.circle(1, SA[3,-3])) |> greenfunction(GS.Bands(subdiv(-π, π, 13), subdiv(-π, π, 13), boundary = 2=>-3)) @test qplot(g) isa Figure # Issue 200 g = LP.linear() |> hamiltonian(@hopping((; q = 1) -> q*I), orbitals = 2) |> attach(@onsite((ω; p = 0) ->p*SA[0 1; 1 0]), cells = 1) |> greenfunction @test qplot(g) isa Figure @test qplot(g(p = 3)) isa Figure end @testset "plot bands" begin SOC(dr) = ifelse(iseven(round(Int, atan(dr[2], dr[1])/(pi/3))), im, -im) model = hopping(1) + @hopping((r, dr; α = 0) -> α * SOC(dr); sublats = :A => :A, range = 1) - @hopping((r, dr; α = 0) -> α * SOC(dr); sublats = :B => :B, range = 1) h = LatticePresets.honeycomb(a0 = 1) |> hamiltonian(model) b = bands(h(α = 0.05), range(0, 2pi, length=60), range(0, 2pi, length = 60)) @test qplot(b, color = (psi, e, k) -> angle(psi[1] / psi[2]), colormap = :cyclic_mrybm_35_75_c68_n256, inspector = true) isa Figure end
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
code
3104
@testset "show methods" begin hs = HP.graphene(orbitals = 2), HP.graphene(orbitals = (2,1)) for h in hs b = bands(h, subdiv(0,2pi,10), subdiv(0,2pi,10)) g = greenfunction(supercell(h) |> attach(@onsite(ω -> im*I)) |> attach(nothing), GS.Spectrum()) @test nothing === show(stdout, sublat((0,0))) @test nothing === show(stdout, LP.honeycomb()) @test nothing === show(stdout, LP.honeycomb()[cells = (0,0)]) @test nothing === show(stdout, siteselector(; cells = (0,0))) @test nothing === show(stdout, hopselector(; range = 1)) @test nothing === show(stdout, onsite(1) + hopping(1)) @test nothing === show(stdout, @onsite(()->1) + @hopping(()->1)) @test nothing === show(stdout, @onsite!(o->1)) @test nothing === show(stdout, @hopping!(t->1)) @test nothing === show(stdout, h) @test nothing === show(stdout, h |> hamiltonian(@onsite!(o->2o))) @test nothing === show(stdout, h |> attach(nothing, cells = (0,0))) @test nothing === show(stdout, current(h)) @test nothing === show(stdout, ES.LinearAlgebra()) @test nothing === show(stdout, spectrum(h, (0,0))) @test nothing === show(stdout, b) @test nothing === show(stdout, b[(0,0)]) @test nothing === show(stdout, Quantica.slice(b, (0,0))) @test nothing === show(stdout, Quantica.slice(b, (0,0))) @test nothing === show(stdout, g) @test nothing === show(stdout, g[cells = ()]) @test nothing === show(stdout, MIME("text/plain"), g[diagonal(cells = ())](0.1)) @test nothing === show(stdout, g(0.1)) @test nothing === show(stdout, ldos(g[1])) @test nothing === show(stdout, ldos(g(0.1))) @test nothing === show(stdout, current(g[1])) @test nothing === show(stdout, current(g(0.1))) @test nothing === show(stdout, conductance(g[1])) @test nothing === show(stdout, transmission(g[1,2])) @test nothing === show(stdout, densitymatrix(g[1])) @test nothing === show(stdout, MIME("text/plain"), densitymatrix(g[1])()) @test nothing === show(stdout, sites(1)) @test nothing === show(stdout, sites(SA[1], 2:4)) @test nothing === show(stdout, sites(:)) @test nothing === show(stdout, sites(SA[0], :)) end h = first(hs) g = greenfunction(supercell(h) |> attach(@onsite(ω -> im*I)) |> attach(nothing)) @test nothing === show(stdout, josephson(g[1], 2)) @test nothing === show(stdout, densitymatrix(g[1], 2)) h = supercell(h, 3) |> supercell g = greenfunction(supercell(h) |> attach(nothing), GS.KPM()) @test nothing === show(stdout, densitymatrix(g[1])) g = greenfunction(supercell(h) |> attach(@onsite(ω -> im*I)) |> attach(nothing), GS.Spectrum()) @test nothing === show(stdout, densitymatrix(g[1])) b = LP.honeycomb() |> Quantica.builder(orbitals = 2) @test nothing === show(stdout, b) w = EP.wannier90("wannier_test_tb.dat"); @test nothing === show(stdout, w) @test nothing === show(stdout, position(w)) end
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
docs
3390
![banner_small](https://github.com/pablosanjose/Quantica.jl/assets/4310809/e1af9dd1-58ae-4eff-8632-69ba8792c582) <!-- [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://pablosanjose.github.io/Quantica.jl/stable) --> [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://pablosanjose.github.io/Quantica.jl/dev) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.4762964.svg)](https://doi.org/10.5281/zenodo.4762964) [![Build Status](https://github.com/pablosanjose/Quantica.jl/workflows/CI/badge.svg)](https://github.com/pablosanjose/Quantica.jl/actions) [![Coverage](https://codecov.io/gh/pablosanjose/Quantica.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/pablosanjose/Quantica.jl) [![GitHub commits since last release](https://img.shields.io/github/commits-since/pablosanjose/Quantica.jl/latest?include_prereleases&sort=semver&style=social)](https://github.com/pablosanjose/Quantica.jl) The Quantica.jl package provides an expressive API to build arbitrary quantum systems on a discrete lattice, and a collection of algorithms to compute some of their properties. Quantica.jl requires Julia v1.9 or later. # Some current features - Build and visualize Hamiltonians on discrete lattices of arbitrary dimensions, using tight-binding models with arbitrary number of orbitals - Compute and visualize band structures of periodic systems - Couple arbitrary Hamiltonians and compute non-interacting Green functions - Compute transport and spectral observables, such as local density of states, current densities, conductance and Josephson currents Some of this functionality, particularly visualization, requires loading some plot backend from the Makie repository, such as GLMakie (GPU-accelerated interactive visualization), CairoMakie (for pdf/svg output) or WGLMakie (Web-GL backend for use inside browsers) # Example A step-by-step construction and visualization of a Kane-Mele model (parametrized by spin orbit strength α)and of its bandstructure, encoding the pseudospin orientation in the color of the subbands. ```julia julia> using Quantica, GLMakie julia> SOC(dr) = ifelse(iseven(round(Int, atan(dr[2], dr[1])/(pi/3))), im, -im); # Kane-Mele spin-orbit coupling julia> model = hopping(1, range = 1/√3) + @hopping((r, dr; α = 0) -> α * SOC(dr); sublats = :A => :A, range = 1) - @hopping((r, dr; α = 0) -> α * SOC(dr); sublats = :B => :B, range = 1); julia> h = LatticePresets.honeycomb(a0 = 1) |> hamiltonian(model) ParametricHamiltonian{Float64,2,2}: Parametric Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 7 Harmonic size : 2 × 2 Orbitals : [1, 1] Element type : scalar (ComplexF64) Onsites : 0 Hoppings : 18 Coordination : 9.0 Parameters : [:α] julia> qplot(h(α = 0.02)) julia> b = bands(h(α = 0.05), range(0, 2pi, length=60), range(0, 2pi, length = 60)) Bandstructure{Float64,3,2}: 3D Bandstructure over a 2-dimensional parameter space of type Float64 Subbands : 2 Vertices : 7200 Edges : 21122 Simplices : 13924 julia> qplot(b, color = (psi, e, k) -> angle(psi[1] / psi[2]), colormap = :cyclic_mrybm_35_75_c68_n256, hide = :wireframe) ``` <p float="left"> <img height="400" alt="Kane-Mele Hamiltonian" src="docs/src/assets/latticeKM.png"> <img height="400" alt="Kane-Mele bandstructure" src="docs/src/assets/bandsKM.png"> </p>
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
docs
108
# [API](@id api) ```@meta CurrentModule = Quantica ``` ```@index ``` ```@autodocs Modules = [Quantica] ```
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
docs
1487
![Quantica.jl logo](assets/banner.png) [Quantica.jl](https://github.com/pablosanjose/Quantica.jl/) is a Julia package for building generic tight-binding models and computing spectral and transport properties. ## Installation ```julia julia> import Pkg; Pkg.add("Quantica") ``` Quantica.jl requires Julia v1.9 or later. Some of its functionality, notably plotting, will become available only after `using GLMakie`, or some other plotting package from the [Makie.jl](https://docs.makie.org/stable/) family. Install `GLMakie` with ```julia julia> import Pkg; Pkg.add("GLMakie") ``` Then, to begin using Quantica, just load it by doing ```julia julia> using Quantica ``` (and possibly also e.g. `using GLMakie` if you need to plot Quantica objects). ## Asking questions, reporting bugs If you encounter problems, please read the tutorial and examples, your question is probably answered there. You can also check the docstring of each Quantica.jl function [here](@ref api) or within the Julia REPL, by entering the function preceded by a `?`, e.g. `?hamiltonian`. If you are still stuck, you may sometimes find me (`@pablosanjose`) at the [Julia Slack](https://julialang.slack.com) or [Julia Discourse](https://discourse.julialang.org). If you believe you found a bug in Quantica.jl, please don't hesitate to file a [GitHub issue](https://github.com/pablosanjose/Quantica.jl/issues), preferably with detailed instructions to reproduce it. Pull requests with fixes are also welcome!
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
docs
12171
# Non-spatial models and self-consistent mean-field problems As briefly mentioned when discussing parametric models and modifiers, we have a special syntax that allows models to depend on sites directly, instead of on their spatial location. We call these non-spatial models. A simple example, with an onsite energy proportional to the site **index** ```julia julia> model = @onsite((i; p = 1) --> ind(i) * p) ParametricModel: model with 1 term ParametricOnsiteTerm{ParametricFunction{1}} Region : any Sublattices : any Cells : any Coefficient : 1 Argument type : non-spatial Parameters : [:p] ``` or a modifier that changes a hopping between different cells ```julia julia> modifier = @hopping!((t, i, j; dir = 1) --> (cell(i) - cell(j))[dir]) HoppingModifier{ParametricFunction{3}}: Region : any Sublattice pairs : any Cell distances : any Hopping range : Inf Reverse hops : false Argument type : non-spatial Parameters : [:dir] ``` Note that we use the special syntax `-->` instead of `->`. This indicates that the positional arguments of the function, here called `i` and `j`, are no longer site positions as up to now. These `i, j` are non-spatial arguments, as noted by the `Argument type` property shown above. Instead of a position, a non-spatial argument `i` represent an individual site, whose index is `ind(i)`, its position is `pos(i)` and the cell it occupies on the lattice is `cell(i)`. Technically `i` is of type `CellSitePos`, which is an internal type not meant for the end user to instantiate. One special property of this type, however, is that it can efficiently index `OrbitalSliceArray`s. We can use this to build a Hamiltonian that depends on an observable, such as a `densitymatrix`. A simple example of a four-site chain with onsite energies shifted by a potential proportional to the local density on each site: ```julia julia> h = LP.linear() |> onsite(2) - hopping(1) |> supercell(4) |> supercell; julia> h(SA[]) 4×4 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 10 stored entries: 2.0+0.0im -1.0+0.0im ⋅ ⋅ -1.0+0.0im 2.0+0.0im -1.0+0.0im ⋅ ⋅ -1.0+0.0im 2.0+0.0im -1.0+0.0im ⋅ ⋅ -1.0+0.0im 2.0+0.0im julia> g = greenfunction(h, GS.Spectrum()); julia> ρ = densitymatrix(g[])(0.5, 0) ## density matrix at chemical potential `µ=0.5` and temperature `kBT = 0` on all sites 4×4 OrbitalSliceMatrix{Matrix{ComplexF64}}: 0.138197+0.0im 0.223607+0.0im 0.223607+0.0im 0.138197+0.0im 0.223607+0.0im 0.361803+0.0im 0.361803+0.0im 0.223607+0.0im 0.223607+0.0im 0.361803+0.0im 0.361803+0.0im 0.223607+0.0im 0.138197+0.0im 0.223607+0.0im 0.223607+0.0im 0.138197+0.0im julia> hρ = h |> @onsite!((o, i; U = 0, ρ) --> o + U * ρ[i]) ParametricHamiltonian{Float64,1,0}: Parametric Hamiltonian on a 0D Lattice in 1D space Bloch harmonics : 1 Harmonic size : 4 × 4 Orbitals : [1] Element type : scalar (ComplexF64) Onsites : 4 Hoppings : 6 Coordination : 1.5 Parameters : [:U, :ρ] julia> hρ(SA[]; U = 1, ρ = ρ0) 4×4 SparseArrays.SparseMatrixCSC{ComplexF64, Int64} with 10 stored entries: 2.1382+0.0im -1.0+0.0im ⋅ ⋅ -1.0+0.0im 2.3618+0.0im -1.0+0.0im ⋅ ⋅ -1.0+0.0im 2.3618+0.0im -1.0+0.0im ⋅ ⋅ -1.0+0.0im 2.1382+0.0im ``` Note the `ρ[i]` above. This indexes `ρ` at site `i`. For a multiorbital hamiltonian, this will be a matrix (the local density matrix on each site `i`). Here it is just a number, either ` 0.138197` (sites 1 and 4) or `0.361803` (sites 2 and 3). The above provides the tools to implement self-consistent mean field. We just need to find a fixed point `ρf(ρ) = ρ` of the function `ρf` that produces the density matrix of the system. In the following example we use the FixedPoint.jl package. It provides a simple utility `afps(f, x0)` that computes the solution of `f(x) = x` with initial condition `x0`. The package requires `x0` to be a (real) `AbstractArray`. Note that any other fixed-point search routine that work with `AbstractArray`s should also work. ```julia julia> using FixedPoint julia> ρf(hρ; µ = 0.5, kBT = 0, U = 0.1) = ρ -> densitymatrix(greenfunction(hρ(; U, ρ), GS.Spectrum())[])(µ, kBT) ρf (generic function with 1 method) julia> (ρsol, ρerror, iters) = @time afps(ρf(hρ; U = 0.4), real(ρ0), tol = 1e-8, ep = 0.95, vel = 0.0); @show iters, ρerror; ρsol 0.000627 seconds (1.91 k allocations: 255.664 KiB) (iters, ρerror) = (8, 2.0632459629688071e-10) 4×4 OrbitalSliceMatrix{Matrix{ComplexF64}}: 0.145836+0.0im 0.227266+0.0im 0.227266+0.0im 0.145836+0.0im 0.227266+0.0im 0.354164+0.0im 0.354164+0.0im 0.227266+0.0im 0.227266+0.0im 0.354164+0.0im 0.354164+0.0im 0.227266+0.0im 0.145836+0.0im 0.227266+0.0im 0.227266+0.0im 0.145836+0.0im ``` !!! note "Bring your own fixed-point solution!" Note that fixed-point calculations can be tricky, and the search algorithm can have a huge impact in convergence (if the problem converges at all!). For this reason, Quantica.jl does not provide built-in fixed-point routines, only the functionality to write functions such as `ρf` above. !!! tip "Sparse mean fields" The method explained above to build a Hamiltonian supports all the `SiteSelector` and `HopSelector` functionality of conventional models. Therefore, although the density matrix computed above is dense, its application to the Hamiltonian is sparse: it only touches the onsite matrix elements. Likewise, we could for example use `@hopping!` with a finite `range` to apply a Fock mean field within a finite range. In the future we will support built-in Hartree-Fock model presets with adjustable sparsity. # Wannier90 imports A common way to obtain quantitative tight-binding models of materials is to *Wannierize* density-functional-theory (DFT) bandstructures. In a nutshell, this procedure consists in obtaining a basis set of a subspace of some DFT bandstructure, subject to the condition that the obtained states are maximally localized. A popular implementation of this algorithm is (Wannier90)[https://wannier.org]. Among other things, this tool produces output files that encode a tight-binding Hamiltonian for the material and the matrix elements of the position operator in the maximally localized Wannier basis. Quantica.jl includes a function that can import Wannier90 tight-binding files. By default these files are 3D systems ``` julia> w = ExternalPresets.wannier90("wannier_tb.dat") WannierBuilder{Float64,3} : 3-dimensional Hamiltonian builder of type Float64 from Wannier90 input cells : 755 elements : 36388 modifiers : 0 ``` In this case, however, the model in the "wannier_tb.dat" file is a 2D MoS2 crystal. We can project out all out-of-plane matrix elements by specifying the dimension with `dim`. We can also drop any Hamiltonian matrix element smaller than, say `htol = 1e-5`, and any position matrix element of norm smaller than `rtol = 1e-4`. This greatly simplifies the problem ``` julia> w = ExternalPresets.wannier90("wannier_tb.dat"; dim = 2, htol = 1e-5, rtol = 1e-4) WannierBuilder{Float64,2} : 2-dimensional Hamiltonian builder of type Float64 from Wannier90 input cells : 151 elements : 7510 modifiers : 0 ``` This object can then be converted into a Hamiltonian `h` or a position operator `r` ``` julia> h = hamiltonian(w) Hamiltonian{Float64,2,2}: Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 151 Harmonic size : 10 × 10 Orbitals : [1] Element type : scalar (ComplexF64) Onsites : 10 Hoppings : 7500 Coordination : 750.0 julia> r = sites(w) BarebonesOperator{2}: a simple collection of 2D Bloch harmonics Bloch harmonics : 151 Harmonic size : 10 × 10 Element type : SVector{2, ComplexF64} Nonzero elements : 7408 ``` Note that `r` is not of type `Hamiltonian`. The `BarebonesOperator` is a specially simple operator type that simply encodes a number of Bloch harmonics (matrices between different unit cells) of arbitrary element type. It supports only a subset of the funcitionality of `AbstractHamiltonian`s. In particular, it supports indexing: ``` julia> r[SA[0,0]] 10×10 SparseArrays.SparseMatrixCSC{SVector{2, ComplexF64}, Int64} with 50 stored entries: [-0.000563148+0.0im, 1.79768+0.0im] … ⋅ ⋅ [0.164126-2.15538e-5im, -0.000484848-0.0144407im] ⋅ [0.0195449-4.9251e-5im, 2.02798e-7+0.00140866im] [2.48859e-5-0.0185437im, -0.00534254-1.88085e-5im] ⋅ ⋅ [2.07772e-7-0.00769914im, 0.00831306+1.45056e-5im] [-0.00340134-1.02057e-5im, 1.89607e-5+0.00656423im] … ⋅ [-0.000371236+0.0227337im, -0.101768+1.64659e-5im] ⋅ ⋅ [0.210672-5.77589e-5im, -0.000233323-0.00456068im] [0.164126-2.14909e-5im, -0.000483435-0.0144407im] ⋅ ⋅ [0.000608652+0.0im, 2.12317+0.0im] julia> r[sites(1), sites(4)] 2-element SVector{2, ComplexF64} with indices SOneTo(2): 2.4885857e-5 + 0.018543702im -0.0053425408 + 1.8808481e-5im ``` It is possible to modify the imported Wannier90 models using the full Quantica.jl machinery. For example, we can add any `AbstractModel` to the Wannier90 model upon import just by passing it as a second argument ``` julia> w = EP.wannier90("wannier_tb.dat", @onsite((; Δ = 0) -> Δ); dim = 2) WannierBuilder{Float64,2} : 2-dimensional Hamiltonian builder of type Float64 from Wannier90 input cells : 151 elements : 7560 modifiers : 1 julia> h = hamiltonian(w) ParametricHamiltonian{Float64,2,2}: Parametric Hamiltonian on a 2D Lattice in 2D space Bloch harmonics : 151 Harmonic size : 10 × 10 Orbitals : [1] Element type : scalar (ComplexF64) Onsites : 10 Hoppings : 7540 Coordination : 754.0 Parameters : [:Δ] ``` Note that since we used a `ParametricModel` with a single parametric term, this introduced one `modifier`, since ParametricModels are simply an ordinary base model plus one modifier for each parametric term. As a result, `h` is now parametric. !!! note "Adding models after import" Although the above is the recommended way to add a Quantica model to a Wannier90 model (i.e. explicitly at import time), one can also do the same with `Quantica.add!(EP.hbuilder(w), model)` to modify `w` in place after its creation. This employs internal functionality, so it is not recommended, as it could change without warning. We can also use the following syntax apply one or more modifiers explicitly ``` julia> w´ = w |> @onsite!((o; k = 0) -> o + k) WannierBuilder{Float64,2} : 2-dimensional Hamiltonian builder of type Float64 from Wannier90 input cells : 151 elements : 7560 modifiers : 2 ``` An interesting application of modifiers is the addition of an electric field that couples to the full `r` operator. In an strict tight-binding limit, we would add an electric field `E` simply as an onsite potential ``` julia> hE = h |> @onsite!((o, r; E = SA[0,0]) -> o + E'*r); ``` However, we actually have the full `r` operator now, which includes non-diagonal matrix elements. We can then incorporate the electric field term `E'*r` more precisely. We can do so using the `-->` syntax and the indexing functionality of the `r::BarebonesOperator` that we obtained from Wannier90 ``` julia> hE = h |> @onsite!((o, i; E = SA[0,0]) --> o + E'*r[i,i]) |> @hopping!((t, i, j; E = SA[0,0]) --> t + E'*r[i,j]); ``` !!! note "Closures over non-constant objects" Note that the above creates a closure over `r`, which is not `const`. As a result this would incur a small performance and allocation cost when evaluating `hE(E=...)`. We can avoid it e.g. by defining `r` as a constant, `const r = sites(w)`.
Quantica
https://github.com/pablosanjose/Quantica.jl.git
[ "MIT" ]
1.1.0
258274c47afd63fe67dade9c3f12244b086288e8
docs
10539
# Bandstructures The eigenpairs (eigenvalues and eigenvectors) of a `Hamiltonian` or `ParametricHamiltonian` at given Bloch phases `ϕᵢ` can be obtained with `spectrum`: ```julia julia> h = LP.honeycomb() |> hopping(1); ϕᵢ = (0, π); julia> eᵢ, ψᵢ = spectrum(h, ϕᵢ; solver = EigenSolvers.LinearAlgebra()) Spectrum{Float64,ComplexF64} : Energies: 2-element Vector{ComplexF64}: -1.0 + 0.0im 1.0 + 0.0im States: 2×2 Matrix{ComplexF64}: 0.707107-8.65956e-17im 0.707107-8.65956e-17im -0.707107+0.0im 0.707107+0.0im ``` The above destructuring syntax assigns eigenvalues and eigenvectors to `eᵢ` and `ψᵢ`, respectively. The available eigensolvers and their options can be checked in the `EigenSolvers` docstrings. !!! warning "Arpack solver is not thread-safe" `EigenSolvers.Arpack` relies on a Fortran library that is not currently thread-safe. If you launch Julia with multiple threads, they will not be used with this specific solver. Otherwise Arpack would segfault. We define a "bandstructure" of an `h::AbstractHamiltonian` as a linear interpolation of its eigenpairs over a portion of the Brillouin zone, which is discretized with a base mesh of `ϕᵢ` values. At each `ϕᵢ` of the base mesh, the Bloch matrix `h(ϕᵢ)` is diagonalized with `spectrum`. The adjacent eigenpairs `eⱼ(ϕᵢ), ψⱼ(ϕᵢ)` are then connected ("stitched") together into a number of band meshes with vertices `(ϕᵢ..., eⱼ(ϕᵢ))` by maximizing the overlap of adjacent `ψⱼ(ϕᵢ)` (since the bands should be continuuous). Degenerate eigenpairs are collected into a single node of the band mesh. The bandstructure of an `h::AbstractHamiltonian` is computed using `bands`: ```julia julia> ϕ₁points = ϕ₂points = range(0, 2π, length = 19); julia> b = bands(h, ϕ₁points, ϕ₂points) Bandstructure{Float64,3,2}: 3D Bandstructure over a 2-dimensional parameter space of type Float64 Subbands : 1 Vertices : 720 Edges : 2016 Simplices : 1296 ``` The first argument is the `AbstractHamiltonian`. Here it is defined on an `L=2` dimensional lattice. The subsequent arguments are collections of Bloch phases on each of the `L` axes of the Brillouin zone, whose direct product `ϕ₁points` ⊗ `ϕ₂points` defines our base mesh of `ϕᵢ` points. Here it is a uniform 19×19 grid. We can once more use `qplot` to visualize the bandstructure, or more precisely the band meshes: ```julia julia> using GLMakie; qplot(b) ``` ```@raw html <img src="../../assets/graphene_bands.png" alt="Graphene bands" width="400" class="center"/> ``` The dots on the bands are the band mesh vertices `(ϕᵢ..., eⱼ(ϕᵢ))`. They can be omitted with the `qplot` keyword `hide = :nodes` (or `hide = :vertices`, both are equivalent). ## Band defects Note that the uniform grid contains the Dirac points. This is the reason for the number `19` of Bloch phases used above. Note also that it is identified as a point in the bands with `degeneracy = 2` (the rest have `degeneracy = 1`). As mentioned, the points on the bands are connected based on eigenstate overlaps between adjacent `ϕᵢ`s. This interpolation algorithm can deal with subspace degeneracies, as here. However, Dirac points (and Diabolical Points in general) must belong to the mesh for the method to work. If the number of points is reduced to 18 per axis, the Dirac points become unavoidable band dislocations, that appear as missing simplices in the bands: ```@raw html <img src="../../assets/graphene_bands_bad.png" alt="Graphene bands with Dirac point dislocation" width="400" class="center"/> ``` !!! tip "Advanced: band defects and patching" If a Dirac point or other type of band dislocation point happens to not belong to the sampling grid, it can be added with the `bands` keyword `defects`. Then, it can be reconnected with the rest of the band by increasing the `patches::Integer` keyword (see `bands` docstring for details). This "band repair" functionality is experimental, and should only be necessary in some cases with Diabolical Points. ## Coordinate mapping and band linecuts The direct product of the `ϕᵢpoints` above define a rectangular mesh over which we want to compute the bandstructure. By default, this mesh is taken as a discretization of Bloch phases, so `h(ϕᵢ)` is diagonalized at each point of the base mesh. We might want, however, a different relation between the mesh and the parameters passed to `h`, for example if we wish to use wavevectors `k` instead of Bloch phases `ϕᵢ = k⋅Aᵢ` for the mesh. This is achieved with the `mapping` keyword, which accepts a function `mapping = (mesh_points...) -> bloch_phases`, ```julia julia> h = LP.honeycomb() |> hopping(2); k₁points = range(-2π, 2π, length = 51); k₂points = range(-2π, 2π, length = 51); julia> Kpoints = [SA[cos(θ) -sin(θ); sin(θ) cos(θ)] * SA[4π/3,0] for θ in range(0, 5*2π/6, length = 6)]; julia> ϕ(k...) = SA[k...]' * bravais_matrix(h) ϕ (generic function with 1 method) julia> b = bands(h, k₁points, k₂points; mapping = ϕ, defects = Kpoints, patches = 20); julia> using GLMakie; qplot(b, hide = (:nodes, :wireframe), color = :orange) ``` ```@raw html <img src="../../assets/graphene_bands_k.png" alt="Graphene bands in k-space" width="400" class="center"/> ``` To compute a bandstructure linecut along a polygonal line in the Brillouin zone, we could once more use the `mapping` functionality, mapping a set of points `xᵢ::Real` in the mesh to Bloch phases `ϕᵢ` that defines the nodes of the polygonal path, and interpolating linearly between them. To avoid having to construct this mapping ourselves, `mapping` accepts a second type of input for this specific usecase, `mapping = xᵢ => ϕᵢ`. Here, `ϕᵢ` can be a collection of `Tuple`s, `SVector{L}`, or even `Symbols` denoting common names for high-symmetry points in the Brillouin zone, such as :Γ, :K, :K´, :M, :X, :Y, and :Z. The following gives a Γ-K-M-Γ linecut for the bands above, where the (Γ, K, M, Γ) points lie at `x = (0, 2, 3, 4)`, respectively, with 10 subdivisions in each segment, ```julia julia> b = bands(h, subdiv((0, 2, 3, 4), 10); mapping = (0, 2, 3, 4) => (:Γ, :K, :M, :Γ)); julia> qplot(b, axis = (; xticks = ([0, 2, 3, 4], ["Γ", "K", "M", "Γ"]), ylabel = "ϵ")) ``` ```@raw html <img src="../../assets/graphene_bands_linecut.png" alt="Graphene bands along a Γ-K-M-Γ cut" width="400" class="center"/> ``` !!! tip "subdiv" The `subdiv` function is a convenience function provided by Quantica.jl that generalizes `range` (see the corresponding docstring for comprehensive details). It is useful to create collections of numbers as subdivisions of intervals, as in the example above. In its simplest form `subdiv(min, max, npoints)` is is equivalent to `range(min, max, length = npoints)` or `collect(LinRange(min, max, npoints))` The `mapping` keyword understand a third syntax that can be used to map a mesh to the space of Bloch phases and parameters of a `ParametricHamiltonian`. To this end we use `mapping = (mesh_points...) -> ftuple(bloch_phases...; params...)`. The `ftuple` function creates a `FrankenTuple`, which is a hybrid between a `Tuple` and a `NamedTuple`. For example, in the following 1D SSH chain we can compute the bandstructure as a function of Bloch phase `ϕ` *and* hopping `t´`, and plot it using more customization options ```julia julia> h = LP.linear() |> supercell(2) |> @hopping((r, dr; t = 1, t´ = 1) -> iseven(r[1]-1/2) ? t : t´); julia> b = bands(h, subdiv(0, 2π, 11), subdiv(0, 10, 11), mapping = (ϕ, y) -> ftuple(ϕ; t´ = y/5), patches = 20) Bandstructure{Float64,3,2}: 3D Bandstructure over a 2-dimensional parameter space of type Float64 Subbands : 1 Vertices : 249 Edges : 664 Simplices : 416 julia> qplot(b, nodedarken = 0.5, axis = (; aspect = (1,1,1), perspectiveness = 0.5, xlabel = "ϕ", ylabel = "t´/t", zlabel = "ϵ"), fancyaxis = false) ``` ```@raw html <img src="../../assets/ssh_bands.png" alt="SSH bandstructure as a function of `ϕ` and `t´/t" width="400" class="center"/> ``` Note that since we didn't specify a value for `t`, it assumed its default `t=1`. In this case we needed to patch the defect at `(ϕ, t´) = (π, 1)` (topological transition) using the `patches` keyword to avoid a band dislocation. ## Band indexing and slicing The individual subbands in a given `b::Bandstructure` can be obtained with `b[inds]` with `inds::Integer` or `inds::Vector`, just as if `b` where a normal `AbstractVector`. The extracted subbands can also be plotted directly. The following example has 12 subbands, of which we extract and plot the first and last ```julia julia> h = LP.triangular() |> supercell(4) |> hopping(1) + onsite(r -> 4*rand()); julia> b = bands(h, subdiv(0, 2π, 31), subdiv(0, 2π, 31)) Bandstructure{Float64,3,2}: 3D Bandstructure over a 2-dimensional parameter space of type Float64 Subbands : 12 Vertices : 15376 Edges : 44152 Simplices : 28696 julia> qplot(b, hide = (:nodes, :wireframe)) julia> qplot(b[[1, end]], hide = (:nodes, :wireframe)) ``` ```@raw html <img src="../../assets/bands_indexed.png" alt="Extracting and plotting a subset of the subbands in a bandstructure" width="600" class="center"/> ``` For a band in a 2D Brillouin zone, we can also obtain the intersection of a bandstructure with a plane of constant energy `ϵ=2` using the syntax `b[(:,:,2)]`. A section at fixed Bloch phase `ϕ₁=0` (or mesh coordinate `x₁=0` if `mapping` was used), can be obtained with `b[(0,:,:)]`. This type of band slicing can be generalized to higher dimensional bandstructures, or to more than one constrain (e.g. energy and/or a subset of Bloch phases). As an example, this would be the Fermi surface of a nearest-neighbor cubic-lattice Hamiltonian at Fermi energy `µ = 0.2t` ```julia julia> pts = subdiv(0, 2π, 41); b = LP.cubic() |> hopping(1) |> bands(pts, pts, pts) Bandstructure{Float64,4,3}: 4D Bandstructure over a 3-dimensional parameter space of type Float64 Subbands : 1 Vertices : 68921 Edges : 462520 Simplices : 384000 julia> qplot(b[(:, :, :, 0.2)], hide = (:nodes, :wireframe)) ``` ```@raw html <img src="../../assets/cubic_Fermi_surface.png" alt="Fermi surface of a cubic crystal at `µ = 0.2t`" width="400" class="center"/> ``` !!! warning "On simplex orientation of bandstructure slices" The above example showcases a current (cosmetic) limitation of the band slicing algorithm: it sometimes fails to align all faces of the resulting manifold to the same orientation. The dark and bright regions of the surface above reveals that approximately half of the faces in this case are facing inward and the rest outward.
Quantica
https://github.com/pablosanjose/Quantica.jl.git